From fcc2157d179cb0eeb1eeaeda794b1daccb2e4715 Mon Sep 17 00:00:00 2001 From: Brian Fopiano Date: Mon, 2 Nov 2026 17:29:25 -0500 Subject: [PATCH 1/8] Fix structure river findings - End object placements in a finally at all four MantleObjectComponent sites - Split recordObjectPlacement for accepted ranges from endObjectPlacement for the water flag - Place forced single-piece structures after admission and let the MantleWriter veto protect the water - Drop the allowWater parameter from piecePlacement - Validate allowWater as a boolean and add it to anonymous grid identity when true - Add placement exit, forced piece, REPLACE_SOURCE, world Y -1 and placePieces failure tests - Add modded stage river start and policy water tests - Rename the misleading planner river test --- .../ModdedNativeStructureRiverStartTest.java | 107 +++++++ ...ddedNativeStructureWorldgenAccessTest.java | 35 ++ .../ModdedNativeStructureRiverStartTest.java | 107 +++++++ .../mantle/IrisStructureComponent.java | 11 +- .../mantle/MantleObjectComponent.java | 42 ++- .../iris/generation/mantle/MantleWriter.java | 2 +- .../mantle/ObjectDestinationTransaction.java | 8 +- .../generation/mantle/ObjectPassPlacer.java | 5 +- .../pack/PackStructurePlacementValidator.java | 4 + .../object/PlacementModuleSurfaceSupport.java | 2 +- .../IrisStructureComponentCarveWaterTest.java | 43 ++- .../IrisStructureComponentWaterTest.java | 232 ++++++++++++-- ...ntleObjectComponentWaterPlacementTest.java | 298 ++++++++++++++++++ .../mantle/MantleWriterObjectWaterTest.java | 6 +- .../mantle/ObjectContinuationTest.java | 9 +- .../ObjectDestinationTransactionTest.java | 41 ++- .../pack/PackValidatorStructureGraphTest.java | 32 ++ .../NativeStructurePlacementPlannerTest.java | 2 +- 18 files changed, 922 insertions(+), 64 deletions(-) create mode 100644 adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedNativeStructureRiverStartTest.java create mode 100644 adapters/modded-common/src/versions/1.21.1/test/java/art/arcane/iris/modded/ModdedNativeStructureRiverStartTest.java create mode 100644 core/src/test/java/art/arcane/iris/generation/mantle/MantleObjectComponentWaterPlacementTest.java diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedNativeStructureRiverStartTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedNativeStructureRiverStartTest.java new file mode 100644 index 000000000..3e06e48b7 --- /dev/null +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedNativeStructureRiverStartTest.java @@ -0,0 +1,107 @@ +package art.arcane.iris.modded; + +import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeModdedStructureStage; +import art.arcane.volmlib.nativelib.terrain.structure.StructureOwnershipRecordView; +import art.arcane.volmlib.nativelib.terrain.structure.StructureReferencePolicy; +import art.arcane.volmlib.nativelib.terrain.structure.StructureStartPlan; +import art.arcane.volmlib.nativelib.terrain.structure.StructureWaterColumn; +import net.minecraft.SharedConstants; +import net.minecraft.core.Registry; +import net.minecraft.core.RegistryAccess; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.server.Bootstrap; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.levelgen.structure.BoundingBox; +import net.minecraft.world.level.levelgen.structure.Structure; +import net.minecraft.world.level.levelgen.structure.StructurePiece; +import net.minecraft.world.level.levelgen.structure.StructureStart; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; +import java.util.Map; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class ModdedNativeStructureRiverStartTest { + private static final String KEY = "minecraft:village_plains"; + + @BeforeClass + public static void bootstrap() { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + } + + @Test + public void plannedStartsWhosePiecesReachARiverBeyondTheStartChunkAreInvalidated() { + Fixture fixture = new Fixture(35); + + fixture.adjust(fixture.plan(false)); + + verify(fixture.chunk).setStartForStructure(fixture.structure, StructureStart.INVALID_START); + verify(fixture.structures).discard(KEY, 0, 0); + } + + @Test + public void plannedStartsWithinTheLimitOrAllowingWaterKeepTheirStart() { + Fixture within = new Fixture(36); + within.adjust(within.plan(false)); + verify(within.chunk, never()).setStartForStructure(any(), any()); + + Fixture flooded = new Fixture(35); + flooded.adjust(flooded.plan(true)); + verify(flooded.chunk, never()).setStartForStructure(any(), any()); + } + + @SuppressWarnings("unchecked") + private static final class Fixture { + private final NativeModdedStructureStage.Policy policy = mock(NativeModdedStructureStage.Policy.class); + private final StructureReferencePolicy structures = mock(StructureReferencePolicy.class); + private final RegistryAccess registries = mock(RegistryAccess.class); + private final ChunkAccess chunk = mock(ChunkAccess.class); + private final Structure structure = mock(Structure.class); + private final NativeModdedStructureStage stage; + + private Fixture(int riverEdgeX) { + Registry registry = mock(Registry.class); + StructureStart start = mock(StructureStart.class); + StructurePiece home = mock(StructurePiece.class); + StructurePiece road = mock(StructurePiece.class); + when(registries.lookupOrThrow(Registries.STRUCTURE)).thenReturn(registry); + when(registry.getKey(structure)).thenReturn(Identifier.parse(KEY)); + when(chunk.getPos()).thenReturn(new ChunkPos(0, 0)); + when(chunk.getAllStarts()).thenReturn(Map.of(structure, start)); + when(start.isValid()).thenReturn(true); + when(start.getChunkPos()).thenReturn(new ChunkPos(0, 0)); + when(start.getBoundingBox()).thenReturn(new BoundingBox(0, 60, 0, 39, 70, 15)); + when(home.getBoundingBox()).thenReturn(new BoundingBox(0, 60, 0, 15, 70, 15)); + when(road.getBoundingBox()).thenReturn(new BoundingBox(16, 64, 0, 39, 65, 15)); + when(start.getPieces()).thenReturn(List.of(home, road)); + when(policy.allowsFootprint(any(), any())).thenReturn(true); + when(policy.structurePolicy(any())).thenReturn(structures); + when(policy.water(any())).thenReturn((x, z) -> x >= riverEdgeX + ? new StructureWaterColumn(true, true, 58, 62) : StructureWaterColumn.DRY); + stage = new NativeModdedStructureStage<>(new NativeModdedStructureStage.Options<>(null, null, policy)); + } + + private StructureStartPlan plan(boolean allowWater) { + StructureStartPlan plan = mock(StructureStartPlan.class); + when(plan.structureKey()).thenReturn(KEY); + when(plan.allowWater()).thenReturn(allowWater); + return plan; + } + + private void adjust(StructureStartPlan plan) { + stage.adjustGeneratedStructures(registries, chunk, Map.of(), Map.of(structure, plan), null, null); + } + } + + private interface Ownership extends StructureOwnershipRecordView { + } +} diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedNativeStructureWorldgenAccessTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedNativeStructureWorldgenAccessTest.java index cbef69d20..12ab1bd17 100644 --- a/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedNativeStructureWorldgenAccessTest.java +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedNativeStructureWorldgenAccessTest.java @@ -1,6 +1,11 @@ package art.arcane.iris.modded; +import art.arcane.iris.generation.hydrology.raster.WaterRole; +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.volmlib.nativelib.terrain.structure.StructureWater; +import art.arcane.volmlib.nativelib.terrain.structure.StructureWaterColumn; +import art.arcane.volmlib.util.stream.ProceduralStream; import art.arcane.volmlib.nativelib.minecraft26_2.modded.ModdedNativeStructureWorldgenAccess; @@ -63,6 +68,9 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyDouble; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class ModdedNativeStructureWorldgenAccessTest { private static final int GENERATION_CENTER_X = 60; @@ -76,6 +84,33 @@ public class ModdedNativeStructureWorldgenAccessTest { Bootstrap.bootStrap(); } + @Test + @SuppressWarnings("unchecked") + public void policyGivesTheStageRealWaterInWorldHeights() { + Engine engine = mock(Engine.class); + IrisComplex complex = mock(IrisComplex.class); + ProceduralStream roles = mock(ProceduralStream.class); + ProceduralStream floors = mock(ProceduralStream.class); + ProceduralStream heads = mock(ProceduralStream.class); + when(engine.getComplex()).thenReturn(complex); + when(engine.getMinHeight()).thenReturn(-64); + when(complex.getWaterRoleStream()).thenReturn(roles); + when(complex.getRoundedHeighteightStream()).thenReturn(floors); + when(complex.getWaterHeadStream()).thenReturn(heads); + when(roles.get(anyDouble(), anyDouble())).thenAnswer(call -> { + int x = (int) Math.floor(call.getArgument(0).doubleValue()); + return x == 5 ? WaterRole.CHANNEL : x == 6 ? WaterRole.MOUTH : WaterRole.NONE; + }); + when(floors.get(anyDouble(), anyDouble())).thenReturn(120); + when(heads.getDouble(anyDouble(), anyDouble())).thenReturn(126D); + + StructureWater water = new ModdedNativeStructurePolicy(mock(IrisModdedChunkGenerator.class)).water(engine); + + assertEquals(new StructureWaterColumn(true, true, 56, 62), water.column(5, 0)); + assertEquals(new StructureWaterColumn(true, false, 56, 62), water.column(6, 0)); + assertEquals(StructureWaterColumn.DRY, water.column(7, 0)); + } + @Test public void ordinaryWorldFlattenPreparationHandlesReferencedVillagePiecesBeyondEightChunks() { int farX = (GENERATION_CENTER_X - 9) << 4; diff --git a/adapters/modded-common/src/versions/1.21.1/test/java/art/arcane/iris/modded/ModdedNativeStructureRiverStartTest.java b/adapters/modded-common/src/versions/1.21.1/test/java/art/arcane/iris/modded/ModdedNativeStructureRiverStartTest.java new file mode 100644 index 000000000..dd6060f74 --- /dev/null +++ b/adapters/modded-common/src/versions/1.21.1/test/java/art/arcane/iris/modded/ModdedNativeStructureRiverStartTest.java @@ -0,0 +1,107 @@ +package art.arcane.iris.modded; + +import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeModdedStructureStage; +import art.arcane.volmlib.nativelib.terrain.structure.StructureOwnershipRecordView; +import art.arcane.volmlib.nativelib.terrain.structure.StructureReferencePolicy; +import art.arcane.volmlib.nativelib.terrain.structure.StructureStartPlan; +import art.arcane.volmlib.nativelib.terrain.structure.StructureWaterColumn; +import net.minecraft.SharedConstants; +import net.minecraft.core.Registry; +import net.minecraft.core.RegistryAccess; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.Bootstrap; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.levelgen.structure.BoundingBox; +import net.minecraft.world.level.levelgen.structure.Structure; +import net.minecraft.world.level.levelgen.structure.StructurePiece; +import net.minecraft.world.level.levelgen.structure.StructureStart; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; +import java.util.Map; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class ModdedNativeStructureRiverStartTest { + private static final String KEY = "minecraft:village_plains"; + + @BeforeClass + public static void bootstrap() { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + } + + @Test + public void plannedStartsWhosePiecesReachARiverBeyondTheStartChunkAreInvalidated() { + Fixture fixture = new Fixture(35); + + fixture.adjust(fixture.plan(false)); + + verify(fixture.chunk).setStartForStructure(fixture.structure, StructureStart.INVALID_START); + verify(fixture.structures).discard(KEY, 0, 0); + } + + @Test + public void plannedStartsWithinTheLimitOrAllowingWaterKeepTheirStart() { + Fixture within = new Fixture(36); + within.adjust(within.plan(false)); + verify(within.chunk, never()).setStartForStructure(any(), any()); + + Fixture flooded = new Fixture(35); + flooded.adjust(flooded.plan(true)); + verify(flooded.chunk, never()).setStartForStructure(any(), any()); + } + + @SuppressWarnings("unchecked") + private static final class Fixture { + private final NativeModdedStructureStage.Policy policy = mock(NativeModdedStructureStage.Policy.class); + private final StructureReferencePolicy structures = mock(StructureReferencePolicy.class); + private final RegistryAccess registries = mock(RegistryAccess.class); + private final ChunkAccess chunk = mock(ChunkAccess.class); + private final Structure structure = mock(Structure.class); + private final NativeModdedStructureStage stage; + + private Fixture(int riverEdgeX) { + Registry registry = mock(Registry.class); + StructureStart start = mock(StructureStart.class); + StructurePiece home = mock(StructurePiece.class); + StructurePiece road = mock(StructurePiece.class); + when(registries.registryOrThrow(Registries.STRUCTURE)).thenReturn(registry); + when(registry.getKey(structure)).thenReturn(ResourceLocation.parse(KEY)); + when(chunk.getPos()).thenReturn(new ChunkPos(0, 0)); + when(chunk.getAllStarts()).thenReturn(Map.of(structure, start)); + when(start.isValid()).thenReturn(true); + when(start.getChunkPos()).thenReturn(new ChunkPos(0, 0)); + when(start.getBoundingBox()).thenReturn(new BoundingBox(0, 60, 0, 39, 70, 15)); + when(home.getBoundingBox()).thenReturn(new BoundingBox(0, 60, 0, 15, 70, 15)); + when(road.getBoundingBox()).thenReturn(new BoundingBox(16, 64, 0, 39, 65, 15)); + when(start.getPieces()).thenReturn(List.of(home, road)); + when(policy.allowsFootprint(any(), any())).thenReturn(true); + when(policy.structurePolicy(any())).thenReturn(structures); + when(policy.water(any())).thenReturn((x, z) -> x >= riverEdgeX + ? new StructureWaterColumn(true, true, 58, 62) : StructureWaterColumn.DRY); + stage = new NativeModdedStructureStage<>(new NativeModdedStructureStage.Options<>(null, null, policy)); + } + + private StructureStartPlan plan(boolean allowWater) { + StructureStartPlan plan = mock(StructureStartPlan.class); + when(plan.structureKey()).thenReturn(KEY); + when(plan.allowWater()).thenReturn(allowWater); + return plan; + } + + private void adjust(StructureStartPlan plan) { + stage.adjustGeneratedStructures(registries, chunk, Map.of(), Map.of(structure, plan), null, null); + } + } + + private interface Ownership extends StructureOwnershipRecordView { + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/IrisStructureComponent.java b/core/src/main/java/art/arcane/iris/generation/mantle/IrisStructureComponent.java index 3fe187035..c5e1699c6 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/IrisStructureComponent.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/IrisStructureComponent.java @@ -165,7 +165,7 @@ public class IrisStructureComponent extends IrisMantleComponent { stilt != null && stilt.isSupportNonOccluding(), placement.isAllowWater()); ObjectPlaceMode mode = structure.getPlaceMode(); int failedPieces = 0; - int water = writer.beginObjectPlacement(run.allowWater()); + writer.beginObjectPlacement(run.allowWater()); try { if (placement.isAnchoredUnderground()) { ObjectPlaceMode undergroundMode = (mode == ObjectPlaceMode.ORGANIC_STILT || mode == ObjectPlaceMode.CEILING_HANG) @@ -190,7 +190,7 @@ public class IrisStructureComponent extends IrisMantleComponent { placeFoundation(writer, run.foundationColumns(), stilt, rng, !placement.isAnchoredUnderground()); } } finally { - writer.endObjectPlacement(water); + writer.endObjectPlacement(); } return failedPieces; } @@ -569,7 +569,7 @@ public class IrisStructureComponent extends IrisMantleComponent { boolean sampledHeight) { IrisObject object = p.getObject(); String objectKey = object.getLoadKey(); - IrisObjectPlacement config = piecePlacement(run.structure(), p, mode, run.allowWater()); + IrisObjectPlacement config = piecePlacement(run.structure(), p, mode); String marker = structurePlacementMarker(run.structure(), p, objectKey); BiConsumer listener = (position, state) -> { StructureFoundationPlanner.recordBaseCell( @@ -584,8 +584,7 @@ public class IrisStructureComponent extends IrisMantleComponent { : object.place(p.getX(), p.getY() - getEngineMantle().getEngine().getMinHeight(), p.getZ(), writer, config, run.rng(), listener, null, getData()); } - static IrisObjectPlacement piecePlacement(IrisStructure structure, PlacedStructurePiece piece, ObjectPlaceMode mode, - boolean allowWater) { + static IrisObjectPlacement piecePlacement(IrisStructure structure, PlacedStructurePiece piece, ObjectPlaceMode mode) { IrisObjectPlacement config = structure.createLootPlacement(piece.getObject().getLoadKey()); config.setMode(mode); config.setRotation(piece.getRotation()); @@ -594,7 +593,7 @@ public class IrisStructureComponent extends IrisMantleComponent { } if (mode != ObjectPlaceMode.STRUCTURE_PIECE && mode != ObjectPlaceMode.FLOATING) { config.setForcePlace(true); - config.setForcedByStructure(!allowWater); + config.setForcedByStructure(true); } return config; } diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java b/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java index 588c2fb99..edaf0f86a 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java @@ -794,7 +794,7 @@ public class MantleObjectComponent extends IrisMantleComponent { }, null, getData()); } if (placeResult >= 0 && (!carving || commitResult == CaveObjectPlacementTransaction.CommitResult.COMMITTED)) { - writer.endObjectPlacement(continuation); + writer.recordObjectPlacement(continuation); } if (golden) { IrisLogging.debug("Goldendebug procedural result: chunk=" + x + "," + z @@ -809,6 +809,8 @@ public class MantleObjectComponent extends IrisMantleComponent { GenerationFailures.rethrowEngineFailure(e); IrisLogging.reportError(e); IrisLogging.error("Failed to place procedural object '" + p.getName() + "' in " + scope); + } finally { + writer.endObjectPlacement(); } } } @@ -1027,7 +1029,7 @@ public class MantleObjectComponent extends IrisMantleComponent { }, null, getData()); if (result >= 0) { - writer.endObjectPlacement(continuation); + writer.recordObjectPlacement(continuation); placed++; } else { rejected++; @@ -1062,6 +1064,8 @@ public class MantleObjectComponent extends IrisMantleComponent { + " densityIndex=" + i + " density=" + density + " error=" + e.getClass().getSimpleName() + ":" + e.getMessage()); + } finally { + writer.endObjectPlacement(); } } @@ -1216,7 +1220,7 @@ public class MantleObjectComponent extends IrisMantleComponent { int result = contained.resultY(); boolean wroteBlocks = contained.commitResult() == CaveObjectPlacementTransaction.CommitResult.COMMITTED; if (wroteBlocks) { - writer.endObjectPlacement(continuation); + writer.recordObjectPlacement(continuation); placed++; } else { rejected++; @@ -1284,6 +1288,8 @@ public class MantleObjectComponent extends IrisMantleComponent { y, e ); + } finally { + writer.endObjectPlacement(); } } @@ -1395,20 +1401,24 @@ public class MantleObjectComponent extends IrisMantleComponent { boolean treePlacement = isTreePlacement(v, objectPlacement); String marker = placementMarker(v, id, "upper"); int continuation = writer.beginObjectPlacement(placement.entersWater()); - int result = v.place(xx, anchorY, zz, writer, placement, rng, (b, data) -> { - if (marker != null) { - writer.setData(b.getX(), b.getY(), b.getZ(), marker); + int result; + try { + result = v.place(xx, anchorY, zz, writer, placement, rng, (b, data) -> { + if (marker != null) { + writer.setData(b.getX(), b.getY(), b.getZ(), marker); + } + if (treePlacement && marker != null) { + writeTreeMaterial(writer, b.getX(), b.getY(), b.getZ(), data); + } + if (placement.isDolphinTarget() && placement.isUnderwater() && B.isStorageChest(data)) { + writer.setData(b.getX(), b.getY(), b.getZ(), MatterStructurePOI.BURIED_TREASURE); + } + }, null, getData()); + if (result >= 0) { + writer.recordObjectPlacement(continuation); } - if (treePlacement && marker != null) { - writeTreeMaterial(writer, b.getX(), b.getY(), b.getZ(), data); - } - if (placement.isDolphinTarget() && placement.isUnderwater() && B.isStorageChest(data)) { - writer.setData(b.getX(), b.getY(), b.getZ(), MatterStructurePOI.BURIED_TREASURE); - } - }, null, getData()); - - if (result >= 0) { - writer.endObjectPlacement(continuation); + } finally { + writer.endObjectPlacement(); } if (traceRegen) { IrisLogging.debug("Upper object placement: chunk=" + chunkX + "," + chunkZ diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/MantleWriter.java b/core/src/main/java/art/arcane/iris/generation/mantle/MantleWriter.java index a135f4847..40e49cf82 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/MantleWriter.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/MantleWriter.java @@ -227,7 +227,7 @@ public class MantleWriter implements ObjectPassPlacer, AutoCloseable { } @Override - public void endObjectPlacement(int checkpoint) { + public void endObjectPlacement() { objectWater.remove(); } diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/ObjectDestinationTransaction.java b/core/src/main/java/art/arcane/iris/generation/mantle/ObjectDestinationTransaction.java index 050743c14..907ced8e6 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/ObjectDestinationTransaction.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/ObjectDestinationTransaction.java @@ -79,13 +79,17 @@ final class ObjectDestinationTransaction implements ObjectPassPlacer { } @Override - public void endObjectPlacement(int checkpoint) { - waterPlacement = false; + public void recordObjectPlacement(int checkpoint) { if (checkpoint >= 0 && checkpoint < log.size()) { placements.add(new PlacementRange(checkpoint, log.size())); } } + @Override + public void endObjectPlacement() { + waterPlacement = false; + } + void apply(ObjectSourcePlan plan) { int slot = plan.destinationSlot(destinationChunkX, destinationChunkZ); if (slot < 0) { diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/ObjectPassPlacer.java b/core/src/main/java/art/arcane/iris/generation/mantle/ObjectPassPlacer.java index 43c1ea1ef..1d3ab669f 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/ObjectPassPlacer.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/ObjectPassPlacer.java @@ -12,7 +12,10 @@ public interface ObjectPassPlacer extends IObjectPlacer { return -1; } - default void endObjectPlacement(int checkpoint) { + default void recordObjectPlacement(int checkpoint) { + } + + default void endObjectPlacement() { } @Override diff --git a/core/src/main/java/art/arcane/iris/pack/PackStructurePlacementValidator.java b/core/src/main/java/art/arcane/iris/pack/PackStructurePlacementValidator.java index c2fee8dfd..c44dfedbd 100644 --- a/core/src/main/java/art/arcane/iris/pack/PackStructurePlacementValidator.java +++ b/core/src/main/java/art/arcane/iris/pack/PackStructurePlacementValidator.java @@ -223,6 +223,7 @@ final class PackStructurePlacementValidator { path, placement, "maxHeight", Integer.MIN_VALUE, Integer.MAX_VALUE, blockingErrors); PackJsonFieldChecks.validateOptionalBoolean(path, placement, "underground", blockingErrors); PackJsonFieldChecks.validateOptionalBoolean(path, placement, "underwater", blockingErrors); + PackJsonFieldChecks.validateOptionalBoolean(path, placement, "allowWater", blockingErrors); PackJsonFieldChecks.validateOptionalEnum(path, placement, "nativeSuppression", Set.of("NONE", "REPLACE_SOURCE"), blockingErrors); @@ -299,6 +300,9 @@ final class PackStructurePlacementValidator { appendIdentity(identity, integerValue(placement, "maxHeight", 2032)); appendIdentity(identity, placement.opt("underground") instanceof Boolean underground && underground); appendIdentity(identity, placement.opt("underwater") instanceof Boolean underwater && underwater); + if (placement.opt("allowWater") instanceof Boolean allowWater && allowWater) { + appendIdentity(identity, "allowWater"); + } JSONArray structures = placement.optJSONArray("structures"); JSONArray nativeStructures = placement.optJSONArray("nativeStructures"); if (structures != null && structures.length() > 0) { diff --git a/core/src/main/java/art/arcane/iris/structure/object/PlacementModuleSurfaceSupport.java b/core/src/main/java/art/arcane/iris/structure/object/PlacementModuleSurfaceSupport.java index 23f949150..ded7f78d2 100644 --- a/core/src/main/java/art/arcane/iris/structure/object/PlacementModuleSurfaceSupport.java +++ b/core/src/main/java/art/arcane/iris/structure/object/PlacementModuleSurfaceSupport.java @@ -56,7 +56,7 @@ final class PlacementModuleSurfaceSupport implements PlacementModule { private static String hydrologyRejection(PlacementContext context, PlacementState state) { IrisObjectPlacement config = state.config; - if (!context.automatic || !config.getCarvingSupport().supportsSurface() + if (!context.automatic || config.isForcedByStructure() || !config.getCarvingSupport().supportsSurface() || config.getMode() == ObjectPlaceMode.FLOATING || config.getMode() == ObjectPlaceMode.STRUCTURE_PIECE) { return null; } diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureComponentCarveWaterTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureComponentCarveWaterTest.java index c437c2e30..e596e266e 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureComponentCarveWaterTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureComponentCarveWaterTest.java @@ -26,11 +26,16 @@ import org.junit.Rule; import org.junit.Test; import org.mockito.InOrder; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyDouble; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.intThat; +import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.calls; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -118,10 +123,36 @@ public class IrisStructureComponentCarveWaterTest { InOrder order = inOrder(writer); order.verify(writer).beginObjectPlacement(false); order.verify(writer, calls(1)).set(anyInt(), anyInt(), anyInt(), any(NativeBlockState.class)); - order.verify(writer).endObjectPlacement(anyInt()); + order.verify(writer).endObjectPlacement(); order.verify(writer).beginObjectPlacement(true); order.verify(writer, calls(1)).set(anyInt(), anyInt(), anyInt(), any(NativeBlockState.class)); - order.verify(writer).endObjectPlacement(anyInt()); + order.verify(writer).endObjectPlacement(); + } + + @Test + public void aPieceAtWorldYMinusOneKeepsItsExplicitHeight() { + KList pieces = slabAt(-1); + IrisStructure structure = new IrisStructure().setPlaceMode(ObjectPlaceMode.STRUCTURE_PIECE); + + component.placePieces(writer, new IrisStructurePlacement(), structure, pieces, new RNG(3L)); + + verify(writer, atLeastOnce()).set(anyInt(), eq(63), anyInt(), any(NativeBlockState.class)); + verify(writer, never()).set(anyInt(), intThat(y -> y != 63), anyInt(), any(NativeBlockState.class)); + } + + @Test + public void aFailureInsidePlacePiecesStillEndsTheObjectPlacement() { + IllegalStateException failure = new IllegalStateException("piece failed"); + doThrow(failure).when(writer).set(anyInt(), anyInt(), anyInt(), any(NativeBlockState.class)); + IrisStructure structure = new IrisStructure().setPlaceMode(ObjectPlaceMode.STRUCTURE_PIECE); + + IllegalStateException thrown = assertThrows(IllegalStateException.class, + () -> component.placePieces(writer, new IrisStructurePlacement(), structure, slab(), new RNG(3L))); + + assertSame(failure, thrown); + InOrder order = inOrder(writer); + order.verify(writer).beginObjectPlacement(false); + order.verify(writer).endObjectPlacement(); } private void assertRiverKept() { @@ -154,6 +185,10 @@ public class IrisStructureComponentCarveWaterTest { } private static KList slab() { + return slabAt(-4); + } + + private static KList slabAt(int y) { NativeBlockState stone = mock(NativeBlockState.class); when(stone.isSolid()).thenReturn(true); when(stone.key()).thenReturn("minecraft:stone"); @@ -164,7 +199,7 @@ public class IrisStructureComponentCarveWaterTest { object.setUnsigned(x, 0, z, stone); } } - return new KList<>(new PlacedStructurePiece(null, object, 4, -4, 1, IrisObjectRotation.of(0, 0, 0), - 0, -4, 0, 8, -4, 2)); + return new KList<>(new PlacedStructurePiece(null, object, 4, y, 1, IrisObjectRotation.of(0, 0, 0), + 0, y, 0, 8, y, 2)); } } diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureComponentWaterTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureComponentWaterTest.java index ec89519b1..2de86599a 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureComponentWaterTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureComponentWaterTest.java @@ -1,42 +1,117 @@ package art.arcane.iris.generation.mantle; +import art.arcane.iris.configuration.IrisSettings; +import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; +import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster; import art.arcane.iris.generation.hydrology.raster.WaterRole; +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.generation.runtime.IrisComplex; +import art.arcane.iris.integration.Identifier; +import art.arcane.iris.structure.nativegen.NativeStructureSuppression; import art.arcane.iris.structure.object.HydrologyWaterFixture; import art.arcane.iris.structure.object.IrisObject; import art.arcane.iris.structure.object.IrisObjectPlacement; import art.arcane.iris.structure.object.IrisObjectRotation; import art.arcane.iris.structure.object.ObjectPlaceMode; import art.arcane.iris.structure.placement.IrisStructure; +import art.arcane.iris.structure.placement.IrisStructureLocator; +import art.arcane.iris.structure.placement.IrisStructurePlacement; import art.arcane.iris.structure.placement.PlacedStructurePiece; import art.arcane.iris.testsupport.PlatformBinding; +import art.arcane.volmlib.nativelib.terrain.NativeBlockState; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.mantle.runtime.Mantle; +import art.arcane.volmlib.util.mantle.runtime.MantleChunk; import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.matter.Matter; +import art.arcane.volmlib.util.matter.MatterSlice; import art.arcane.volmlib.util.stream.ProceduralStream; +import org.junit.After; +import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import java.util.ArrayList; +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.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyDouble; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class IrisStructureComponentWaterTest { + private static final int X = 4; + private static final int Z = 4; + @Rule public final PlatformBinding platform = PlatformBinding.mockPlatform(); private final HydrologyWaterFixture world = new HydrologyWaterFixture(); + private final List writes = new ArrayList<>(); + private final Map sections = new HashMap<>(); + private IrisSettings previousSettings; + private MantleWriter writer; + private IrisStructureComponent component; + + @Before + @SuppressWarnings("unchecked") + public void setUp() { + previousSettings = IrisSettings.settings; + IrisSettings.settings = new IrisSettings(); + Engine engine = world.data().getEngine(); + IrisComplex complex = world.complex(); + HydrologyRuntime runtime = mock(HydrologyRuntime.class); + ChunkWaterRaster raster = mock(ChunkWaterRaster.class); + ProceduralStream floors = mock(ProceduralStream.class); + when(floors.get(anyDouble(), anyDouble())).thenAnswer(call -> world.floorAt(block(call.getArgument(0)), block(call.getArgument(1)))); + when(complex.getRoundedHeighteightStream()).thenReturn(floors); + when(complex.getHydrologyRuntime()).thenReturn(runtime); + when(runtime.enabled()).thenReturn(true); + when(runtime.raster(anyInt(), anyInt())).thenReturn(raster); + when(raster.role(anyInt(), anyInt())).thenAnswer(call -> complex.getWaterRoleStream().get((double) call.getArgument(0), (double) call.getArgument(1))); + when(raster.waterHead(anyInt(), anyInt())).thenAnswer(call -> world.headAt(call.getArgument(0), call.getArgument(1))); + when(raster.terrainHeight(anyInt(), anyInt())).thenAnswer(call -> world.floorAt(call.getArgument(0), call.getArgument(1))); + EngineMantle engineMantle = mock(EngineMantle.class); + when(engineMantle.getEngine()).thenReturn(engine); + when(engineMantle.getComplex()).thenReturn(complex); + when(engineMantle.getData()).thenReturn(world.data()); + HydrologyWaterFixture.Placer heights = world.placer(); + when(engineMantle.getHighest(anyInt(), anyInt(), any(), anyBoolean())).thenAnswer(call -> heights.getHighest(call.getArgument(0), call.getArgument(1), world.data(), call.getArgument(3))); + Mantle mantle = mock(Mantle.class); + MantleChunk chunk = mock(MantleChunk.class); + when(mantle.getWorldHeight()).thenReturn(256); + when(mantle.getChunk(0, 0)).thenReturn(chunk); + when(mantle.useChunk(0, 0)).thenAnswer(call -> chunk.use()); + when(chunk.use()).thenReturn(chunk); + when(chunk.getOrCreate(anyInt())).thenAnswer(call -> section(call.getArgument(0))); + writer = new MantleWriter(engineMantle, mantle, 0, 0, 0, false); + component = new IrisStructureComponent(engineMantle); + } + + @After + public void tearDown() { + writer.close(); + IrisSettings.settings = previousSettings; + } @Test public void forcedSinglePieceStructureStaysOutOfRiverWater() { world.water(WaterRole.CHANNEL, 9, 13); - HydrologyWaterFixture.Placer placer = world.placer(); - IrisObject object = HydrologyWaterFixture.raft(); - IrisObjectPlacement config = IrisStructureComponent.piecePlacement(new IrisStructure(), piece(object), ObjectPlaceMode.CENTER_HEIGHT, false); - assertTrue(config.isForcePlace()); - assertEquals(-1, object.place(0, 0, placer, config, new RNG(7L), world.data())); - assertTrue(placer.writes().isEmpty()); + int failed = placeSinglePiece(new IrisStructurePlacement()); + + assertEquals(0, failed); + assertFalse("the part of the piece above the water places", writes.isEmpty()); + assertNoWaterOverwritten(); } @Test @@ -45,40 +120,151 @@ public class IrisStructureComponentWaterTest { @SuppressWarnings("unchecked") ProceduralStream heights = mock(ProceduralStream.class); when(heights.get(anyDouble(), anyDouble())).thenAnswer(invocation -> (double) world.floorAt( - (int) Math.floor((Double) invocation.getArgument(0)), (int) Math.floor((Double) invocation.getArgument(1)))); + block(invocation.getArgument(0)), block(invocation.getArgument(1)))); when(world.complex().getHeightStream()).thenReturn(heights); - HydrologyWaterFixture.Placer placer = world.placer(); IrisObject object = HydrologyWaterFixture.raft(); - IrisObjectPlacement config = IrisStructureComponent.piecePlacement(new IrisStructure(), piece(object), ObjectPlaceMode.CENTER_HEIGHT, false); + IrisObjectPlacement config = IrisStructureComponent.piecePlacement(new IrisStructure(), piece(object), ObjectPlaceMode.CENTER_HEIGHT); config.setRotateTowardsSlope(true); - assertEquals(-1, object.place(0, 0, placer, config, new RNG(7L), world.data())); - assertTrue(placer.writes().isEmpty()); + writer.beginObjectPlacement(false); + int result = object.place(X, Z, writer, config, new RNG(7L), world.data()); + writer.endObjectPlacement(); + + assertTrue(result >= 0); + assertFalse(writes.isEmpty()); + assertNoWaterOverwritten(); + } + + @Test + public void aFewWetSupportColumnsDoNotStopAForcedSinglePiece() { + world.column(X + 1, Z, WaterRole.CHANNEL, 15, 19); + world.column(X - 1, Z, WaterRole.SHORE, 15, 19); + world.column(X, Z + 1, WaterRole.DAM, 15, 19); + + int failed = placeSinglePiece(new IrisStructurePlacement()); + + assertEquals(0, failed); + int anchorLayer = lowestWriteAt(X, Z); + assertEquals("the anchor column keeps its block", world.floorAt(X, Z), anchorLayer); + assertTrue("the anchor layer sits inside the river column's water", + anchorLayer > world.floorAt(X + 1, Z) && anchorLayer <= world.headAt(X + 1, Z)); + assertNoWaterOverwritten(); + } + + @Test + public void replaceSourceKeepsAForcedSinglePieceOverWaterWithoutFailingTheChunk() { + world.water(WaterRole.CHANNEL, 9, 13); + IrisStructurePlacement placement = new IrisStructurePlacement() + .setNativeSuppression(NativeStructureSuppression.REPLACE_SOURCE); + + int failed = placeSinglePiece(placement); + + IrisStructureComponent.requireAppliedPieces(resolved(placement), 0, 0, failed); + assertEquals(0, failed); + assertNoWaterOverwritten(); + } + + @Test + public void replaceSourceKeepsAWaterPieceOnUnevenWaterWithoutFailingTheChunk() { + world.water(WaterRole.CHANNEL, 9, 13); + world.column(X + 1, Z, WaterRole.CHANNEL, 9, 16); + IrisStructurePlacement placement = new IrisStructurePlacement() + .setNativeSuppression(NativeStructureSuppression.REPLACE_SOURCE) + .setAllowWater(true); + + int failed = placeSinglePiece(placement); + + IrisStructureComponent.requireAppliedPieces(resolved(placement), 0, 0, failed); + assertEquals(0, failed); + assertEquals("a piece that allows water fills it", world.headAt(X - 1, Z - 1), lowestWriteAt(X - 1, Z - 1)); } @Test public void forcedSinglePieceStructureThatAllowsWaterPlacesOnFlatRiverWater() { world.water(WaterRole.CHANNEL, 9, 13); - HydrologyWaterFixture.Placer placer = world.placer(); - IrisObject object = HydrologyWaterFixture.raft(); - IrisObjectPlacement config = IrisStructureComponent.piecePlacement(new IrisStructure(), piece(object), ObjectPlaceMode.CENTER_HEIGHT, true); - assertTrue(config.entersWater()); - assertTrue(object.place(0, 0, placer, config, new RNG(7L), world.data()) >= 0); - assertEquals(world.headAt(0, 0), placer.lowestWrite()); + int failed = placeSinglePiece(new IrisStructurePlacement().setAllowWater(true)); + + assertEquals(0, failed); + assertEquals(world.headAt(X, Z), lowestWriteAt(X, Z)); } @Test public void forcedSinglePieceStructureStillPlacesOnDryLand() { - HydrologyWaterFixture.Placer placer = world.placer(); - IrisObject object = HydrologyWaterFixture.raft(); - IrisObjectPlacement config = IrisStructureComponent.piecePlacement(new IrisStructure(), piece(object), ObjectPlaceMode.CENTER_HEIGHT, false); + int failed = placeSinglePiece(new IrisStructurePlacement()); - assertTrue(object.place(0, 0, placer, config, new RNG(7L), world.data()) >= 0); - assertFalse(placer.writes().isEmpty()); + assertEquals(0, failed); + assertEquals(10, writes.size()); + } + + @Test + public void objectsThatForcePlaceThemselvesStillStayOffUnevenWater() { + world.water(WaterRole.CHANNEL, 9, 13); + world.column(X + 1, Z, WaterRole.CHANNEL, 9, 16); + IrisObject object = HydrologyWaterFixture.raft(); + + int result = object.place(X, Z, writer, new IrisObjectPlacement().setForcePlace(true), new RNG(7L), world.data()); + + assertEquals(-1, result); + assertTrue(writes.isEmpty()); + } + + private int placeSinglePiece(IrisStructurePlacement placement) { + IrisObject object = HydrologyWaterFixture.raft(); + IrisStructure structure = new IrisStructure().setPlaceMode(ObjectPlaceMode.CENTER_HEIGHT); + return component.placePieces(writer, placement, structure, new KList<>(piece(object)), new RNG(7L)); + } + + private IrisStructureLocator.ResolvedPlacement resolved(IrisStructurePlacement placement) { + IrisObject object = HydrologyWaterFixture.raft(); + return new IrisStructureLocator.ResolvedPlacement(placement, "test/raft", new IrisStructure(), + new KList<>(piece(object)), new RNG(7L), X, 0, Z, false); + } + + private void assertNoWaterOverwritten() { + for (Write write : writes) { + WaterRole role = world.complex().getWaterRoleStream().get((double) write.x(), (double) write.z()); + if (role.wet()) { + assertFalse(write + " overwrites river water", + write.y() > world.floorAt(write.x(), write.z()) && write.y() <= world.headAt(write.x(), write.z())); + } + } + } + + private int lowestWriteAt(int x, int z) { + int lowest = Integer.MAX_VALUE; + for (Write write : writes) { + if (write.x() == x && write.z() == z) { + lowest = Math.min(lowest, write.y()); + } + } + return lowest; + } + + @SuppressWarnings("unchecked") + private Matter section(int index) { + return sections.computeIfAbsent(index, ignored -> { + Matter matter = mock(Matter.class); + MatterSlice blocks = mock(MatterSlice.class); + doAnswer(call -> { + writes.add(new Write(call.getArgument(0), (index << 4) | call.getArgument(1), call.getArgument(2))); + return null; + }).when(blocks).set(anyInt(), anyInt(), anyInt(), any()); + when(matter.getClass(any())).thenAnswer(call -> call.getArgument(0).getClass()); + doReturn(blocks).when(matter).slice(NativeBlockState.class); + doReturn(mock(MatterSlice.class)).when(matter).getSlice(Identifier.class); + return matter; + }); } private static PlacedStructurePiece piece(IrisObject object) { - return new PlacedStructurePiece(null, object, 0, 0, 0, IrisObjectRotation.of(0, 0, 0), -1, 0, -1, 1, 2, 1); + return new PlacedStructurePiece(null, object, X, 0, Z, IrisObjectRotation.of(0, 0, 0), X - 1, 0, Z - 1, X + 1, 2, Z + 1); + } + + private static int block(Object coordinate) { + return (int) Math.floor(((Number) coordinate).doubleValue()); + } + + private record Write(int x, int y, int z) { } } diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/MantleObjectComponentWaterPlacementTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/MantleObjectComponentWaterPlacementTest.java new file mode 100644 index 000000000..74223b007 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/generation/mantle/MantleObjectComponentWaterPlacementTest.java @@ -0,0 +1,298 @@ +package art.arcane.iris.generation.mantle; + +import art.arcane.iris.configuration.IrisSettings; +import art.arcane.iris.generation.biome.IrisBiome; +import art.arcane.iris.generation.cave.CarvingMode; +import art.arcane.iris.generation.context.ChunkContext; +import art.arcane.iris.generation.decoration.IrisProceduralObjects; +import art.arcane.iris.generation.decoration.IrisProceduralPlacement; +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.generation.runtime.IrisComplex; +import art.arcane.iris.generation.runtime.SeedManager; +import art.arcane.iris.generation.runtime.UpperDimensionContext; +import art.arcane.iris.generation.terrain.IrisDimension; +import art.arcane.iris.generation.terrain.IrisRegion; +import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.structure.object.IObjectPlacer; +import art.arcane.iris.structure.object.IrisObject; +import art.arcane.iris.structure.object.IrisObjectPlacement; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.matter.MatterCavern; +import art.arcane.volmlib.util.stream.ProceduralStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.stubbing.Answer; + +import java.util.Arrays; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyDouble; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class MantleObjectComponentWaterPlacementTest { + private static final Answer PLACES = call -> 64; + private static final Answer REJECTS = call -> -1; + private static final Answer THROWS = call -> { + throw new IllegalArgumentException("malformed object"); + }; + + private IrisSettings previousSettings; + + @Before + public void bindSettings() { + previousSettings = IrisSettings.settings; + IrisSettings.settings = new IrisSettings(); + } + + @After + public void restoreSettings() { + IrisSettings.settings = previousSettings; + } + + @Test + public void acceptedSurfacePlacementIsRecordedThenEnded() { + Fixture fixture = new Fixture(PLACES); + fixture.biome.setObjects(new KList<>(fixture.surfacePlacement())); + + fixture.generate(); + + fixture.assertRecordedThenEnded(); + } + + @Test + public void rejectedSurfacePlacementEndsWithoutBeingRecorded() { + Fixture fixture = new Fixture(REJECTS); + fixture.biome.setObjects(new KList<>(fixture.surfacePlacement())); + + fixture.generate(); + + fixture.assertEndedUnrecorded(); + } + + @Test + public void thrownSurfacePlacementEndsWithoutBeingRecorded() { + Fixture fixture = new Fixture(THROWS); + fixture.biome.setObjects(new KList<>(fixture.surfacePlacement())); + + fixture.generate(); + + fixture.assertEndedUnrecorded(); + } + + @Test + public void rejectedCavePlacementEndsWithoutBeingRecorded() { + Fixture fixture = new Fixture(REJECTS); + fixture.biome.setObjects(new KList<>(fixture.cavePlacement())); + + fixture.generate(); + + fixture.assertEndedUnrecorded(); + } + + @Test + public void thrownCavePlacementEndsWithoutBeingRecorded() { + Fixture fixture = new Fixture(THROWS); + fixture.biome.setObjects(new KList<>(fixture.cavePlacement())); + + fixture.generate(); + + fixture.assertEndedUnrecorded(); + } + + @Test + public void proceduralPlacementOutsideTheTransitionFootprintEndsWithoutBeingRecorded() { + Fixture fixture = new Fixture(PLACES); + fixture.biome.setProceduralObjects(fixture.proceduralObjects()); + when(fixture.complex.allowsNewGenerationFootprint(anyInt(), anyInt(), anyInt(), anyInt())).thenReturn(false); + + fixture.generate(); + + fixture.assertEndedUnrecorded(); + } + + @Test + public void rejectedProceduralPlacementEndsWithoutBeingRecorded() { + Fixture fixture = new Fixture(REJECTS); + fixture.biome.setProceduralObjects(fixture.proceduralObjects()); + + fixture.generate(); + + fixture.assertEndedUnrecorded(); + } + + @Test + public void thrownProceduralPlacementEndsWithoutBeingRecorded() { + Fixture fixture = new Fixture(THROWS); + fixture.biome.setProceduralObjects(fixture.proceduralObjects()); + + fixture.generate(); + + fixture.assertEndedUnrecorded(); + } + + @Test + public void rejectedUpperPlacementEndsWithoutBeingRecorded() { + Fixture fixture = new Fixture(REJECTS); + fixture.upperObjects(); + + fixture.generate(); + + fixture.assertEndedUnrecorded(); + } + + @Test + public void thrownUpperPlacementEndsWithoutBeingRecorded() { + Fixture fixture = new Fixture(THROWS); + fixture.upperObjects(); + + fixture.generate(); + + fixture.assertEndedUnrecorded(); + } + + private static final class Fixture { + private final IrisBiome biome = new IrisBiome(); + private final IrisComplex complex = mock(IrisComplex.class); + private final IrisObject object = mock(IrisObject.class); + private final Engine engine = mock(Engine.class); + private final IrisDimension dimension = mock(IrisDimension.class); + private final ObjectPassPlacer placer = mock(ObjectPassPlacer.class); + private final ChunkContext context = mock(ChunkContext.class); + private final MantleObjectComponent component; + + @SuppressWarnings("unchecked") + private Fixture(Answer placement) { + when(dimension.getAllRegions(any())).thenReturn(new KList<>()); + when(dimension.getReachableBiomes(any())).thenReturn(new KList<>()); + when(engine.getDimension()).thenReturn(dimension); + when(engine.getSeedManager()).thenReturn(mock(SeedManager.class)); + when(engine.getHeight()).thenReturn(256); + when(engine.getComplex()).thenReturn(complex); + EngineMantle engineMantle = mock(EngineMantle.class); + when(engineMantle.getEngine()).thenReturn(engine); + when(engineMantle.getData()).thenReturn(mock(IrisData.class)); + when(engineMantle.getComplex()).thenReturn(complex); + when(engineMantle.trueHeight(anyInt(), anyInt())).thenReturn(120); + + when(object.getLoadKey()).thenReturn("trees/water"); + when(object.getW()).thenReturn(1); + when(object.getH()).thenReturn(1); + when(object.getD()).thenReturn(1); + doAnswer(placement).when(object).place(anyInt(), anyInt(), any(IObjectPlacer.class), any(IrisObjectPlacement.class), + any(RNG.class), any(), any(), any()); + doAnswer(placement).when(object).place(anyInt(), anyInt(), anyInt(), any(IObjectPlacer.class), any(IrisObjectPlacement.class), + any(RNG.class), any(), any(), any()); + + biome.setLoadKey("water-biome"); + IrisRegion region = new IrisRegion(); + region.setLoadKey("water-region"); + ProceduralStream regions = mock(ProceduralStream.class); + when(regions.get(anyDouble(), anyDouble())).thenReturn(region); + ProceduralStream biomes = mock(ProceduralStream.class); + when(biomes.get(anyDouble(), anyDouble())).thenReturn(biome); + ProceduralStream heights = mock(ProceduralStream.class); + when(heights.get(anyDouble(), anyDouble())).thenReturn(64); + when(complex.allowsNewGenerationChunk(anyInt(), anyInt())).thenReturn(true); + when(complex.allowsNewGenerationFootprint(anyInt(), anyInt(), anyInt(), anyInt())).thenReturn(true); + when(complex.getRegionStream()).thenReturn(regions); + when(complex.getTrueBiomeStream()).thenReturn(biomes); + when(complex.getRoundedHeighteightStream()).thenReturn(heights); + when(context.getComplex()).thenReturn(complex); + when(placer.getEngine()).thenReturn(engine); + when(placer.getCarvedColumn(anyInt(), anyInt(), anyInt())).thenAnswer(call -> { + byte[] column = new byte[call.getArgument(2)]; + Arrays.fill(column, 20, 28, (byte) 1); + return column; + }); + when(placer.getDataIfPresent(anyInt(), anyInt(), anyInt(), eq(MatterCavern.class))) + .thenReturn(new MatterCavern(true, "", (byte) 0)); + component = new MantleObjectComponent(engineMantle); + } + + private IrisObjectPlacement surfacePlacement() { + IrisObjectPlacement placement = placement(CarvingMode.SURFACE_ONLY); + when(placement.getDensity(any(RNG.class), anyDouble(), anyDouble(), any())).thenReturn(1); + when(placement.getObject(any(), any(RNG.class))).thenReturn(object); + return placement; + } + + private IrisObjectPlacement cavePlacement() { + IrisObjectPlacement placement = placement(CarvingMode.CARVING_ONLY); + when(placement.getDensity(any(RNG.class), anyDouble(), anyDouble(), any())).thenReturn(1); + when(placement.getObject(any(), any(RNG.class))).thenReturn(object); + return placement; + } + + private IrisProceduralObjects proceduralObjects() { + IrisObjectPlacement placement = placement(CarvingMode.SURFACE_ONLY); + IrisProceduralPlacement procedural = mock(IrisProceduralPlacement.class); + when(procedural.getChance()).thenReturn(2D); + when(procedural.getName()).thenReturn("water-procedural"); + when(procedural.getDensity()).thenReturn(1); + when(procedural.asPlacement()).thenReturn(placement); + when(procedural.getVariantObject(any(), any(), any())).thenReturn(object); + IrisProceduralObjects objects = mock(IrisProceduralObjects.class); + when(objects.isEmpty()).thenReturn(false); + when(objects.getAllPlacements()).thenReturn(new KList<>(procedural)); + return objects; + } + + private void upperObjects() { + IrisObjectPlacement forced = placement(CarvingMode.ANYWHERE); + IrisObjectPlacement source = placement(CarvingMode.SURFACE_ONLY); + when(source.getDensity(any(RNG.class), anyDouble(), anyDouble(), any())).thenReturn(1); + when(source.getObject(any(UpperDimensionContext.class), any(RNG.class))).thenReturn(object); + when(source.toPlacement(anyString())).thenReturn(forced); + IrisBiome upperBiome = new IrisBiome(); + upperBiome.setLoadKey("upper-biome"); + upperBiome.setObjects(new KList<>(source)); + UpperDimensionContext upper = mock(UpperDimensionContext.class); + when(upper.getUpperBiome(anyInt(), anyInt())).thenReturn(upperBiome); + when(upper.getDimension()).thenReturn(dimension); + when(upper.getEffectiveSurfaceY(anyInt(), anyInt())).thenReturn(64); + when(engine.getUpperContext()).thenReturn(upper); + when(dimension.isUpperDimensionObjects()).thenReturn(true); + } + + private IrisObjectPlacement placement(CarvingMode carving) { + IrisObjectPlacement placement = mock(IrisObjectPlacement.class); + when(placement.getChance()).thenReturn(2D); + when(placement.getCarvingSupport()).thenReturn(carving); + when(placement.getPlace()).thenReturn(new KList<>("trees/water")); + when(placement.getAllowedCollisions()).thenReturn(new KList<>()); + when(placement.getForbiddenCollisions()).thenReturn(new KList<>()); + when(placement.scaleObject(any(RNG.class), any(), any())).thenReturn(object); + when(placement.entersWater()).thenReturn(true); + return placement; + } + + private void generate() { + component.generateOrigin(placer, 0, 0, context); + } + + private void assertEndedUnrecorded() { + InOrder order = inOrder(placer); + order.verify(placer).beginObjectPlacement(true); + order.verify(placer).endObjectPlacement(); + verify(placer, never()).recordObjectPlacement(anyInt()); + } + + private void assertRecordedThenEnded() { + InOrder order = inOrder(placer); + order.verify(placer).beginObjectPlacement(true); + order.verify(placer).recordObjectPlacement(anyInt()); + order.verify(placer).endObjectPlacement(); + } + } +} diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/MantleWriterObjectWaterTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/MantleWriterObjectWaterTest.java index 8b401918c..17744f9c7 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/MantleWriterObjectWaterTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/MantleWriterObjectWaterTest.java @@ -100,7 +100,7 @@ public class MantleWriterObjectWaterTest { writer.set(3, 5, 3, stone); writer.set(3, 10, 3, stone); writer.set(8, 7, 8, stone); - writer.endObjectPlacement(land); + writer.endObjectPlacement(); verify(blocks, never()).set(3, 7, 3, stone); verify(blocks, never()).set(3, 8, 3, air); @@ -112,7 +112,7 @@ public class MantleWriterObjectWaterTest { int water = writer.beginObjectPlacement(true); writer.set(3, 6, 3, stone); writer.set(3, 9, 3, air); - writer.endObjectPlacement(water); + writer.endObjectPlacement(); verify(blocks).set(3, 6, 3, stone); verify(blocks, never()).set(3, 9, 3, air); @@ -121,7 +121,7 @@ public class MantleWriterObjectWaterTest { @Test public void writesOutsideAnObjectPlacementAreNotVetoed() { int land = writer.beginObjectPlacement(false); - writer.endObjectPlacement(land); + writer.endObjectPlacement(); writer.set(3, 7, 3, stone); writer.set(3, 8, 3, air); diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/ObjectContinuationTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/ObjectContinuationTest.java index 37e143796..bf14a310a 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/ObjectContinuationTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/ObjectContinuationTest.java @@ -60,15 +60,18 @@ public class ObjectContinuationTest { ObjectDestinationTransaction source = new ObjectDestinationTransaction(fixture.writer, 0, 0); int checkpoint = source.beginObjectPlacement(false); source.setData(1, 5, 1, "inside"); - source.endObjectPlacement(checkpoint); + source.recordObjectPlacement(checkpoint); + source.endObjectPlacement(); checkpoint = source.beginObjectPlacement(false); source.setData(15, 5, 1, "crossing"); source.setData(16, 5, 1, "crossing"); - source.endObjectPlacement(checkpoint); + source.recordObjectPlacement(checkpoint); + source.endObjectPlacement(); checkpoint = source.beginObjectPlacement(false); source.setData(32, 5, 1, "unrelated"); source.setData(48, 5, 1, "unrelated"); - source.endObjectPlacement(checkpoint); + source.recordObjectPlacement(checkpoint); + source.endObjectPlacement(); source.setData(17, 5, 1, "rejected"); ObjectSourcePlan plan = source.sourcePlanSince(0); diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/ObjectDestinationTransactionTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/ObjectDestinationTransactionTest.java index 4cec84ab6..b617fe309 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/ObjectDestinationTransactionTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/ObjectDestinationTransactionTest.java @@ -294,7 +294,8 @@ public class ObjectDestinationTransactionTest { transaction.set(4, 9, 3, leaves); assertEquals("an underwater object keeps its solid blocks in the water", underwater + 2, transaction.mutationCheckpoint()); - transaction.endObjectPlacement(underwater); + transaction.recordObjectPlacement(underwater); + transaction.endObjectPlacement(); ObjectDestinationTransaction destination = new ObjectDestinationTransaction(writer, 0, 0); destination.apply(transaction.sourcePlanSince(start)); assertEquals("the destination replay keeps the underwater blocks", 6, destination.mutationCheckpoint()); @@ -325,7 +326,7 @@ public class ObjectDestinationTransactionTest { IrisObjectPlacement raft = new IrisObjectPlacement().setOnwater(true); IrisObjectPlacement forced = new IrisObjectPlacement().setForcePlace(true); IrisObjectPlacement piece = IrisStructureComponent.piecePlacement(new IrisStructure(), new PlacedStructurePiece(null, - new IrisObject(1, 1, 1), 4, 14, 3, IrisObjectRotation.of(0, 0, 0), 4, 14, 3, 4, 14, 3), ObjectPlaceMode.CENTER_HEIGHT, false); + new IrisObject(1, 1, 1), 4, 14, 3, IrisObjectRotation.of(0, 0, 0), 4, 14, 3, 4, 14, 3), ObjectPlaceMode.CENTER_HEIGHT); assertTrue(piece.isForcePlace()); ObjectDestinationTransaction transaction = new ObjectDestinationTransaction(writer, 0, 0); @@ -368,13 +369,47 @@ public class ObjectDestinationTransactionTest { int raft = transaction.beginObjectPlacement(true); transaction.set(3, 12, 3, pier); - transaction.endObjectPlacement(raft); + transaction.recordObjectPlacement(raft); + transaction.endObjectPlacement(); int afterRaft = transaction.mutationCheckpoint(); transaction.set(3, 13, 3, pier); assertEquals("a write after the water placement ends follows land rules", afterRaft, transaction.mutationCheckpoint()); } + @Test + public void aRejectedWaterPlacementReturnsToLandRules() { + MantleWriter writer = writer(); + waterAtColumnThree(writer); + NativeBlockState pier = mock(NativeBlockState.class); + when(pier.isSolid()).thenReturn(true); + ObjectDestinationTransaction transaction = new ObjectDestinationTransaction(writer, 0, 0); + + transaction.beginObjectPlacement(true); + transaction.set(3, 12, 3, pier); + transaction.endObjectPlacement(); + int afterRaft = transaction.mutationCheckpoint(); + transaction.set(3, 13, 3, pier); + + assertEquals("a write after a rejected water placement follows land rules", afterRaft, transaction.mutationCheckpoint()); + } + + private static void waterAtColumnThree(MantleWriter writer) { + IrisComplex complex = mock(IrisComplex.class); + HydrologyRuntime runtime = mock(HydrologyRuntime.class); + ChunkWaterRaster raster = mock(ChunkWaterRaster.class); + when(writer.getEngine().getComplex()).thenReturn(complex); + when(complex.getHydrologyRuntime()).thenReturn(runtime); + when(runtime.enabled()).thenReturn(true); + when(runtime.raster(anyInt(), anyInt())).thenReturn(raster); + when(raster.role(anyInt(), anyInt())).thenReturn(WaterRole.NONE); + when(raster.waterHead(anyInt(), anyInt())).thenReturn(Integer.MIN_VALUE); + when(raster.role(3, 3)).thenReturn(WaterRole.CHANNEL); + when(raster.waterHead(3, 3)).thenReturn(14); + when(raster.terrainHeight(3, 3)).thenReturn(10); + followRasterStreams(complex, raster); + } + @Test public void sourceCaptureCannotReplaceAuthoredRoomSolids() { MantleWriter writer = writer(); diff --git a/core/src/test/java/art/arcane/iris/pack/PackValidatorStructureGraphTest.java b/core/src/test/java/art/arcane/iris/pack/PackValidatorStructureGraphTest.java index 34601f80d..fb57cc550 100644 --- a/core/src/test/java/art/arcane/iris/pack/PackValidatorStructureGraphTest.java +++ b/core/src/test/java/art/arcane/iris/pack/PackValidatorStructureGraphTest.java @@ -251,6 +251,38 @@ public class PackValidatorStructureGraphTest { assertTrue(errors.toString(), errors.stream().anyMatch(message -> message.contains("duplicates an anonymous placement grid"))); } + @Test + public void allowWaterMustBeABoolean() throws Exception { + File pack = temporaryFolder.newFolder("invalid-allow-water"); + write(pack, "dimensions/main.json", "{\"structures\":[{" + + "\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"}]," + + "\"allowWater\":\"yes\"}]}"); + + List errors = PackObjectSurfaceValidator.validateStructureGraph(pack); + + assertTrue(errors.toString(), errors.stream().anyMatch(message -> message.contains("allowWater must be a boolean"))); + } + + @Test + public void allowWaterSeparatesAnonymousGridsOnlyWhenTrue() throws Exception { + File separate = temporaryFolder.newFolder("allow-water-grid"); + write(separate, "dimensions/main.json", "{\"structures\":[{" + + "\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"}]}]}"); + write(separate, "regions/river.json", "{\"structures\":[{\"allowWater\":true," + + "\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"}]}]}"); + File duplicate = temporaryFolder.newFolder("allow-water-false-grid"); + write(duplicate, "dimensions/main.json", "{\"structures\":[{" + + "\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"}]}]}"); + write(duplicate, "regions/river.json", "{\"structures\":[{\"allowWater\":false," + + "\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"}]}]}"); + + List separateErrors = PackObjectSurfaceValidator.validateStructureGraph(separate); + List duplicateErrors = PackObjectSurfaceValidator.validateStructureGraph(duplicate); + + assertTrue(separateErrors.toString(), separateErrors.stream().noneMatch(message -> message.contains("duplicates an anonymous placement grid"))); + assertTrue(duplicateErrors.toString(), duplicateErrors.stream().anyMatch(message -> message.contains("duplicates an anonymous placement grid"))); + } + @Test public void rejectsDuplicateEditableStructureKeysIgnoringCase() throws Exception { File pack = temporaryFolder.newFolder("duplicate-editable-key"); diff --git a/core/src/test/java/art/arcane/iris/structure/nativegen/NativeStructurePlacementPlannerTest.java b/core/src/test/java/art/arcane/iris/structure/nativegen/NativeStructurePlacementPlannerTest.java index f7e0164f7..f60bdbb24 100644 --- a/core/src/test/java/art/arcane/iris/structure/nativegen/NativeStructurePlacementPlannerTest.java +++ b/core/src/test/java/art/arcane/iris/structure/nativegen/NativeStructurePlacementPlannerTest.java @@ -190,7 +190,7 @@ public class NativeStructurePlacementPlannerTest { } @Test - public void riverInTheStartChunkLeavesTheDecisionToThePieces() { + public void waterAroundAStartColumnAboveItsHeadLeavesTheDecisionToThePieces() { Engine engine = engine(77L, -64, 384, 150); Map roles = new HashMap<>(); waterComplex(engine, roles, false); From 8d235e77574f4ba84d7d96b65763406dbe3d6762 Mon Sep 17 00:00:00 2001 From: Brian Fopiano Date: Mon, 2 Nov 2026 17:39:53 -0500 Subject: [PATCH 2/8] Warn on unsealed river fluids - Warn when a non-water river fluid without a seam can meet the sea or another river fluid - Resolve river fluids from tiers and surface biome, region and dimension policies - Compare fluids by palette blocks and skip fluids already lined by a seam - Give the full hydrology test fixture a lava seam - Cover the warning and its silent cases in validator tests --- .../iris/pack/PackHydrologyValidator.java | 92 ++++++++++++ .../iris/pack/PackHydrologyValidatorTest.java | 132 +++++++++++++++++- 2 files changed, 223 insertions(+), 1 deletion(-) diff --git a/core/src/main/java/art/arcane/iris/pack/PackHydrologyValidator.java b/core/src/main/java/art/arcane/iris/pack/PackHydrologyValidator.java index e0a93d75b..2aa7cf5bd 100644 --- a/core/src/main/java/art/arcane/iris/pack/PackHydrologyValidator.java +++ b/core/src/main/java/art/arcane/iris/pack/PackHydrologyValidator.java @@ -1,14 +1,17 @@ package art.arcane.iris.pack; import art.arcane.iris.generation.biome.IrisBiome; +import art.arcane.iris.generation.block.IrisBlockData; import art.arcane.iris.generation.decoration.HydrologyVegetation; import art.arcane.iris.generation.decoration.IrisDecorator; +import art.arcane.iris.generation.hydrology.config.IrisFluidProfile; import art.arcane.iris.generation.hydrology.config.IrisHydrology; import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy; import art.arcane.iris.generation.hydrology.config.IrisHydrologyTier; import art.arcane.iris.generation.hydrology.config.IrisHydrologyWetness; import art.arcane.iris.generation.hydrology.plan.HydrologySettings; import art.arcane.iris.generation.terrain.IrisDimension; +import art.arcane.iris.generation.terrain.IrisMaterialPalette; import art.arcane.iris.generation.terrain.IrisRegion; import art.arcane.iris.generation.terrain.ShoreBiomeLineages; import art.arcane.iris.pack.loading.IrisData; @@ -22,12 +25,15 @@ import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; +import java.util.HashMap; import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TreeMap; +import java.util.TreeSet; final class PackHydrologyValidator { private static final String CONFIG = "hydrology"; @@ -47,6 +53,7 @@ final class PackHydrologyValidator { ); private static final List FLUID_REFERENCES = List.of("ponds.fluid", "underground.cavePools.fluid"); private static final IrisHydrologyTier DEFAULT_TIER = new IrisHydrologyTier(); + private static final Set WATER_BLOCKS = Set.of("minecraft:water"); private static final String MANTLE_WATER = "the falling water at waterfalls and cascades, sea inlets and cave pools"; private PackHydrologyValidator() { @@ -105,6 +112,7 @@ final class PackHydrologyValidator { warnShoreBiomesWithoutWidth(dimensionKey, loaded, loadedDimension, findings.warnings()); if (errors.size() == reported && validateCompile(path, loadedDimension, errors)) { validateDecoratorBlocks(path, loaded, loadedDimension.getHydrology(), errors); + warnFluidsWithoutSeam(dimensionKey, loaded, loadedDimension, findings.warnings()); } return loaded; } @@ -354,6 +362,90 @@ final class PackHydrologyValidator { } } + private static void warnFluidsWithoutSeam(String dimensionKey, IrisData data, IrisDimension dimension, List warnings) { + String path = "Dimension '" + dimensionKey + "'." + CONFIG; + Map profiles = new HashMap<>(); + for (IrisFluidProfile profile : dimension.getHydrology().getFluids()) { + profiles.put(profile.getName(), profile); + } + Map> rivers = riverFluidSources(dimensionKey, data, dimension); + rivers.keySet().retainAll(profiles.keySet()); + for (Map.Entry> river : rivers.entrySet()) { + IrisFluidProfile profile = profiles.get(river.getKey()); + Set blocks = blockIds(profile.getPalette()); + if (hasSeam(profile) || blocks.equals(WATER_BLOCKS)) { + continue; + } + List met = new ArrayList<>(); + if (dimension.getFluidHeight() > 0 && !blocks.equals(blockIds(dimension.getFluidPalette()))) { + met.add("the sea"); + } + for (String other : rivers.keySet()) { + IrisFluidProfile otherProfile = profiles.get(other); + if (!hasSeam(otherProfile) && !blocks.equals(blockIds(otherProfile.getPalette()))) { + met.add("fluid '" + other + "'"); + } + } + if (!met.isEmpty()) { + warnings.add(path + ".fluids profile '" + river.getKey() + "' sets no seam, so where its rivers meet " + String.join(" or ", met) + + " the fluids lie side by side. Set seam on the profile to line that edge. Its rivers come from " + + String.join(", ", river.getValue()) + "."); + } + } + } + + private static Map> riverFluidSources(String dimensionKey, IrisData data, IrisDimension dimension) { + Map> sources = new TreeMap<>(); + List regions = new ArrayList<>(dimension.getAllRegions(() -> data)); + ShoreBiomeLineages.visit(dimension, regions, () -> data, (lineage, region) -> { + String fluid = IrisHydrologyPolicy.inherited(lineage, region, dimension, IrisHydrologyPolicy::getFluid); + if (fluid == null) { + addTierSources(dimensionKey, dimension, sources); + } else { + sources.computeIfAbsent(fluid, name -> new TreeSet<>()).add(policyFluidOwner(dimensionKey, lineage, region)); + } + }); + if (sources.isEmpty()) { + addTierSources(dimensionKey, dimension, sources); + } + return sources; + } + + private static void addTierSources(String dimensionKey, IrisDimension dimension, Map> sources) { + List tiers = dimension.getHydrology().getTiers(); + for (int index = 0; index < tiers.size(); index++) { + sources.computeIfAbsent(tiers.get(index).getFluid(), name -> new TreeSet<>()) + .add("Dimension '" + dimensionKey + "'." + CONFIG + ".tiers[" + index + "].fluid"); + } + } + + private static String policyFluidOwner(String dimensionKey, List lineage, IrisRegion region) { + for (IrisBiome biome : lineage) { + if (biome.getHydrologyPolicy() != null && biome.getHydrologyPolicy().getFluid() != null) { + return "Biome '" + biome.getLoadKey() + "'." + POLICY + ".fluid"; + } + } + if (region != null && region.getHydrologyPolicy() != null && region.getHydrologyPolicy().getFluid() != null) { + return "Region '" + region.getLoadKey() + "'." + POLICY + ".fluid"; + } + return "Dimension '" + dimensionKey + "'." + POLICY + ".fluid"; + } + + private static boolean hasSeam(IrisFluidProfile profile) { + return profile.getSeam() != null && !profile.getSeam().isBlank(); + } + + private static Set blockIds(IrisMaterialPalette palette) { + Set blocks = new TreeSet<>(); + for (IrisBlockData block : palette.getPalette()) { + String id = block.getBlock().toLowerCase(Locale.ROOT); + int state = id.indexOf('['); + String name = state < 0 ? id : id.substring(0, state); + blocks.add(name.contains(":") ? name : "minecraft:" + name); + } + return blocks; + } + private static void requireMultiplier(String field, Double value, List errors) { if (value != null && !IrisHydrologyPolicy.validMultiplier(value)) { errors.add(field + " must be a finite value from 0 to " + (int) IrisHydrologyPolicy.MAX_MULTIPLIER + ", got " + value + "."); diff --git a/core/src/test/java/art/arcane/iris/pack/PackHydrologyValidatorTest.java b/core/src/test/java/art/arcane/iris/pack/PackHydrologyValidatorTest.java index 7db7a4e5b..fae4a255a 100644 --- a/core/src/test/java/art/arcane/iris/pack/PackHydrologyValidatorTest.java +++ b/core/src/test/java/art/arcane/iris/pack/PackHydrologyValidatorTest.java @@ -22,6 +22,10 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public class PackHydrologyValidatorTest { + private static final String WATER = "{\"name\": \"water\", \"palette\": {\"palette\": [{\"block\": \"minecraft:water\"}]}}"; + private static final String LAVA = "{\"name\": \"lava\", \"palette\": {\"palette\": [{\"block\": \"minecraft:lava\"}]}}"; + private static final String CRUST = "{\"name\": \"crust\", \"palette\": {\"palette\": [{\"block\": \"minecraft:obsidian\"}]}}"; + private static final String SEA_IS_LAVA = "\"fluidPalette\": {\"palette\": [{\"block\": \"minecraft:lava\"}]},"; private static final String WATER_ONLY = "{\"enabled\": true, \"fluids\": [{\"name\": \"water\"}]}"; @Rule @@ -46,7 +50,8 @@ public class PackHydrologyValidatorTest { }, "fluids": [ {"name": "water", "palette": {"palette": [{"block": "minecraft:water"}]}}, - {"name": "lava", "palette": {"palette": [{"block": "minecraft:lava"}]}} + {"name": "lava", "palette": {"palette": [{"block": "minecraft:lava"}]}, "seam": "crust"}, + {"name": "crust", "palette": {"palette": [{"block": "minecraft:obsidian"}]}} ] } """, "\"hydrologyPolicy\": {\"fluid\": \"lava\"},"))); @@ -661,6 +666,131 @@ public class PackHydrologyValidatorTest { assertTrue(widened.warnings().toString(), widened.warnings().isEmpty()); } + @Test + public void warnsWhenALavaRiverWithoutASeamCanMeetTheSea() throws Exception { + File pack = pack(dimension(hydrology("lava", "lava", LAVA), "")); + + PackHydrologyValidator.Validation validation = validate(pack); + + assertTrue(validation.errors().toString(), validation.errors().isEmpty()); + assertEquals(List.of("Dimension 'main'.hydrology.fluids profile 'lava' sets no seam, so where its rivers meet the sea" + + " the fluids lie side by side. Set seam on the profile to line that edge. Its rivers come from" + + " Dimension 'main'.hydrology.tiers[0].fluid, Dimension 'main'.hydrology.tiers[1].fluid."), validation.warnings()); + } + + @Test + public void warnsAgainstADifferentRiverFluidAndNamesTheBiomeItComesFrom() throws Exception { + File pack = pack(dimension(hydrology("water", "water", WATER + ", " + LAVA), SEA_IS_LAVA)); + write(pack, "biomes/biome.json", """ + {"name": "Biome", "hydrologyPolicy": {"fluid": "lava"}} + """); + write(pack, "regions/region.json", """ + {"landBiomes": ["biome", "plain"]} + """); + write(pack, "biomes/plain.json", "{\"name\": \"Plain\"}"); + + PackHydrologyValidator.Validation validation = validate(pack); + + assertTrue(validation.errors().toString(), validation.errors().isEmpty()); + assertEquals(List.of("Dimension 'main'.hydrology.fluids profile 'lava' sets no seam, so where its rivers meet fluid 'water'" + + " the fluids lie side by side. Set seam on the profile to line that edge. Its rivers come from" + + " Biome 'biome'.hydrologyPolicy.fluid."), validation.warnings()); + } + + @Test + public void aSeamOnTheOtherRiverFluidLinesTheEdgeBetweenThem() throws Exception { + String fluids = WATER + ", " + LAVA + ", " + """ + {"name": "tar", "palette": {"palette": [{"block": "mod:tar"}]}, "seam": "crust"}, %s + """.formatted(CRUST); + File pack = pack(dimension(hydrology("lava", "tar", fluids), SEA_IS_LAVA)); + + PackHydrologyValidator.Validation validation = validate(pack); + + assertTrue(validation.errors().toString(), validation.errors().isEmpty()); + assertTrue(validation.warnings().toString(), validation.warnings().isEmpty()); + } + + @Test + public void silentWhenTheFluidHasASeam() throws Exception { + String fluids = """ + {"name": "lava", "palette": {"palette": [{"block": "minecraft:lava"}]}, "seam": "crust"}, %s, %s + """.formatted(CRUST, WATER); + PackHydrologyValidator.Validation validation = validate(pack(dimension(hydrology("lava", "water", fluids), ""))); + + assertTrue(validation.errors().toString(), validation.errors().isEmpty()); + assertTrue(validation.warnings().toString(), validation.warnings().isEmpty()); + } + + @Test + public void silentForWaterRiversWhateverTheProfileIsCalled() throws Exception { + String fluids = """ + {"name": "marsh", "palette": {"palette": [{"block": "water"}]}}, %s + """.formatted(WATER); + File pack = pack(dimension(hydrology("marsh", "water", fluids), SEA_IS_LAVA)); + + PackHydrologyValidator.Validation validation = validate(pack); + + assertTrue(validation.errors().toString(), validation.errors().isEmpty()); + assertTrue(validation.warnings().toString(), validation.warnings().isEmpty()); + } + + @Test + public void silentWhenTheFluidsAreTheSame() throws Exception { + String fluids = LAVA + ", " + """ + {"name": "magma", "palette": {"palette": [{"block": "lava"}]}} + """; + PackHydrologyValidator.Validation validation = validate(pack(dimension(hydrology("lava", "magma", fluids), SEA_IS_LAVA))); + + assertTrue(validation.errors().toString(), validation.errors().isEmpty()); + assertTrue(validation.warnings().toString(), validation.warnings().isEmpty()); + } + + @Test + public void silentWhenAPolicyFluidReplacesEveryTierFluid() throws Exception { + String config = hydrology("water", "water", WATER + ", " + LAVA); + PackHydrologyValidator.Validation validation = validate(pack(dimension(config, + SEA_IS_LAVA + " \"hydrologyPolicy\": {\"fluid\": \"lava\"},"))); + + assertTrue(validation.errors().toString(), validation.errors().isEmpty()); + assertTrue(validation.warnings().toString(), validation.warnings().isEmpty()); + } + + @Test + public void aCaveBiomePolicyFluidIsNotARiverFluid() throws Exception { + File pack = pack(dimension(hydrology("water", "water", WATER + ", " + LAVA), "")); + write(pack, "regions/region.json", """ + {"landBiomes": ["biome"], "caveBiomes": ["hollow"]} + """); + write(pack, "biomes/hollow.json", """ + {"name": "Hollow", "hydrologyPolicy": {"fluid": "lava"}} + """); + + PackHydrologyValidator.Validation validation = validate(pack); + + assertTrue(validation.errors().toString(), validation.errors().isEmpty()); + assertTrue(validation.warnings().toString(), validation.warnings().isEmpty()); + } + + @Test + public void silentAboutTheSeaWhenTheDimensionHasNoFluidHeight() throws Exception { + PackHydrologyValidator.Validation validation = validate(pack(dimension(hydrology("lava", "lava", LAVA), "\"fluidHeight\": -64,"))); + + assertTrue(validation.errors().toString(), validation.errors().isEmpty()); + assertTrue(validation.warnings().toString(), validation.warnings().isEmpty()); + } + + private static String hydrology(String streamFluid, String riverFluid, String fluids) { + return """ + {"enabled": true, + "tiers": [ + {"name": "stream", "minCatchment": 1500, "halfWidth": [0.5, 2], "bankBand": 0, "fluid": "%s"}, + {"name": "river", "minCatchment": 20000, "halfWidth": [2, 16], "bankBand": 8, "fluid": "%s"}], + "ponds": {"fluid": "%s"}, + "underground": {"cavePools": {"fluid": "%s"}}, + "fluids": [%s]} + """.formatted(streamFluid, riverFluid, streamFluid, streamFluid, fluids); + } + private File shorePack(String dimensionWidth) throws Exception { File pack = pack(dimension(WATER_ONLY, "\"hydrologyPolicy\": {\"shoreBiomes\": [\"beach\"]" + dimensionWidth + "},")); write(pack, "regions/region.json", """ From 90fdd980e011140017936dcf19a49a8252e68c4d Mon Sep 17 00:00:00 2001 From: Brian Fopiano Date: Mon, 2 Nov 2026 17:49:34 -0500 Subject: [PATCH 3/8] Rename hydrology config fields - Rename climateDrawdown to dryDrawdown - Rename minimumHeadKeep to minHeadKeep - Rename minimumCliffHeight to minCliffHeight - Rename waterfallMinimumDrop to waterfallMinDrop - Repin the schema digest for the new names --- .../config/IrisHydrologyDrainage.java | 2 +- .../hydrology/config/IrisHydrologyLakes.java | 2 +- .../hydrology/config/IrisHydrologyPonds.java | 4 ++-- .../hydrology/config/IrisHydrologyTier.java | 2 +- .../config/IrisHydrologyWetness.java | 6 ++--- .../hydrology/config/IrisSeaInlets.java | 2 +- .../hydrology/plan/HydrologySettings.java | 24 +++++++++---------- .../hydrology/plan/WindowPlanner.java | 2 +- .../hydrology/raster/LinkBlend.java | 12 +++++----- .../hydrology/raster/RasterComposer.java | 6 ++--- .../underground/SeaInletPlanner.java | 4 ++-- .../hydrology/water/ConfluenceGrader.java | 18 +++++++------- .../hydrology/water/HydrologyTier.java | 2 +- .../hydrology/water/PondPlanner.java | 2 +- .../hydrology/water/ReachGrader.java | 20 ++++++++-------- .../hydrology/water/ReachShaper.java | 12 +++++----- .../config/IrisHydrologyDefaultsTest.java | 12 +++++----- .../IrisHydrologyTerrainSourceTest.java | 2 +- .../plan/ConfluenceIncisionTest.java | 2 +- .../hydrology/plan/PlannedScene.java | 4 ++-- .../hydrology/plan/PlannedSceneTest.java | 4 ++-- .../hydrology/plan/WindowPlannerTest.java | 2 +- .../raster/ChunkWaterRasterTest.java | 6 ++--- .../hydrology/water/PondPlannerTest.java | 4 ++-- .../hydrology/water/ReachShaperTest.java | 10 ++++---- .../iris/pack/PackHydrologyValidatorTest.java | 8 +++---- .../schema/SchemaBuilderIdentityTest.java | 2 +- .../studio/workspace/IrisRiverSchemaTest.java | 4 ++-- .../arcane/iris/testsupport/WaterScene.java | 2 +- 29 files changed, 91 insertions(+), 91 deletions(-) diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyDrainage.java b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyDrainage.java index 192b9a428..d01b5dd76 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyDrainage.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyDrainage.java @@ -28,7 +28,7 @@ public class IrisHydrologyDrainage { @MinNumber(0) @MaxNumber(1) @Description("Smallest share of stream heads kept in the driest areas when wetness thinning is on.") - private double minimumHeadKeep = 0.25D; + private double minHeadKeep = 0.25D; @MinNumber(0) @MaxNumber(64) diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyLakes.java b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyLakes.java index 78ec8e287..d9740412c 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyLakes.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyLakes.java @@ -9,7 +9,7 @@ import lombok.experimental.Accessors; @Accessors(chain = true) @NoArgsConstructor -@Description("Large lakes that fill the biggest hollows in the terrain. Each lake has one water level across its whole surface. A hollow becomes a lake only when it is at least ponds.natural.minDepth deep and no more than 2048 blocks across. Lakes take their freeboard, climateDrawdown, shore roundness, materials, decorators and fluid from ponds.") +@Description("Large lakes that fill the biggest hollows in the terrain. Each lake has one water level across its whole surface. A hollow becomes a lake only when it is at least ponds.natural.minDepth deep and no more than 2048 blocks across. Lakes take their freeboard, dryDrawdown, shore roundness, materials, decorators and fluid from ponds.") @Data public class IrisHydrologyLakes { @Description("Turns large hollows into lakes.") diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyPonds.java b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyPonds.java index bb92196e0..8709a6e53 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyPonds.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyPonds.java @@ -13,7 +13,7 @@ import lombok.experimental.Accessors; @Accessors(chain = true) @NoArgsConstructor -@Description("Standing water above sea level. Ponds fill natural hollows, seeded cups and optional dams, each with its own level, so ponds sit at many heights and streams link them into chains. Lakes take their freeboard, climateDrawdown, shore roundness, materials, decorators and fluid from here as well.") +@Description("Standing water above sea level. Ponds fill natural hollows, seeded cups and optional dams, each with its own level, so ponds sit at many heights and streams link them into chains. Lakes take their freeboard, dryDrawdown, shore roundness, materials, decorators and fluid from here as well.") @Data public class IrisHydrologyPonds { @Description("Ponds that fill hollows already present in the terrain.") @@ -32,7 +32,7 @@ public class IrisHydrologyPonds { @MinNumber(0) @MaxNumber(32) @Description("Most extra blocks a pond or lake surface drops below its freeboard, in the driest areas. The drop is this value times the dryness at the floor, rounded: one minus the zone wetness, after the area's wetness bounds, where the dimension's wet and dry zones apply, and one minus the area's rainfall elsewhere, so water at a wetness or rainfall of 1 or more stays full.") - private int climateDrawdown = 6; + private int dryDrawdown = 6; @Description("Shape of pond shores and floors. Lakes take only its roundness.") private IrisPondShore shore = new IrisPondShore(); diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyTier.java b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyTier.java index 45100fc1b..27048d7e1 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyTier.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyTier.java @@ -50,7 +50,7 @@ public class IrisHydrologyTier { @MinNumber(2) @MaxNumber(64) @Description("Smallest drop in blocks that becomes a waterfall.") - private int waterfallMinimumDrop = 6; + private int waterfallMinDrop = 6; @MinNumber(0) @MaxNumber(64) diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyWetness.java b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyWetness.java index b0309bbeb..5e2147da9 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyWetness.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyWetness.java @@ -9,16 +9,16 @@ import lombok.experimental.Accessors; @Accessors(chain = true) @NoArgsConstructor -@Description("Bounds on how wet the dimension's wet and dry zones make this area. The zone wetness runs from the climate's dryRainfall in dry zones to 1 in wet zones and is held between min and max here. The bounded wetness scales rainfall and pond density, and a pond or lake whose floor lies here drops ponds.climateDrawdown times one minus it, rounded, below its freeboard.") +@Description("Bounds on how wet the dimension's wet and dry zones make this area. The zone wetness runs from the climate's dryRainfall in dry zones to 1 in wet zones and is held between min and max here. The bounded wetness scales rainfall and pond density, and a pond or lake whose floor lies here drops ponds.dryDrawdown times one minus it, rounded, below its freeboard.") @Data public class IrisHydrologyWetness { @MinNumber(0) @MaxNumber(1) - @Description("Lowest wetness this area falls to, even inside a dry zone. 0.7 keeps 70% of the rainfall and pond density in dry zones and lowers ponds and lakes by at most 30% of ponds.climateDrawdown. Left out, it is 0.") + @Description("Lowest wetness this area falls to, even inside a dry zone. 0.7 keeps 70% of the rainfall and pond density in dry zones and lowers ponds and lakes by at most 30% of ponds.dryDrawdown. Left out, it is 0.") private double min = 0D; @MinNumber(0) @MaxNumber(1) - @Description("Highest wetness this area reaches, even inside a wet zone. 0.35 keeps at most 35% of the rainfall and pond density and lowers ponds and lakes by at least 65% of ponds.climateDrawdown. Must not be below min. Left out, it is 1.") + @Description("Highest wetness this area reaches, even inside a wet zone. 0.35 keeps at most 35% of the rainfall and pond density and lowers ponds and lakes by at least 65% of ponds.dryDrawdown. Must not be below min. Left out, it is 1.") private double max = 1D; } diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisSeaInlets.java b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisSeaInlets.java index 248c0905f..03e48ae4b 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisSeaInlets.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/config/IrisSeaInlets.java @@ -25,7 +25,7 @@ public class IrisSeaInlets { @MinNumber(1) @MaxNumber(128) @Description("Height in blocks the coastal land must rise above sea level to be a site. The passage also needs ground at least headroom min + roofClearance + 2 blocks above sea level within about 16 blocks of the coast, so gentle coasts hold no inlets.") - private int minimumCliffHeight = 8; + private int minCliffHeight = 8; @ArrayType(type = Integer.class, min = 2) @Description("Length of an inlet in blocks, written as [min, max]. The max plus 12, plus the larger of halfWidth max and chamberRadius max, plus 3 must not exceed 512.") diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/plan/HydrologySettings.java b/core/src/main/java/art/arcane/iris/generation/hydrology/plan/HydrologySettings.java index 9e327d711..37d1adf2c 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/plan/HydrologySettings.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/plan/HydrologySettings.java @@ -219,7 +219,7 @@ public final class HydrologySettings { private static Drainage drainage(IrisHydrologyDrainage config) { return new Drainage((float) config.getFillEpsilon(), config.getBreachDepth(), config.isWetnessThinning(), - (float) config.getMinimumHeadKeep(), (float) config.getHeadRelief(), (float) config.getSaturationCatchment()); + (float) config.getMinHeadKeep(), (float) config.getHeadRelief(), (float) config.getSaturationCatchment()); } private static List tiers(List configs) { @@ -258,7 +258,7 @@ public final class HydrologySettings { } return new HydrologyTier(config.getName(), (float) config.getMinCatchment(), halfWidth.min(), halfWidth.max(), (float) config.getWidthFactor(), (float) config.getDepthRatio(), config.getInset(), config.isCascades(), - config.getWaterfallMinimumDrop(), config.getBankBand(), config.getBankStyle(), + config.getWaterfallMinDrop(), config.getBankBand(), config.getBankStyle(), estuary(config.getEstuary(), field + ".estuary"), delta(config, halfWidth.max(), field + ".delta"), materials(config.getMaterials(), field + ".materials"), config.getFluid(), decorators(config.getDecorators(), field + ".decorators")); } @@ -310,7 +310,7 @@ public final class HydrologySettings { return new Ponds(naturalPonds(config.getNatural()), seededPonds(config.getSeeded()), new PondDams(dams.isEnabled(), dams.getMaxRaise()), intRange(config.getFreeboard(), "ponds.freeboard", RangeFloor.NON_NEGATIVE), - config.getClimateDrawdown(), pondShore(config.getShore()), materials(config.getMaterials(), "ponds.materials"), config.getFluid(), + config.getDryDrawdown(), pondShore(config.getShore()), materials(config.getMaterials(), "ponds.materials"), config.getFluid(), decorators(config.getDecorators(), "ponds.decorators")); } @@ -347,7 +347,7 @@ public final class HydrologySettings { } private SeaInlets seaInlets(IrisSeaInlets config) { - SeaInlets inlets = new SeaInlets(config.isEnabled(), config.getSpacing(), config.getMinimumCliffHeight(), + SeaInlets inlets = new SeaInlets(config.isEnabled(), config.getSpacing(), config.getMinCliffHeight(), intRange(config.getLength(), "underground.seaInlets.length", RangeFloor.POSITIVE), floatRange(config.getHalfWidth(), "underground.seaInlets.halfWidth", RangeFloor.POSITIVE), intRange(config.getDepth(), "underground.seaInlets.depth", RangeFloor.POSITIVE), @@ -582,7 +582,7 @@ public final class HydrologySettings { private static void requireTierBounds(IrisHydrologyTier config, String field) { requireNonNegative(config.getWidthFactor(), field + ".widthFactor"); requireNonNegative(config.getDepthRatio(), field + ".depthRatio"); - requireAtLeast(config.getWaterfallMinimumDrop(), MIN_WATERFALL_DROP, field + ".waterfallMinimumDrop"); + requireAtLeast(config.getWaterfallMinDrop(), MIN_WATERFALL_DROP, field + ".waterfallMinDrop"); requireShoreDepth(config.getMaterials(), field + ".materials"); } @@ -679,7 +679,7 @@ public final class HydrologySettings { private void addDrainage(Fingerprint hash) { hash.add(drainage.fillEpsilon()).add(drainage.breachDepth()).add(drainage.wetnessThinning()) - .add(drainage.minimumHeadKeep()).add(drainage.headRelief()).add(drainage.saturationCatchment()); + .add(drainage.minHeadKeep()).add(drainage.headRelief()).add(drainage.saturationCatchment()); } private void addTiers(Fingerprint hash) { @@ -687,7 +687,7 @@ public final class HydrologySettings { for (HydrologyTier tier : tiers) { hash.add(tier.name()).add(tier.minCatchment()).add(tier.minHalfWidth()).add(tier.maxHalfWidth()) .add(tier.widthFactor()).add(tier.depthRatio()).add(tier.inset()).add(tier.cascades()) - .add(tier.waterfallMinimumDrop()).add(tier.bankBand()).add(tier.bankStyle()) + .add(tier.waterfallMinDrop()).add(tier.bankBand()).add(tier.bankStyle()) .add(tier.estuary().length()).add(tier.estuary().flare()) .add(tier.delta().channels()).add(tier.delta().spreadDegrees()).add(tier.delta().length()) .add(tier.materials()).add(tier.fluid()); @@ -703,7 +703,7 @@ public final class HydrologySettings { .add(seeded.enabled()).add(seeded.density()).add(seeded.radius()).add(seeded.depth()) .add(seeded.maxSlope()).add(seeded.alongChannels()).add(seeded.channelSpacing()) .add(ponds.dams().enabled()).add(ponds.dams().maxRaise()) - .add(ponds.freeboard()).add(ponds.climateDrawdown()) + .add(ponds.freeboard()).add(ponds.dryDrawdown()) .add(shore.roundness()).add(shore.shelf()).add(shore.taper()).add(shore.maxDepth()) .add(ponds.materials()).add(ponds.fluid()); } @@ -717,7 +717,7 @@ public final class HydrologySettings { private void addUnderground(Fingerprint hash) { SeaInlets inlets = underground.seaInlets(); CavePools pools = underground.cavePools(); - hash.add(inlets.enabled()).add(inlets.spacing()).add(inlets.minimumCliffHeight()).add(inlets.length()) + hash.add(inlets.enabled()).add(inlets.spacing()).add(inlets.minCliffHeight()).add(inlets.length()) .add(inlets.halfWidth()).add(inlets.depth()).add(inlets.headroom()).add(inlets.roofClearance()) .add(inlets.chamberRadius()) .add(pools.enabled()).add(pools.density()).add(pools.minArea()).add(pools.maxArea()) @@ -754,7 +754,7 @@ public final class HydrologySettings { } } - public record Drainage(float fillEpsilon, int breachDepth, boolean wetnessThinning, float minimumHeadKeep, float headRelief, + public record Drainage(float fillEpsilon, int breachDepth, boolean wetnessThinning, float minHeadKeep, float headRelief, float saturationCatchment) { } @@ -772,7 +772,7 @@ public final class HydrologySettings { } public record Ponds(NaturalPonds natural, SeededPonds seeded, PondDams dams, IntRange freeboard, - int climateDrawdown, PondShore shore, IrisHydrologyMaterials materials, String fluid, + int dryDrawdown, PondShore shore, IrisHydrologyMaterials materials, String fluid, List decorators) { } @@ -782,7 +782,7 @@ public final class HydrologySettings { public record Deformation(int maxFill, float bankSlope, float bankSteepFactor, float bankNoise, boolean caveMask) { } - public record SeaInlets(boolean enabled, int spacing, int minimumCliffHeight, IntRange length, FloatRange halfWidth, + public record SeaInlets(boolean enabled, int spacing, int minCliffHeight, IntRange length, FloatRange halfWidth, IntRange depth, IntRange headroom, int roofClearance, IntRange chamberRadius) { } diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/plan/WindowPlanner.java b/core/src/main/java/art/arcane/iris/generation/hydrology/plan/WindowPlanner.java index 2f5a979aa..5a4f5e905 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/plan/WindowPlanner.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/plan/WindowPlanner.java @@ -269,7 +269,7 @@ public final class WindowPlanner { private boolean keepHead(DemGrid surface, int cell, float rainfall) { HydrologySettings.Drainage drainage = settings.drainage(); - float keep = drainage.wetnessThinning() ? Math.clamp(Math.max(drainage.minimumHeadKeep(), rainfall), 0f, 1f) : 1f; + float keep = drainage.wetnessThinning() ? Math.clamp(Math.max(drainage.minHeadKeep(), rainfall), 0f, 1f) : 1f; keep *= settings.density(); return CellHash.unit(CellHash.mix(settings.seed(), SALT_HEAD, surface.blockX(cell), surface.blockZ(cell))) < keep; } diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/raster/LinkBlend.java b/core/src/main/java/art/arcane/iris/generation/hydrology/raster/LinkBlend.java index c03ced239..c66d3d70e 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/raster/LinkBlend.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/raster/LinkBlend.java @@ -60,13 +60,13 @@ public final class LinkBlend { int[] grade = feeder.grade(); int level = junction.level(); boolean[] fixed = fixed(feeder, lips, junction.fed() && grade[0] - level > ConfluenceGrader.MAX_START_LOWERING); - int waterfallMinimumDrop = feeder.tier().waterfallMinimumDrop(); - int[] settled = ConfluenceGrader.settle(footprint(feeder), grade, fixed, receiving, level, waterfallMinimumDrop); + int waterfallMinDrop = feeder.tier().waterfallMinDrop(); + int[] settled = ConfluenceGrader.settle(footprint(feeder), grade, fixed, receiving, level, waterfallMinDrop); if (settled == grade) { return feeder; } if (!feeder.tier().cascades()) { - ConfluenceGrader.spreadJunction(settled, grade, fixed, waterfallMinimumDrop, Integer.MIN_VALUE); + ConfluenceGrader.spreadJunction(settled, grade, fixed, waterfallMinDrop, Integer.MIN_VALUE); } return regraded(feeder, settled, feeder.halfWidth(), feeder.depth(), seaLevel); } @@ -101,19 +101,19 @@ public final class LinkBlend { } private static Reach regraded(Reach reach, int[] grade, float[] halfWidth, float[] depth, int seaLevel) { - ReachStyle[] style = grade == reach.grade() ? reach.style() : restyled(reach.style(), grade, reach.tier().waterfallMinimumDrop(), seaLevel); + ReachStyle[] style = grade == reach.grade() ? reach.style() : restyled(reach.style(), grade, reach.tier().waterfallMinDrop(), seaLevel); return new Reach(reach.id(), reach.tier(), reach.downstreamId(), reach.xs(), reach.zs(), grade, halfWidth, depth, style, reach.catchment()); } - private static ReachStyle[] restyled(ReachStyle[] style, int[] grade, int waterfallMinimumDrop, int seaLevel) { + private static ReachStyle[] restyled(ReachStyle[] style, int[] grade, int waterfallMinDrop, int seaLevel) { boolean[] mouth = new boolean[style.length]; boolean[] outlet = new boolean[style.length]; for (int point = 0; point < style.length; point++) { mouth[point] = style[point] == ReachStyle.MOUTH; outlet[point] = style[point] == ReachStyle.POND_OUTLET; } - return ReachShaper.styles(grade, mouth, outlet, waterfallMinimumDrop, seaLevel); + return ReachShaper.styles(grade, mouth, outlet, waterfallMinDrop, seaLevel); } private static int lowestEnd(List feeders) { diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/raster/RasterComposer.java b/core/src/main/java/art/arcane/iris/generation/hydrology/raster/RasterComposer.java index 34c77860d..dbfd16ea8 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/raster/RasterComposer.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/raster/RasterComposer.java @@ -284,7 +284,7 @@ final class RasterComposer { continue; } int drop = 0; - int waterfallMinimumDrop = Integer.MAX_VALUE; + int waterfallMinDrop = Integer.MAX_VALUE; for (int side : SIDES) { int upper = cell + side; if (!role[upper].flowing() || feature[upper] == feature[cell]) { @@ -293,11 +293,11 @@ final class RasterComposer { int step = head[upper] - head[cell]; if (step >= 2 && step > drop) { drop = step; - waterfallMinimumDrop = tier[upper].waterfallMinimumDrop(); + waterfallMinDrop = tier[upper].waterfallMinDrop(); } } if (drop > 0) { - role[cell] = drop >= waterfallMinimumDrop ? WaterRole.WATERFALL : WaterRole.CASCADE; + role[cell] = drop >= waterfallMinDrop ? WaterRole.WATERFALL : WaterRole.CASCADE; } } } diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/underground/SeaInletPlanner.java b/core/src/main/java/art/arcane/iris/generation/hydrology/underground/SeaInletPlanner.java index 719e5aeff..026d5739b 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/underground/SeaInletPlanner.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/underground/SeaInletPlanner.java @@ -100,7 +100,7 @@ public final class SeaInletPlanner { private Map> sites(Terrain terrain, HydrologySettings.SeaInlets config) { Map> sites = new TreeMap<>(); DemGrid grid = terrain.grid; - float cliff = settings.seaLevel() + config.minimumCliffHeight(); + float cliff = settings.seaLevel() + config.minCliffHeight(); for (int j = 1; j < grid.depth() - 1; j++) { for (int i = 1; i < grid.width() - 1; i++) { int cell = grid.index(i, j); @@ -467,7 +467,7 @@ public final class SeaInletPlanner { if (columns.first() < 0L || rows.first() < 0L || columns.last() > lastColumn || rows.last() > lastRow) { return true; } - float cliff = settings.seaLevel() + config.minimumCliffHeight(); + float cliff = settings.seaLevel() + config.minCliffHeight(); for (int i = (int) columns.first(); i <= columns.last(); i++) { if (rows.first() == 0L && cliffLand(terrain, i, 0, cliff) || rows.last() == lastRow && cliffLand(terrain, i, lastRow, cliff)) { return true; diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/water/ConfluenceGrader.java b/core/src/main/java/art/arcane/iris/generation/hydrology/water/ConfluenceGrader.java index 66026b3eb..6f1859407 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/water/ConfluenceGrader.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/water/ConfluenceGrader.java @@ -18,7 +18,7 @@ public final class ConfluenceGrader { public record Footprint(float[] xs, float[] zs, float[] halfWidth) { } - public static int[] settle(Footprint feeder, int[] grade, boolean[] fixed, List receiving, int level, int waterfallMinimumDrop) { + public static int[] settle(Footprint feeder, int[] grade, boolean[] fixed, List receiving, int level, int waterfallMinDrop) { int last = grade.length - 1; double[] arc = arcFromEnd(feeder); int[] settled = lower(grade, grade, last, level); @@ -27,20 +27,20 @@ public final class ConfluenceGrader { settled = lower(settled, grade, point, level); edge = point; } - int meet = approach(grade, fixed, arc, edge, level, waterfallMinimumDrop); + int meet = approach(grade, fixed, arc, edge, level, waterfallMinDrop); for (int point = edge - 1; point > meet; point--) { settled = lower(settled, grade, point, envelope(arc, edge, point, level)); } return settled; } - public static void spreadJunction(int[] settled, int[] grade, boolean[] fixed, int waterfallMinimumDrop, int startLimit) { + public static void spreadJunction(int[] settled, int[] grade, boolean[] fixed, int waterfallMinDrop, int startLimit) { int lowered = 0; while (settled[lowered] == grade[lowered]) { lowered++; } for (int point = settled.length - 2; point >= 0; point--) { - if (!ReachGrader.spreadPoint(settled, point, waterfallMinimumDrop, startLimit, fixed) && point < lowered) { + if (!ReachGrader.spreadPoint(settled, point, waterfallMinDrop, startLimit, fixed) && point < lowered) { return; } } @@ -55,14 +55,14 @@ public final class ConfluenceGrader { requireJunction(window, draft, downstream); boolean[] fixed = draft.fixed(); fixed[0] |= draft.incoming.length > 0 && draft.grade[0] - downstream.grade[0] > MAX_START_LOWERING; - int waterfallMinimumDrop = draft.tier.waterfallMinimumDrop(); + int waterfallMinDrop = draft.tier.waterfallMinDrop(); int[] settled = settle(footprint(draft), draft.grade, fixed, receiving(drafts, downstream, feeder), downstream.grade[0], - waterfallMinimumDrop); + waterfallMinDrop); if (settled == draft.grade) { continue; } if (!draft.tier.cascades()) { - spreadJunction(settled, draft.grade, fixed, waterfallMinimumDrop, ReachGrader.startLimit(drafts, draft)); + spreadJunction(settled, draft.grade, fixed, waterfallMinDrop, ReachGrader.startLimit(drafts, draft)); } draft.grade = settled; touched[feeder] = true; @@ -116,8 +116,8 @@ public final class ConfluenceGrader { return beside && lowering <= MARGIN_LOWERING; } - private static int approach(int[] grade, boolean[] fixed, double[] arc, int edge, int level, int waterfallMinimumDrop) { - double window = (waterfallMinimumDrop - 1) / (double) APPROACH_SLOPE; + private static int approach(int[] grade, boolean[] fixed, double[] arc, int edge, int level, int waterfallMinDrop) { + double window = (waterfallMinDrop - 1) / (double) APPROACH_SLOPE; for (int point = edge - 1; point >= 0 && arc[point] - arc[edge] <= window; point--) { if (grade[point] <= envelope(arc, edge, point, level)) { return point; diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/water/HydrologyTier.java b/core/src/main/java/art/arcane/iris/generation/hydrology/water/HydrologyTier.java index 0011b8664..d4aa7d423 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/water/HydrologyTier.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/water/HydrologyTier.java @@ -15,7 +15,7 @@ public record HydrologyTier( float depthRatio, int inset, boolean cascades, - int waterfallMinimumDrop, + int waterfallMinDrop, int bankBand, IrisBankStyle bankStyle, Estuary estuary, diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/water/PondPlanner.java b/core/src/main/java/art/arcane/iris/generation/hydrology/water/PondPlanner.java index 629dac70a..280ba8cfa 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/water/PondPlanner.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/water/PondPlanner.java @@ -776,7 +776,7 @@ public final class PondPlanner { } private int drawdown(float dryness) { - return Math.round(settings.ponds().climateDrawdown() * dryness); + return Math.round(settings.ponds().dryDrawdown() * dryness); } private static int radius(DemGrid raw, Basin basin) { diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachGrader.java b/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachGrader.java index bc2f58484..b9e3827e2 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachGrader.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachGrader.java @@ -74,7 +74,7 @@ final class ReachGrader { for (int position = upstreamFirst.length - 1; position >= 0; position--) { ReachDraft draft = drafts.get(upstreamFirst[position]); if (!draft.tier.cascades()) { - spread(draft.grade, draft.tier.waterfallMinimumDrop(), startLimit(drafts, draft), draft.held); + spread(draft.grade, draft.tier.waterfallMinDrop(), startLimit(drafts, draft), draft.held); } lowerIncomingEnds(drafts, draft); } @@ -158,16 +158,16 @@ final class ReachGrader { int limit = Integer.MIN_VALUE; for (int upstream : draft.incoming) { ReachDraft feeder = drafts.get(upstream); - limit = Math.max(limit, carryLimit(feeder.grade, feeder.grade.length - 1, feeder.tier.waterfallMinimumDrop())); + limit = Math.max(limit, carryLimit(feeder.grade, feeder.grade.length - 1, feeder.tier.waterfallMinDrop())); } return limit; } - private static int carryLimit(int[] grade, int point, int waterfallMinimumDrop) { - if (point == 0 || grade[point - 1] - grade[point] >= waterfallMinimumDrop) { + private static int carryLimit(int[] grade, int point, int waterfallMinDrop) { + if (point == 0 || grade[point - 1] - grade[point] >= waterfallMinDrop) { return Integer.MIN_VALUE; } - return grade[point - 1] - (waterfallMinimumDrop - 1); + return grade[point - 1] - (waterfallMinDrop - 1); } private static int[] profile(List drafts, ReachDraft draft) { @@ -210,18 +210,18 @@ final class ReachGrader { return sorted[Math.max(0, (int) Math.ceil(POOL_QUANTILE * sorted.length) - 1)]; } - private static void spread(int[] grade, int waterfallMinimumDrop, int startLimit, boolean[] held) { + private static void spread(int[] grade, int waterfallMinDrop, int startLimit, boolean[] held) { for (int point = grade.length - 2; point >= 0; point--) { - spreadPoint(grade, point, waterfallMinimumDrop, startLimit, held); + spreadPoint(grade, point, waterfallMinDrop, startLimit, held); } } - static boolean spreadPoint(int[] grade, int point, int waterfallMinimumDrop, int startLimit, boolean[] held) { + static boolean spreadPoint(int[] grade, int point, int waterfallMinDrop, int startLimit, boolean[] held) { int drop = grade[point] - grade[point + 1]; - if (drop < 2 || drop >= waterfallMinimumDrop || held != null && held[point]) { + if (drop < 2 || drop >= waterfallMinDrop || held != null && held[point]) { return false; } - int limit = point == 0 ? startLimit : carryLimit(grade, point, waterfallMinimumDrop); + int limit = point == 0 ? startLimit : carryLimit(grade, point, waterfallMinDrop); int spread = Math.min(grade[point], Math.max(grade[point + 1] + 1, limit)); boolean lowered = spread < grade[point]; grade[point] = spread; diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachShaper.java b/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachShaper.java index 1e887a69d..152800d76 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachShaper.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachShaper.java @@ -385,7 +385,7 @@ public final class ReachShaper { } private static void restyle(ReachDraft draft, int seaLevel) { - draft.style = styles(draft.grade, draft.ocean, draft.fixed(), draft.tier.waterfallMinimumDrop(), seaLevel); + draft.style = styles(draft.grade, draft.ocean, draft.fixed(), draft.tier.waterfallMinDrop(), seaLevel); } private static void chaikin(ReachDraft draft) { @@ -548,11 +548,11 @@ public final class ReachShaper { return Math.clamp(1f - remaining / length, 0f, 1f); } - public static ReachStyle[] styles(int[] grade, boolean[] ocean, boolean[] outletZone, int waterfallMinimumDrop, int seaLevel) { + public static ReachStyle[] styles(int[] grade, boolean[] ocean, boolean[] outletZone, int waterfallMinDrop, int seaLevel) { ReachStyle[] styles = new ReachStyle[grade.length]; for (int point = 0; point < grade.length; point++) { int drop = point == 0 ? 0 : grade[point - 1] - grade[point]; - styles[point] = style(drop, waterfallMinimumDrop, ocean[point], outletZone[point]); + styles[point] = style(drop, waterfallMinDrop, ocean[point], outletZone[point]); if (drop == 1 && !ocean[point] && outletZone[point - 1] && WaterHeads.snap(grade[point - 1], seaLevel) - WaterHeads.snap(grade[point], seaLevel) >= 2) { styles[point] = ReachStyle.CASCADE; @@ -560,18 +560,18 @@ public final class ReachShaper { } for (int point = 1; point < grade.length; point++) { if (styles[point] == ReachStyle.MOUTH && styles[point - 1] != ReachStyle.MOUTH - && grade[point - 1] - grade[point] >= waterfallMinimumDrop) { + && grade[point - 1] - grade[point] >= waterfallMinDrop) { styles[point - 1] = ReachStyle.WATERFALL; } } return styles; } - private static ReachStyle style(int drop, int waterfallMinimumDrop, boolean mouth, boolean outlet) { + private static ReachStyle style(int drop, int waterfallMinDrop, boolean mouth, boolean outlet) { if (mouth) { return ReachStyle.MOUTH; } - if (drop >= waterfallMinimumDrop) { + if (drop >= waterfallMinDrop) { return ReachStyle.WATERFALL; } if (drop >= 2) { diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyDefaultsTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyDefaultsTest.java index 81d3dc62b..f78004bae 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyDefaultsTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/config/IrisHydrologyDefaultsTest.java @@ -16,24 +16,24 @@ public class IrisHydrologyDefaultsTest { private static final String PLAN_JSON = """ { "enabled": false, - "drainage": { "fillEpsilon": 0.001, "breachDepth": 24, "wetnessThinning": true, "minimumHeadKeep": 0.25, "saturationCatchment": 4194304 }, + "drainage": { "fillEpsilon": 0.001, "breachDepth": 24, "wetnessThinning": true, "minHeadKeep": 0.25, "saturationCatchment": 4194304 }, "tiers": [ - { "name": "stream", "minCatchment": 1500, "halfWidth": [0.5, 2], "widthFactor": 1.0, "depthRatio": 0.4, "inset": 1, "cascades": true, "waterfallMinimumDrop": 6, "bankBand": 0, "bankStyle": "SMOOTH", "estuary": { "length": 48, "flare": 2.5 }, "delta": { "channels": 0, "spreadDegrees": 35, "length": 64 }, "materials": {}, "fluid": "water" }, - { "name": "river", "minCatchment": 20000, "halfWidth": [2, 8], "widthFactor": 1.0, "depthRatio": 0.45, "inset": 2, "cascades": true, "waterfallMinimumDrop": 6, "bankBand": 32, "bankStyle": "SMOOTH", "estuary": { "length": 48, "flare": 2.5 }, "delta": { "channels": 0, "spreadDegrees": 35, "length": 64 }, "materials": {}, "fluid": "water" }, - { "name": "major", "minCatchment": 320000, "halfWidth": [8, 16], "widthFactor": 1.0, "depthRatio": 0.5, "inset": 3, "cascades": true, "waterfallMinimumDrop": 6, "bankBand": 48, "bankStyle": "SMOOTH", "estuary": { "length": 48, "flare": 2.5 }, "delta": { "channels": 0, "spreadDegrees": 35, "length": 64 }, "materials": {}, "fluid": "water" } + { "name": "stream", "minCatchment": 1500, "halfWidth": [0.5, 2], "widthFactor": 1.0, "depthRatio": 0.4, "inset": 1, "cascades": true, "waterfallMinDrop": 6, "bankBand": 0, "bankStyle": "SMOOTH", "estuary": { "length": 48, "flare": 2.5 }, "delta": { "channels": 0, "spreadDegrees": 35, "length": 64 }, "materials": {}, "fluid": "water" }, + { "name": "river", "minCatchment": 20000, "halfWidth": [2, 8], "widthFactor": 1.0, "depthRatio": 0.45, "inset": 2, "cascades": true, "waterfallMinDrop": 6, "bankBand": 32, "bankStyle": "SMOOTH", "estuary": { "length": 48, "flare": 2.5 }, "delta": { "channels": 0, "spreadDegrees": 35, "length": 64 }, "materials": {}, "fluid": "water" }, + { "name": "major", "minCatchment": 320000, "halfWidth": [8, 16], "widthFactor": 1.0, "depthRatio": 0.5, "inset": 3, "cascades": true, "waterfallMinDrop": 6, "bankBand": 48, "bankStyle": "SMOOTH", "estuary": { "length": 48, "flare": 2.5 }, "delta": { "channels": 0, "spreadDegrees": 35, "length": 64 }, "materials": {}, "fluid": "water" } ], "ponds": { "natural": { "enabled": true, "keep": 1.0, "minArea": 256, "maxArea": 65536, "minDepth": 2 }, "seeded": { "enabled": true, "density": 4.0, "radius": [6, 24], "depth": [3, 8], "maxSlope": 0.6, "alongChannels": true, "channelSpacing": [96, 256] }, "dams": { "enabled": false, "maxRaise": 4 }, - "freeboard": [1, 3], "climateDrawdown": 6, + "freeboard": [1, 3], "dryDrawdown": 6, "shore": { "roundness": 0.5, "shelf": 6, "taper": 14, "maxDepth": 8 }, "materials": {}, "fluid": "water" }, "lakes": { "enabled": true, "minArea": 65536, "maxArea": 4194304 }, "deformation": { "maxFill": 6, "bankSlope": 0.2, "bankSteepFactor": 3.5, "bankNoise": 0.2, "caveMask": true }, "underground": { - "seaInlets": { "enabled": true, "spacing": 192, "minimumCliffHeight": 8, "length": [64, 256], "halfWidth": [2, 5], "depth": [2, 5], "headroom": [4, 10], "roofClearance": 6, "chamberRadius": [6, 12] }, + "seaInlets": { "enabled": true, "spacing": 192, "minCliffHeight": 8, "length": [64, 256], "halfWidth": [2, 5], "depth": [2, 5], "headroom": [4, 10], "roofClearance": 6, "chamberRadius": [6, 12] }, "cavePools": { "enabled": true, "density": 0.15, "minArea": 6, "maxArea": 400, "maxDepth": 4, "radius": 15, "freeboard": [0, 1], "fluid": "water" } }, "fluids": [ { "name": "water", "palette": { "palette": [ { "block": "minecraft:water" } ] } } ], diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/engine/IrisHydrologyTerrainSourceTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/engine/IrisHydrologyTerrainSourceTest.java index 9298015e3..d0121eab9 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/engine/IrisHydrologyTerrainSourceTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/engine/IrisHydrologyTerrainSourceTest.java @@ -263,7 +263,7 @@ public class IrisHydrologyTerrainSourceTest { Pond swamp = floorPond(fixture, settings, column); spires.setHydrologyPolicy(new IrisHydrologyPolicy().setPondDensity(16D).setWetness(new IrisHydrologyWetness().setMin(1D))); Pond kept = floorPond(fixture, settings, column); - int drawdown = settings.ponds().climateDrawdown(); + int drawdown = settings.ponds().dryDrawdown(); assertEquals((int) Math.floor(kept.spillHeight()) - 1, kept.level()); assertEquals(kept.level() - Math.round(drawdown * 0.3f), swamp.level()); assertEquals(kept.level() - Math.round(drawdown * 0.85f), dry.level()); diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/plan/ConfluenceIncisionTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/plan/ConfluenceIncisionTest.java index dbac246f9..6406d8808 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/plan/ConfluenceIncisionTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/plan/ConfluenceIncisionTest.java @@ -88,7 +88,7 @@ public class ConfluenceIncisionTest { } } assertTrue(major + " is cut " + cut + " into the wall", cut <= MAX_WALL_CUT); - double tallestFall = WALL_HEIGHT / 2D + major.tier().waterfallMinimumDrop(); + double tallestFall = WALL_HEIGHT / 2D + major.tier().waterfallMinDrop(); assertTrue(major + " falls " + largest + " blocks at once down a " + WALL_HEIGHT + "-block wall", largest <= tallestFall); } diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/plan/PlannedScene.java b/core/src/test/java/art/arcane/iris/generation/hydrology/plan/PlannedScene.java index d10c4cbfa..9ab06768d 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/plan/PlannedScene.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/plan/PlannedScene.java @@ -103,9 +103,9 @@ final class PlannedScene { new IrisHydrologyTier().setName("river").setMinCatchment(5000D).setHalfWidth(new KList<>(2.5D, 9D)).setWidthFactor(1.2D) .setDepthRatio(0.45D).setInset(2).setBankBand(32), new IrisHydrologyTier().setName("major").setMinCatchment(200000D).setHalfWidth(new KList<>(9D, 18D)).setWidthFactor(1.2D) - .setDepthRatio(0.5D).setInset(3).setBankBand(48).setWaterfallMinimumDrop(8))); + .setDepthRatio(0.5D).setInset(3).setBankBand(48).setWaterfallMinDrop(8))); config.getPonds().setFreeboard(new KList<>(1, 2)); - config.getPonds().setClimateDrawdown(3); + config.getPonds().setDryDrawdown(3); config.getPonds().getSeeded().setDensity(10D).setRadius(new KList<>(6, 22)).setMaxSlope(0.7D).setChannelSpacing(new KList<>(80, 192)); config.getPonds().getShore().setRoundness(0.5D).setShelf(6).setTaper(14).setMaxDepth(8); return config; diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/plan/PlannedSceneTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/plan/PlannedSceneTest.java index 045a8028b..724c14f60 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/plan/PlannedSceneTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/plan/PlannedSceneTest.java @@ -308,7 +308,7 @@ public class PlannedSceneTest { } zone[point] = along <= OUTLET_LENGTH; } - ReachStyle[] style = ReachShaper.styles(reach.grade(), new boolean[zone.length], zone, reach.tier().waterfallMinimumDrop(), seaLevel); + ReachStyle[] style = ReachShaper.styles(reach.grade(), new boolean[zone.length], zone, reach.tier().waterfallMinDrop(), seaLevel); return new Reach(reach.id(), reach.tier(), reach.downstreamId(), reach.xs(), reach.zs(), reach.grade(), reach.halfWidth(), reach.depth(), style, reach.catchment()); } @@ -334,7 +334,7 @@ public class PlannedSceneTest { halfWidths[point] = halfWidth; depths[point] = tier.depth(halfWidth); int drop = point == 0 ? 0 : grades[point - 1] - grades[point]; - styles[point] = drop >= tier.waterfallMinimumDrop() ? ReachStyle.WATERFALL + styles[point] = drop >= tier.waterfallMinDrop() ? ReachStyle.WATERFALL : drop >= 2 ? ReachStyle.CASCADE : drop == 1 ? ReachStyle.RIFFLE : ReachStyle.RUN; } return new Reach(id, tier, downstreamId, xs, zs, grades, halfWidths, depths, styles, 1000f); diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/plan/WindowPlannerTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/plan/WindowPlannerTest.java index a122c060b..a9129cff8 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/plan/WindowPlannerTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/plan/WindowPlannerTest.java @@ -1153,7 +1153,7 @@ public class WindowPlannerTest { int last = feeder.xs().length - 1; int drop = feeder.grade()[last] - downstream.grade()[0]; assertTrue(feeder + " meets " + downstream + " across the window line with a drop of " + drop, - drop >= 0 && drop < downstream.tier().waterfallMinimumDrop()); + drop >= 0 && drop < downstream.tier().waterfallMinDrop()); } assertTrue("reaches near the window line " + westOwned.size() + " + " + eastOwned.size(), westOwned.size() + eastOwned.size() >= 3); assertTrue("reach links between the two windows' plans " + links, links >= 1); diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/raster/ChunkWaterRasterTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/raster/ChunkWaterRasterTest.java index 41ff70c4e..c1a1fb54c 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/raster/ChunkWaterRasterTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/raster/ChunkWaterRasterTest.java @@ -817,7 +817,7 @@ public class ChunkWaterRasterTest { public void clampedSeamDropsAreStyledAsFalls() { HydrologyTier narrow = tier("river", 2f, 0.5f, 4, IrisBankStyle.SMOOTH); HydrologyTier wide = tier("river", 3f, 0.5f, 4, IrisBankStyle.SMOOTH); - assertEquals(6, narrow.waterfallMinimumDrop()); + assertEquals(6, narrow.waterfallMinDrop()); Reach low = line(232L, wide, 0L, 504f, 200f, 600f, 200f, (x, z) -> 62); Reach hanging = line(231L, narrow, low.id(), 440f, 200f, 504f, 200f, (x, z) -> 70); Scene falls = new Scene(settings(new IrisHydrology()), (x, z) -> 90).reach(hanging).reach(low); @@ -922,7 +922,7 @@ public class ChunkWaterRasterTest { for (int point = 0; point < zone.length; point++) { zone[point] = drawn.xs()[point] - drawn.xs()[0] <= 8f; } - ReachStyle[] style = ReachShaper.styles(drawn.grade(), new boolean[zone.length], zone, narrow.waterfallMinimumDrop(), SEA_LEVEL); + ReachStyle[] style = ReachShaper.styles(drawn.grade(), new boolean[zone.length], zone, narrow.waterfallMinDrop(), SEA_LEVEL); assertEquals("the last outlet zone point steps down one block, shown as two", ReachStyle.CASCADE, style[4]); assertTrue("the step lies at the end of the outlet zone", zone[4] && !zone[5]); Reach outlet = new Reach(drawn.id(), narrow, drawn.downstreamId(), drawn.xs(), drawn.zs(), drawn.grade(), drawn.halfWidth(), drawn.depth(), @@ -1523,7 +1523,7 @@ public class ChunkWaterRasterTest { halfWidth[point] = tier.minHalfWidth(); depth[point] = tier.depth(tier.minHalfWidth()); int drop = point == 0 ? 0 : grades[point - 1] - grades[point]; - style[point] = drop >= tier.waterfallMinimumDrop() ? ReachStyle.WATERFALL + style[point] = drop >= tier.waterfallMinDrop() ? ReachStyle.WATERFALL : drop >= 2 ? ReachStyle.CASCADE : drop == 1 ? ReachStyle.RIFFLE : ReachStyle.RUN; } return new Reach(id, tier, downstreamId, xs, zs, grades, halfWidth, depth, style, 1000f); diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/water/PondPlannerTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/water/PondPlannerTest.java index b57001e87..34e5398a9 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/water/PondPlannerTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/water/PondPlannerTest.java @@ -451,7 +451,7 @@ public class PondPlannerTest { Pond dry = single(plan(settings, new Terrain(terrain, 0f, ALLOW_ALL, null, MIN_Y, MAX_Y), 0, 0, 64, 64, null, List.of())); Pond damp = single(plan(settings, new Terrain(terrain, 0.5f, ALLOW_ALL, null, MIN_Y, MAX_Y), 0, 0, 64, 64, null, List.of())); assertEquals(wet.id(), dry.id()); - assertEquals(settings.ponds().climateDrawdown(), wet.level() - dry.level()); + assertEquals(settings.ponds().dryDrawdown(), wet.level() - dry.level()); assertTrue(damp.level() < wet.level() && damp.level() > dry.level()); assertContained(dry, terrain); } @@ -460,7 +460,7 @@ public class PondPlannerTest { public void drawdownFollowsClimateDryness() { HydrologySettings settings = settings(PondPlannerTest::naturalOnly, MIN_Y, MAX_Y); DoubleBinaryOperator terrain = bowl(256, 256, 60, 100, 12, 0.1); - int drawdown = settings.ponds().climateDrawdown(); + int drawdown = settings.ponds().dryDrawdown(); Pond full = single(plan(settings, new Terrain(terrain, 1f, ALLOW_ALL, null, MIN_Y, MAX_Y), 0, 0, 64, 64, null, List.of())); Pond wetZone = single(plan(settings, new Terrain(terrain, 0.5f, ALLOW_ALL, null, MIN_Y, MAX_Y).climateZoned((x, z) -> 1D), 0, 0, 64, 64, null, List.of())); diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/water/ReachShaperTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/water/ReachShaperTest.java index 234d59af7..18562c6d2 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/water/ReachShaperTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/water/ReachShaperTest.java @@ -74,7 +74,7 @@ public class ReachShaperTest { for (Reach reach : spread.reaches()) { Reach twin = steppedById.get(reach.id()); assertNotNull(twin); - int fall = reach.tier().waterfallMinimumDrop(); + int fall = reach.tier().waterfallMinDrop(); int junction = twin.downstreamId() == 0L ? Integer.MIN_VALUE : twin.grade()[twin.grade().length - 1]; assertTrue("trial " + trial + " " + reach + " gained a waterfall", dropsAbove(reach, junction, fall, Integer.MAX_VALUE) <= dropsAbove(twin, junction, fall, Integer.MAX_VALUE)); @@ -230,7 +230,7 @@ public class ReachShaperTest { public void dropAtWaterfallMinimumBecomesWaterfall() { HydrologySettings cascading = settings(config -> { }); - int minimum = cascading.tiers().get(1).waterfallMinimumDrop(); + int minimum = cascading.tiers().get(1).waterfallMinDrop(); List waterfall = drops(cascading, steppedValley(minimum)); assertEquals("drops " + waterfall, 1, waterfall.size()); assertEquals(minimum, waterfall.get(0).size()); @@ -293,9 +293,9 @@ public class ReachShaperTest { int[] grade = steep.grade; for (int index = 1; index < grade.length; index++) { int drop = grade[index - 1] - grade[index]; - assertTrue(Arrays.toString(grade), drop >= 0 && drop < tier.waterfallMinimumDrop()); + assertTrue(Arrays.toString(grade), drop >= 0 && drop < tier.waterfallMinDrop()); } - assertTrue(Arrays.toString(grade), grade[0] > (int) ground[0] - tier.inset() - tier.waterfallMinimumDrop()); + assertTrue(Arrays.toString(grade), grade[0] > (int) ground[0] - tier.inset() - tier.waterfallMinDrop()); assertEquals((int) ground[ground.length - 1] - tier.inset(), grade[grade.length - 1]); } @@ -1570,7 +1570,7 @@ public class ReachShaperTest { for (int index = 1; index <= entry && fall < 0; index++) { fall = reach.grade()[index] == SEA_LEVEL ? index : -1; } - if (reach.grade()[fall - 1] - SEA_LEVEL >= reach.tier().waterfallMinimumDrop()) { + if (reach.grade()[fall - 1] - SEA_LEVEL >= reach.tier().waterfallMinDrop()) { falls++; int lip = fall == entry ? entry - 1 : fall; assertEquals(reach.toString(), ReachStyle.WATERFALL, reach.style()[lip]); diff --git a/core/src/test/java/art/arcane/iris/pack/PackHydrologyValidatorTest.java b/core/src/test/java/art/arcane/iris/pack/PackHydrologyValidatorTest.java index fae4a255a..0d0c8af6e 100644 --- a/core/src/test/java/art/arcane/iris/pack/PackHydrologyValidatorTest.java +++ b/core/src/test/java/art/arcane/iris/pack/PackHydrologyValidatorTest.java @@ -514,16 +514,16 @@ public class PackHydrologyValidatorTest { } @Test - public void rejectsWaterfallMinimumDropBelowTwo() throws Exception { + public void rejectsWaterfallMinDropBelowTwo() throws Exception { File pack = pack(dimension(""" {"enabled": true, "tiers": [{"name": "stream", "halfWidth": [0.5, 2], "bankBand": 0}, - {"name": "river", "minCatchment": 20000, "halfWidth": [2, 8], "bankBand": 32, "waterfallMinimumDrop": 1}]} + {"name": "river", "minCatchment": 20000, "halfWidth": [2, 8], "bankBand": 32, "waterfallMinDrop": 1}]} """, "")); write(pack, "dimensions/edge.json", dimension(""" - {"enabled": true, "tiers": [{"name": "stream", "halfWidth": [0.5, 2], "bankBand": 0, "waterfallMinimumDrop": 2}]} + {"enabled": true, "tiers": [{"name": "stream", "halfWidth": [0.5, 2], "bankBand": 0, "waterfallMinDrop": 2}]} """, "")); - assertEquals(List.of("Dimension 'main'.hydrology does not compile: Hydrology tiers[1].waterfallMinimumDrop must be at least 2, got 1"), + assertEquals(List.of("Dimension 'main'.hydrology does not compile: Hydrology tiers[1].waterfallMinDrop must be at least 2, got 1"), validate(pack).errors()); } diff --git a/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java b/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java index a6b20f7af..c5ca13aaf 100644 --- a/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java +++ b/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java @@ -84,7 +84,7 @@ public class SchemaBuilderIdentityTest { @ClassRule public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean(); - private static final String EXPECTED_SCHEMA_DIGEST = "3377c4bd7994ef223bbb054391c191e6dc202475232d19c5c3fe4f43402ffed1"; + private static final String EXPECTED_SCHEMA_DIGEST = "7eaf3ddcf305811c453a61368a9ae886cedb1ce47d4ca6dc53953ab8f26f5a77"; private static final List> SCHEMA_ROOTS = List.of( IrisDimension.class, diff --git a/core/src/test/java/art/arcane/iris/studio/workspace/IrisRiverSchemaTest.java b/core/src/test/java/art/arcane/iris/studio/workspace/IrisRiverSchemaTest.java index 281e961f3..89e5132ea 100644 --- a/core/src/test/java/art/arcane/iris/studio/workspace/IrisRiverSchemaTest.java +++ b/core/src/test/java/art/arcane/iris/studio/workspace/IrisRiverSchemaTest.java @@ -80,8 +80,8 @@ public class IrisRiverSchemaTest { assertTrue(section, properties.getJSONObject(section).has("$ref")); } assertEquals("array", tier.getJSONObject("halfWidth").getString("type")); - assertEquals(2, tier.getJSONObject("waterfallMinimumDrop").getInt("minimum")); - assertEquals(64, tier.getJSONObject("waterfallMinimumDrop").getInt("maximum")); + assertEquals(2, tier.getJSONObject("waterfallMinDrop").getInt("minimum")); + assertEquals(64, tier.getJSONObject("waterfallMinDrop").getInt("maximum")); assertEquals(64, tier.getJSONObject("bankBand").getInt("maximum")); assertEquals(0.05D, tier.getJSONObject("depthRatio").getDouble("minimum"), 0D); assertEquals(List.of("SMOOTH", "LINEAR", "CONCAVE", "TERRACED", "CLIFF"), diff --git a/core/src/test/java/art/arcane/iris/testsupport/WaterScene.java b/core/src/test/java/art/arcane/iris/testsupport/WaterScene.java index 99344dcfd..1d7e5c272 100644 --- a/core/src/test/java/art/arcane/iris/testsupport/WaterScene.java +++ b/core/src/test/java/art/arcane/iris/testsupport/WaterScene.java @@ -101,7 +101,7 @@ public final class WaterScene { halfWidth[point] = tier.minHalfWidth(); depth[point] = tier.depth(tier.minHalfWidth()); int drop = point == 0 ? 0 : grades[point - 1] - grades[point]; - style[point] = drop >= tier.waterfallMinimumDrop() ? ReachStyle.WATERFALL + style[point] = drop >= tier.waterfallMinDrop() ? ReachStyle.WATERFALL : drop >= 2 ? ReachStyle.CASCADE : drop == 1 ? ReachStyle.RIFFLE : ReachStyle.RUN; } return new Reach(id, tier, 0L, xs, zs, grades, halfWidth, depth, style, 1000f); From d6a3456024a05c3b9d3bae2468241dc75095ac39 Mon Sep 17 00:00:00 2001 From: Brian Fopiano Date: Mon, 2 Nov 2026 18:06:17 -0500 Subject: [PATCH 4/8] Reject unknown hydrology keys - Report keys under hydrology and hydrologyPolicy that the config classes do not declare, with the full JSON path, as blocking errors - Derive known keys by reflection over the fields Gson reads, and treat map keys as data while checking the objects inside - Check a disabled hydrology block too, so a misspelt enabled flag is caught - Follow snippet references from hydrology into their files - Replace the tests that pinned unknown keys as ignored - Pin the no-sea warning on both sides of its boundary, fluidHeight -64 and -63 --- .../iris/pack/PackHydrologyValidator.java | 116 +++++++++ .../iris/pack/PackHydrologyValidatorTest.java | 231 +++++++++++++++--- 2 files changed, 317 insertions(+), 30 deletions(-) diff --git a/core/src/main/java/art/arcane/iris/pack/PackHydrologyValidator.java b/core/src/main/java/art/arcane/iris/pack/PackHydrologyValidator.java index 2aa7cf5bd..e3989980a 100644 --- a/core/src/main/java/art/arcane/iris/pack/PackHydrologyValidator.java +++ b/core/src/main/java/art/arcane/iris/pack/PackHydrologyValidator.java @@ -15,17 +15,27 @@ import art.arcane.iris.generation.terrain.IrisMaterialPalette; import art.arcane.iris.generation.terrain.IrisRegion; import art.arcane.iris.generation.terrain.ShoreBiomeLineages; import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.pack.loading.IrisRegistrant; +import art.arcane.iris.pack.schema.annotation.Snippet; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisPlatforms; import art.arcane.volmlib.util.json.JSONArray; import art.arcane.volmlib.util.json.JSONObject; import art.arcane.volmlib.util.mantle.flag.ReservedFlag; +import com.google.gson.annotations.SerializedName; +import com.google.gson.reflect.TypeToken; import java.io.File; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; +import java.util.HashSet; import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -39,6 +49,7 @@ final class PackHydrologyValidator { private static final String CONFIG = "hydrology"; private static final String POLICY = "hydrologyPolicy"; private static final String DEFAULT_FLUID = "water"; + private static final String SNIPPET_ROOT = "snippet/"; private static final List RANGES = List.of( new RangeField("ponds.freeboard", Floor.NON_NEGATIVE, true), new RangeField("ponds.seeded.radius", Floor.POSITIVE, true), @@ -93,6 +104,7 @@ final class PackHydrologyValidator { errors.add(path + " must be an object."); return data; } + rejectUnknownKeys(path, hydrology, IrisHydrology.class, packFolder, errors); if (!hydrology.optBoolean("enabled", false)) { return data; } @@ -117,6 +129,96 @@ final class PackHydrologyValidator { return loaded; } + static void rejectUnknownKeys(String field, Object value, Type type, File packFolder, List errors) { + rejectUnknownKeys(field, value, type, new KeyScan(packFolder, errors, new HashSet<>())); + } + + private static void rejectUnknownKeys(String field, Object value, Type type, KeyScan scan) { + Class raw = TypeToken.get(type).getRawType(); + if (value instanceof JSONArray array) { + Type element = elementType(type, raw); + for (int index = 0; index < array.length(); index++) { + rejectUnknownKeys(field + "[" + index + "]", array.opt(index), element, scan); + } + } else if (value instanceof JSONObject object) { + if (Map.class.isAssignableFrom(raw)) { + Type entry = typeArgument(type, 1); + for (String key : new TreeSet<>(object.keySet())) { + rejectUnknownKeys(field + "." + key, object.opt(key), entry, scan); + } + } else if (hasDeclaredKeys(raw)) { + rejectUnknownFields(field, object, raw, scan); + } + } else if (value instanceof String reference && reference.startsWith(SNIPPET_ROOT) && raw.isAnnotationPresent(Snippet.class)) { + rejectUnknownSnippetKeys(field, reference, raw, scan); + } + } + + private static void rejectUnknownFields(String field, JSONObject object, Class type, KeyScan scan) { + Map declared = declaredKeys(type); + for (String key : new TreeSet<>(object.keySet())) { + String child = field + "." + key; + Type declaredType = declared.get(key); + if (declaredType == null) { + scan.errors().add(child + " is not a known key, so its value would be ignored. Known keys there: " + declared.keySet() + "."); + } else { + rejectUnknownKeys(child, object.opt(key), declaredType, scan); + } + } + } + + private static void rejectUnknownSnippetKeys(String field, String reference, Class type, KeyScan scan) { + String base = SNIPPET_ROOT + type.getDeclaredAnnotation(Snippet.class).value() + "/"; + String snippet = reference.startsWith(base) ? reference : base + reference.substring(SNIPPET_ROOT.length()); + if (!scan.activeSnippets().add(snippet)) { + return; + } + File file = new File(scan.packFolder(), snippet + ".json"); + JSONObject object = file.isFile() ? PackValidationIo.readJson(file) : null; + if (object != null) { + rejectUnknownFields(field + " (" + snippet + ")", object, type, scan); + } + scan.activeSnippets().remove(snippet); + } + + private static Type elementType(Type type, Class raw) { + if (raw.isArray()) { + return raw.getComponentType(); + } + return Collection.class.isAssignableFrom(raw) ? typeArgument(type, 0) : Object.class; + } + + private static Type typeArgument(Type type, int index) { + if (type instanceof ParameterizedType parameterized && index < parameterized.getActualTypeArguments().length) { + return parameterized.getActualTypeArguments()[index]; + } + return Object.class; + } + + private static boolean hasDeclaredKeys(Class type) { + return !type.isPrimitive() && !type.isEnum() && !type.isArray() && !type.getPackageName().startsWith("java."); + } + + private static Map declaredKeys(Class type) { + Map keys = new TreeMap<>(); + for (Class current = type; current != null && current != Object.class; current = current.getSuperclass()) { + for (Field field : current.getDeclaredFields()) { + int modifiers = field.getModifiers(); + if (Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers) || field.isSynthetic()) { + continue; + } + SerializedName serialized = field.getAnnotation(SerializedName.class); + keys.putIfAbsent(serialized == null ? field.getName() : serialized.value(), field.getGenericType()); + if (serialized != null) { + for (String alternate : serialized.alternate()) { + keys.putIfAbsent(alternate, field.getGenericType()); + } + } + } + } + return keys; + } + private static boolean validateCompile(String path, IrisDimension dimension, List errors) { try { HydrologySettings.compile(dimension.getHydrology(), 0L, dimension.getFluidHeight(), 0, @@ -282,11 +384,13 @@ final class PackHydrologyValidator { private static void validatePolicies(String path, String dimensionKey, IrisData data, IrisDimension dimension, PolicyFluids fluids, List errors) { + rejectUnknownPolicyKeys("Dimension '" + dimensionKey + "'." + POLICY, dimension, data, errors); validatePolicy("Dimension '" + dimensionKey + "'." + POLICY, dimension.getHydrologyPolicy(), data, fluids, path, errors); List regions = new ArrayList<>(dimension.getAllRegions(() -> data)); regions.sort(Comparator.comparing(IrisRegion::getLoadKey, Comparator.nullsFirst(Comparator.naturalOrder()))); for (IrisRegion region : regions) { if (region != null) { + rejectUnknownPolicyKeys("Region '" + region.getLoadKey() + "'." + POLICY, region, data, errors); validatePolicy("Region '" + region.getLoadKey() + "'." + POLICY, region.getHydrologyPolicy(), data, fluids, path, errors); } } @@ -294,11 +398,20 @@ final class PackHydrologyValidator { biomes.sort(Comparator.comparing(IrisBiome::getLoadKey, Comparator.nullsFirst(Comparator.naturalOrder()))); for (IrisBiome biome : biomes) { if (biome != null) { + rejectUnknownPolicyKeys("Biome '" + biome.getLoadKey() + "'." + POLICY, biome, data, errors); validatePolicy("Biome '" + biome.getLoadKey() + "'." + POLICY, biome.getHydrologyPolicy(), data, fluids, path, errors); } } } + private static void rejectUnknownPolicyKeys(String field, IrisRegistrant owner, IrisData data, List errors) { + File file = owner.getLoadFile(); + JSONObject json = file == null ? null : PackValidationIo.readJson(file); + if (json != null) { + rejectUnknownKeys(field, json.opt(POLICY), IrisHydrologyPolicy.class, data.getDataFolder(), errors); + } + } + private static void validatePolicy(String field, IrisHydrologyPolicy policy, IrisData data, PolicyFluids fluids, String configPath, List errors) { if (policy == null) { @@ -501,4 +614,7 @@ final class PackHydrologyValidator { private record Findings(List errors, List warnings) { } + + private record KeyScan(File packFolder, List errors, Set activeSnippets) { + } } diff --git a/core/src/test/java/art/arcane/iris/pack/PackHydrologyValidatorTest.java b/core/src/test/java/art/arcane/iris/pack/PackHydrologyValidatorTest.java index 0d0c8af6e..e595f0a6f 100644 --- a/core/src/test/java/art/arcane/iris/pack/PackHydrologyValidatorTest.java +++ b/core/src/test/java/art/arcane/iris/pack/PackHydrologyValidatorTest.java @@ -1,10 +1,19 @@ package art.arcane.iris.pack; +import art.arcane.iris.generation.block.IrisBlockData; +import art.arcane.iris.generation.decoration.IrisDecorator; import art.arcane.iris.generation.hydrology.config.IrisHydrology; +import art.arcane.iris.generation.hydrology.config.IrisHydrologyPermission; +import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy; import art.arcane.iris.generation.hydrology.config.IrisHydrologyTier; +import art.arcane.iris.generation.hydrology.config.IrisHydrologyWetness; import art.arcane.iris.generation.hydrology.plan.HydrologySettings; +import art.arcane.iris.generation.noise.IrisGeneratorStyle; +import art.arcane.iris.generation.terrain.IrisMaterialPalette; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.testsupport.CompatTestPlatform; +import art.arcane.volmlib.util.json.JSONObject; +import com.google.gson.Gson; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -13,7 +22,9 @@ import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; import java.util.List; +import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -266,45 +277,192 @@ public class PackHydrologyValidatorTest { } @Test - public void unknownHydrologyKeysAreIgnoredAndAMissingEnabledFlagLoadsAsOff() throws Exception { + public void rejectsAnUnknownKeyAtTheTopOfHydrology() throws Exception { + List errors = validate(pack(dimension("{\"enabled\": true, \"unknownSection\": {\"enabled\": true, \"tiers\": 4}}", ""))).errors(); + + assertContains(errors, "Dimension 'main'.hydrology.unknownSection is not a known key, so its value would be ignored."); + assertContains(errors, "prefetchRings"); + assertEquals(errors.toString(), 1, errors.size()); + } + + @Test + public void rejectsAMisspeltEnabledFlagThoughTheBlockLoadsAsOff() throws Exception { + File pack = pack(dimension("{\"enable\": true, \"ponds\": {\"dryDrawdon\": 3}}", "")); + + List errors = validate(pack).errors(); + + assertContains(errors, "Dimension 'main'.hydrology.enable is not a known key"); + assertContains(errors, "Dimension 'main'.hydrology.ponds.dryDrawdon is not a known key"); + assertEquals(errors.toString(), 2, errors.size()); + assertFalse(loadHydrology(pack).isEnabled()); + } + + @Test + public void rejectsUnknownKeysInNestedObjects() throws Exception { + List errors = validate(pack(dimension(""" + { + "enabled": true, + "ponds": {"seeded": {"radiusRange": [4, 12]}}, + "underground": {"cavePools": {"surface": 3}, "seaInlets": {"length": [24, 96], "chamber": {"radius": 4}}} + } + """, ""))).errors(); + + assertContains(errors, "Dimension 'main'.hydrology.ponds.seeded.radiusRange is not a known key"); + assertContains(errors, "Dimension 'main'.hydrology.underground.cavePools.surface is not a known key"); + assertContains(errors, "Dimension 'main'.hydrology.underground.seaInlets.chamber is not a known key"); + assertEquals(errors.toString(), 3, errors.size()); + } + + @Test + public void rejectsUnknownKeysInsideTierArrayElements() throws Exception { File pack = pack(dimension(""" - {"unknownSection": {"enabled": true, "tiers": 4}, "unknownList": [{"enabled": true}]} + {"enabled": true, "fluids": [{"name": "water", "palette": {"palette": [{"block": "minecraft:water", "bloc": 1}]}, "sealed": true}], + "tiers": [ + {"name": "stream", "minCatchment": 900, "halfWidth": [0.5, 2.5], "bankBand": 8}, + {"name": "major", "minCatchment": 200000, "halfWidth": [9, 18], "bankBand": 48, "notATierField": {"depth": 3}, + "estuary": {"flair": 2}, + "decorators": [{"partOf": "SEA_FLOOR", "palette": [{"block": "minecraft:kelp"}], "stacks": 1}]} + ]} """, "")); - assertTrue(validate(pack).errors().isEmpty()); - IrisData data = IrisData.openDatapackCompiler(pack); - try { - IrisHydrology hydrology = data.getDimensionLoader().load("main").getHydrology(); - assertNotNull(hydrology); - assertFalse(hydrology.isEnabled()); - } finally { - data.close(); + List errors = validate(pack).errors(); + + assertContains(errors, "Dimension 'main'.hydrology.tiers[1].notATierField is not a known key"); + assertContains(errors, "Dimension 'main'.hydrology.tiers[1].estuary.flair is not a known key"); + assertContains(errors, "Dimension 'main'.hydrology.tiers[1].decorators[0].stacks is not a known key"); + assertContains(errors, "Dimension 'main'.hydrology.fluids[0].sealed is not a known key"); + assertContains(errors, "Dimension 'main'.hydrology.fluids[0].palette.palette[0].bloc is not a known key"); + assertEquals(errors.toString(), 5, errors.size()); + for (IrisHydrologyTier tier : loadHydrology(pack).getTiers()) { + assertEquals(tier.getName(), 48, tier.getEstuary().getLength()); + assertEquals(tier.getName(), 2.5D, tier.getEstuary().getFlare(), 0D); } } @Test - public void unknownTierKeysAreIgnoredAndTiersKeepTheDefaultEstuary() throws Exception { - String written = """ - {"enabled": true, "tiers": [ - {"name": "stream", "minCatchment": 900, "halfWidth": [0.5, 2.5], "bankBand": 8%s}, - {"name": "major", "minCatchment": 200000, "halfWidth": [9, 18], "bankBand": 48%s} - ]} - """; - File extra = pack(dimension(written.formatted(", \"notATierField\": false", ", \"notATierField\": {\"depth\": 3}"), "")); - File current = pack(dimension(written.formatted("", ""), "")); + public void treatsMapKeysAsDataAndChecksTheObjectsInside() throws Exception { + List errors = new ArrayList<>(); + JSONObject written = new JSONObject(""" + {"zones": {"swamp": {"min": 0.7, "max": 1}, "desert": {"minimum": 0.1}}} + """); + + PackHydrologyValidator.rejectUnknownKeys("root", written, NamedZones.class, temporaryFolder.getRoot(), errors); + + assertContains(errors, "root.zones.desert.minimum is not a known key"); + assertEquals(errors.toString(), 1, errors.size()); + } + + @Test + public void acceptsAnyKeyInsideABlockDataMap() throws Exception { + PackHydrologyValidator.Validation validation = validate(pack(dimension(""" + {"enabled": true, "fluids": [{"name": "water", "palette": {"palette": [ + {"block": "minecraft:water", "data": {"level": 0, "anything": {"at": "all"}}, "tileData": {"SpawnData": {"entity": {}}}} + ]}}]} + """, ""))); - PackHydrologyValidator.Validation validation = validate(extra); assertTrue(validation.errors().toString(), validation.errors().isEmpty()); - assertTrue(validation.warnings().isEmpty()); - PackValidationResult packaging = PackValidator.validateForPackaging(extra); - assertEquals(PackValidator.validateForPackaging(current).getBlockingErrors(), packaging.getBlockingErrors()); - IrisHydrology loaded = loadHydrology(extra); - for (IrisHydrologyTier tier : loaded.getTiers()) { - assertEquals(tier.getName(), 48, tier.getEstuary().getLength()); - assertEquals(tier.getName(), 2.5D, tier.getEstuary().getFlare(), 0D); - } - assertEquals(HydrologySettings.compile(loadHydrology(current), 1337L, 62, -64, 320).fingerprint(), - HydrologySettings.compile(loaded, 1337L, 62, -64, 320).fingerprint()); + } + + @Test + public void acceptsEveryKeyGsonWritesForTheConfigClasses() throws Exception { + Gson gson = new Gson(); + PackHydrologyValidator.Validation defaults = validate(pack(dimension(gson.toJson(new IrisHydrology().setEnabled(true)), ""))); + assertTrue(defaults.errors().toString(), defaults.errors().isEmpty()); + + IrisHydrology hydrology = new IrisHydrology().setEnabled(true); + hydrology.getTiers().get(0).getMaterials().setBed(new IrisMaterialPalette()).setShore(new IrisMaterialPalette()).setBank(new IrisMaterialPalette()); + IrisDecorator decorator = new IrisDecorator().setForceBlock(new IrisBlockData("minecraft:stone")); + decorator.getStyle().setFracture(new IrisGeneratorStyle()); + hydrology.getTiers().get(0).getDecorators().add(decorator); + IrisHydrologyPolicy policy = new IrisHydrologyPolicy().setRainfall(1D).setWetness(new IrisHydrologyWetness()).setStreams(IrisHydrologyPermission.ALLOW); + + List errors = validate(pack(dimension(gson.toJson(hydrology), "\"hydrologyPolicy\": " + gson.toJson(policy) + ","))).errors(); + + assertEquals(List.of(), errors.stream().filter(error -> error.contains("not a known key")).toList()); + } + + @Test + public void rejectsEachRenamedKeyByItsOldName() throws Exception { + List errors = validate(pack(dimension(""" + { + "enabled": true, + "drainage": {"minimumHeadKeep": 0.6}, + "tiers": [ + {"name": "stream", "halfWidth": [0.5, 2], "bankBand": 0, "waterfallMinimumDrop": 6}, + {"name": "river", "minCatchment": 20000, "halfWidth": [2, 8], "bankBand": 32, "waterfallMinimumDrop": 8} + ], + "ponds": {"climateDrawdown": 3}, + "underground": {"seaInlets": {"minimumCliffHeight": 8}} + } + """, ""))).errors(); + + assertContains(errors, "Dimension 'main'.hydrology.drainage.minimumHeadKeep is not a known key"); + assertContains(errors, "Dimension 'main'.hydrology.tiers[0].waterfallMinimumDrop is not a known key"); + assertContains(errors, "Dimension 'main'.hydrology.tiers[1].waterfallMinimumDrop is not a known key"); + assertContains(errors, "Dimension 'main'.hydrology.ponds.climateDrawdown is not a known key"); + assertContains(errors, "Dimension 'main'.hydrology.underground.seaInlets.minimumCliffHeight is not a known key"); + assertEquals(errors.toString(), 5, errors.size()); + } + + @Test + public void rejectsUnknownKeysInHydrologyPoliciesAtEveryScope() throws Exception { + File pack = pack(dimension(WATER_ONLY, "\"hydrologyPolicy\": {\"rainFall\": 1},")); + write(pack, "regions/region.json", """ + {"landBiomes": ["biome"], "hydrologyPolicy": {"streamz": "BLOCK"}} + """); + write(pack, "biomes/biome.json", """ + {"name": "Biome", "hydrologyPolicy": {"wetness": {"middle": 0.5}, + "decorators": [{"partOf": "SHORE_LINE", "palette": [{"block": "minecraft:fern"}], "odds": 2}]}} + """); + + List errors = validate(pack).errors(); + + assertContains(errors, "Dimension 'main'.hydrologyPolicy.rainFall is not a known key"); + assertContains(errors, "Region 'region'.hydrologyPolicy.streamz is not a known key"); + assertContains(errors, "Biome 'biome'.hydrologyPolicy.wetness.middle is not a known key"); + assertContains(errors, "Biome 'biome'.hydrologyPolicy.decorators[0].odds is not a known key"); + assertEquals(errors.toString(), 4, errors.size()); + } + + @Test + public void followsSnippetsAndNamesThemInThePath() throws Exception { + File pack = pack(dimension(""" + {"enabled": true, "tiers": [{"name": "stream", "halfWidth": [0.5, 2], "bankBand": 0, + "decorators": ["snippet/reeds", "snippet/decorator/fern", "snippet/decorator/missing"]}]} + """, "")); + write(pack, "snippet/decorator/reeds.json", """ + {"partOf": "SHORE_LINE", "palette": [{"block": "minecraft:sugar_cane"}], "odds": 2} + """); + write(pack, "snippet/decorator/fern.json", """ + {"partOf": "SHORE_LINE", "palette": [{"block": "minecraft:fern"}]} + """); + + List errors = validate(pack).errors().stream().filter(error -> error.contains("not a known key")).toList(); + + assertContains(errors, "Dimension 'main'.hydrology.tiers[0].decorators[0] (snippet/decorator/reeds).odds is not a known key"); + assertEquals(errors.toString(), 1, errors.size()); + } + + @Test + public void aSnippetThatRefersToItselfEnds() throws Exception { + File pack = temporaryFolder.newFolder("cycle"); + write(pack, "snippet/style/loop.json", """ + {"fracture": "snippet/style/loop", "fractures": 1} + """); + List errors = new ArrayList<>(); + + PackHydrologyValidator.rejectUnknownKeys("style", "snippet/style/loop", IrisGeneratorStyle.class, pack, errors); + + assertContains(errors, "style (snippet/style/loop).fractures is not a known key"); + assertEquals(errors.toString(), 1, errors.size()); + } + + @Test + public void leavesKeysOutsideTheHydrologyBlockAlone() throws Exception { + File pack = pack("{\"regions\": [\"region\"], \"notADimensionKey\": 1, \"hydrology\": " + WATER_ONLY + "}"); + write(pack, "biomes/biome.json", "{\"name\": \"Biome\", \"notABiomeKey\": {\"a\": 1}}"); + + assertTrue(validate(pack).errors().isEmpty()); } @Test @@ -779,6 +937,15 @@ public class PackHydrologyValidatorTest { assertTrue(validation.warnings().toString(), validation.warnings().isEmpty()); } + @Test + public void warnsAboutTheSeaOneBlockAboveTheDimensionFloor() throws Exception { + String noInlets = hydrology("lava", "lava", LAVA).replace("\"underground\": {", "\"underground\": {\"seaInlets\": {\"enabled\": false}, "); + PackHydrologyValidator.Validation validation = validate(pack(dimension(noInlets, "\"fluidHeight\": -63,"))); + + assertTrue(validation.errors().toString(), validation.errors().isEmpty()); + assertContains(validation.warnings(), "where its rivers meet the sea"); + } + private static String hydrology(String streamFluid, String riverFluid, String fluids) { return """ {"enabled": true, @@ -806,6 +973,10 @@ public class PackHydrologyValidatorTest { return pack; } + private static final class NamedZones { + private Map zones; + } + private PackHydrologyValidator.Validation validate(File pack) { File[] dimensions = new File(pack, "dimensions").listFiles( file -> file.isFile() && file.getName().endsWith(".json")); From 4ddbcc9c973147244c60eab9b658aeff80717235 Mon Sep 17 00:00:00 2001 From: Brian Fopiano Date: Mon, 2 Nov 2026 19:01:55 -0500 Subject: [PATCH 5/8] Force place ignores water - Add ObjectWaterRule with KEEP_OUT, ENTERS_WATER and FORCED, carried through placers, mutation logs and source plans - Skip the whole hydrology veto for forced placements in MantleWriter, ObjectDestinationTransaction and FloatingObjectPlacementTransaction - Skip the hydrology-support and uneven-water rejections for every forcePlace placement - Admit forced Iris pieces past the 10% limit and the submerged start check in IrisStructureLocator - Decide piece mode and forcing once in IrisStructurePlacement so locate and generation agree - Remove forcedByStructure, now covered by forcePlace - Update tests to the new behaviour, including a piece inside a river and a forced object over a channel --- .../FloatingObjectPlacementTransaction.java | 13 +-- .../mantle/IrisStructureComponent.java | 32 +++---- .../mantle/MantleFloatingObjectComponent.java | 6 +- .../mantle/MantleObjectComponent.java | 8 +- .../iris/generation/mantle/MantleWriter.java | 11 ++- .../iris/generation/mantle/MutationLog.java | 17 ++-- .../mantle/ObjectDestinationTransaction.java | 39 ++++---- .../mantle/ObjectHydrologyVeto.java | 11 ++- .../generation/mantle/ObjectPassPlacer.java | 3 +- .../generation/mantle/ObjectSourcePlan.java | 21 ++++- .../structure/object/IrisObjectPlacement.java | 9 +- .../structure/object/ObjectWaterRule.java | 7 ++ .../object/PlacementModuleSurfaceSupport.java | 4 +- .../placement/IrisStructureLocator.java | 13 ++- .../placement/IrisStructurePlacement.java | 14 +++ ...loatingObjectPlacementTransactionTest.java | 23 +++-- .../IrisStructureComponentCarveWaterTest.java | 7 +- .../IrisStructureComponentWaterTest.java | 91 ++++++++++++------- ...ntleObjectComponentWaterPlacementTest.java | 7 +- .../mantle/MantleWriterObjectWaterTest.java | 21 ++++- .../generation/mantle/MutationLogTest.java | 13 ++- .../mantle/ObjectContinuationCanopyTest.java | 3 +- .../mantle/ObjectContinuationTest.java | 7 +- .../ObjectDestinationTransactionTest.java | 36 +++++--- .../IrisObjectPlacementToPlacementTest.java | 2 - .../PlacementModuleSurfaceSupportTest.java | 13 ++- .../IrisStructureLocatorContractTest.java | 40 ++++++++ 27 files changed, 310 insertions(+), 161 deletions(-) create mode 100644 core/src/main/java/art/arcane/iris/structure/object/ObjectWaterRule.java diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/FloatingObjectPlacementTransaction.java b/core/src/main/java/art/arcane/iris/generation/mantle/FloatingObjectPlacementTransaction.java index afbdc068f..df5bbf36a 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/FloatingObjectPlacementTransaction.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/FloatingObjectPlacementTransaction.java @@ -23,6 +23,7 @@ import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.structure.object.IObjectPlacer; import art.arcane.iris.generation.block.TileData; +import art.arcane.iris.structure.object.ObjectWaterRule; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; import art.arcane.volmlib.util.math.BlockPosition; import art.arcane.iris.generation.block.B; @@ -44,18 +45,18 @@ final class FloatingObjectPlacementTransaction implements IObjectPlacer { private final ObjectContinuationBundle.PlacementKey placementKey; private final KList mutations; private final Map bufferedBlocks; - private final boolean entersWater; + private final ObjectWaterRule waterRule; private ObjectHydrologyVeto waterVeto; private int blockWrites; private BlockPosition canopyPosition; FloatingObjectPlacementTransaction(IObjectPlacer delegate, ObjectContinuationBundle.PlacementKey placementKey, - boolean entersWater) { + ObjectWaterRule waterRule) { this.delegate = Objects.requireNonNull(delegate); this.placementKey = Objects.requireNonNull(placementKey); this.mutations = new KList<>(); this.bufferedBlocks = new HashMap<>(); - this.entersWater = entersWater; + this.waterRule = waterRule; } CommitResult commit() { @@ -161,7 +162,7 @@ final class FloatingObjectPlacementTransaction implements IObjectPlacer { @Override public void set(int x, int y, int z, NativeBlockState state) { - if (state == null || waterVeto().keepsBlock(x, y, z, state, entersWater)) { + if (state == null || waterVeto().keepsBlock(x, y, z, state, waterRule)) { return; } mutations.add(new BlockMutation(x, y, z, state, isCanopy(x, y, z))); @@ -251,9 +252,9 @@ final class FloatingObjectPlacementTransaction implements IObjectPlacer { private boolean keepsWater(int x, int y, int z, Object data) { if (data instanceof NativeBlockState state) { - return waterVeto().keepsBlock(x, y, z, state, entersWater); + return waterVeto().keepsBlock(x, y, z, state, waterRule); } - return data instanceof MatterCavern && waterVeto().keeps(x, y, z, false, entersWater); + return data instanceof MatterCavern && waterVeto().keeps(x, y, z, false, waterRule); } private ObjectHydrologyVeto waterVeto() { diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/IrisStructureComponent.java b/core/src/main/java/art/arcane/iris/generation/mantle/IrisStructureComponent.java index c5e1699c6..8582d2d0c 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/IrisStructureComponent.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/IrisStructureComponent.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.mantle; +import art.arcane.iris.structure.object.ObjectWaterRule; import art.arcane.volmlib.util.structure.StructureCarvingFootprint; import art.arcane.volmlib.util.structure.StructureCarveEnvelope; @@ -162,29 +163,19 @@ public class IrisStructureComponent extends IrisMantleComponent { KList pieces, RNG rng) { IrisStructureStiltSettings stilt = placement.getStilt(); PieceRun run = new PieceRun(structure, rng, stilt == null ? null : new Long2IntOpenHashMap(), - stilt != null && stilt.isSupportNonOccluding(), placement.isAllowWater()); - ObjectPlaceMode mode = structure.getPlaceMode(); + stilt != null && stilt.isSupportNonOccluding()); + ObjectPlaceMode mode = placement.pieceMode(structure, pieces.size()); + boolean forced = placement.forcesPieces(structure, pieces.size()); + boolean sampledHeight = forced && !placement.isAnchoredUnderground(); + ObjectWaterRule rule = forced ? ObjectWaterRule.FORCED + : placement.isAllowWater() ? ObjectWaterRule.ENTERS_WATER : ObjectWaterRule.KEEP_OUT; int failedPieces = 0; - writer.beginObjectPlacement(run.allowWater()); + writer.beginObjectPlacement(rule); try { - if (placement.isAnchoredUnderground()) { - ObjectPlaceMode undergroundMode = (mode == ObjectPlaceMode.ORGANIC_STILT || mode == ObjectPlaceMode.CEILING_HANG) - ? mode : ObjectPlaceMode.STRUCTURE_PIECE; - for (PlacedStructurePiece p : pieces) { - if (placeObject(writer, run, p, undergroundMode, false) == -1) { - failedPieces++; - } - } - } else if (pieces.size() == 1 && mode != ObjectPlaceMode.STRUCTURE_PIECE && mode != ObjectPlaceMode.FLOATING) { - if (placeObject(writer, run, pieces.getFirst(), mode, true) == -1) { + for (PlacedStructurePiece p : pieces) { + if (placeObject(writer, run, p, mode, sampledHeight) == -1) { failedPieces++; } - } else { - for (PlacedStructurePiece p : pieces) { - if (placeObject(writer, run, p, ObjectPlaceMode.STRUCTURE_PIECE, false) == -1) { - failedPieces++; - } - } } if (failedPieces == 0 && stilt != null) { placeFoundation(writer, run.foundationColumns(), stilt, rng, !placement.isAnchoredUnderground()); @@ -593,7 +584,6 @@ public class IrisStructureComponent extends IrisMantleComponent { } if (mode != ObjectPlaceMode.STRUCTURE_PIECE && mode != ObjectPlaceMode.FLOATING) { config.setForcePlace(true); - config.setForcedByStructure(true); } return config; } @@ -720,6 +710,6 @@ public class IrisStructureComponent extends IrisMantleComponent { } private record PieceRun(IrisStructure structure, RNG rng, Long2IntOpenHashMap foundationColumns, - boolean supportNonOccluding, boolean allowWater) { + boolean supportNonOccluding) { } } diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/MantleFloatingObjectComponent.java b/core/src/main/java/art/arcane/iris/generation/mantle/MantleFloatingObjectComponent.java index bf2aef4be..2074ec042 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/MantleFloatingObjectComponent.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/MantleFloatingObjectComponent.java @@ -217,7 +217,7 @@ public class MantleFloatingObjectComponent extends IrisMantleComponent { int id = rng.i(0, Integer.MAX_VALUE); FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction( - writer, placements.next(minX >> 4, minZ >> 4), placement.entersWater()); + writer, placements.next(minX >> 4, minZ >> 4), placement.waterRule()); try { int resultY = obj.place(xx, zz, transaction, floatingPlacement, rng, (b, bd) -> { String marker = placementMarker(obj, id); @@ -312,7 +312,7 @@ public class MantleFloatingObjectComponent extends IrisMantleComponent { IslandObjectPlacer islandPlacer = IslandObjectPlacer.top(writer, sampleProvider, entry, pickTopY); FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction( - islandPlacer, placements.next(minX >> 4, minZ >> 4), placement.entersWater()); + islandPlacer, placements.next(minX >> 4, minZ >> 4), placement.waterRule()); int id = rng.i(0, Integer.MAX_VALUE); try { @@ -426,7 +426,7 @@ public class MantleFloatingObjectComponent extends IrisMantleComponent { IslandObjectPlacer islandPlacer = IslandObjectPlacer.bottom(writer, sampleProvider, entry, pickBottomY); FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction( - islandPlacer, placements.next(minX >> 4, minZ >> 4), placement.entersWater()); + islandPlacer, placements.next(minX >> 4, minZ >> 4), placement.waterRule()); int id = rng.i(0, Integer.MAX_VALUE); try { diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java b/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java index edaf0f86a..3cbafb881 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java @@ -751,7 +751,7 @@ public class MantleObjectComponent extends IrisMantleComponent { try { int placeResult = -1; CaveObjectPlacementTransaction.CommitResult commitResult = CaveObjectPlacementTransaction.CommitResult.EMPTY; - int continuation = writer.beginObjectPlacement(placement.entersWater()); + int continuation = writer.beginObjectPlacement(placement.waterRule()); if (carving) { int caveFloorY = caveAnchor.y(); if (golden) { @@ -1015,7 +1015,7 @@ public class MantleObjectComponent extends IrisMantleComponent { } try { String marker = placementMarker(v, id, "surface"); - int continuation = writer.beginObjectPlacement(effectivePlacement.entersWater()); + int continuation = writer.beginObjectPlacement(effectivePlacement.waterRule()); int result = v.place(xx, zz, placePlacer, effectivePlacement, rng, (b, data) -> { if (marker != null) { writer.setData(b.getX(), b.getY(), b.getZ(), marker); @@ -1202,7 +1202,7 @@ public class MantleObjectComponent extends IrisMantleComponent { IrisObjectPlacement effectivePlacement = resolveCavePlacement(objectPlacement, object, caveProfile); try { - int continuation = writer.beginObjectPlacement(effectivePlacement.entersWater()); + int continuation = writer.beginObjectPlacement(effectivePlacement.waterRule()); ContainedPlacementResult contained = placeContainedCaveObject( writer, object, @@ -1400,7 +1400,7 @@ public class MantleObjectComponent extends IrisMantleComponent { } boolean treePlacement = isTreePlacement(v, objectPlacement); String marker = placementMarker(v, id, "upper"); - int continuation = writer.beginObjectPlacement(placement.entersWater()); + int continuation = writer.beginObjectPlacement(placement.waterRule()); int result; try { result = v.place(xx, anchorY, zz, writer, placement, rng, (b, data) -> { diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/MantleWriter.java b/core/src/main/java/art/arcane/iris/generation/mantle/MantleWriter.java index 40e49cf82..29630cb94 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/MantleWriter.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/MantleWriter.java @@ -20,6 +20,7 @@ package art.arcane.iris.generation.mantle; import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.structure.object.ObjectWaterRule; import art.arcane.iris.world.storage.matter.TileWrapper; import art.arcane.iris.world.storage.matter.PreObjectMatterCell; import art.arcane.iris.configuration.IrisSettings; @@ -221,8 +222,8 @@ public class MantleWriter implements ObjectPassPlacer, AutoCloseable { } @Override - public int beginObjectPlacement(boolean entersWater) { - objectWater.set(new ObjectWater(ObjectHydrologyVeto.of(getEngine()), entersWater)); + public int beginObjectPlacement(ObjectWaterRule rule) { + objectWater.set(new ObjectWater(ObjectHydrologyVeto.of(getEngine()), rule)); return -1; } @@ -237,9 +238,9 @@ public class MantleWriter implements ObjectPassPlacer, AutoCloseable { return false; } if (value instanceof NativeBlockState state) { - return water.veto().keepsBlock(x, y, z, state, water.entersWater()); + return water.veto().keepsBlock(x, y, z, state, water.rule()); } - return value instanceof MatterCavern && water.veto().keeps(x, y, z, false, water.entersWater()); + return value instanceof MatterCavern && water.veto().keeps(x, y, z, false, water.rule()); } private void recordObjectValue(int x, int y, int z, Class type, Object value) { @@ -1034,7 +1035,7 @@ public class MantleWriter implements ObjectPassPlacer, AutoCloseable { naturalOpening ? ALWAYS : NEVER, cavern ? ALWAYS : NEVER) ? (byte) 1 : 0; } - private record ObjectWater(ObjectHydrologyVeto veto, boolean entersWater) { + private record ObjectWater(ObjectHydrologyVeto veto, ObjectWaterRule rule) { } public final class ObjectPlacementCapture implements AutoCloseable { diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/MutationLog.java b/core/src/main/java/art/arcane/iris/generation/mantle/MutationLog.java index 9ee50d17a..0386bc194 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/MutationLog.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/MutationLog.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.mantle; +import art.arcane.iris.structure.object.ObjectWaterRule; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; import java.util.Arrays; @@ -10,6 +11,7 @@ final class MutationLog { private static final byte CUSTOM = 1; private static final byte CANOPY = 2; private static final byte ENTERS_WATER = 4; + private static final byte FORCED = 8; private int size; private int[] x = new int[32]; @@ -30,16 +32,16 @@ final class MutationLog { throw new IllegalArgumentException("Object mutation type " + key.type().getName() + " does not match its value " + value.getClass().getName()); } - log.add(key.x(), key.y(), key.z(), value, false, set.canopy(), false); + log.add(key.x(), key.y(), key.z(), value, false, set.canopy(), ObjectWaterRule.KEEP_OUT); } case ObjectDestinationTransaction.CustomBlockMutation block -> log.add(key.x(), key.y(), key.z(), - Objects.requireNonNull(block.state(), "custom block state"), true, block.canopy(), false); + Objects.requireNonNull(block.state(), "custom block state"), true, block.canopy(), ObjectWaterRule.KEEP_OUT); } } return log; } - void add(int blockX, int blockY, int blockZ, Object value, boolean custom, boolean canopy, boolean entersWater) { + void add(int blockX, int blockY, int blockZ, Object value, boolean custom, boolean canopy, ObjectWaterRule rule) { if (size == values.length) { int capacity = size * 2; x = Arrays.copyOf(x, capacity); @@ -52,7 +54,7 @@ final class MutationLog { y[size] = blockY; z[size] = blockZ; values[size] = value; - flags[size] = (byte) ((custom ? CUSTOM : 0) | (canopy ? CANOPY : 0) | (entersWater ? ENTERS_WATER : 0)); + flags[size] = (byte) ((custom ? CUSTOM : 0) | (canopy ? CANOPY : 0) | (rule == ObjectWaterRule.ENTERS_WATER ? ENTERS_WATER : 0) | (rule == ObjectWaterRule.FORCED ? FORCED : 0)); size++; } @@ -84,8 +86,11 @@ final class MutationLog { return (flags[index] & CANOPY) != 0; } - boolean entersWater(int index) { - return (flags[index] & ENTERS_WATER) != 0; + ObjectWaterRule waterRule(int index) { + if ((flags[index] & FORCED) != 0) { + return ObjectWaterRule.FORCED; + } + return (flags[index] & ENTERS_WATER) != 0 ? ObjectWaterRule.ENTERS_WATER : ObjectWaterRule.KEEP_OUT; } Class type(int index) { diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/ObjectDestinationTransaction.java b/core/src/main/java/art/arcane/iris/generation/mantle/ObjectDestinationTransaction.java index 907ced8e6..1e8b36c8f 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/ObjectDestinationTransaction.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/ObjectDestinationTransaction.java @@ -7,6 +7,7 @@ import art.arcane.iris.generation.decoration.tree.TreeBlockMaterial; import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell; import art.arcane.iris.generation.subterrain.SubterrainRasterizer; import art.arcane.iris.generation.block.TileData; +import art.arcane.iris.structure.object.ObjectWaterRule; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; import art.arcane.volmlib.util.math.BlockPosition; import art.arcane.iris.generation.block.B; @@ -41,7 +42,7 @@ final class ObjectDestinationTransaction implements ObjectPassPlacer { private int subterrainZ; private boolean subterrainProtects; private ObjectHydrologyVeto waterVeto; - private boolean waterPlacement; + private ObjectWaterRule waterRule = ObjectWaterRule.KEEP_OUT; ObjectDestinationTransaction(MantleWriter writer, int destinationChunkX, int destinationChunkZ) { this.writer = writer; @@ -73,8 +74,8 @@ final class ObjectDestinationTransaction implements ObjectPassPlacer { } @Override - public int beginObjectPlacement(boolean entersWater) { - waterPlacement = entersWater; + public int beginObjectPlacement(ObjectWaterRule rule) { + waterRule = rule; return log.size(); } @@ -87,7 +88,7 @@ final class ObjectDestinationTransaction implements ObjectPassPlacer { @Override public void endObjectPlacement() { - waterPlacement = false; + waterRule = ObjectWaterRule.KEEP_OUT; } void apply(ObjectSourcePlan plan) { @@ -107,7 +108,7 @@ final class ObjectDestinationTransaction implements ObjectPassPlacer { Object value = plan.valueAt(index); boolean custom = ObjectSourcePlan.isCustom(cell); boolean canopy = ObjectSourcePlan.isCanopy(cell); - boolean entersWater = ObjectSourcePlan.entersWater(cell); + ObjectWaterRule rule = ObjectSourcePlan.waterRule(cell); if (custom || value instanceof NativeBlockState) { NativeBlockState existing = canopy ? get(x, y, z) : null; skipCanopy = existing != null && existing.isSolid(); @@ -116,9 +117,9 @@ final class ObjectDestinationTransaction implements ObjectPassPlacer { continue; } if (custom) { - set(x, y, z, (NativeBlockState) value, canopy, entersWater); + set(x, y, z, (NativeBlockState) value, canopy, rule); } else { - setData(x, y, z, value, canopy, entersWater); + setData(x, y, z, value, canopy, rule); } } } @@ -183,17 +184,17 @@ final class ObjectDestinationTransaction implements ObjectPassPlacer { @Override public void set(int x, int y, int z, NativeBlockState state) { - set(x, y, z, state, isCanopy(x, y, z), waterPlacement); + set(x, y, z, state, isCanopy(x, y, z), waterRule); } - private void set(int x, int y, int z, NativeBlockState state, boolean canopy, boolean entersWater) { + private void set(int x, int y, int z, NativeBlockState state, boolean canopy, ObjectWaterRule rule) { if (state == null) { return; } String placementKey = state.deferredPlacementKey(); NativeBlockState baseState = state.placementBaseState(); if (state.isCustom() && placementKey != null && baseState != null) { - if (!canSetBlock(x, y, z) || hydrologyKeeps(x, y, z, baseState.isSolid(), entersWater)) { + if (!canSetBlock(x, y, z) || hydrologyKeeps(x, y, z, baseState.isSolid(), rule)) { return; } Identifier identifier = Identifier.fromString(placementKey); @@ -201,10 +202,10 @@ final class ObjectDestinationTransaction implements ObjectPassPlacer { cell.block = baseState; cell.tile = CLEARED; cell.identifier = identifier; - log.add(x, y, z, state, true, canopy, entersWater); + log.add(x, y, z, state, true, canopy, rule); return; } - setData(x, y, z, state, canopy, entersWater); + setData(x, y, z, state, canopy, rule); } @Override @@ -295,18 +296,18 @@ final class ObjectDestinationTransaction implements ObjectPassPlacer { @Override public void setData(int x, int y, int z, T data) { - setData(x, y, z, data, isCanopy(x, y, z), waterPlacement); + setData(x, y, z, data, isCanopy(x, y, z), waterRule); } - private void setData(int x, int y, int z, Object data, boolean canopy, boolean entersWater) { + private void setData(int x, int y, int z, Object data, boolean canopy, ObjectWaterRule rule) { if (data == null || y < 0 || y >= worldHeight || protectsSubterrain(x, y, z)) { return; } - if (data instanceof NativeBlockState state && (!canSetBlock(x, y, z) || hydrologyKeeps(x, y, z, state.isSolid(), entersWater))) { + if (data instanceof NativeBlockState state && (!canSetBlock(x, y, z) || hydrologyKeeps(x, y, z, state.isSolid(), rule))) { return; } - if (data instanceof MatterCavern && (hasProtectedHydrology(x, y, z) || hydrologyKeeps(x, y, z, false, entersWater))) { + if (data instanceof MatterCavern && (hasProtectedHydrology(x, y, z) || hydrologyKeeps(x, y, z, false, rule))) { return; } Class type = data instanceof NativeBlockState ? NativeBlockState.class : data.getClass(); @@ -318,7 +319,7 @@ final class ObjectDestinationTransaction implements ObjectPassPlacer { } else { cell.put(type, data); } - log.add(x, y, z, data, false, canopy, entersWater); + log.add(x, y, z, data, false, canopy, rule); } @Override @@ -415,11 +416,11 @@ final class ObjectDestinationTransaction implements ObjectPassPlacer { && !protectsSubterrain(x, y, z); } - private boolean hydrologyKeeps(int x, int y, int z, boolean solid, boolean entersWater) { + private boolean hydrologyKeeps(int x, int y, int z, boolean solid, ObjectWaterRule rule) { if (waterVeto == null) { waterVeto = ObjectHydrologyVeto.of(getEngine()); } - return waterVeto.keeps(x, y, z, solid, entersWater); + return waterVeto.keeps(x, y, z, solid, rule); } private boolean protectsSubterrain(int x, int y, int z) { diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/ObjectHydrologyVeto.java b/core/src/main/java/art/arcane/iris/generation/mantle/ObjectHydrologyVeto.java index 19de6e261..e9d70fbdb 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/ObjectHydrologyVeto.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/ObjectHydrologyVeto.java @@ -5,6 +5,7 @@ import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster; import art.arcane.iris.generation.hydrology.raster.WaterRole; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.IrisComplex; +import art.arcane.iris.structure.object.ObjectWaterRule; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; final class ObjectHydrologyVeto { @@ -25,13 +26,13 @@ final class ObjectHydrologyVeto { return runtime != null && runtime.enabled() ? new ObjectHydrologyVeto(complex, runtime) : NONE; } - boolean keepsBlock(int x, int y, int z, NativeBlockState state, boolean entersWater) { + boolean keepsBlock(int x, int y, int z, NativeBlockState state, ObjectWaterRule rule) { NativeBlockState base = state.isCustom() && state.placementBaseState() != null ? state.placementBaseState() : state; - return keeps(x, y, z, base.isSolid(), entersWater); + return keeps(x, y, z, base.isSolid(), rule); } - boolean keeps(int x, int y, int z, boolean solid, boolean entersWater) { - if (runtime == null) { + boolean keeps(int x, int y, int z, boolean solid, ObjectWaterRule rule) { + if (runtime == null || rule == ObjectWaterRule.FORCED) { return false; } ChunkWaterRaster raster = runtime.raster(x >> 4, z >> 4); @@ -42,7 +43,7 @@ final class ObjectHydrologyVeto { if (role == WaterRole.INLET && y >= raster.waterHead(x & 15, z & 15) && y <= complex.naturalTrueHeight(x, z)) { return true; } - if (solid && !entersWater && fillsWater(x, y, z)) { + if (solid && rule != ObjectWaterRule.ENTERS_WATER && fillsWater(x, y, z)) { return true; } if (role.wet()) { diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/ObjectPassPlacer.java b/core/src/main/java/art/arcane/iris/generation/mantle/ObjectPassPlacer.java index 1d3ab669f..f26600df9 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/ObjectPassPlacer.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/ObjectPassPlacer.java @@ -1,6 +1,7 @@ package art.arcane.iris.generation.mantle; import art.arcane.iris.structure.object.IObjectPlacer; +import art.arcane.iris.structure.object.ObjectWaterRule; import org.jetbrains.annotations.Nullable; public interface ObjectPassPlacer extends IObjectPlacer { @@ -8,7 +9,7 @@ public interface ObjectPassPlacer extends IObjectPlacer { byte[] getCarvedColumn(int x, int z, int height); - default int beginObjectPlacement(boolean entersWater) { + default int beginObjectPlacement(ObjectWaterRule rule) { return -1; } diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/ObjectSourcePlan.java b/core/src/main/java/art/arcane/iris/generation/mantle/ObjectSourcePlan.java index 21bb4a652..f1afbeb33 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/ObjectSourcePlan.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/ObjectSourcePlan.java @@ -3,6 +3,7 @@ package art.arcane.iris.generation.mantle; import art.arcane.iris.generation.decoration.tree.TreeBlockMaterial; import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell; import art.arcane.iris.integration.Identifier; +import art.arcane.iris.structure.object.ObjectWaterRule; import art.arcane.iris.world.storage.matter.IrisMatterSupport; import art.arcane.iris.world.storage.matter.TileWrapper; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; @@ -33,7 +34,8 @@ final class ObjectSourcePlan { private static final int CUSTOM_BIT = 1 << 8; private static final int CANOPY_BIT = 1 << 9; private static final int ENTERS_WATER_BIT = 1 << 10; - private static final int Y_SHIFT = 11; + private static final int FORCED_BIT = 1 << 11; + private static final int Y_SHIFT = 12; private static final int MAXIMUM_Y = (1 << (31 - Y_SHIFT)) - 1; private final long[] destinations; @@ -91,7 +93,7 @@ final class ObjectSourcePlan { throw new IllegalArgumentException("Object mutation height is outside the plan range: " + y); } cells[position] = (y << Y_SHIFT) | (log.custom(logged) ? CUSTOM_BIT : 0) | (log.canopy(logged) ? CANOPY_BIT : 0) - | (log.entersWater(logged) ? ENTERS_WATER_BIT : 0) | ((log.z(logged) & 15) << 4) | (log.x(logged) & 15); + | waterBits(log.waterRule(logged)) | ((log.z(logged) & 15) << 4) | (log.x(logged) & 15); valueIndexes[position] = table.indexOf(log.value(logged)); } values = table.values.toArray(); @@ -242,8 +244,19 @@ final class ObjectSourcePlan { return (cell & CANOPY_BIT) != 0; } - static boolean entersWater(int cell) { - return (cell & ENTERS_WATER_BIT) != 0; + static ObjectWaterRule waterRule(int cell) { + if ((cell & FORCED_BIT) != 0) { + return ObjectWaterRule.FORCED; + } + return (cell & ENTERS_WATER_BIT) != 0 ? ObjectWaterRule.ENTERS_WATER : ObjectWaterRule.KEEP_OUT; + } + + private static int waterBits(ObjectWaterRule rule) { + return switch (rule) { + case KEEP_OUT -> 0; + case ENTERS_WATER -> ENTERS_WATER_BIT; + case FORCED -> FORCED_BIT; + }; } ObjectDestinationTransaction.Mutation mutationAt(int chunkX, int chunkZ, int index) { diff --git a/core/src/main/java/art/arcane/iris/structure/object/IrisObjectPlacement.java b/core/src/main/java/art/arcane/iris/structure/object/IrisObjectPlacement.java index 843d46f82..60d98d731 100644 --- a/core/src/main/java/art/arcane/iris/structure/object/IrisObjectPlacement.java +++ b/core/src/main/java/art/arcane/iris/structure/object/IrisObjectPlacement.java @@ -201,7 +201,6 @@ public class IrisObjectPlacement { @Description("Ignore any placement restrictions for this object") @SerializedName(value = "forcePlace", alternate = {"force"}) private boolean forcePlace = false; - private transient boolean forcedByStructure = false; private transient AtomicCache cache = new AtomicCache<>(); private transient AtomicCache compatCache = new AtomicCache<>(); @Getter(AccessLevel.NONE) @@ -307,8 +306,11 @@ public class IrisObjectPlacement { return place.size() == 1 ? place.getFirst() : place.toString(", "); } - public boolean entersWater() { - return underwater || onwater || forcePlace && !forcedByStructure; + public ObjectWaterRule waterRule() { + if (forcePlace) { + return ObjectWaterRule.FORCED; + } + return underwater || onwater ? ObjectWaterRule.ENTERS_WATER : ObjectWaterRule.KEEP_OUT; } public IrisObjectPlacement toPlacement(String... place) { @@ -354,7 +356,6 @@ public class IrisObjectPlacement { p.setAllowedCollisions(allowedCollisions); p.setForbiddenCollisions(forbiddenCollisions); p.setForcePlace(forcePlace); - p.setForcedByStructure(forcedByStructure); return p; } diff --git a/core/src/main/java/art/arcane/iris/structure/object/ObjectWaterRule.java b/core/src/main/java/art/arcane/iris/structure/object/ObjectWaterRule.java new file mode 100644 index 000000000..a4d167ce4 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/structure/object/ObjectWaterRule.java @@ -0,0 +1,7 @@ +package art.arcane.iris.structure.object; + +public enum ObjectWaterRule { + KEEP_OUT, + ENTERS_WATER, + FORCED +} diff --git a/core/src/main/java/art/arcane/iris/structure/object/PlacementModuleSurfaceSupport.java b/core/src/main/java/art/arcane/iris/structure/object/PlacementModuleSurfaceSupport.java index ded7f78d2..f182e5f3c 100644 --- a/core/src/main/java/art/arcane/iris/structure/object/PlacementModuleSurfaceSupport.java +++ b/core/src/main/java/art/arcane/iris/structure/object/PlacementModuleSurfaceSupport.java @@ -56,12 +56,12 @@ final class PlacementModuleSurfaceSupport implements PlacementModule { private static String hydrologyRejection(PlacementContext context, PlacementState state) { IrisObjectPlacement config = state.config; - if (!context.automatic || config.isForcedByStructure() || !config.getCarvingSupport().supportsSurface() + if (!context.automatic || config.isForcePlace() || !config.getCarvingSupport().supportsSurface() || config.getMode() == ObjectPlaceMode.FLOATING || config.getMode() == ObjectPlaceMode.STRUCTURE_PIECE) { return null; } boolean painted = state.paintProjection != null; - if (config.entersWater()) { + if (config.waterRule() == ObjectWaterRule.ENTERS_WATER) { return (painted ? IrisSurfaceSupport.intersectsUnevenWater(context.placer, context.x, context.z, null, null, 0, 0, 0, state.paintSupport) : IrisSurfaceSupport.intersectsUnevenWater(context.placer, context.x, context.z, config.getTranslate(), diff --git a/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureLocator.java b/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureLocator.java index 4728e977d..184167c5b 100644 --- a/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureLocator.java +++ b/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureLocator.java @@ -536,6 +536,11 @@ public final class IrisStructureLocator { // Gated out on this Minecraft version; the pack report already says why. return null; } + boolean submerged = !placement.resolvedAnchor().isCave() && !placement.isUnderwater() + && NativeStructurePlacementPlanner.isSubmerged(engine, originX, originZ); + if (submerged && !placement.forcesPieces(structure, 1)) { + return null; + } StructureGraphCompilation compilation = StructureGraphCatalog.compile(engine.getData(), structure); if (!compilation.isAssemblyViable()) { throw new IllegalStateException("Iris structure '" + selectedKey @@ -545,6 +550,9 @@ public final class IrisStructureLocator { StructureAssembler assembler = StructureAssembler.forData( engine.getData(), structure, new IrisPosition(originX, baseY, originZ)); StructureAssemblyResult assembly = assembler.assemble(rng); + if (submerged && !placement.forcesPieces(structure, assembly.pieces().size())) { + return null; + } if (!requirePlacementOutput(placement, selectedKey, cx, cz, assembly.hasOutput(), "runtime assembly produced " + assembly.status() + ": " + assembly.detail())) { return null; @@ -593,6 +601,7 @@ public final class IrisStructureLocator { return null; } if (!placement.isAnchoredUnderground() && !placement.isAllowWater() + && !placement.forcesPieces(structure, pieces.size()) && !StructureWaterRules.admitsFootprint(IrisStructureWater.mantle(engine.getComplex()), pieceFootprints(pieces))) { return null; } @@ -687,10 +696,6 @@ public final class IrisStructureLocator { if (worldMin > worldMax) { return null; } - if (!placement.isUnderwater() - && NativeStructurePlacementPlanner.isSubmerged(engine, originX, originZ)) { - return null; - } if (placement.resolvedAnchor() == IrisStructureAnchorMode.SURFACE) { int surfaceY = Engine.hostHeight(engine, originX, originZ, true) + engine.getMinHeight(); return surfaceY < placement.getMinHeight() || surfaceY > placement.getMaxHeight() ? null : surfaceY; diff --git a/core/src/main/java/art/arcane/iris/structure/placement/IrisStructurePlacement.java b/core/src/main/java/art/arcane/iris/structure/placement/IrisStructurePlacement.java index 902f4bdbc..4ea3d1233 100644 --- a/core/src/main/java/art/arcane/iris/structure/placement/IrisStructurePlacement.java +++ b/core/src/main/java/art/arcane/iris/structure/placement/IrisStructurePlacement.java @@ -18,6 +18,7 @@ package art.arcane.iris.structure.placement; +import art.arcane.iris.structure.object.ObjectPlaceMode; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.pack.validation.CompatPools; import art.arcane.iris.structure.nativegen.IrisNativeStructure; @@ -152,6 +153,19 @@ public class IrisStructurePlacement { return anchor; } + public ObjectPlaceMode pieceMode(IrisStructure structure, int pieces) { + ObjectPlaceMode mode = structure.getPlaceMode(); + if (isAnchoredUnderground()) { + return mode == ObjectPlaceMode.ORGANIC_STILT || mode == ObjectPlaceMode.CEILING_HANG + ? mode : ObjectPlaceMode.STRUCTURE_PIECE; + } + return pieces == 1 && mode != ObjectPlaceMode.FLOATING ? mode : ObjectPlaceMode.STRUCTURE_PIECE; + } + + public boolean forcesPieces(IrisStructure structure, int pieces) { + return pieceMode(structure, pieces) != ObjectPlaceMode.STRUCTURE_PIECE; + } + public boolean isAnchoredUnderground() { IrisStructureAnchorMode activeAnchor = resolvedAnchor(); return activeAnchor == IrisStructureAnchorMode.HEIGHT_BAND || activeAnchor.isCave(); diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/FloatingObjectPlacementTransactionTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/FloatingObjectPlacementTransactionTest.java index 095e8d84e..a63811bdb 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/FloatingObjectPlacementTransactionTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/FloatingObjectPlacementTransactionTest.java @@ -24,6 +24,7 @@ import art.arcane.iris.generation.hydrology.raster.WaterRole; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.block.TileData; +import art.arcane.iris.structure.object.ObjectWaterRule; import art.arcane.volmlib.util.stream.ProceduralStream; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; import art.arcane.volmlib.util.math.BlockPosition; @@ -54,7 +55,7 @@ public class FloatingObjectPlacementTransactionTest { public void canopyCommitRechecksSolidsAndSkipsAssociatedMetadata() { IslandObjectPlacer delegate = createPlacer(true); FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction(delegate, - new ObjectContinuationBundle.PlacementKey(ObjectContinuationBundle.Kind.FLOATING, 0, 0, 0), false); + new ObjectContinuationBundle.PlacementKey(ObjectContinuationBundle.Kind.FLOATING, 0, 0, 0), ObjectWaterRule.KEEP_OUT); NativeBlockState canopy = mock(NativeBlockState.class); NativeBlockState trunk = mock(NativeBlockState.class); when(trunk.isSolid()).thenReturn(true); @@ -76,7 +77,7 @@ public class FloatingObjectPlacementTransactionTest { public void unsupportedFinalTerrainRejectsBlocksTilesAndMarkersTogether() { IslandObjectPlacer delegate = createPlacer(false); FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction(delegate, - new ObjectContinuationBundle.PlacementKey(ObjectContinuationBundle.Kind.FLOATING, 0, 0, 0), false); + new ObjectContinuationBundle.PlacementKey(ObjectContinuationBundle.Kind.FLOATING, 0, 0, 0), ObjectWaterRule.KEEP_OUT); NativeBlockState first = mock(NativeBlockState.class); NativeBlockState second = mock(NativeBlockState.class); TileData tile = mock(TileData.class); @@ -103,7 +104,7 @@ public class FloatingObjectPlacementTransactionTest { public void supportedNeighborChunkCommitsBlocksTilesAndMarkers() { IslandObjectPlacer delegate = createPlacer(true); FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction(delegate, - new ObjectContinuationBundle.PlacementKey(ObjectContinuationBundle.Kind.FLOATING, 0, 0, 0), false); + new ObjectContinuationBundle.PlacementKey(ObjectContinuationBundle.Kind.FLOATING, 0, 0, 0), ObjectWaterRule.KEEP_OUT); NativeBlockState first = mock(NativeBlockState.class); NativeBlockState second = mock(NativeBlockState.class); TileData tile = mock(TileData.class); @@ -149,7 +150,7 @@ public class FloatingObjectPlacementTransactionTest { NativeBlockState state = mock(NativeBlockState.class); when(state.key()).thenReturn("minecraft:oak_log"); ObjectContinuationBundle.PlacementKey key = new ObjectContinuationBundle.PlacementKey(ObjectContinuationBundle.Kind.FLOATING, 0, 0, 7); - FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction(delegate, key, false); + FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction(delegate, key, ObjectWaterRule.KEEP_OUT); transaction.set(15, 101, 8, state); transaction.set(16, 101, 8, state); transaction.setData(16, 101, 8, "floating-tree@7"); @@ -166,7 +167,7 @@ public class FloatingObjectPlacementTransactionTest { @Test @SuppressWarnings("unchecked") - public void floatingObjectsKeepSolidBlocksOutOfRiverWaterUnlessTheyEnterWater() { + public void floatingObjectsFollowTheirWaterRuleInRiverWater() { IObjectPlacer delegate = mock(IObjectPlacer.class); Engine engine = mock(Engine.class); IrisComplex complex = mock(IrisComplex.class); @@ -196,17 +197,25 @@ public class FloatingObjectPlacementTransactionTest { when(stone.isSolid()).thenReturn(true); ObjectContinuationBundle.PlacementKey key = new ObjectContinuationBundle.PlacementKey(ObjectContinuationBundle.Kind.FLOATING, 0, 0, 0); - FloatingObjectPlacementTransaction land = new FloatingObjectPlacementTransaction(delegate, key, false); + FloatingObjectPlacementTransaction land = new FloatingObjectPlacementTransaction(delegate, key, ObjectWaterRule.KEEP_OUT); land.set(3, 7, 3, stone); land.set(3, 10, 3, stone); assertEquals(FloatingObjectPlacementTransaction.CommitResult.COMMITTED, land.commit()); verify(delegate, never()).set(3, 7, 3, stone); verify(delegate).set(3, 10, 3, stone); - FloatingObjectPlacementTransaction water = new FloatingObjectPlacementTransaction(delegate, key, true); + FloatingObjectPlacementTransaction water = new FloatingObjectPlacementTransaction(delegate, key, ObjectWaterRule.ENTERS_WATER); water.set(3, 7, 3, stone); assertEquals(FloatingObjectPlacementTransaction.CommitResult.COMMITTED, water.commit()); verify(delegate).set(3, 7, 3, stone); + + NativeBlockState air = mock(NativeBlockState.class); + FloatingObjectPlacementTransaction forced = new FloatingObjectPlacementTransaction(delegate, key, ObjectWaterRule.FORCED); + forced.set(3, 8, 3, stone); + forced.set(3, 6, 3, air); + assertEquals(FloatingObjectPlacementTransaction.CommitResult.COMMITTED, forced.commit()); + verify(delegate).set(3, 8, 3, stone); + verify(delegate).set(3, 6, 3, air); } private static int local(Object coordinate) { diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureComponentCarveWaterTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureComponentCarveWaterTest.java index e596e266e..9c1037346 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureComponentCarveWaterTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureComponentCarveWaterTest.java @@ -6,6 +6,7 @@ import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.structure.object.ObjectPlaceMode; +import art.arcane.iris.structure.object.ObjectWaterRule; import art.arcane.iris.structure.placement.IrisStructure; import art.arcane.iris.structure.placement.IrisStructurePlacement; import art.arcane.iris.structure.object.IrisObject; @@ -121,10 +122,10 @@ public class IrisStructureComponentCarveWaterTest { component.placePieces(writer, placement, structure, slab(), new RNG(3L)); InOrder order = inOrder(writer); - order.verify(writer).beginObjectPlacement(false); + order.verify(writer).beginObjectPlacement(ObjectWaterRule.KEEP_OUT); order.verify(writer, calls(1)).set(anyInt(), anyInt(), anyInt(), any(NativeBlockState.class)); order.verify(writer).endObjectPlacement(); - order.verify(writer).beginObjectPlacement(true); + order.verify(writer).beginObjectPlacement(ObjectWaterRule.ENTERS_WATER); order.verify(writer, calls(1)).set(anyInt(), anyInt(), anyInt(), any(NativeBlockState.class)); order.verify(writer).endObjectPlacement(); } @@ -151,7 +152,7 @@ public class IrisStructureComponentCarveWaterTest { assertSame(failure, thrown); InOrder order = inOrder(writer); - order.verify(writer).beginObjectPlacement(false); + order.verify(writer).beginObjectPlacement(ObjectWaterRule.KEEP_OUT); order.verify(writer).endObjectPlacement(); } diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureComponentWaterTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureComponentWaterTest.java index 2de86599a..f4e90b18a 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureComponentWaterTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureComponentWaterTest.java @@ -13,6 +13,7 @@ import art.arcane.iris.structure.object.IrisObject; import art.arcane.iris.structure.object.IrisObjectPlacement; import art.arcane.iris.structure.object.IrisObjectRotation; import art.arcane.iris.structure.object.ObjectPlaceMode; +import art.arcane.iris.structure.object.ObjectWaterRule; import art.arcane.iris.structure.placement.IrisStructure; import art.arcane.iris.structure.placement.IrisStructureLocator; import art.arcane.iris.structure.placement.IrisStructurePlacement; @@ -104,18 +105,19 @@ public class IrisStructureComponentWaterTest { } @Test - public void forcedSinglePieceStructureStaysOutOfRiverWater() { + public void aForcedPieceFullyInsideARiverWritesEveryBlock() { world.water(WaterRole.CHANNEL, 9, 13); int failed = placeSinglePiece(new IrisStructurePlacement()); assertEquals(0, failed); - assertFalse("the part of the piece above the water places", writes.isEmpty()); - assertNoWaterOverwritten(); + assertEquals("every block of the raft lands", 10, writes.size()); + assertEquals(world.headAt(X, Z), lowestWriteAt(X, Z)); + assertEquals(world.headAt(X - 1, Z - 1), lowestWriteAt(X - 1, Z - 1)); } @Test - public void forcedSinglePieceStructureTurnedTowardsTheSlopeStaysOutOfRiverWater() { + public void aForcedPieceTurnedTowardsTheSlopeWritesThroughTheRiver() { world.water(WaterRole.CHANNEL, 9, 13); @SuppressWarnings("unchecked") ProceduralStream heights = mock(ProceduralStream.class); @@ -126,17 +128,16 @@ public class IrisStructureComponentWaterTest { IrisObjectPlacement config = IrisStructureComponent.piecePlacement(new IrisStructure(), piece(object), ObjectPlaceMode.CENTER_HEIGHT); config.setRotateTowardsSlope(true); - writer.beginObjectPlacement(false); + writer.beginObjectPlacement(config.waterRule()); int result = object.place(X, Z, writer, config, new RNG(7L), world.data()); writer.endObjectPlacement(); assertTrue(result >= 0); - assertFalse(writes.isEmpty()); - assertNoWaterOverwritten(); + assertEquals(10, writes.size()); } @Test - public void aFewWetSupportColumnsDoNotStopAForcedSinglePiece() { + public void aForcedPieceWritesAcrossWetSupportColumns() { world.column(X + 1, Z, WaterRole.CHANNEL, 15, 19); world.column(X - 1, Z, WaterRole.SHORE, 15, 19); world.column(X, Z + 1, WaterRole.DAM, 15, 19); @@ -145,14 +146,12 @@ public class IrisStructureComponentWaterTest { assertEquals(0, failed); int anchorLayer = lowestWriteAt(X, Z); - assertEquals("the anchor column keeps its block", world.floorAt(X, Z), anchorLayer); - assertTrue("the anchor layer sits inside the river column's water", - anchorLayer > world.floorAt(X + 1, Z) && anchorLayer <= world.headAt(X + 1, Z)); - assertNoWaterOverwritten(); + assertEquals(world.floorAt(X, Z), anchorLayer); + assertEquals("the river column keeps the piece's block", anchorLayer, lowestWriteAt(X + 1, Z)); } @Test - public void replaceSourceKeepsAForcedSinglePieceOverWaterWithoutFailingTheChunk() { + public void replaceSourceKeepsAForcedPieceOverWaterWithoutFailingTheChunk() { world.water(WaterRole.CHANNEL, 9, 13); IrisStructurePlacement placement = new IrisStructurePlacement() .setNativeSuppression(NativeStructureSuppression.REPLACE_SOURCE); @@ -161,36 +160,24 @@ public class IrisStructureComponentWaterTest { IrisStructureComponent.requireAppliedPieces(resolved(placement), 0, 0, failed); assertEquals(0, failed); - assertNoWaterOverwritten(); + assertEquals(10, writes.size()); } @Test - public void replaceSourceKeepsAWaterPieceOnUnevenWaterWithoutFailingTheChunk() { + public void aForcedPieceWritesAcrossAFallWhetherOrNotItAllowsWater() { world.water(WaterRole.CHANNEL, 9, 13); world.column(X + 1, Z, WaterRole.CHANNEL, 9, 16); - IrisStructurePlacement placement = new IrisStructurePlacement() - .setNativeSuppression(NativeStructureSuppression.REPLACE_SOURCE) - .setAllowWater(true); - int failed = placeSinglePiece(placement); + assertEquals(0, placeSinglePiece(new IrisStructurePlacement())); + assertEquals(10, writes.size()); + writes.clear(); - IrisStructureComponent.requireAppliedPieces(resolved(placement), 0, 0, failed); - assertEquals(0, failed); - assertEquals("a piece that allows water fills it", world.headAt(X - 1, Z - 1), lowestWriteAt(X - 1, Z - 1)); + assertEquals(0, placeSinglePiece(new IrisStructurePlacement().setAllowWater(true))); + assertEquals(10, writes.size()); } @Test - public void forcedSinglePieceStructureThatAllowsWaterPlacesOnFlatRiverWater() { - world.water(WaterRole.CHANNEL, 9, 13); - - int failed = placeSinglePiece(new IrisStructurePlacement().setAllowWater(true)); - - assertEquals(0, failed); - assertEquals(world.headAt(X, Z), lowestWriteAt(X, Z)); - } - - @Test - public void forcedSinglePieceStructureStillPlacesOnDryLand() { + public void aForcedPiecePlacesOnDryLand() { int failed = placeSinglePiece(new IrisStructurePlacement()); assertEquals(0, failed); @@ -198,12 +185,46 @@ public class IrisStructureComponentWaterTest { } @Test - public void objectsThatForcePlaceThemselvesStillStayOffUnevenWater() { + public void objectsThatForcePlaceThemselvesWriteThroughUnevenWater() { world.water(WaterRole.CHANNEL, 9, 13); world.column(X + 1, Z, WaterRole.CHANNEL, 9, 16); IrisObject object = HydrologyWaterFixture.raft(); + IrisObjectPlacement config = new IrisObjectPlacement().setForcePlace(true); - int result = object.place(X, Z, writer, new IrisObjectPlacement().setForcePlace(true), new RNG(7L), world.data()); + writer.beginObjectPlacement(config.waterRule()); + int result = object.place(X, Z, writer, config, new RNG(7L), world.data()); + writer.endObjectPlacement(); + + assertTrue(result >= 0); + assertEquals("every block lands over the channel", 10, writes.size()); + assertEquals(world.headAt(X, Z), lowestWriteAt(X, Z)); + } + + @Test + public void unforcedPiecesKeepTheVeto() { + world.water(WaterRole.CHANNEL, 9, 13); + IrisObject object = HydrologyWaterFixture.raft(); + IrisStructure structure = new IrisStructure().setPlaceMode(ObjectPlaceMode.STRUCTURE_PIECE); + int head = world.headAt(X, Z); + PlacedStructurePiece explicit = new PlacedStructurePiece(null, object, X, head + 1, Z, IrisObjectRotation.of(0, 0, 0), + X - 1, head, Z - 1, X + 1, head + 2, Z + 1); + + assertEquals(0, component.placePieces(writer, new IrisStructurePlacement(), structure, new KList<>(explicit), new RNG(7L))); + + assertFalse("the block above the water places", writes.isEmpty()); + assertNoWaterOverwritten(); + writes.clear(); + + assertEquals(0, component.placePieces(writer, new IrisStructurePlacement().setAllowWater(true), structure, new KList<>(explicit), new RNG(7L))); + assertTrue("allowWater fills the water", writes.stream().anyMatch(write -> write.y() == head)); + } + + @Test + public void unforcedObjectsStayOffRiverWater() { + world.water(WaterRole.CHANNEL, 9, 13); + IrisObject object = HydrologyWaterFixture.raft(); + + int result = object.place(X, Z, writer, new IrisObjectPlacement(), new RNG(7L), world.data()); assertEquals(-1, result); assertTrue(writes.isEmpty()); diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/MantleObjectComponentWaterPlacementTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/MantleObjectComponentWaterPlacementTest.java index 74223b007..263e07314 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/MantleObjectComponentWaterPlacementTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/MantleObjectComponentWaterPlacementTest.java @@ -16,6 +16,7 @@ import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.structure.object.IObjectPlacer; import art.arcane.iris.structure.object.IrisObject; import art.arcane.iris.structure.object.IrisObjectPlacement; +import art.arcane.iris.structure.object.ObjectWaterRule; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.matter.MatterCavern; @@ -273,7 +274,7 @@ public class MantleObjectComponentWaterPlacementTest { when(placement.getAllowedCollisions()).thenReturn(new KList<>()); when(placement.getForbiddenCollisions()).thenReturn(new KList<>()); when(placement.scaleObject(any(RNG.class), any(), any())).thenReturn(object); - when(placement.entersWater()).thenReturn(true); + when(placement.waterRule()).thenReturn(ObjectWaterRule.ENTERS_WATER); return placement; } @@ -283,14 +284,14 @@ public class MantleObjectComponentWaterPlacementTest { private void assertEndedUnrecorded() { InOrder order = inOrder(placer); - order.verify(placer).beginObjectPlacement(true); + order.verify(placer).beginObjectPlacement(ObjectWaterRule.ENTERS_WATER); order.verify(placer).endObjectPlacement(); verify(placer, never()).recordObjectPlacement(anyInt()); } private void assertRecordedThenEnded() { InOrder order = inOrder(placer); - order.verify(placer).beginObjectPlacement(true); + order.verify(placer).beginObjectPlacement(ObjectWaterRule.ENTERS_WATER); order.verify(placer).recordObjectPlacement(anyInt()); order.verify(placer).endObjectPlacement(); } diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/MantleWriterObjectWaterTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/MantleWriterObjectWaterTest.java index 17744f9c7..923d45e20 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/MantleWriterObjectWaterTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/MantleWriterObjectWaterTest.java @@ -8,6 +8,7 @@ import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.iris.integration.Identifier; +import art.arcane.iris.structure.object.ObjectWaterRule; import art.arcane.iris.testsupport.PlatformBinding; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; import art.arcane.volmlib.util.mantle.runtime.Mantle; @@ -93,7 +94,7 @@ public class MantleWriterObjectWaterTest { @Test public void structurePiecesKeepOutOfRiverWaterUnlessTheyAllowIt() { MatterCavern cavern = new MatterCavern(true, "", (byte) 3); - int land = writer.beginObjectPlacement(false); + int land = writer.beginObjectPlacement(ObjectWaterRule.KEEP_OUT); writer.set(3, 7, 3, stone); writer.set(3, 8, 3, air); writer.setData(3, 6, 3, cavern); @@ -109,7 +110,7 @@ public class MantleWriterObjectWaterTest { verify(blocks).set(3, 10, 3, stone); verify(blocks).set(8, 7, 8, stone); - int water = writer.beginObjectPlacement(true); + int water = writer.beginObjectPlacement(ObjectWaterRule.ENTERS_WATER); writer.set(3, 6, 3, stone); writer.set(3, 9, 3, air); writer.endObjectPlacement(); @@ -118,9 +119,23 @@ public class MantleWriterObjectWaterTest { verify(blocks, never()).set(3, 9, 3, air); } + @Test + public void forcedPlacementsWriteThroughRiverWater() { + MatterCavern cavern = new MatterCavern(true, "", (byte) 3); + writer.beginObjectPlacement(ObjectWaterRule.FORCED); + writer.set(3, 7, 3, stone); + writer.set(3, 8, 3, air); + writer.setData(3, 6, 3, cavern); + writer.endObjectPlacement(); + + verify(blocks).set(3, 7, 3, stone); + verify(blocks).set(3, 8, 3, air); + verify(caverns).set(3, 6, 3, cavern); + } + @Test public void writesOutsideAnObjectPlacementAreNotVetoed() { - int land = writer.beginObjectPlacement(false); + int land = writer.beginObjectPlacement(ObjectWaterRule.KEEP_OUT); writer.endObjectPlacement(); writer.set(3, 7, 3, stone); diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/MutationLogTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/MutationLogTest.java index f454e8d84..3f10b5136 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/MutationLogTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/MutationLogTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.mantle; +import art.arcane.iris.structure.object.ObjectWaterRule; import art.arcane.iris.testsupport.KeyedBlockState; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; import org.junit.Test; @@ -21,7 +22,8 @@ public class MutationLogTest { new ObjectDestinationTransaction.SetMutation(new ObjectDestinationTransaction.DataKey(3, 70, -2, String.class), "marker", true), new ObjectDestinationTransaction.CustomBlockMutation(new ObjectDestinationTransaction.DataKey(-17, 4, 40, NativeBlockState.class), state, false))); for (int index = 0; index < 100; index++) { - log.add(index, index + 1, -index, "grow" + index, (index & 1) == 0, (index & 2) == 0, (index & 4) == 0); + log.add(index, index + 1, -index, "grow" + index, (index & 1) == 0, (index & 2) == 0, + (index & 4) == 0 ? ObjectWaterRule.ENTERS_WATER : (index & 8) == 0 ? ObjectWaterRule.FORCED : ObjectWaterRule.KEEP_OUT); } assertEquals(102, log.size()); @@ -41,9 +43,10 @@ public class MutationLogTest { assertFalse(log.custom(101)); assertTrue(log.canopy(98)); assertFalse(log.canopy(100)); - assertFalse(log.entersWater(0)); - assertTrue(log.entersWater(98)); - assertFalse(log.entersWater(6)); + assertEquals(ObjectWaterRule.KEEP_OUT, log.waterRule(0)); + assertEquals(ObjectWaterRule.ENTERS_WATER, log.waterRule(98)); + assertEquals(ObjectWaterRule.FORCED, log.waterRule(6)); + assertEquals(ObjectWaterRule.KEEP_OUT, log.waterRule(14)); } @Test @@ -62,7 +65,7 @@ public class MutationLogTest { int z = (index * 5) - 20; String value = "value" + (index % 9); boolean canopy = index % 4 == 0; - log.add(x, y, z, value, false, canopy, false); + log.add(x, y, z, value, false, canopy, ObjectWaterRule.KEEP_OUT); if (index >= 10) { tail.add(new ObjectDestinationTransaction.SetMutation(new ObjectDestinationTransaction.DataKey(x, y, z, String.class), value, canopy)); } diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/ObjectContinuationCanopyTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/ObjectContinuationCanopyTest.java index b25362ade..07643aeb9 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/ObjectContinuationCanopyTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/ObjectContinuationCanopyTest.java @@ -8,6 +8,7 @@ import art.arcane.iris.spi.IrisPlatform; import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.PlatformRegistries; import art.arcane.iris.structure.object.IObjectPlacer; +import art.arcane.iris.structure.object.ObjectWaterRule; import art.arcane.iris.testsupport.PlatformLeakGuard; import art.arcane.iris.world.storage.matter.IrisMatterSupport; import art.arcane.iris.world.storage.matter.TileWrapper; @@ -173,7 +174,7 @@ public class ObjectContinuationCanopyTest { when(firstChunk.getOrCreate(0)).thenReturn(first); when(secondChunk.getOrCreate(0)).thenReturn(second); FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction(delegate, - new ObjectContinuationBundle.PlacementKey(ObjectContinuationBundle.Kind.FLOATING, 0, 0, 0), false); + new ObjectContinuationBundle.PlacementKey(ObjectContinuationBundle.Kind.FLOATING, 0, 0, 0), ObjectWaterRule.KEEP_OUT); transaction.set(15, 5, 1, trunk); assertTrue(transaction.beginTreeCanopy(new BlockPosition(16, 5, 1))); transaction.set(16, 5, 1, custom); diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/ObjectContinuationTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/ObjectContinuationTest.java index bf14a310a..12d1bfb05 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/ObjectContinuationTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/ObjectContinuationTest.java @@ -8,6 +8,7 @@ import art.arcane.iris.integration.Identifier; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.IrisRegistrant; import art.arcane.iris.pack.loading.ResourceLoader; +import art.arcane.iris.structure.object.ObjectWaterRule; import art.arcane.iris.world.entity.IrisSpawner; import art.arcane.iris.world.storage.matter.IrisMatterContext; import art.arcane.iris.spi.IrisPlatform; @@ -58,16 +59,16 @@ public class ObjectContinuationTest { public void onlyAcceptedCrossingPlacementsLeaveFutureFragments() throws Exception { Fixture fixture = new Fixture(); ObjectDestinationTransaction source = new ObjectDestinationTransaction(fixture.writer, 0, 0); - int checkpoint = source.beginObjectPlacement(false); + int checkpoint = source.beginObjectPlacement(ObjectWaterRule.KEEP_OUT); source.setData(1, 5, 1, "inside"); source.recordObjectPlacement(checkpoint); source.endObjectPlacement(); - checkpoint = source.beginObjectPlacement(false); + checkpoint = source.beginObjectPlacement(ObjectWaterRule.KEEP_OUT); source.setData(15, 5, 1, "crossing"); source.setData(16, 5, 1, "crossing"); source.recordObjectPlacement(checkpoint); source.endObjectPlacement(); - checkpoint = source.beginObjectPlacement(false); + checkpoint = source.beginObjectPlacement(ObjectWaterRule.KEEP_OUT); source.setData(32, 5, 1, "unrelated"); source.setData(48, 5, 1, "unrelated"); source.recordObjectPlacement(checkpoint); diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/ObjectDestinationTransactionTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/ObjectDestinationTransactionTest.java index b617fe309..e3e53ef98 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/ObjectDestinationTransactionTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/ObjectDestinationTransactionTest.java @@ -16,6 +16,7 @@ import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.iris.generation.terrain.Terrain3DColumnFixtures; import art.arcane.iris.spi.IrisPlatform; import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.structure.object.ObjectWaterRule; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; import art.arcane.volmlib.util.math.BlockPosition; import art.arcane.iris.structure.object.DecayControlPlacer; @@ -193,14 +194,14 @@ public class ObjectDestinationTransactionTest { transaction.set(3, 9, 3, pier); transaction.set(6, 18, 6, pier); assertEquals("a pier keeps its blocks on the river bed and the shore", start + 2, transaction.mutationCheckpoint()); - transaction.beginObjectPlacement(true); + transaction.beginObjectPlacement(ObjectWaterRule.ENTERS_WATER); transaction.set(3, 10, 3, pier); transaction.set(4, 15, 3, pier); assertEquals("an underwater pier keeps its blocks in the river", start + 4, transaction.mutationCheckpoint()); transaction.set(3, 12, 3, pier); transaction.set(3, 10, 3, vine); assertEquals("an underwater object still keeps out of falls and open water", start + 4, transaction.mutationCheckpoint()); - transaction.beginObjectPlacement(false); + transaction.beginObjectPlacement(ObjectWaterRule.KEEP_OUT); transaction.set(3, 16, 3, vine); transaction.set(3, 8, 3, vine); transaction.set(6, 19, 6, vine); @@ -239,12 +240,12 @@ public class ObjectDestinationTransactionTest { transaction.set(3, 10, 3, boulder); assertEquals("nothing an object places roofs or fills the slot between its water and the cliff top", start, transaction.mutationCheckpoint()); - transaction.beginObjectPlacement(true); + transaction.beginObjectPlacement(ObjectWaterRule.ENTERS_WATER); transaction.set(3, 10, 3, boulder); transaction.set(3, 12, 3, boulder); assertEquals("an underwater object's solid block below the water may still sit on the slot bed", start + 1, transaction.mutationCheckpoint()); - transaction.beginObjectPlacement(false); + transaction.beginObjectPlacement(ObjectWaterRule.KEEP_OUT); transaction.set(3, 31, 3, leaves); transaction.set(3, 36, 3, leaves); transaction.set(3, 33, 3, boulder); @@ -289,7 +290,7 @@ public class ObjectDestinationTransactionTest { setCanopy(transaction, 5, 14, 3, leaves); assertEquals("the bed, the air above the surface and dry land keep their leaves", start + 4, transaction.mutationCheckpoint()); - int underwater = transaction.beginObjectPlacement(true); + int underwater = transaction.beginObjectPlacement(ObjectWaterRule.ENTERS_WATER); transaction.set(3, 12, 3, leaves); transaction.set(4, 9, 3, leaves); assertEquals("an underwater object keeps its solid blocks in the water", underwater + 2, @@ -304,7 +305,7 @@ public class ObjectDestinationTransactionTest { } @Test - public void onwaterRaftsAndOwnForcedObjectsKeepTheirLayerOnRiversButForcedStructurePiecesDoNot() { + public void onwaterRaftsAndForcedPlacementsKeepTheirWritesThroughReplay() { MantleWriter writer = writer(); IrisComplex complex = mock(IrisComplex.class); HydrologyRuntime runtime = mock(HydrologyRuntime.class); @@ -330,21 +331,28 @@ public class ObjectDestinationTransactionTest { assertTrue(piece.isForcePlace()); ObjectDestinationTransaction transaction = new ObjectDestinationTransaction(writer, 0, 0); - int raftStart = transaction.beginObjectPlacement(raft.entersWater()); + int raftStart = transaction.beginObjectPlacement(raft.waterRule()); for (int x = 3; x <= 5; x++) { transaction.set(x, 14, 3, plank); } assertEquals("a one-block onwater raft keeps its layer on the river surface", raftStart + 3, transaction.mutationCheckpoint()); - int forcedStart = transaction.beginObjectPlacement(forced.entersWater()); + assertEquals(ObjectWaterRule.FORCED, forced.waterRule()); + assertEquals(ObjectWaterRule.FORCED, piece.waterRule()); + int forcedStart = transaction.beginObjectPlacement(forced.waterRule()); transaction.set(3, 13, 3, plank); - assertEquals("an object's own forcePlace keeps its solid blocks in the river", forcedStart + 1, transaction.mutationCheckpoint()); - int pieceStart = transaction.beginObjectPlacement(piece.entersWater()); + transaction.set(3, 12, 3, mock(NativeBlockState.class)); + transaction.setData(3, 11, 3, new MatterCavern(true, "", (byte) 3)); + assertEquals("a forced object writes solid blocks, open blocks and carves through the river", forcedStart + 3, transaction.mutationCheckpoint()); + int pieceStart = transaction.beginObjectPlacement(piece.waterRule()); transaction.set(4, 13, 3, plank); transaction.set(5, 11, 3, plank); - assertEquals("a forced structure piece still keeps its solid blocks out of the river", pieceStart, transaction.mutationCheckpoint()); + assertEquals("a forced structure piece writes through the river", pieceStart + 2, transaction.mutationCheckpoint()); + int landStart = transaction.beginObjectPlacement(ObjectWaterRule.KEEP_OUT); + transaction.set(4, 12, 3, plank); + assertEquals("an unforced object stays out of the river", landStart, transaction.mutationCheckpoint()); ObjectDestinationTransaction destination = new ObjectDestinationTransaction(writer, 0, 0); destination.apply(transaction.sourcePlanSince(raftStart)); - assertEquals("the destination replay keeps the raft and the forced block", 4, destination.mutationCheckpoint()); + assertEquals("the destination replay keeps the forced writes beside the raft", 8, destination.mutationCheckpoint()); } @Test @@ -367,7 +375,7 @@ public class ObjectDestinationTransactionTest { when(pier.isSolid()).thenReturn(true); ObjectDestinationTransaction transaction = new ObjectDestinationTransaction(writer, 0, 0); - int raft = transaction.beginObjectPlacement(true); + int raft = transaction.beginObjectPlacement(ObjectWaterRule.ENTERS_WATER); transaction.set(3, 12, 3, pier); transaction.recordObjectPlacement(raft); transaction.endObjectPlacement(); @@ -385,7 +393,7 @@ public class ObjectDestinationTransactionTest { when(pier.isSolid()).thenReturn(true); ObjectDestinationTransaction transaction = new ObjectDestinationTransaction(writer, 0, 0); - transaction.beginObjectPlacement(true); + transaction.beginObjectPlacement(ObjectWaterRule.ENTERS_WATER); transaction.set(3, 12, 3, pier); transaction.endObjectPlacement(); int afterRaft = transaction.mutationCheckpoint(); diff --git a/core/src/test/java/art/arcane/iris/structure/object/IrisObjectPlacementToPlacementTest.java b/core/src/test/java/art/arcane/iris/structure/object/IrisObjectPlacementToPlacementTest.java index 2c8e24af7..ffd063f2b 100644 --- a/core/src/test/java/art/arcane/iris/structure/object/IrisObjectPlacementToPlacementTest.java +++ b/core/src/test/java/art/arcane/iris/structure/object/IrisObjectPlacementToPlacementTest.java @@ -88,7 +88,6 @@ public class IrisObjectPlacementToPlacementTest { source.setAllowedCollisions(allowedCollisions); source.setForbiddenCollisions(forbiddenCollisions); source.setForcePlace(true); - source.setForcedByStructure(true); IrisObjectPlacement copy = source.toPlacement("objects/replaced"); @@ -133,6 +132,5 @@ public class IrisObjectPlacementToPlacementTest { assertSame(allowedCollisions, copy.getAllowedCollisions()); assertSame(forbiddenCollisions, copy.getForbiddenCollisions()); assertTrue(copy.isForcePlace()); - assertTrue(copy.isForcedByStructure()); } } diff --git a/core/src/test/java/art/arcane/iris/structure/object/PlacementModuleSurfaceSupportTest.java b/core/src/test/java/art/arcane/iris/structure/object/PlacementModuleSurfaceSupportTest.java index 32a281d94..5bf80765f 100644 --- a/core/src/test/java/art/arcane/iris/structure/object/PlacementModuleSurfaceSupportTest.java +++ b/core/src/test/java/art/arcane/iris/structure/object/PlacementModuleSurfaceSupportTest.java @@ -131,7 +131,7 @@ public class PlacementModuleSurfaceSupportTest { world.water(WaterRole.CHANNEL, 9, 13); world.column(1, 0, WaterRole.CHANNEL, 8, 12); - for (IrisObjectPlacement placement : List.of(underwater(), onwater(), forced())) { + for (IrisObjectPlacement placement : List.of(underwater(), onwater())) { HydrologyWaterFixture.Placer placer = world.placer(); assertEquals(-1, place(HydrologyWaterFixture.raft(), placer, placement)); @@ -139,6 +139,17 @@ public class PlacementModuleSurfaceSupportTest { } } + @Test + public void forcedObjectsPlaceOnWaterAtAnotherHeadAndOnDams() { + world.water(WaterRole.CHANNEL, 9, 13); + world.column(1, 0, WaterRole.CHANNEL, 8, 12); + world.column(0, 1, WaterRole.DAM, 8, 12); + HydrologyWaterFixture.Placer placer = world.placer(); + + assertTrue(place(HydrologyWaterFixture.raft(), placer, forced()) >= 0); + assertFalse(placer.writes().isEmpty()); + } + @Test public void waterObjectsNeverPlaceOnProvisionalHydrology() { world.water(WaterRole.POND, 7, 13); diff --git a/core/src/test/java/art/arcane/iris/structure/placement/IrisStructureLocatorContractTest.java b/core/src/test/java/art/arcane/iris/structure/placement/IrisStructureLocatorContractTest.java index d7442b875..6b993adfe 100644 --- a/core/src/test/java/art/arcane/iris/structure/placement/IrisStructureLocatorContractTest.java +++ b/core/src/test/java/art/arcane/iris/structure/placement/IrisStructureLocatorContractTest.java @@ -500,6 +500,46 @@ public class IrisStructureLocatorContractTest { assertNotNull(IrisStructureLocator.resolvePlacement(engine, placement, 3, 4)); } + @Test + public void forcedSinglePiecesPlaceInTheMiddleOfARiver() { + Engine engine = densityEngine(1.0, false, -64, 384, -2032, 2032); + IrisObject object = engine.getData().load(IrisObject.class, "test:density/object", false); + when(object.getW()).thenReturn(10); + when(object.getD()).thenReturn(10); + IrisComplex complex = mock(IrisComplex.class); + when(engine.getComplex()).thenReturn(complex); + when(complex.allowsNewGenerationFootprint(anyInt(), anyInt(), anyInt(), anyInt())).thenReturn(true); + @SuppressWarnings("unchecked") + ProceduralStream waterHead = mock(ProceduralStream.class); + when(complex.getWaterHeadStream()).thenReturn(waterHead); + when(waterHead.get(anyDouble(), anyDouble())).thenReturn(124D); + when(waterHead.getDouble(anyDouble(), anyDouble())).thenReturn(124D); + @SuppressWarnings("unchecked") + ProceduralStream roles = mock(ProceduralStream.class); + when(complex.getWaterRoleStream()).thenReturn(roles); + when(roles.get(anyDouble(), anyDouble())).thenReturn(WaterRole.CHANNEL); + @SuppressWarnings("unchecked") + ProceduralStream beds = mock(ProceduralStream.class); + when(beds.get(anyDouble(), anyDouble())).thenReturn(120); + when(complex.getRoundedHeighteightStream()).thenReturn(beds); + when(engine.getHeight(anyInt(), anyInt(), eq(true))).thenReturn(120); + when(engine.getDimension().getFluidHeight()).thenReturn(63); + IrisStructurePlacement placement = engine.getDimension().getStructures().get(0); + IrisStructure structure = engine.getData().load(IrisStructure.class, "test:density", false); + + assertNull("an unforced structure stays off a submerged start", + IrisStructureLocator.resolvePlacement(engine, placement, 3, 4)); + placement.setUnderwater(true); + assertNull("an unforced structure keeps the 10% limit", + IrisStructureLocator.resolvePlacement(engine, placement, 3, 4)); + placement.setUnderwater(false); + + structure.setPlaceMode(ObjectPlaceMode.CENTER_HEIGHT); + + assertNotNull("a forced piece places on a river column and over a river footprint", + IrisStructureLocator.resolvePlacement(engine, placement, 3, 4)); + } + @Test public void undergroundIrisStructuresIgnoreRiversAbove() { Engine engine = densityEngine(1.0, true, -64, 384, -40, -20); From b2255d6bf9494cf5e4a31b500c2378251993a957 Mon Sep 17 00:00:00 2001 From: Brian Fopiano Date: Mon, 2 Nov 2026 19:10:36 -0500 Subject: [PATCH 6/8] Warn on unknown hydrology keys - Report keys under hydrology and hydrologyPolicy that the config classes do not declare as warnings on every validation path - Keep the reflection walk and the full path, and word the message as a warning - Stop treating collections, interfaces and abstract classes as having declared keys - Rename the rejects tests and expect warnings with no errors - Cover validate, validateForPackaging and validateForDatapackBootstrap --- .../iris/pack/PackHydrologyValidator.java | 46 +++--- .../iris/pack/PackHydrologyValidatorTest.java | 145 +++++++++++------- 2 files changed, 112 insertions(+), 79 deletions(-) diff --git a/core/src/main/java/art/arcane/iris/pack/PackHydrologyValidator.java b/core/src/main/java/art/arcane/iris/pack/PackHydrologyValidator.java index e3989980a..c30674ed5 100644 --- a/core/src/main/java/art/arcane/iris/pack/PackHydrologyValidator.java +++ b/core/src/main/java/art/arcane/iris/pack/PackHydrologyValidator.java @@ -104,7 +104,7 @@ final class PackHydrologyValidator { errors.add(path + " must be an object."); return data; } - rejectUnknownKeys(path, hydrology, IrisHydrology.class, packFolder, errors); + warnUnknownKeys(path, hydrology, IrisHydrology.class, packFolder, findings.warnings()); if (!hydrology.optBoolean("enabled", false)) { return data; } @@ -120,7 +120,7 @@ final class PackHydrologyValidator { return loaded; } warnMantleOff("Dimension '" + dimensionKey + "'", loadedDimension, findings.warnings()); - validatePolicies(path, dimensionKey, loaded, loadedDimension, new PolicyFluids(fluids, seams), errors); + validatePolicies(path, dimensionKey, loaded, loadedDimension, new PolicyFluids(fluids, seams), errors, findings.warnings()); warnShoreBiomesWithoutWidth(dimensionKey, loaded, loadedDimension, findings.warnings()); if (errors.size() == reported && validateCompile(path, loadedDimension, errors)) { validateDecoratorBlocks(path, loaded, loadedDimension.getHydrology(), errors); @@ -129,45 +129,45 @@ final class PackHydrologyValidator { return loaded; } - static void rejectUnknownKeys(String field, Object value, Type type, File packFolder, List errors) { - rejectUnknownKeys(field, value, type, new KeyScan(packFolder, errors, new HashSet<>())); + static void warnUnknownKeys(String field, Object value, Type type, File packFolder, List warnings) { + warnUnknownKeys(field, value, type, new KeyScan(packFolder, warnings, new HashSet<>())); } - private static void rejectUnknownKeys(String field, Object value, Type type, KeyScan scan) { + private static void warnUnknownKeys(String field, Object value, Type type, KeyScan scan) { Class raw = TypeToken.get(type).getRawType(); if (value instanceof JSONArray array) { Type element = elementType(type, raw); for (int index = 0; index < array.length(); index++) { - rejectUnknownKeys(field + "[" + index + "]", array.opt(index), element, scan); + warnUnknownKeys(field + "[" + index + "]", array.opt(index), element, scan); } } else if (value instanceof JSONObject object) { if (Map.class.isAssignableFrom(raw)) { Type entry = typeArgument(type, 1); for (String key : new TreeSet<>(object.keySet())) { - rejectUnknownKeys(field + "." + key, object.opt(key), entry, scan); + warnUnknownKeys(field + "." + key, object.opt(key), entry, scan); } } else if (hasDeclaredKeys(raw)) { - rejectUnknownFields(field, object, raw, scan); + warnUnknownFields(field, object, raw, scan); } } else if (value instanceof String reference && reference.startsWith(SNIPPET_ROOT) && raw.isAnnotationPresent(Snippet.class)) { - rejectUnknownSnippetKeys(field, reference, raw, scan); + warnUnknownSnippetKeys(field, reference, raw, scan); } } - private static void rejectUnknownFields(String field, JSONObject object, Class type, KeyScan scan) { + private static void warnUnknownFields(String field, JSONObject object, Class type, KeyScan scan) { Map declared = declaredKeys(type); for (String key : new TreeSet<>(object.keySet())) { String child = field + "." + key; Type declaredType = declared.get(key); if (declaredType == null) { - scan.errors().add(child + " is not a known key, so its value would be ignored. Known keys there: " + declared.keySet() + "."); + scan.warnings().add(child + " is not a known key, so its value is ignored. Known keys there: " + declared.keySet() + "."); } else { - rejectUnknownKeys(child, object.opt(key), declaredType, scan); + warnUnknownKeys(child, object.opt(key), declaredType, scan); } } } - private static void rejectUnknownSnippetKeys(String field, String reference, Class type, KeyScan scan) { + private static void warnUnknownSnippetKeys(String field, String reference, Class type, KeyScan scan) { String base = SNIPPET_ROOT + type.getDeclaredAnnotation(Snippet.class).value() + "/"; String snippet = reference.startsWith(base) ? reference : base + reference.substring(SNIPPET_ROOT.length()); if (!scan.activeSnippets().add(snippet)) { @@ -176,7 +176,7 @@ final class PackHydrologyValidator { File file = new File(scan.packFolder(), snippet + ".json"); JSONObject object = file.isFile() ? PackValidationIo.readJson(file) : null; if (object != null) { - rejectUnknownFields(field + " (" + snippet + ")", object, type, scan); + warnUnknownFields(field + " (" + snippet + ")", object, type, scan); } scan.activeSnippets().remove(snippet); } @@ -196,7 +196,9 @@ final class PackHydrologyValidator { } private static boolean hasDeclaredKeys(Class type) { - return !type.isPrimitive() && !type.isEnum() && !type.isArray() && !type.getPackageName().startsWith("java."); + return !type.isPrimitive() && !type.isEnum() && !type.isArray() && !type.isInterface() + && !Modifier.isAbstract(type.getModifiers()) && !Collection.class.isAssignableFrom(type) + && !type.getPackageName().startsWith("java."); } private static Map declaredKeys(Class type) { @@ -383,14 +385,14 @@ final class PackHydrologyValidator { } private static void validatePolicies(String path, String dimensionKey, IrisData data, IrisDimension dimension, PolicyFluids fluids, - List errors) { - rejectUnknownPolicyKeys("Dimension '" + dimensionKey + "'." + POLICY, dimension, data, errors); + List errors, List warnings) { + warnUnknownPolicyKeys("Dimension '" + dimensionKey + "'." + POLICY, dimension, data, warnings); validatePolicy("Dimension '" + dimensionKey + "'." + POLICY, dimension.getHydrologyPolicy(), data, fluids, path, errors); List regions = new ArrayList<>(dimension.getAllRegions(() -> data)); regions.sort(Comparator.comparing(IrisRegion::getLoadKey, Comparator.nullsFirst(Comparator.naturalOrder()))); for (IrisRegion region : regions) { if (region != null) { - rejectUnknownPolicyKeys("Region '" + region.getLoadKey() + "'." + POLICY, region, data, errors); + warnUnknownPolicyKeys("Region '" + region.getLoadKey() + "'." + POLICY, region, data, warnings); validatePolicy("Region '" + region.getLoadKey() + "'." + POLICY, region.getHydrologyPolicy(), data, fluids, path, errors); } } @@ -398,17 +400,17 @@ final class PackHydrologyValidator { biomes.sort(Comparator.comparing(IrisBiome::getLoadKey, Comparator.nullsFirst(Comparator.naturalOrder()))); for (IrisBiome biome : biomes) { if (biome != null) { - rejectUnknownPolicyKeys("Biome '" + biome.getLoadKey() + "'." + POLICY, biome, data, errors); + warnUnknownPolicyKeys("Biome '" + biome.getLoadKey() + "'." + POLICY, biome, data, warnings); validatePolicy("Biome '" + biome.getLoadKey() + "'." + POLICY, biome.getHydrologyPolicy(), data, fluids, path, errors); } } } - private static void rejectUnknownPolicyKeys(String field, IrisRegistrant owner, IrisData data, List errors) { + private static void warnUnknownPolicyKeys(String field, IrisRegistrant owner, IrisData data, List warnings) { File file = owner.getLoadFile(); JSONObject json = file == null ? null : PackValidationIo.readJson(file); if (json != null) { - rejectUnknownKeys(field, json.opt(POLICY), IrisHydrologyPolicy.class, data.getDataFolder(), errors); + warnUnknownKeys(field, json.opt(POLICY), IrisHydrologyPolicy.class, data.getDataFolder(), warnings); } } @@ -615,6 +617,6 @@ final class PackHydrologyValidator { private record Findings(List errors, List warnings) { } - private record KeyScan(File packFolder, List errors, Set activeSnippets) { + private record KeyScan(File packFolder, List warnings, Set activeSnippets) { } } diff --git a/core/src/test/java/art/arcane/iris/pack/PackHydrologyValidatorTest.java b/core/src/test/java/art/arcane/iris/pack/PackHydrologyValidatorTest.java index e595f0a6f..ebd3eab33 100644 --- a/core/src/test/java/art/arcane/iris/pack/PackHydrologyValidatorTest.java +++ b/core/src/test/java/art/arcane/iris/pack/PackHydrologyValidatorTest.java @@ -277,44 +277,44 @@ public class PackHydrologyValidatorTest { } @Test - public void rejectsAnUnknownKeyAtTheTopOfHydrology() throws Exception { - List errors = validate(pack(dimension("{\"enabled\": true, \"unknownSection\": {\"enabled\": true, \"tiers\": 4}}", ""))).errors(); + public void warnsAboutAnUnknownKeyAtTheTopOfHydrology() throws Exception { + List warnings = unknownKeyWarnings(validate(pack(dimension("{\"enabled\": true, \"unknownSection\": {\"enabled\": true, \"tiers\": 4}}", "")))); - assertContains(errors, "Dimension 'main'.hydrology.unknownSection is not a known key, so its value would be ignored."); - assertContains(errors, "prefetchRings"); - assertEquals(errors.toString(), 1, errors.size()); + assertContains(warnings, "Dimension 'main'.hydrology.unknownSection is not a known key, so its value is ignored."); + assertContains(warnings, "prefetchRings"); + assertEquals(warnings.toString(), 1, warnings.size()); } @Test - public void rejectsAMisspeltEnabledFlagThoughTheBlockLoadsAsOff() throws Exception { + public void warnsAboutAMisspeltEnabledFlagThoughTheBlockLoadsAsOff() throws Exception { File pack = pack(dimension("{\"enable\": true, \"ponds\": {\"dryDrawdon\": 3}}", "")); - List errors = validate(pack).errors(); + List warnings = unknownKeyWarnings(validate(pack)); - assertContains(errors, "Dimension 'main'.hydrology.enable is not a known key"); - assertContains(errors, "Dimension 'main'.hydrology.ponds.dryDrawdon is not a known key"); - assertEquals(errors.toString(), 2, errors.size()); + assertContains(warnings, "Dimension 'main'.hydrology.enable is not a known key"); + assertContains(warnings, "Dimension 'main'.hydrology.ponds.dryDrawdon is not a known key"); + assertEquals(warnings.toString(), 2, warnings.size()); assertFalse(loadHydrology(pack).isEnabled()); } @Test - public void rejectsUnknownKeysInNestedObjects() throws Exception { - List errors = validate(pack(dimension(""" + public void warnsAboutUnknownKeysInNestedObjects() throws Exception { + List warnings = unknownKeyWarnings(validate(pack(dimension(""" { "enabled": true, "ponds": {"seeded": {"radiusRange": [4, 12]}}, "underground": {"cavePools": {"surface": 3}, "seaInlets": {"length": [24, 96], "chamber": {"radius": 4}}} } - """, ""))).errors(); + """, "")))); - assertContains(errors, "Dimension 'main'.hydrology.ponds.seeded.radiusRange is not a known key"); - assertContains(errors, "Dimension 'main'.hydrology.underground.cavePools.surface is not a known key"); - assertContains(errors, "Dimension 'main'.hydrology.underground.seaInlets.chamber is not a known key"); - assertEquals(errors.toString(), 3, errors.size()); + assertContains(warnings, "Dimension 'main'.hydrology.ponds.seeded.radiusRange is not a known key"); + assertContains(warnings, "Dimension 'main'.hydrology.underground.cavePools.surface is not a known key"); + assertContains(warnings, "Dimension 'main'.hydrology.underground.seaInlets.chamber is not a known key"); + assertEquals(warnings.toString(), 3, warnings.size()); } @Test - public void rejectsUnknownKeysInsideTierArrayElements() throws Exception { + public void warnsAboutUnknownKeysInsideTierArrayElements() throws Exception { File pack = pack(dimension(""" {"enabled": true, "fluids": [{"name": "water", "palette": {"palette": [{"block": "minecraft:water", "bloc": 1}]}, "sealed": true}], "tiers": [ @@ -325,14 +325,14 @@ public class PackHydrologyValidatorTest { ]} """, "")); - List errors = validate(pack).errors(); + List warnings = unknownKeyWarnings(validate(pack)); - assertContains(errors, "Dimension 'main'.hydrology.tiers[1].notATierField is not a known key"); - assertContains(errors, "Dimension 'main'.hydrology.tiers[1].estuary.flair is not a known key"); - assertContains(errors, "Dimension 'main'.hydrology.tiers[1].decorators[0].stacks is not a known key"); - assertContains(errors, "Dimension 'main'.hydrology.fluids[0].sealed is not a known key"); - assertContains(errors, "Dimension 'main'.hydrology.fluids[0].palette.palette[0].bloc is not a known key"); - assertEquals(errors.toString(), 5, errors.size()); + assertContains(warnings, "Dimension 'main'.hydrology.tiers[1].notATierField is not a known key"); + assertContains(warnings, "Dimension 'main'.hydrology.tiers[1].estuary.flair is not a known key"); + assertContains(warnings, "Dimension 'main'.hydrology.tiers[1].decorators[0].stacks is not a known key"); + assertContains(warnings, "Dimension 'main'.hydrology.fluids[0].sealed is not a known key"); + assertContains(warnings, "Dimension 'main'.hydrology.fluids[0].palette.palette[0].bloc is not a known key"); + assertEquals(warnings.toString(), 5, warnings.size()); for (IrisHydrologyTier tier : loadHydrology(pack).getTiers()) { assertEquals(tier.getName(), 48, tier.getEstuary().getLength()); assertEquals(tier.getName(), 2.5D, tier.getEstuary().getFlare(), 0D); @@ -341,15 +341,15 @@ public class PackHydrologyValidatorTest { @Test public void treatsMapKeysAsDataAndChecksTheObjectsInside() throws Exception { - List errors = new ArrayList<>(); + List warnings = new ArrayList<>(); JSONObject written = new JSONObject(""" {"zones": {"swamp": {"min": 0.7, "max": 1}, "desert": {"minimum": 0.1}}} """); - PackHydrologyValidator.rejectUnknownKeys("root", written, NamedZones.class, temporaryFolder.getRoot(), errors); + PackHydrologyValidator.warnUnknownKeys("root", written, NamedZones.class, temporaryFolder.getRoot(), warnings); - assertContains(errors, "root.zones.desert.minimum is not a known key"); - assertEquals(errors.toString(), 1, errors.size()); + assertContains(warnings, "root.zones.desert.minimum is not a known key"); + assertEquals(warnings.toString(), 1, warnings.size()); } @Test @@ -360,14 +360,14 @@ public class PackHydrologyValidatorTest { ]}}]} """, ""))); - assertTrue(validation.errors().toString(), validation.errors().isEmpty()); + assertEquals(List.of(), unknownKeyWarnings(validation)); } @Test public void acceptsEveryKeyGsonWritesForTheConfigClasses() throws Exception { Gson gson = new Gson(); PackHydrologyValidator.Validation defaults = validate(pack(dimension(gson.toJson(new IrisHydrology().setEnabled(true)), ""))); - assertTrue(defaults.errors().toString(), defaults.errors().isEmpty()); + assertEquals(List.of(), unknownKeyWarnings(defaults)); IrisHydrology hydrology = new IrisHydrology().setEnabled(true); hydrology.getTiers().get(0).getMaterials().setBed(new IrisMaterialPalette()).setShore(new IrisMaterialPalette()).setBank(new IrisMaterialPalette()); @@ -376,14 +376,14 @@ public class PackHydrologyValidatorTest { hydrology.getTiers().get(0).getDecorators().add(decorator); IrisHydrologyPolicy policy = new IrisHydrologyPolicy().setRainfall(1D).setWetness(new IrisHydrologyWetness()).setStreams(IrisHydrologyPermission.ALLOW); - List errors = validate(pack(dimension(gson.toJson(hydrology), "\"hydrologyPolicy\": " + gson.toJson(policy) + ","))).errors(); + PackHydrologyValidator.Validation written = validate(pack(dimension(gson.toJson(hydrology), "\"hydrologyPolicy\": " + gson.toJson(policy) + ","))); - assertEquals(List.of(), errors.stream().filter(error -> error.contains("not a known key")).toList()); + assertEquals(List.of(), keyWarnings(written)); } @Test - public void rejectsEachRenamedKeyByItsOldName() throws Exception { - List errors = validate(pack(dimension(""" + public void warnsAboutEachRenamedKeyByItsOldName() throws Exception { + List warnings = unknownKeyWarnings(validate(pack(dimension(""" { "enabled": true, "drainage": {"minimumHeadKeep": 0.6}, @@ -394,18 +394,18 @@ public class PackHydrologyValidatorTest { "ponds": {"climateDrawdown": 3}, "underground": {"seaInlets": {"minimumCliffHeight": 8}} } - """, ""))).errors(); + """, "")))); - assertContains(errors, "Dimension 'main'.hydrology.drainage.minimumHeadKeep is not a known key"); - assertContains(errors, "Dimension 'main'.hydrology.tiers[0].waterfallMinimumDrop is not a known key"); - assertContains(errors, "Dimension 'main'.hydrology.tiers[1].waterfallMinimumDrop is not a known key"); - assertContains(errors, "Dimension 'main'.hydrology.ponds.climateDrawdown is not a known key"); - assertContains(errors, "Dimension 'main'.hydrology.underground.seaInlets.minimumCliffHeight is not a known key"); - assertEquals(errors.toString(), 5, errors.size()); + assertContains(warnings, "Dimension 'main'.hydrology.drainage.minimumHeadKeep is not a known key"); + assertContains(warnings, "Dimension 'main'.hydrology.tiers[0].waterfallMinimumDrop is not a known key"); + assertContains(warnings, "Dimension 'main'.hydrology.tiers[1].waterfallMinimumDrop is not a known key"); + assertContains(warnings, "Dimension 'main'.hydrology.ponds.climateDrawdown is not a known key"); + assertContains(warnings, "Dimension 'main'.hydrology.underground.seaInlets.minimumCliffHeight is not a known key"); + assertEquals(warnings.toString(), 5, warnings.size()); } @Test - public void rejectsUnknownKeysInHydrologyPoliciesAtEveryScope() throws Exception { + public void warnsAboutUnknownKeysInHydrologyPoliciesAtEveryScope() throws Exception { File pack = pack(dimension(WATER_ONLY, "\"hydrologyPolicy\": {\"rainFall\": 1},")); write(pack, "regions/region.json", """ {"landBiomes": ["biome"], "hydrologyPolicy": {"streamz": "BLOCK"}} @@ -415,13 +415,13 @@ public class PackHydrologyValidatorTest { "decorators": [{"partOf": "SHORE_LINE", "palette": [{"block": "minecraft:fern"}], "odds": 2}]}} """); - List errors = validate(pack).errors(); + List warnings = unknownKeyWarnings(validate(pack)); - assertContains(errors, "Dimension 'main'.hydrologyPolicy.rainFall is not a known key"); - assertContains(errors, "Region 'region'.hydrologyPolicy.streamz is not a known key"); - assertContains(errors, "Biome 'biome'.hydrologyPolicy.wetness.middle is not a known key"); - assertContains(errors, "Biome 'biome'.hydrologyPolicy.decorators[0].odds is not a known key"); - assertEquals(errors.toString(), 4, errors.size()); + assertContains(warnings, "Dimension 'main'.hydrologyPolicy.rainFall is not a known key"); + assertContains(warnings, "Region 'region'.hydrologyPolicy.streamz is not a known key"); + assertContains(warnings, "Biome 'biome'.hydrologyPolicy.wetness.middle is not a known key"); + assertContains(warnings, "Biome 'biome'.hydrologyPolicy.decorators[0].odds is not a known key"); + assertEquals(warnings.toString(), 4, warnings.size()); } @Test @@ -437,10 +437,10 @@ public class PackHydrologyValidatorTest { {"partOf": "SHORE_LINE", "palette": [{"block": "minecraft:fern"}]} """); - List errors = validate(pack).errors().stream().filter(error -> error.contains("not a known key")).toList(); + List warnings = keyWarnings(validate(pack)); - assertContains(errors, "Dimension 'main'.hydrology.tiers[0].decorators[0] (snippet/decorator/reeds).odds is not a known key"); - assertEquals(errors.toString(), 1, errors.size()); + assertContains(warnings, "Dimension 'main'.hydrology.tiers[0].decorators[0] (snippet/decorator/reeds).odds is not a known key"); + assertEquals(warnings.toString(), 1, warnings.size()); } @Test @@ -449,12 +449,12 @@ public class PackHydrologyValidatorTest { write(pack, "snippet/style/loop.json", """ {"fracture": "snippet/style/loop", "fractures": 1} """); - List errors = new ArrayList<>(); + List warnings = new ArrayList<>(); - PackHydrologyValidator.rejectUnknownKeys("style", "snippet/style/loop", IrisGeneratorStyle.class, pack, errors); + PackHydrologyValidator.warnUnknownKeys("style", "snippet/style/loop", IrisGeneratorStyle.class, pack, warnings); - assertContains(errors, "style (snippet/style/loop).fractures is not a known key"); - assertEquals(errors.toString(), 1, errors.size()); + assertContains(warnings, "style (snippet/style/loop).fractures is not a known key"); + assertEquals(warnings.toString(), 1, warnings.size()); } @Test @@ -462,7 +462,29 @@ public class PackHydrologyValidatorTest { File pack = pack("{\"regions\": [\"region\"], \"notADimensionKey\": 1, \"hydrology\": " + WATER_ONLY + "}"); write(pack, "biomes/biome.json", "{\"name\": \"Biome\", \"notABiomeKey\": {\"a\": 1}}"); - assertTrue(validate(pack).errors().isEmpty()); + assertEquals(List.of(), unknownKeyWarnings(validate(pack))); + } + + @Test + public void unknownKeysNeverBlockAPackOnAnyValidationPath() throws Exception { + File pack = pack(dimension("{\"enabled\": true, \"ponds\": {\"climateDrawdown\": 3}}", "\"hydrologyPolicy\": {\"rainFall\": 1},")); + String key = "not a known key"; + + for (PackValidationResult result : List.of(PackValidator.validate(pack), PackValidator.validateForPackaging(pack), PackValidator.validateForDatapackBootstrap(pack))) { + assertFalse(result.getBlockingErrors().toString(), result.getBlockingErrors().stream().anyMatch(message -> message.contains(key))); + assertContains(result.getWarnings(), "Dimension 'main'.hydrology.ponds.climateDrawdown is " + key); + assertContains(result.getWarnings(), "Dimension 'main'.hydrologyPolicy.rainFall is " + key); + } + } + + @Test + public void anObjectWhereAListIsDeclaredReportsNoListInternals() throws Exception { + List warnings = new ArrayList<>(); + JSONObject written = new JSONObject("{\"tiers\": {\"name\": \"stream\"}, \"fluids\": {\"elementData\": 1}}"); + + PackHydrologyValidator.warnUnknownKeys("root", written, IrisHydrology.class, temporaryFolder.getRoot(), warnings); + + assertEquals(List.of(), warnings); } @Test @@ -1003,6 +1025,15 @@ public class PackHydrologyValidatorTest { return pack; } + private List unknownKeyWarnings(PackHydrologyValidator.Validation validation) { + assertEquals(List.of(), validation.errors()); + return keyWarnings(validation); + } + + private List keyWarnings(PackHydrologyValidator.Validation validation) { + return validation.warnings().stream().filter(warning -> warning.contains("not a known key")).toList(); + } + private void assertContains(List messages, String fragment) { for (String message : messages) { if (message.contains(fragment)) { From bad795f9a7000cd29678ba0aa84664df50c9b43c Mon Sep 17 00:00:00 2001 From: Brian Fopiano Date: Mon, 2 Nov 2026 19:51:52 -0500 Subject: [PATCH 7/8] Narrow force place scope - Stop treating underground ORGANIC_STILT and CEILING_HANG pieces as forced, so they keep the veto and submerged check - Return null for broken references on a submerged start, as before force place - State force placement in the placeMode, underwater and allowWater descriptions and recapture the schema digest - Pin static objects writing every block over planned river and pond water - Add tests for forced pieces on open sea, unforced multi-piece starts on sea columns and underground pieces in water --- .../mantle/IrisStructureComponent.java | 3 +- .../structure/placement/IrisStructure.java | 2 +- .../placement/IrisStructureLocator.java | 37 +++-- .../placement/IrisStructurePlacement.java | 6 +- .../IrisStructureComponentWaterTest.java | 19 +++ .../schema/SchemaBuilderIdentityTest.java | 2 +- .../object/IrisStaticObjectLayerTest.java | 55 +++++++ .../IrisStructureLocatorContractTest.java | 154 +++++++++++++++--- 8 files changed, 239 insertions(+), 39 deletions(-) diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/IrisStructureComponent.java b/core/src/main/java/art/arcane/iris/generation/mantle/IrisStructureComponent.java index 8582d2d0c..74482fb73 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/IrisStructureComponent.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/IrisStructureComponent.java @@ -166,14 +166,13 @@ public class IrisStructureComponent extends IrisMantleComponent { stilt != null && stilt.isSupportNonOccluding()); ObjectPlaceMode mode = placement.pieceMode(structure, pieces.size()); boolean forced = placement.forcesPieces(structure, pieces.size()); - boolean sampledHeight = forced && !placement.isAnchoredUnderground(); ObjectWaterRule rule = forced ? ObjectWaterRule.FORCED : placement.isAllowWater() ? ObjectWaterRule.ENTERS_WATER : ObjectWaterRule.KEEP_OUT; int failedPieces = 0; writer.beginObjectPlacement(rule); try { for (PlacedStructurePiece p : pieces) { - if (placeObject(writer, run, p, mode, sampledHeight) == -1) { + if (placeObject(writer, run, p, mode, forced) == -1) { failedPieces++; } } diff --git a/core/src/main/java/art/arcane/iris/structure/placement/IrisStructure.java b/core/src/main/java/art/arcane/iris/structure/placement/IrisStructure.java index 97c67cf85..06ac83a22 100644 --- a/core/src/main/java/art/arcane/iris/structure/placement/IrisStructure.java +++ b/core/src/main/java/art/arcane/iris/structure/placement/IrisStructure.java @@ -100,7 +100,7 @@ public class IrisStructure extends IrisRegistrant { @Description("Whether every open connector must close with a real terminal piece through a mandatory direct fallback.") private boolean requireCaps = false; - @Description("The place mode used when stamping each piece object into the world.") + @Description("The place mode used when stamping each piece object into the world. A surface structure with a mode other than STRUCTURE_PIECE or FLOATING that assembles to one piece is force placed: it ignores the river limit and the submerged start check and writes through river, pond and sea water.") private ObjectPlaceMode placeMode = ObjectPlaceMode.STRUCTURE_PIECE; @ArrayType(min = 1, type = IrisObjectReplace.class) diff --git a/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureLocator.java b/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureLocator.java index 184167c5b..5fedea8a0 100644 --- a/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureLocator.java +++ b/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureLocator.java @@ -41,6 +41,8 @@ import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.structure.nativegen.IrisNativeStructure; import art.arcane.iris.pack.value.IrisPosition; import art.arcane.iris.generation.terrain.IrisRegion; +import art.arcane.iris.generation.runtime.GenerationFailures; +import art.arcane.iris.generation.stream.ProvisionalAnswerException; import art.arcane.iris.structure.nativegen.NativeStructureSuppression; import art.arcane.iris.structure.object.ObjectPlaceMode; import art.arcane.iris.structure.object.IrisObjectVacuum; @@ -523,12 +525,20 @@ public final class IrisStructureLocator { originZ = anchor.z(); int baseY = anchor.y(); + boolean submerged = !placement.resolvedAnchor().isCave() && !placement.isUnderwater() + && NativeStructurePlacementPlanner.isSubmerged(engine, originX, originZ); String selectedKey = selectStructureKey(placement, rng); if (selectedKey == null || selectedKey.isBlank()) { + if (submerged) { + return null; + } throw new IllegalStateException("Iris structure placement selected a blank structure key"); } IrisStructure structure = engine.getData().load(IrisStructure.class, selectedKey, false); if (structure == null) { + if (submerged) { + return null; + } throw new IllegalStateException("Iris structure placement references missing structure '" + selectedKey + "'"); } @@ -536,20 +546,19 @@ public final class IrisStructureLocator { // Gated out on this Minecraft version; the pack report already says why. return null; } - boolean submerged = !placement.resolvedAnchor().isCave() && !placement.isUnderwater() - && NativeStructurePlacementPlanner.isSubmerged(engine, originX, originZ); if (submerged && !placement.forcesPieces(structure, 1)) { return null; } - StructureGraphCompilation compilation = StructureGraphCatalog.compile(engine.getData(), structure); - if (!compilation.isAssemblyViable()) { - throw new IllegalStateException("Iris structure '" + selectedKey - + "' has no runtime-viable assembly graph"); + StructureAssemblyResult assembly; + try { + assembly = assemble(engine, structure, selectedKey, new IrisPosition(originX, baseY, originZ), rng); + } catch (IllegalStateException failure) { + GenerationFailures.rethrowEngineFailure(failure); + if (!submerged || failure instanceof ProvisionalAnswerException) { + throw failure; + } + return null; } - - StructureAssembler assembler = StructureAssembler.forData( - engine.getData(), structure, new IrisPosition(originX, baseY, originZ)); - StructureAssemblyResult assembly = assembler.assemble(rng); if (submerged && !placement.forcesPieces(structure, assembly.pieces().size())) { return null; } @@ -611,6 +620,14 @@ public final class IrisStructureLocator { return new ResolvedPlacement(placement, selectedKey, structure, pieces, rng, originX, baseY, originZ, exactY); } + private static StructureAssemblyResult assemble(Engine engine, IrisStructure structure, String key, IrisPosition origin, RNG rng) { + StructureGraphCompilation compilation = StructureGraphCatalog.compile(engine.getData(), structure); + if (!compilation.isAssemblyViable()) { + throw new IllegalStateException("Iris structure '" + key + "' has no runtime-viable assembly graph"); + } + return StructureAssembler.forData(engine.getData(), structure, origin).assemble(rng); + } + public static boolean allowsResolvedFootprint(Engine engine, ResolvedPlacement resolved) { Objects.requireNonNull(resolved, "resolved placement"); return allowsResolvedFootprint(engine, resolved.placement(), resolved.structure(), resolved.pieces()); diff --git a/core/src/main/java/art/arcane/iris/structure/placement/IrisStructurePlacement.java b/core/src/main/java/art/arcane/iris/structure/placement/IrisStructurePlacement.java index 4ea3d1233..c079316d7 100644 --- a/core/src/main/java/art/arcane/iris/structure/placement/IrisStructurePlacement.java +++ b/core/src/main/java/art/arcane/iris/structure/placement/IrisStructurePlacement.java @@ -128,10 +128,10 @@ public class IrisStructurePlacement { @Description("Optional foundation columns placed beneath the assembled structure's occupied bottom cells. Columns pass through air and fluids until they reach solid ground, up to maxDepth.") private IrisStructureStiltSettings stilt = null; - @Description("If false, the placement is skipped when its selected surface or cave column is submerged.") + @Description("If false, the placement is skipped when its selected surface or cave column is submerged. A force placed surface structure, as described on the structure's placeMode, ignores this.") private boolean underwater = false; - @Description("If true, a surface structure may cover river, stream, pond and lake water, and its pieces and stilts may fill it. If false, a surface placement is skipped when more than 10% of its footprint columns are channel, pond, cascade or waterfall water, and its pieces keep their solid blocks out of the water they touch.") + @Description("If true, a surface structure may cover river, stream, pond and lake water, and its pieces and stilts may fill it. If false, a surface placement is skipped when more than 10% of its footprint columns are channel, pond, cascade or waterfall water, and its pieces keep their solid blocks out of the water they touch. A force placed surface structure, as described on the structure's placeMode, ignores the limit and writes through the water whatever this is set to.") private boolean allowWater = false; public IrisStructureTerrain resolvedTerrain() { @@ -163,7 +163,7 @@ public class IrisStructurePlacement { } public boolean forcesPieces(IrisStructure structure, int pieces) { - return pieceMode(structure, pieces) != ObjectPlaceMode.STRUCTURE_PIECE; + return !isAnchoredUnderground() && pieceMode(structure, pieces) != ObjectPlaceMode.STRUCTURE_PIECE; } public boolean isAnchoredUnderground() { diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureComponentWaterTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureComponentWaterTest.java index f4e90b18a..681464b68 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureComponentWaterTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureComponentWaterTest.java @@ -219,6 +219,25 @@ public class IrisStructureComponentWaterTest { assertTrue("allowWater fills the water", writes.stream().anyMatch(write -> write.y() == head)); } + @Test + public void undergroundPiecesKeepTheVeto() { + world.water(WaterRole.CHANNEL, 9, 13); + IrisObject object = HydrologyWaterFixture.raft(); + int head = world.headAt(X, Z); + PlacedStructurePiece explicit = new PlacedStructurePiece(null, object, X, head + 1, Z, IrisObjectRotation.of(0, 0, 0), + X - 1, head, Z - 1, X + 1, head + 2, Z + 1); + for (ObjectPlaceMode mode : List.of(ObjectPlaceMode.ORGANIC_STILT, ObjectPlaceMode.CEILING_HANG)) { + writes.clear(); + IrisStructure structure = new IrisStructure().setPlaceMode(mode); + IrisStructurePlacement placement = new IrisStructurePlacement().setUnderground(true); + + assertEquals(mode.name(), 0, component.placePieces(writer, placement, structure, new KList<>(explicit), new RNG(7L))); + + assertFalse(mode.name(), writes.isEmpty()); + assertNoWaterOverwritten(); + } + } + @Test public void unforcedObjectsStayOffRiverWater() { world.water(WaterRole.CHANNEL, 9, 13); diff --git a/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java b/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java index c5ca13aaf..308135f53 100644 --- a/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java +++ b/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java @@ -84,7 +84,7 @@ public class SchemaBuilderIdentityTest { @ClassRule public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean(); - private static final String EXPECTED_SCHEMA_DIGEST = "7eaf3ddcf305811c453a61368a9ae886cedb1ce47d4ca6dc53953ab8f26f5a77"; + private static final String EXPECTED_SCHEMA_DIGEST = "4a9903e9c810bf297530a347175cd4a7ce24f181f4f623db9704727204c9573a"; private static final List> SCHEMA_ROOTS = List.of( IrisDimension.class, diff --git a/core/src/test/java/art/arcane/iris/structure/object/IrisStaticObjectLayerTest.java b/core/src/test/java/art/arcane/iris/structure/object/IrisStaticObjectLayerTest.java index f4ba419b4..06f874792 100644 --- a/core/src/test/java/art/arcane/iris/structure/object/IrisStaticObjectLayerTest.java +++ b/core/src/test/java/art/arcane/iris/structure/object/IrisStaticObjectLayerTest.java @@ -1,6 +1,9 @@ package art.arcane.iris.structure.object; import art.arcane.iris.generation.block.TileData; +import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; +import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster; +import art.arcane.iris.generation.hydrology.raster.WaterRole; import art.arcane.iris.generation.mantle.ObjectContinuationBundle; import art.arcane.iris.integration.Identifier; import art.arcane.iris.world.storage.matter.IrisMatterSupport; @@ -32,6 +35,7 @@ import art.arcane.volmlib.util.matter.Matter; import art.arcane.volmlib.util.matter.IrisMatter; import art.arcane.volmlib.util.mantle.flag.MantleFlag; import art.arcane.volmlib.util.matter.MatterSlice; +import art.arcane.volmlib.util.stream.ProceduralStream; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; @@ -50,6 +54,7 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyDouble; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; @@ -206,6 +211,56 @@ public class IrisStaticObjectLayerTest { verify(tiles).set(15, 0, 15, null); } + @Test + @SuppressWarnings("unchecked") + public void staticObjectOverPlannedRiverOrPondWaterWritesEveryBlock() { + for (WaterRole role : List.of(WaterRole.CHANNEL, WaterRole.POND)) { + IrisObject object = object("through-water", 3, 3, 1); + for (int x = -1; x <= 1; x++) { + for (int y = -1; y <= 1; y++) { + object.getBlocks().put(new IrisBlockVector(x, y, 0), state("minecraft:stone")); + } + } + IrisStaticObjectLayer layer = compile(entry("through-water", 8, 0, 8)); + Engine engine = mock(Engine.class); + IrisComplex complex = mock(IrisComplex.class); + HydrologyRuntime runtime = mock(HydrologyRuntime.class); + ChunkWaterRaster raster = mock(ChunkWaterRaster.class); + ProceduralStream roles = mock(ProceduralStream.class); + ProceduralStream heads = mock(ProceduralStream.class); + ProceduralStream floors = mock(ProceduralStream.class); + when(engine.getComplex()).thenReturn(complex); + when(complex.getHydrologyRuntime()).thenReturn(runtime); + when(complex.getWaterRoleStream()).thenReturn(roles); + when(complex.getWaterHeadStream()).thenReturn(heads); + when(complex.getRoundedHeighteightStream()).thenReturn(floors); + when(runtime.enabled()).thenReturn(true); + when(runtime.raster(anyInt(), anyInt())).thenReturn(raster); + when(raster.role(anyInt(), anyInt())).thenReturn(role); + when(raster.waterHead(anyInt(), anyInt())).thenReturn(70); + when(raster.terrainHeight(anyInt(), anyInt())).thenReturn(60); + when(roles.get(anyDouble(), anyDouble())).thenReturn(role); + when(heads.getDouble(anyDouble(), anyDouble())).thenReturn(70D); + when(floors.get(anyDouble(), anyDouble())).thenReturn(60); + EngineMantle engineMantle = mock(EngineMantle.class); + Mantle mantle = mock(Mantle.class); + MantleChunk chunk = mock(MantleChunk.class); + when(engine.getMantle()).thenReturn(engineMantle); + when(engineMantle.getMantle()).thenReturn(mantle); + when(mantle.useChunk(anyInt(), anyInt())).thenReturn(chunk); + when(chunk.getOrCreate(anyInt())).thenReturn(mock(Matter.class)); + Hunk output = Hunk.newArrayHunk(16, 384, 16); + + layer.apply(engine, 0, 0, output); + + for (int x = 7; x <= 9; x++) { + for (int y = 63; y <= 65; y++) { + assertSame(role + " " + x + "," + y, state("minecraft:stone"), output.get(x, y, 8)); + } + } + } + } + @Test public void transitionRejectsWholeRotatedPlacementBeforeChunkWrites() { IrisObject object = object("rotated", 1, 1, 5); diff --git a/core/src/test/java/art/arcane/iris/structure/placement/IrisStructureLocatorContractTest.java b/core/src/test/java/art/arcane/iris/structure/placement/IrisStructureLocatorContractTest.java index 6b993adfe..379391a48 100644 --- a/core/src/test/java/art/arcane/iris/structure/placement/IrisStructureLocatorContractTest.java +++ b/core/src/test/java/art/arcane/iris/structure/placement/IrisStructureLocatorContractTest.java @@ -47,6 +47,7 @@ import art.arcane.volmlib.util.stream.ProceduralStream; import org.junit.Test; import java.util.HashSet; +import java.util.List; import java.util.Set; import static org.junit.Assert.assertEquals; @@ -54,6 +55,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; @@ -502,28 +504,7 @@ public class IrisStructureLocatorContractTest { @Test public void forcedSinglePiecesPlaceInTheMiddleOfARiver() { - Engine engine = densityEngine(1.0, false, -64, 384, -2032, 2032); - IrisObject object = engine.getData().load(IrisObject.class, "test:density/object", false); - when(object.getW()).thenReturn(10); - when(object.getD()).thenReturn(10); - IrisComplex complex = mock(IrisComplex.class); - when(engine.getComplex()).thenReturn(complex); - when(complex.allowsNewGenerationFootprint(anyInt(), anyInt(), anyInt(), anyInt())).thenReturn(true); - @SuppressWarnings("unchecked") - ProceduralStream waterHead = mock(ProceduralStream.class); - when(complex.getWaterHeadStream()).thenReturn(waterHead); - when(waterHead.get(anyDouble(), anyDouble())).thenReturn(124D); - when(waterHead.getDouble(anyDouble(), anyDouble())).thenReturn(124D); - @SuppressWarnings("unchecked") - ProceduralStream roles = mock(ProceduralStream.class); - when(complex.getWaterRoleStream()).thenReturn(roles); - when(roles.get(anyDouble(), anyDouble())).thenReturn(WaterRole.CHANNEL); - @SuppressWarnings("unchecked") - ProceduralStream beds = mock(ProceduralStream.class); - when(beds.get(anyDouble(), anyDouble())).thenReturn(120); - when(complex.getRoundedHeighteightStream()).thenReturn(beds); - when(engine.getHeight(anyInt(), anyInt(), eq(true))).thenReturn(120); - when(engine.getDimension().getFluidHeight()).thenReturn(63); + Engine engine = submergedEngine(WaterRole.CHANNEL, false, -2032, 2032); IrisStructurePlacement placement = engine.getDimension().getStructures().get(0); IrisStructure structure = engine.getData().load(IrisStructure.class, "test:density", false); @@ -540,6 +521,135 @@ public class IrisStructureLocatorContractTest { IrisStructureLocator.resolvePlacement(engine, placement, 3, 4)); } + @Test + public void forcedSurfacePiecesPlaceOnOpenSea() { + Engine engine = submergedEngine(WaterRole.NONE, false, -2032, 2032); + IrisStructurePlacement placement = engine.getDimension().getStructures().get(0); + IrisStructure structure = engine.getData().load(IrisStructure.class, "test:density", false); + assertFalse(placement.isUnderwater()); + + assertNull("an unforced structure stays off the sea", + IrisStructureLocator.resolvePlacement(engine, placement, 3, 4)); + + structure.setPlaceMode(ObjectPlaceMode.CENTER_HEIGHT); + + assertNotNull(IrisStructureLocator.resolvePlacement(engine, placement, 3, 4)); + } + + @Test + public void unforcedMultiPieceStartsStayOffSeaColumns() { + Engine engine = submergedEngine(WaterRole.NONE, false, -2032, 2032); + IrisStructurePlacement placement = engine.getDimension().getStructures().get(0); + IrisStructure structure = engine.getData().load(IrisStructure.class, "test:density", false); + structure.setPlaceMode(ObjectPlaceMode.CENTER_HEIGHT); + registerTwoPieceGraph(engine.getData(), structure, "test:density"); + + placement.setUnderwater(true); + IrisStructureLocator.ResolvedPlacement allowed = IrisStructureLocator.resolvePlacement(engine, placement, 3, 4); + assertNotNull(allowed); + assertEquals(2, allowed.pieces().size()); + placement.setUnderwater(false); + + assertNull(IrisStructureLocator.resolvePlacement(engine, placement, 3, 4)); + } + + @Test + public void undergroundPiecesKeepTheSubmergedCheck() { + for (ObjectPlaceMode mode : List.of(ObjectPlaceMode.ORGANIC_STILT, ObjectPlaceMode.CEILING_HANG)) { + Engine engine = submergedEngine(WaterRole.CHANNEL, true, -40, -20); + IrisStructurePlacement placement = engine.getDimension().getStructures().get(0); + IrisStructure structure = engine.getData().load(IrisStructure.class, "test:density", false); + structure.setPlaceMode(mode); + + assertFalse(placement.forcesPieces(structure, 1)); + assertNull(mode.name(), IrisStructureLocator.resolvePlacement(engine, placement, 3, 4)); + } + } + + @Test + public void brokenReferencesOnASubmergedStartReturnNull() { + Engine engine = submergedEngine(WaterRole.NONE, false, -2032, 2032); + IrisStructurePlacement placement = engine.getDimension().getStructures().get(0); + IrisStructure structure = engine.getData().load(IrisStructure.class, "test:density", false); + structure.setPlaceMode(ObjectPlaceMode.CENTER_HEIGHT); + structure.setStartPool("test:missing-pool"); + + assertNull("a graph that cannot assemble", IrisStructureLocator.resolvePlacement(engine, placement, 3, 4)); + + placement.getStructures().clear(); + placement.getStructures().add("test:missing-structure"); + + assertNull("a missing structure", IrisStructureLocator.resolvePlacement(engine, placement, 3, 4)); + } + + @Test + public void brokenReferencesOnADryStartStillThrow() { + Engine engine = submergedEngine(WaterRole.NONE, false, -2032, 2032); + when(engine.getHeight(anyInt(), anyInt(), eq(true))).thenReturn(180); + IrisStructurePlacement placement = engine.getDimension().getStructures().get(0); + IrisStructure structure = engine.getData().load(IrisStructure.class, "test:density", false); + structure.setStartPool("test:missing-pool"); + + assertThrows(IllegalStateException.class, () -> IrisStructureLocator.resolvePlacement(engine, placement, 3, 4)); + + placement.getStructures().clear(); + placement.getStructures().add("test:missing-structure"); + + assertThrows(IllegalStateException.class, () -> IrisStructureLocator.resolvePlacement(engine, placement, 3, 4)); + } + + private Engine submergedEngine(WaterRole role, boolean underground, int placementMin, int placementMax) { + Engine engine = densityEngine(1.0, underground, -64, 384, placementMin, placementMax); + IrisObject object = engine.getData().load(IrisObject.class, "test:density/object", false); + when(object.getW()).thenReturn(10); + when(object.getD()).thenReturn(10); + IrisComplex complex = mock(IrisComplex.class); + when(engine.getComplex()).thenReturn(complex); + when(complex.allowsNewGenerationFootprint(anyInt(), anyInt(), anyInt(), anyInt())).thenReturn(true); + @SuppressWarnings("unchecked") + ProceduralStream waterHead = mock(ProceduralStream.class); + when(complex.getWaterHeadStream()).thenReturn(waterHead); + when(waterHead.get(anyDouble(), anyDouble())).thenReturn(124D); + when(waterHead.getDouble(anyDouble(), anyDouble())).thenReturn(124D); + @SuppressWarnings("unchecked") + ProceduralStream roles = mock(ProceduralStream.class); + when(complex.getWaterRoleStream()).thenReturn(roles); + when(roles.get(anyDouble(), anyDouble())).thenReturn(role); + @SuppressWarnings("unchecked") + ProceduralStream beds = mock(ProceduralStream.class); + when(beds.get(anyDouble(), anyDouble())).thenReturn(120); + when(complex.getRoundedHeighteightStream()).thenReturn(beds); + when(engine.getHeight(anyInt(), anyInt(), eq(true))).thenReturn(120); + when(engine.getDimension().getFluidHeight()).thenReturn(63); + return engine; + } + + private void registerTwoPieceGraph(IrisData data, IrisStructure structure, String prefix) { + registerSinglePieceGraph(data, structure, prefix); + String targetPool = prefix + "/target"; + String targetPiece = prefix + "/target-piece"; + IrisJigsawPiece start = data.load(IrisJigsawPiece.class, prefix + "/piece", false); + start.setRotatable(false); + start.getConnectors().add(new IrisJigsawConnector() + .setPosition(new IrisPosition(0, 0, 0)) + .setDirection(IrisDirection.EAST_POSITIVE_X) + .setPool(targetPool) + .setName("source") + .setTargetName("door")); + IrisJigsawPiece target = new IrisJigsawPiece().setObject(prefix + "/object").setRotatable(false); + target.getConnectors().add(new IrisJigsawConnector() + .setPosition(new IrisPosition(0, 0, 0)) + .setDirection(IrisDirection.WEST_NEGATIVE_X) + .setPool(targetPool) + .setName("door") + .setTargetName("unused")); + IrisJigsawPool pool = new IrisJigsawPool(); + pool.getPieces().add(new IrisJigsawPieceEntry(targetPiece, 1)); + when(data.load(IrisJigsawPool.class, targetPool, false)).thenReturn(pool); + when(data.load(IrisJigsawPiece.class, targetPiece, false)).thenReturn(target); + structure.setMaxDepth(1); + } + @Test public void undergroundIrisStructuresIgnoreRiversAbove() { Engine engine = densityEngine(1.0, true, -64, 384, -40, -20); From 75567295c0199b33a9587e19eae641a87eee76e9 Mon Sep 17 00:00:00 2001 From: Brian Fopiano Date: Mon, 2 Nov 2026 20:01:45 -0500 Subject: [PATCH 8/8] Fail broken forced structures - Remove the catch around assembly so a forced-mode structure with a broken graph fails on a submerged start as on a dry one - Keep returning null for blank and missing keys on a submerged start - Test that an unforced structure returns null on a submerged start without reaching assembly --- .../placement/IrisStructureLocator.java | 13 +----------- .../IrisStructureLocatorContractTest.java | 21 ++++++++++++++++--- 2 files changed, 19 insertions(+), 15 deletions(-) diff --git a/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureLocator.java b/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureLocator.java index 5fedea8a0..8c09364b1 100644 --- a/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureLocator.java +++ b/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureLocator.java @@ -41,8 +41,6 @@ import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.structure.nativegen.IrisNativeStructure; import art.arcane.iris.pack.value.IrisPosition; import art.arcane.iris.generation.terrain.IrisRegion; -import art.arcane.iris.generation.runtime.GenerationFailures; -import art.arcane.iris.generation.stream.ProvisionalAnswerException; import art.arcane.iris.structure.nativegen.NativeStructureSuppression; import art.arcane.iris.structure.object.ObjectPlaceMode; import art.arcane.iris.structure.object.IrisObjectVacuum; @@ -549,16 +547,7 @@ public final class IrisStructureLocator { if (submerged && !placement.forcesPieces(structure, 1)) { return null; } - StructureAssemblyResult assembly; - try { - assembly = assemble(engine, structure, selectedKey, new IrisPosition(originX, baseY, originZ), rng); - } catch (IllegalStateException failure) { - GenerationFailures.rethrowEngineFailure(failure); - if (!submerged || failure instanceof ProvisionalAnswerException) { - throw failure; - } - return null; - } + StructureAssemblyResult assembly = assemble(engine, structure, selectedKey, new IrisPosition(originX, baseY, originZ), rng); if (submerged && !placement.forcesPieces(structure, assembly.pieces().size())) { return null; } diff --git a/core/src/test/java/art/arcane/iris/structure/placement/IrisStructureLocatorContractTest.java b/core/src/test/java/art/arcane/iris/structure/placement/IrisStructureLocatorContractTest.java index 379391a48..b71aeb0ac 100644 --- a/core/src/test/java/art/arcane/iris/structure/placement/IrisStructureLocatorContractTest.java +++ b/core/src/test/java/art/arcane/iris/structure/placement/IrisStructureLocatorContractTest.java @@ -567,19 +567,34 @@ public class IrisStructureLocatorContractTest { } @Test - public void brokenReferencesOnASubmergedStartReturnNull() { + public void anUnforcedStructureNeverAssemblesOnASubmergedStart() { + Engine engine = submergedEngine(WaterRole.NONE, false, -2032, 2032); + IrisStructurePlacement placement = engine.getDimension().getStructures().get(0); + IrisStructure structure = engine.getData().load(IrisStructure.class, "test:density", false); + structure.setStartPool("test:missing-pool"); + + assertNull(IrisStructureLocator.resolvePlacement(engine, placement, 3, 4)); + } + + @Test + public void aForcedModeStructureWithABrokenGraphThrowsOnASubmergedStart() { Engine engine = submergedEngine(WaterRole.NONE, false, -2032, 2032); IrisStructurePlacement placement = engine.getDimension().getStructures().get(0); IrisStructure structure = engine.getData().load(IrisStructure.class, "test:density", false); structure.setPlaceMode(ObjectPlaceMode.CENTER_HEIGHT); structure.setStartPool("test:missing-pool"); - assertNull("a graph that cannot assemble", IrisStructureLocator.resolvePlacement(engine, placement, 3, 4)); + assertThrows(IllegalStateException.class, () -> IrisStructureLocator.resolvePlacement(engine, placement, 3, 4)); + } + @Test + public void aMissingStructureOnASubmergedStartReturnsNull() { + Engine engine = submergedEngine(WaterRole.NONE, false, -2032, 2032); + IrisStructurePlacement placement = engine.getDimension().getStructures().get(0); placement.getStructures().clear(); placement.getStructures().add("test:missing-structure"); - assertNull("a missing structure", IrisStructureLocator.resolvePlacement(engine, placement, 3, 4)); + assertNull(IrisStructureLocator.resolvePlacement(engine, placement, 3, 4)); } @Test