Integrate lane B

- Merge lane B (sea surface, sea inlets, cave pools, wetness, persisted codes, scheduling knobs) onto lane A
- PackHydrologyValidatorTest keeps lane A's loadHydrology helper and lane B's validation tests
- Recapture HydrologySettingsTest.DEFAULT_FINGERPRINT and SchemaBuilderIdentityTest.EXPECTED_SCHEMA_DIGEST for the combined settings and schema
This commit is contained in:
Brian Neumann-Fopiano committed 2026-11-02 05:11:09 -05:00
commit 2ddc9f1106
171 files changed
+7337 -1896

No files matched your search

@@ -11,6 +11,7 @@ import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureFoundat
import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureSurfaceSupportBuilder;
import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureSurfaceFitter;
import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureSurfaceFitter.SeaSurface;
import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureVegetationClearer;
@@ -238,7 +239,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)),
(x, z) -> x < 2 ? groundY - 32 : groundY + 32);
(x, z) -> x < 2 ? groundY - 32 : groundY + 32, SeaSurface.NONE);
for (int x = 0; x <= 3; x++) {
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, x, groundY, 0));
@@ -266,7 +267,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
put(blocks, 0, groundY - 19, 0, Blocks.DIRT.defaultBlockState());
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY);
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY, SeaSurface.NONE);
for (int y = groundY - 19; y <= groundY; y++) {
assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, y, 0));
@@ -292,7 +293,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureTerrainIntegrator.TerrainTarget target = surfaceTarget(start, StructureTerrainMode.FLATTEN);
((IrisStructureTerrain) target.terrain()).setHorizontalPadding(24).setFlattenRange(64);
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area, List.of(target), (px, pz) -> groundY);
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area, List.of(target), (px, pz) -> groundY, SeaSurface.NONE);
for (int y = groundY - 34; y <= groundY - 13; y++) {
assertEquals("Cave at " + y, Blocks.CAVE_AIR.defaultBlockState(), state(blocks, x, y, z));
@@ -315,7 +316,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
}
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY);
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY, SeaSurface.NONE);
for (int y = groundY - 8; y < groundY; y++) {
assertEquals("Foundation at " + y, Blocks.STONE.defaultBlockState(), state(blocks, 0, y, 0));
@@ -337,9 +338,9 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
Map<BlockPos, BlockState> originalSubmerged = new HashMap<>(submerged);
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(buried), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> 100);
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> 100, SeaSurface.NONE);
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(submerged), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY - 8);
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY - 8, SeaSurface.NONE);
assertEquals(originalBuried, buried);
assertEquals(originalSubmerged, submerged);
@@ -386,7 +387,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
return method.invoke(delegate, arguments);
});
NativeStructureSurfaceFitter.prepareSurfaceStructures(bounded, area, List.of(target), (x, z) -> 127);
NativeStructureSurfaceFitter.prepareSurfaceStructures(bounded, area, List.of(target), (x, z) -> 127, SeaSurface.NONE);
assertEquals(Blocks.GOLD_BLOCK.defaultBlockState(), state(blocks, 0, 94, 0));
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 95, 0));
@@ -477,7 +478,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)),
(x, z) -> x == footprint.minX() ? 80 : 112);
(x, z) -> x == footprint.minX() ? 80 : 112, SeaSurface.NONE);
assertEquals(81, piece.getBoundingBox().minY());
assertTrue(piece.attemptVanillaAlignment());
@@ -511,7 +512,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
WorldGenLevel world = world(blocks);
NativeStructureSurfaceFitter.prepareSurfaceStructures(world, area, List.of(target),
(x, z) -> x == 0 || x == 8 ? 64 : 96);
(x, z) -> x == 0 || x == 8 ? 64 : 96, SeaSurface.NONE);
NativeStructureTemplateOccupancy.OccupancyResult occupancy = NativeStructureTemplateOccupancy.resolve(
world, path, BlockPos.ZERO, area,
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
@@ -555,7 +556,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
WorldGenLevel world = world(chunk);
NativeStructureSurfaceFitter.SurfaceTerrainPlan plan = NativeStructureSurfaceFitter.prepareSurfaceStructures(
world, area, List.of(target), (x, z) -> x < 4 ? 96 : 32);
world, area, List.of(target), (x, z) -> x < 4 ? 96 : 32, SeaSurface.NONE);
assertEquals(96, chunk.getHeight(Heightmap.Types.WORLD_SURFACE_WG, 0, 0));
assertEquals(32, chunk.getHeight(Heightmap.Types.WORLD_SURFACE_WG, 8, 0));
@@ -615,7 +616,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
WorldGenLevel world = world(chunk);
NativeStructureSurfaceFitter.SurfaceTerrainPlan plan = NativeStructureSurfaceFitter.prepareSurfaceStructures(
world, area, List.of(target), (x, z) -> x == 0 || x == 8 ? 64 : 96);
world, area, List.of(target), (x, z) -> x == 0 || x == 8 ? 64 : 96, SeaSurface.NONE);
plan.primeHeightmaps(chunk);
NativeStructureTemplateOccupancy.OccupancyResult occupancy = NativeStructureTemplateOccupancy.resolve(
world, path, BlockPos.ZERO, area,
@@ -670,7 +671,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
}
NativeStructureSurfaceFitter.SurfaceTerrainPlan plan = NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, List.of(target),
(x, z) -> (x == 0 || x == 8) && (z == 0 || z == 8) ? 64 : 96);
(x, z) -> (x == 0 || x == 8) && (z == 0 || z == 8) ? 64 : 96, SeaSurface.NONE);
for (int x = 0; x <= 8; x++) {
for (int z = 0; z <= 8; z++) {
@@ -740,7 +741,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, List.of(surfaceTarget(start)),
(x, z) -> 64);
(x, z) -> 64, SeaSurface.NONE);
assertEquals(before, blocks);
}
@@ -866,7 +867,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
new IrisStructureTerrain().setMode(StructureTerrainMode.SOURCE)));
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, targets,
(x, z) -> 65);
(x, z) -> 65, SeaSurface.NONE);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 1, 71, 1));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 11, 71, 1));
@@ -891,7 +892,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, List.of(surfaceTarget(start)),
(x, z) -> 64);
(x, z) -> 64, SeaSurface.NONE);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 68, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 15, 64, 0));
@@ -912,7 +913,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, List.of(surfaceTarget(start)),
(x, z) -> 40);
(x, z) -> 40, SeaSurface.NONE);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 46, 0));
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 47, 0));
@@ -944,7 +945,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, List.of(surfaceTarget(start)),
(x, z) -> x == 0 ? 60 : x == 30 ? 72 : 64);
(x, z) -> x == 0 ? 60 : x == 30 ? 72 : 64, SeaSurface.NONE);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 61, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 30, 71, 0));
@@ -972,7 +973,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 64, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 63, 0));
@@ -997,7 +998,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 65, 0));
assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, 64, 0));
@@ -1018,7 +1019,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 80);
(x, z) -> 80, SeaSurface.NONE);
for (int y = 61; y <= 74; y++) {
assertFalse(state(blocks, 0, y, 0).isAir());
@@ -1043,7 +1044,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 79);
(x, z) -> 79, SeaSurface.NONE);
for (int y = 61; y <= 74; y++) {
assertFalse(state(blocks, 0, y, 0).isAir());
@@ -1075,7 +1076,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
for (int y = 61; y <= 64; y++) {
put(blocks, 0, y, 0, Blocks.CAVE_AIR.defaultBlockState());
}
@@ -1115,7 +1116,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
put(blocks, 0, 65, 0, Blocks.COBBLESTONE.defaultBlockState());
NativeStructureSurfaceFitter.repairVacuumFoundations(
@@ -1145,13 +1146,13 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.SurfaceTerrainPlan widePlan =
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(wideBlocks), wideArea, List.of(target), (x, z) -> 60);
world(wideBlocks), wideArea, List.of(target), (x, z) -> 60, SeaSurface.NONE);
NativeStructureSurfaceFitter.SurfaceTerrainPlan westPlan =
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(splitBlocks), westArea, List.of(target), (x, z) -> 60);
world(splitBlocks), westArea, List.of(target), (x, z) -> 60, SeaSurface.NONE);
NativeStructureSurfaceFitter.SurfaceTerrainPlan eastPlan =
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(splitBlocks), eastArea, List.of(target), (x, z) -> 60);
world(splitBlocks), eastArea, List.of(target), (x, z) -> 60, SeaSurface.NONE);
for (int x = 15; x <= 16; x++) {
for (int y = 61; y <= 64; y++) {
put(wideBlocks, x, y, 0, Blocks.CAVE_AIR.defaultBlockState());
@@ -1186,7 +1187,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
assertEquals(originalBlocks, blocks);
}
@@ -1207,7 +1208,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
assertEquals(originalBlocks, blocks);
}
@@ -1231,7 +1232,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 1, 66, 0));
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 1, 67, 0));
@@ -1256,7 +1257,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
assertEquals(originalBlocks, blocks);
}
@@ -1276,7 +1277,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 65, 0));
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 66, 0));
@@ -1301,7 +1302,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
assertEquals(originalBlocks, blocks);
}
@@ -1322,7 +1323,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 4, 61, 4));
}
@@ -1340,7 +1341,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 50);
(x, z) -> 50, SeaSurface.NONE);
assertEquals(originalBlocks, blocks);
}
@@ -1359,7 +1360,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60, 1);
(x, z) -> 60, SeaSurface.NONE, 1);
assertEquals(originalBlocks, blocks);
}
@@ -1383,7 +1384,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
for (int y = 61; y <= 65; y++) {
assertFalse(state(blocks, 10, y, 0).isAir());
@@ -1411,15 +1412,15 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
Map<BlockPos, BlockState> reverseSplitBlocks = flatTerrain(wideArea, 60);
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(wideBlocks), wideArea, List.of(target), (x, z) -> 60);
world(wideBlocks), wideArea, List.of(target), (x, z) -> 60, SeaSurface.NONE);
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(splitBlocks), westArea, List.of(target), (x, z) -> 60);
world(splitBlocks), westArea, List.of(target), (x, z) -> 60, SeaSurface.NONE);
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(splitBlocks), eastArea, List.of(target), (x, z) -> 60);
world(splitBlocks), eastArea, List.of(target), (x, z) -> 60, SeaSurface.NONE);
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(reverseSplitBlocks), eastArea, List.of(target), (x, z) -> 60);
world(reverseSplitBlocks), eastArea, List.of(target), (x, z) -> 60, SeaSurface.NONE);
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(reverseSplitBlocks), westArea, List.of(target), (x, z) -> 60);
world(reverseSplitBlocks), westArea, List.of(target), (x, z) -> 60, SeaSurface.NONE);
assertEquals(wideBlocks, splitBlocks);
assertEquals(wideBlocks, reverseSplitBlocks);
@@ -1883,7 +1884,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
List<NativeStructureTerrainIntegrator.TerrainTarget> targets =
List.of(surfaceTarget(start));
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world, area, targets, (x, z) -> 60);
world, area, targets, (x, z) -> 60, SeaSurface.NONE);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 2, 62, 2));
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 2, 65, 2));
@@ -1937,7 +1938,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(lowered), new BlockPos.MutableBlockPos(),
0, 0, 64, 62, -64, 319);
0, 0, 64, 62, -64, 319, false, SeaSurface.NONE);
assertEquals(Blocks.STONE.defaultBlockState(), state(lowered, 0, 61, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(lowered, 0, 62, 0));
@@ -1952,7 +1953,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(raised), new BlockPos.MutableBlockPos(),
0, 0, 64, 68, -64, 319);
0, 0, 64, 68, -64, 319, false, SeaSurface.NONE);
assertEquals(Blocks.DIRT.defaultBlockState(), state(raised, 0, 65, 0));
assertEquals(Blocks.DIRT.defaultBlockState(), state(raised, 0, 66, 0));
@@ -1971,7 +1972,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 99, 83, -64, 319);
0, 0, 99, 83, -64, 319, false, SeaSurface.NONE);
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 82, 0));
assertEquals(Blocks.SNOW_BLOCK.defaultBlockState(), state(blocks, 0, 83, 0));
@@ -1993,7 +1994,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 62, -64, 319);
0, 0, 64, 62, -64, 319, false, SeaSurface.NONE);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 62, 0));
for (int y = 63; y <= 68; y++) {
@@ -2015,7 +2016,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 62, -64, 319);
0, 0, 64, 62, -64, 319, false, SeaSurface.NONE);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 62, 0));
for (int y = 63; y <= 65; y++) {
@@ -2034,7 +2035,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 64, -64, 319, true);
0, 0, 64, 64, -64, 319, true, SeaSurface.NONE);
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 63, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 64, 0));
@@ -2047,7 +2048,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 64, -64, 319, true);
0, 0, 64, 64, -64, 319, true, SeaSurface.NONE);
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 63, 0));
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 64, 0));
@@ -2059,7 +2060,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, -64, -64, -64, 319, true);
0, 0, -64, -64, -64, 319, true, SeaSurface.NONE);
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, -64, 0));
}
@@ -2076,7 +2077,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 68, -64, 319);
0, 0, 64, 68, -64, 319, false, SeaSurface.NONE);
assertEquals(log, state(blocks, 0, 66, 0));
assertEquals(leaves, state(blocks, 0, 68, 0));
@@ -2098,7 +2099,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
world, chunk, area, List.of(desertStart()));
NativeStructureSurfaceFitter.applySurfaceColumn(
world, new BlockPos.MutableBlockPos(),
0, 0, 64, 68, -64, 319);
0, 0, 64, 68, -64, 319, false, SeaSurface.NONE);
assertEquals(Blocks.DIRT.defaultBlockState(), chunk.getBlockState(new BlockPos(0, 65, 0)));
assertEquals(Blocks.DIRT.defaultBlockState(), chunk.getBlockState(new BlockPos(0, 66, 0)));
@@ -2116,7 +2117,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 62, -64, 319);
0, 0, 64, 62, -64, 319, false, SeaSurface.NONE);
assertEquals(Blocks.WATER.defaultBlockState(), state(blocks, 0, 63, 0));
assertEquals(Blocks.WATER.defaultBlockState(), state(blocks, 0, 64, 0));
@@ -3,6 +3,7 @@ package art.arcane.iris.nativegen;
import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureVerticalPlacer;
import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureSurfaceFitter;
import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureSurfaceFitter.SeaSurface;
import art.arcane.volmlib.nativelib.minecraft26_2.terrain.NativeStructureVegetationClearer;
@@ -206,7 +207,7 @@ public class NativeStructurePostProcessorVegetationTest {
write(chunk, 4, 106, 4, Blocks.CACTUS_FLOWER.defaultBlockState());
NativeStructureSurfaceFitter.applySurfaceColumn(
world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 102, 93, MIN_Y, MAX_Y);
world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 102, 93, MIN_Y, MAX_Y, false, SeaSurface.NONE);
assertEquals(Blocks.SAND.defaultBlockState(), chunk.getBlockState(new BlockPos(4, 93, 4)));
for (int y = 94; y <= 106; y++) {
@@ -227,9 +228,9 @@ public class NativeStructurePostProcessorVegetationTest {
WorldGenLevel world = world(chunk);
NativeStructureSurfaceFitter.applySurfaceColumn(
world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y);
world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y, false, SeaSurface.NONE);
NativeStructureSurfaceFitter.applySurfaceColumn(
world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y);
world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y, false, SeaSurface.NONE);
assertTrue(chunk.getBlockState(new BlockPos(4, 65, 4)).isAir());
assertTrue(chunk.getBlockState(new BlockPos(4, 66, 4)).isAir());
@@ -249,7 +250,7 @@ public class NativeStructurePostProcessorVegetationTest {
write(chunk, 4, 67, 4, Blocks.CACTUS_FLOWER.defaultBlockState());
NativeStructureSurfaceFitter.applySurfaceColumn(
world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y);
world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y, false, SeaSurface.NONE);
assertEquals(boundary, chunk.getBlockState(new BlockPos(4, 65, 4)));
assertEquals(Blocks.CACTUS.defaultBlockState(), chunk.getBlockState(new BlockPos(4, 66, 4)));
@@ -271,9 +272,9 @@ public class NativeStructurePostProcessorVegetationTest {
WorldGenLevel world = world(chunk);
NativeStructureSurfaceFitter.applySurfaceColumn(
world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y);
world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y, false, SeaSurface.NONE);
NativeStructureSurfaceFitter.applySurfaceColumn(
world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y);
world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y, false, SeaSurface.NONE);
assertEquals(Blocks.SAND.defaultBlockState(), chunk.getBlockState(new BlockPos(4, 60, 4)));
for (int y = 61; y <= 67; y++) {
@@ -11,6 +11,7 @@ import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureFoundationBu
import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureSurfaceSupportBuilder;
import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureSurfaceFitter;
import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureSurfaceFitter.SeaSurface;
import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureVegetationClearer;
@@ -238,7 +239,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)),
(x, z) -> x < 2 ? groundY - 32 : groundY + 32);
(x, z) -> x < 2 ? groundY - 32 : groundY + 32, SeaSurface.NONE);
for (int x = 0; x <= 3; x++) {
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, x, groundY, 0));
@@ -266,7 +267,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
put(blocks, 0, groundY - 19, 0, Blocks.DIRT.defaultBlockState());
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY);
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY, SeaSurface.NONE);
for (int y = groundY - 19; y <= groundY; y++) {
assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, y, 0));
@@ -292,7 +293,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureTerrainIntegrator.TerrainTarget target = surfaceTarget(start, StructureTerrainMode.FLATTEN);
((IrisStructureTerrain) target.terrain()).setHorizontalPadding(24).setFlattenRange(64);
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area, List.of(target), (px, pz) -> groundY);
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area, List.of(target), (px, pz) -> groundY, SeaSurface.NONE);
for (int y = groundY - 34; y <= groundY - 13; y++) {
assertEquals("Cave at " + y, Blocks.CAVE_AIR.defaultBlockState(), state(blocks, x, y, z));
@@ -315,7 +316,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
}
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY);
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY, SeaSurface.NONE);
for (int y = groundY - 8; y < groundY; y++) {
assertEquals("Foundation at " + y, Blocks.STONE.defaultBlockState(), state(blocks, 0, y, 0));
@@ -337,9 +338,9 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
Map<BlockPos, BlockState> originalSubmerged = new HashMap<>(submerged);
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(buried), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> 100);
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> 100, SeaSurface.NONE);
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(submerged), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY - 8);
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)), (x, z) -> groundY - 8, SeaSurface.NONE);
assertEquals(originalBuried, buried);
assertEquals(originalSubmerged, submerged);
@@ -386,7 +387,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
return method.invoke(delegate, arguments);
});
NativeStructureSurfaceFitter.prepareSurfaceStructures(bounded, area, List.of(target), (x, z) -> 127);
NativeStructureSurfaceFitter.prepareSurfaceStructures(bounded, area, List.of(target), (x, z) -> 127, SeaSurface.NONE);
assertEquals(Blocks.GOLD_BLOCK.defaultBlockState(), state(blocks, 0, 94, 0));
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 95, 0));
@@ -477,7 +478,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.FLATTEN)),
(x, z) -> x == footprint.minX() ? 80 : 112);
(x, z) -> x == footprint.minX() ? 80 : 112, SeaSurface.NONE);
assertEquals(81, piece.getBoundingBox().minY());
assertTrue(piece.attemptVanillaAlignment());
@@ -511,7 +512,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
WorldGenLevel world = world(blocks);
NativeStructureSurfaceFitter.prepareSurfaceStructures(world, area, List.of(target),
(x, z) -> x == 0 || x == 8 ? 64 : 96);
(x, z) -> x == 0 || x == 8 ? 64 : 96, SeaSurface.NONE);
NativeStructureTemplateOccupancy.OccupancyResult occupancy = NativeStructureTemplateOccupancy.resolve(
world, path, BlockPos.ZERO, area,
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
@@ -555,7 +556,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
WorldGenLevel world = world(chunk);
NativeStructureSurfaceFitter.SurfaceTerrainPlan plan = NativeStructureSurfaceFitter.prepareSurfaceStructures(
world, area, List.of(target), (x, z) -> x < 4 ? 96 : 32);
world, area, List.of(target), (x, z) -> x < 4 ? 96 : 32, SeaSurface.NONE);
assertEquals(96, chunk.getHeight(Heightmap.Types.WORLD_SURFACE_WG, 0, 0));
assertEquals(32, chunk.getHeight(Heightmap.Types.WORLD_SURFACE_WG, 8, 0));
@@ -615,7 +616,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
WorldGenLevel world = world(chunk);
NativeStructureSurfaceFitter.SurfaceTerrainPlan plan = NativeStructureSurfaceFitter.prepareSurfaceStructures(
world, area, List.of(target), (x, z) -> x == 0 || x == 8 ? 64 : 96);
world, area, List.of(target), (x, z) -> x == 0 || x == 8 ? 64 : 96, SeaSurface.NONE);
plan.primeHeightmaps(chunk);
NativeStructureTemplateOccupancy.OccupancyResult occupancy = NativeStructureTemplateOccupancy.resolve(
world, path, BlockPos.ZERO, area,
@@ -670,7 +671,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
}
NativeStructureSurfaceFitter.SurfaceTerrainPlan plan = NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, List.of(target),
(x, z) -> (x == 0 || x == 8) && (z == 0 || z == 8) ? 64 : 96);
(x, z) -> (x == 0 || x == 8) && (z == 0 || z == 8) ? 64 : 96, SeaSurface.NONE);
for (int x = 0; x <= 8; x++) {
for (int z = 0; z <= 8; z++) {
@@ -740,7 +741,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, List.of(surfaceTarget(start)),
(x, z) -> 64);
(x, z) -> 64, SeaSurface.NONE);
assertEquals(before, blocks);
}
@@ -866,7 +867,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
new IrisStructureTerrain().setMode(StructureTerrainMode.SOURCE)));
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, targets,
(x, z) -> 65);
(x, z) -> 65, SeaSurface.NONE);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 1, 71, 1));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 11, 71, 1));
@@ -891,7 +892,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, List.of(surfaceTarget(start)),
(x, z) -> 64);
(x, z) -> 64, SeaSurface.NONE);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 68, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 15, 64, 0));
@@ -912,7 +913,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, List.of(surfaceTarget(start)),
(x, z) -> 40);
(x, z) -> 40, SeaSurface.NONE);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 46, 0));
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 47, 0));
@@ -944,7 +945,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area, List.of(surfaceTarget(start)),
(x, z) -> x == 0 ? 60 : x == 30 ? 72 : 64);
(x, z) -> x == 0 ? 60 : x == 30 ? 72 : 64, SeaSurface.NONE);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 61, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 30, 71, 0));
@@ -972,7 +973,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 64, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 63, 0));
@@ -997,7 +998,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 65, 0));
assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, 64, 0));
@@ -1018,7 +1019,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 80);
(x, z) -> 80, SeaSurface.NONE);
for (int y = 61; y <= 74; y++) {
assertFalse(state(blocks, 0, y, 0).isAir());
@@ -1043,7 +1044,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 79);
(x, z) -> 79, SeaSurface.NONE);
for (int y = 61; y <= 74; y++) {
assertFalse(state(blocks, 0, y, 0).isAir());
@@ -1075,7 +1076,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
for (int y = 61; y <= 64; y++) {
put(blocks, 0, y, 0, Blocks.CAVE_AIR.defaultBlockState());
}
@@ -1115,7 +1116,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
put(blocks, 0, 65, 0, Blocks.COBBLESTONE.defaultBlockState());
NativeStructureSurfaceFitter.repairVacuumFoundations(
@@ -1145,13 +1146,13 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.SurfaceTerrainPlan widePlan =
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(wideBlocks), wideArea, List.of(target), (x, z) -> 60);
world(wideBlocks), wideArea, List.of(target), (x, z) -> 60, SeaSurface.NONE);
NativeStructureSurfaceFitter.SurfaceTerrainPlan westPlan =
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(splitBlocks), westArea, List.of(target), (x, z) -> 60);
world(splitBlocks), westArea, List.of(target), (x, z) -> 60, SeaSurface.NONE);
NativeStructureSurfaceFitter.SurfaceTerrainPlan eastPlan =
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(splitBlocks), eastArea, List.of(target), (x, z) -> 60);
world(splitBlocks), eastArea, List.of(target), (x, z) -> 60, SeaSurface.NONE);
for (int x = 15; x <= 16; x++) {
for (int y = 61; y <= 64; y++) {
put(wideBlocks, x, y, 0, Blocks.CAVE_AIR.defaultBlockState());
@@ -1186,7 +1187,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
assertEquals(originalBlocks, blocks);
}
@@ -1207,7 +1208,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
assertEquals(originalBlocks, blocks);
}
@@ -1231,7 +1232,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 1, 66, 0));
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 1, 67, 0));
@@ -1256,7 +1257,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
assertEquals(originalBlocks, blocks);
}
@@ -1276,7 +1277,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 65, 0));
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 66, 0));
@@ -1301,7 +1302,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
assertEquals(originalBlocks, blocks);
}
@@ -1322,7 +1323,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 4, 61, 4));
}
@@ -1340,7 +1341,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 50);
(x, z) -> 50, SeaSurface.NONE);
assertEquals(originalBlocks, blocks);
}
@@ -1359,7 +1360,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60, 1);
(x, z) -> 60, SeaSurface.NONE, 1);
assertEquals(originalBlocks, blocks);
}
@@ -1383,7 +1384,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(blocks), area,
List.of(surfaceTarget(start, StructureTerrainMode.VACUUM)),
(x, z) -> 60);
(x, z) -> 60, SeaSurface.NONE);
for (int y = 61; y <= 65; y++) {
assertFalse(state(blocks, 10, y, 0).isAir());
@@ -1411,15 +1412,15 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
Map<BlockPos, BlockState> reverseSplitBlocks = flatTerrain(wideArea, 60);
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(wideBlocks), wideArea, List.of(target), (x, z) -> 60);
world(wideBlocks), wideArea, List.of(target), (x, z) -> 60, SeaSurface.NONE);
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(splitBlocks), westArea, List.of(target), (x, z) -> 60);
world(splitBlocks), westArea, List.of(target), (x, z) -> 60, SeaSurface.NONE);
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(splitBlocks), eastArea, List.of(target), (x, z) -> 60);
world(splitBlocks), eastArea, List.of(target), (x, z) -> 60, SeaSurface.NONE);
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(reverseSplitBlocks), eastArea, List.of(target), (x, z) -> 60);
world(reverseSplitBlocks), eastArea, List.of(target), (x, z) -> 60, SeaSurface.NONE);
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world(reverseSplitBlocks), westArea, List.of(target), (x, z) -> 60);
world(reverseSplitBlocks), westArea, List.of(target), (x, z) -> 60, SeaSurface.NONE);
assertEquals(wideBlocks, splitBlocks);
assertEquals(wideBlocks, reverseSplitBlocks);
@@ -1883,7 +1884,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
List<NativeStructureTerrainIntegrator.TerrainTarget> targets =
List.of(surfaceTarget(start));
NativeStructureSurfaceFitter.prepareSurfaceStructures(
world, area, targets, (x, z) -> 60);
world, area, targets, (x, z) -> 60, SeaSurface.NONE);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 2, 62, 2));
assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 2, 65, 2));
@@ -1937,7 +1938,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(lowered), new BlockPos.MutableBlockPos(),
0, 0, 64, 62, -64, 319);
0, 0, 64, 62, -64, 319, false, SeaSurface.NONE);
assertEquals(Blocks.STONE.defaultBlockState(), state(lowered, 0, 61, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(lowered, 0, 62, 0));
@@ -1952,7 +1953,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(raised), new BlockPos.MutableBlockPos(),
0, 0, 64, 68, -64, 319);
0, 0, 64, 68, -64, 319, false, SeaSurface.NONE);
assertEquals(Blocks.DIRT.defaultBlockState(), state(raised, 0, 65, 0));
assertEquals(Blocks.DIRT.defaultBlockState(), state(raised, 0, 66, 0));
@@ -1971,7 +1972,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 99, 83, -64, 319);
0, 0, 99, 83, -64, 319, false, SeaSurface.NONE);
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 82, 0));
assertEquals(Blocks.SNOW_BLOCK.defaultBlockState(), state(blocks, 0, 83, 0));
@@ -1993,7 +1994,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 62, -64, 319);
0, 0, 64, 62, -64, 319, false, SeaSurface.NONE);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 62, 0));
for (int y = 63; y <= 68; y++) {
@@ -2015,7 +2016,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 62, -64, 319);
0, 0, 64, 62, -64, 319, false, SeaSurface.NONE);
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 62, 0));
for (int y = 63; y <= 65; y++) {
@@ -2034,7 +2035,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 64, -64, 319, true);
0, 0, 64, 64, -64, 319, true, SeaSurface.NONE);
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 63, 0));
assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 64, 0));
@@ -2047,7 +2048,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 64, -64, 319, true);
0, 0, 64, 64, -64, 319, true, SeaSurface.NONE);
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 63, 0));
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 64, 0));
@@ -2059,7 +2060,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, -64, -64, -64, 319, true);
0, 0, -64, -64, -64, 319, true, SeaSurface.NONE);
assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, -64, 0));
}
@@ -2076,7 +2077,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 68, -64, 319);
0, 0, 64, 68, -64, 319, false, SeaSurface.NONE);
assertEquals(log, state(blocks, 0, 66, 0));
assertEquals(leaves, state(blocks, 0, 68, 0));
@@ -2098,7 +2099,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
world, chunk, area, List.of(desertStart()));
NativeStructureSurfaceFitter.applySurfaceColumn(
world, new BlockPos.MutableBlockPos(),
0, 0, 64, 68, -64, 319);
0, 0, 64, 68, -64, 319, false, SeaSurface.NONE);
assertEquals(Blocks.DIRT.defaultBlockState(), chunk.getBlockState(new BlockPos(0, 65, 0)));
assertEquals(Blocks.DIRT.defaultBlockState(), chunk.getBlockState(new BlockPos(0, 66, 0)));
@@ -2116,7 +2117,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructureSurfaceFitter.applySurfaceColumn(
world(blocks), new BlockPos.MutableBlockPos(),
0, 0, 64, 62, -64, 319);
0, 0, 64, 62, -64, 319, false, SeaSurface.NONE);
assertEquals(Blocks.WATER.defaultBlockState(), state(blocks, 0, 63, 0));
assertEquals(Blocks.WATER.defaultBlockState(), state(blocks, 0, 64, 0));
@@ -3,6 +3,7 @@ package art.arcane.iris.nativegen.v26_3_R1;
import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureVerticalPlacer;
import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureSurfaceFitter;
import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureSurfaceFitter.SeaSurface;
import art.arcane.volmlib.nativelib.v26_3_R1.terrain.NativeStructureVegetationClearer;
@@ -206,7 +207,7 @@ public class NativeStructurePostProcessorVegetationTest {
write(chunk, 4, 106, 4, Blocks.CACTUS_FLOWER.defaultBlockState());
NativeStructureSurfaceFitter.applySurfaceColumn(
world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 102, 93, MIN_Y, MAX_Y);
world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 102, 93, MIN_Y, MAX_Y, false, SeaSurface.NONE);
assertEquals(Blocks.SAND.defaultBlockState(), chunk.getBlockState(new BlockPos(4, 93, 4)));
for (int y = 94; y <= 106; y++) {
@@ -227,9 +228,9 @@ public class NativeStructurePostProcessorVegetationTest {
WorldGenLevel world = world(chunk);
NativeStructureSurfaceFitter.applySurfaceColumn(
world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y);
world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y, false, SeaSurface.NONE);
NativeStructureSurfaceFitter.applySurfaceColumn(
world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y);
world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y, false, SeaSurface.NONE);
assertTrue(chunk.getBlockState(new BlockPos(4, 65, 4)).isAir());
assertTrue(chunk.getBlockState(new BlockPos(4, 66, 4)).isAir());
@@ -249,7 +250,7 @@ public class NativeStructurePostProcessorVegetationTest {
write(chunk, 4, 67, 4, Blocks.CACTUS_FLOWER.defaultBlockState());
NativeStructureSurfaceFitter.applySurfaceColumn(
world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y);
world(chunk), new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y, false, SeaSurface.NONE);
assertEquals(boundary, chunk.getBlockState(new BlockPos(4, 65, 4)));
assertEquals(Blocks.CACTUS.defaultBlockState(), chunk.getBlockState(new BlockPos(4, 66, 4)));
@@ -271,9 +272,9 @@ public class NativeStructurePostProcessorVegetationTest {
WorldGenLevel world = world(chunk);
NativeStructureSurfaceFitter.applySurfaceColumn(
world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y);
world, new BlockPos.MutableBlockPos(), 4, 4, 64, 60, MIN_Y, MAX_Y, false, SeaSurface.NONE);
NativeStructureSurfaceFitter.applySurfaceColumn(
world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y);
world, new BlockPos.MutableBlockPos(), 5, 4, 64, 64, MIN_Y, MAX_Y, false, SeaSurface.NONE);
assertEquals(Blocks.SAND.defaultBlockState(), chunk.getBlockState(new BlockPos(4, 60, 4)));
for (int y = 61; y <= 67; y++) {
@@ -12,7 +12,8 @@ public record IrisColumnSample(
IrisRiverState riverState,
double riverDistance,
int riverFlow,
int riverWaterSurfaceY
int riverWaterSurfaceY,
boolean provisional
) {
public static final int UNAVAILABLE_HEIGHT = Integer.MIN_VALUE;
public static final double UNAVAILABLE_RIVER_DISTANCE = Double.NaN;
@@ -70,6 +70,7 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CancellationException;
@Director(name = "find", origin = DirectorOrigin.PLAYER, description = "Iris Find commands", descriptionKey = "iris.director.commandfind.director.iris_find_commands", aliases = "goto")
public class CommandFind implements DirectorExecutor {
@@ -218,41 +219,51 @@ public class CommandFind implements DirectorExecutor {
commandSender.sendMessage(C.RED + error.getMessage());
return;
}
String label = featureType.key().replace('_', ' ');
Location origin = target.getLocation();
World originWorld = origin.getWorld();
int maximumDistance = GenerationSemanticQueries.RIVER_SEARCH_DISTANCE;
commandSender.sendMessage(C.GRAY + GenerationSemanticQueries.riverSearchMessage(featureType, maximumDistance));
J.a(() -> {
try {
GenerationSemanticQueries.RiverResult feature = GenerationSemanticQueries.nearestRiver(
activeEngine,
featureType,
origin.getBlockX(),
origin.getBlockZ(),
maximumDistance
).orElse(null);
if (feature == null) {
sendStructureMessage(target, commandSender,
C.YELLOW + GenerationSemanticQueries.riverNotFoundMessage(featureType, maximumDistance));
return;
}
if (!teleport) {
sendStructureMessage(target, commandSender,
C.GREEN + "Found " + label + " at " + feature.x() + ", " + feature.y() + ", " + feature.z() + ".");
return;
}
Location destination = new Location(
originWorld, feature.x(), feature.y(), feature.z());
prepareStructureTeleport(
target, originWorld, commandSender, label, destination, true);
} catch (Throwable error) {
sendStructureMessage(target, commandSender,
C.RED + "Could not search for " + label + ": " + error.getClass().getSimpleName()
+ (error.getMessage() == null ? "" : " - " + error.getMessage()));
Iris.reportError("Could not locate hydrology feature '" + featureType.key() + "'.", error);
RiverRequest request = new RiverRequest(target, origin.getWorld(), commandSender, featureType, teleport);
commandSender.sendMessage(C.GRAY + GenerationSemanticQueries.riverSearchMessage(featureType,
GenerationSemanticQueries.RIVER_SEARCH_DISTANCE));
GenerationSemanticQueries.startRiverSearch(target.getUniqueId(), J::a, activeEngine, featureType, origin.getBlockX(),
origin.getBlockZ())
.whenComplete((search, failure) -> finishRiverSearch(request, search, failure));
}
private void finishRiverSearch(RiverRequest request, GenerationSemanticQueries.RiverSearch search, Throwable failure) {
if (failure instanceof CancellationException) {
return;
}
if (failure != null) {
reportRiverFailure(request, failure);
return;
}
try {
switch (search) {
case GenerationSemanticQueries.RiverSearch.Missing missing ->
sendStructureMessage(request.target(), request.sender(), C.YELLOW + missing.message());
case GenerationSemanticQueries.RiverSearch.Stopped stopped ->
sendStructureMessage(request.target(), request.sender(), C.YELLOW + stopped.message());
case GenerationSemanticQueries.RiverSearch.Found found -> arriveAtRiver(request, found.feature());
}
});
} catch (Throwable error) {
reportRiverFailure(request, error);
}
}
private void arriveAtRiver(RiverRequest request, GenerationSemanticQueries.RiverResult feature) {
if (!request.teleport()) {
sendStructureMessage(request.target(), request.sender(),
C.GREEN + "Found " + request.label() + " at " + feature.x() + ", " + feature.y() + ", " + feature.z() + ".");
return;
}
Location destination = new Location(request.world(), feature.x(), feature.y(), feature.z());
prepareStructureTeleport(request.target(), request.world(), request.sender(), request.label(), destination, true);
}
private void reportRiverFailure(RiverRequest request, Throwable failure) {
Iris.reportError("Could not locate hydrology feature '" + request.type().key() + "'.", failure);
sendStructureMessage(request.target(), request.sender(),
C.RED + "Could not search for " + request.label() + ": " + failure.getClass().getSimpleName()
+ (failure.getMessage() == null ? "" : " - " + failure.getMessage()));
}
@Director(description = "Find a structure (a vanilla key like minecraft:village_plains or minecraft:stronghold, or an imported iris structure key)", descriptionKey = "iris.director.commandfind.director.find_structure_vanilla_key_like_minecraft_village_plains_minecraft_stronghold_imported_iris", sync = true)
@@ -919,6 +930,12 @@ public class CommandFind implements DirectorExecutor {
int configuredUnregistered, int editableUnplaced, int managedUnregistered) {
}
private record RiverRequest(Player target, World world, VolmitSender sender, HydrologyFeatureType type, boolean teleport) {
private String label() {
return type.key().replace('_', ' ');
}
}
private record ManagedDatapackStructure(String key, Set<String> sourceIds) {
private ManagedDatapackStructure(String key) {
this(key, new LinkedHashSet<>());
@@ -18,6 +18,7 @@ import art.arcane.iris.platform.bukkit.terrain.IrisSurfaceClassifier;
import art.arcane.iris.platform.bukkit.terrain.IrisWorldInfoFactory;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.hydrology.raster.WaterRole;
import art.arcane.iris.generation.stream.ProvisionalSampling;
import art.arcane.iris.generation.terrain.InferredType;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.terrain.IrisRegion;
@@ -91,7 +92,9 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
}
try {
return OptionalInt.of(engine.getHeight(blockX, blockZ) + engine.getMinHeight());
long revision = ProvisionalSampling.revision();
int height = engine.getHeight(blockX, blockZ) + engine.getMinHeight();
return provisionalSince(revision) ? OptionalInt.empty() : OptionalInt.of(height);
} catch (Throwable error) {
reportQueryFault("surfaceHeight", world, error);
return OptionalInt.empty();
@@ -106,6 +109,7 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
}
try {
long revision = ProvisionalSampling.revision();
int surface = engine.getHeight(blockX, blockZ);
WaterRole role = engine.getComplex().getWaterRoleStream().get(blockX, blockZ);
int fluid = (int) Math.round(
@@ -115,7 +119,8 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
IrisBiome biome = engine.getSurfaceBiome(blockX, blockZ);
inferredType = biome == null ? null : biome.getInferredType();
}
return IrisSurfaceClassifier.classify(surface, fluid, inferredType, role);
IrisSurfaceKind kind = IrisSurfaceClassifier.classify(surface, fluid, inferredType, role);
return provisionalSince(revision) ? IrisSurfaceKind.UNKNOWN : kind;
} catch (Throwable error) {
reportQueryFault("surfaceKind", world, error);
return IrisSurfaceKind.UNKNOWN;
@@ -130,7 +135,9 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
}
try {
return key(engine.getSurfaceBiome(blockX, blockZ));
long revision = ProvisionalSampling.revision();
Optional<String> key = key(engine.getSurfaceBiome(blockX, blockZ));
return provisionalSince(revision) ? Optional.empty() : key;
} catch (Throwable error) {
reportQueryFault("surfaceBiomeKey", world, error);
return Optional.empty();
@@ -145,7 +152,9 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
}
try {
return name(engine.getSurfaceBiome(blockX, blockZ));
long revision = ProvisionalSampling.revision();
Optional<String> name = name(engine.getSurfaceBiome(blockX, blockZ));
return provisionalSince(revision) ? Optional.empty() : name;
} catch (Throwable error) {
reportQueryFault("surfaceBiomeName", world, error);
return Optional.empty();
@@ -160,8 +169,10 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
}
try {
return Optional.of(IrisBiomeInfoFactory.surface(engine, blockX, blockZ,
error -> reportQueryFault("surfaceBiomeInfo", world, error)));
long revision = ProvisionalSampling.revision();
IrisBiomeInfo info = IrisBiomeInfoFactory.surface(engine, blockX, blockZ,
error -> reportQueryFault("surfaceBiomeInfo", world, error));
return provisionalSince(revision) ? Optional.empty() : Optional.of(info);
} catch (Throwable error) {
reportQueryFault("surfaceBiomeInfo", world, error);
return Optional.empty();
@@ -176,7 +187,9 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
}
try {
return key(engine.getBiome(blockX, blockY - engine.getMinHeight(), blockZ));
long revision = ProvisionalSampling.revision();
Optional<String> key = key(engine.getBiome(blockX, blockY - engine.getMinHeight(), blockZ));
return provisionalSince(revision) ? Optional.empty() : key;
} catch (Throwable error) {
reportQueryFault("biomeKey", world, error);
return Optional.empty();
@@ -191,9 +204,10 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
}
try {
long revision = ProvisionalSampling.revision();
IrisRegion region = engine.getRegion(blockX, blockZ);
String loadKey = region == null ? null : region.getLoadKey();
return loadKey == null || loadKey.isEmpty() ? Optional.empty() : Optional.of(loadKey);
return provisionalSince(revision) || loadKey == null || loadKey.isEmpty() ? Optional.empty() : Optional.of(loadKey);
} catch (Throwable error) {
reportQueryFault("regionKey", world, error);
return Optional.empty();
@@ -208,9 +222,10 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
}
try {
long revision = ProvisionalSampling.revision();
IrisRegion region = engine.getRegion(blockX, blockZ);
String name = region == null ? null : region.getName();
return name == null || name.isEmpty() ? Optional.empty() : Optional.of(name);
return provisionalSince(revision) || name == null || name.isEmpty() ? Optional.empty() : Optional.of(name);
} catch (Throwable error) {
reportQueryFault("regionName", world, error);
return Optional.empty();
@@ -265,6 +280,7 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
return false;
}
long revision = ProvisionalSampling.revision();
WaterRole role = wantRiver
? engine.getComplex().getWaterRoleStream().get(blockX, blockZ)
: WaterRole.NONE;
@@ -309,7 +325,8 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
riverState,
riverDistance,
riverFlow,
riverWaterSurfaceY
riverWaterSurfaceY,
provisionalSince(revision)
));
return true;
});
@@ -351,6 +368,10 @@ public class IrisTerrainSVC implements IrisService, IrisTerrainService {
return name == null || name.isEmpty() ? Optional.empty() : Optional.of(name);
}
private static boolean provisionalSince(long revision) {
return ProvisionalSampling.revision() != revision;
}
private static int noiseCacheChunks() {
return IrisSettings.get().getPerformance().getNoiseCacheSize();
}
@@ -139,7 +139,8 @@ public class IrisColumnSampleTest {
riverState,
riverDistance,
riverFlow,
riverWaterSurfaceY
riverWaterSurfaceY,
false
);
}
}
@@ -1,6 +1,10 @@
package art.arcane.iris.command;
import art.arcane.iris.Iris;
import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef;
import art.arcane.iris.generation.hydrology.query.HydrologySearchTimeoutException;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.IrisComplex;
@@ -17,8 +21,10 @@ import org.bukkit.entity.Player;
import org.junit.Test;
import org.mockito.MockedStatic;
import java.time.Duration;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;
@@ -29,6 +35,7 @@ import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
@@ -126,11 +133,12 @@ public class CommandFindHydrologyTest {
for (HydrologyFeatureType type : HydrologyFeatureType.values()) {
try (Fixture fixture = new Fixture()) {
fixture.command.river(type.key(), false);
fixture.queries.verify(() -> GenerationSemanticQueries.nearestRiver(any(), any(), anyInt(), anyInt(), anyInt()), never());
fixture.queries.verify(() -> GenerationSemanticQueries.nearestRiver(any(), any(), anyInt(), anyInt(), anyInt(), any()),
never());
fixture.search.get().run();
fixture.queries.verify(() -> GenerationSemanticQueries.nearestRiver(fixture.engine, type, 0, 0,
GenerationSemanticQueries.RIVER_SEARCH_DISTANCE));
fixture.queries.verify(() -> GenerationSemanticQueries.nearestRiver(eq(fixture.engine), eq(type), eq(0), eq(0),
eq(GenerationSemanticQueries.RIVER_SEARCH_DISTANCE), any()));
verify(fixture.sender).sendMessage(contains("Found " + type.key().replace('_', ' ') + " at 32, 63, 32."));
}
}
@@ -146,11 +154,72 @@ public class CommandFindHydrologyTest {
}
}
@Test
public void aNewSearchSilentlyReplacesThePlayersRunningSearch() {
try (Fixture fixture = new Fixture()) {
fixture.command.river("pond", false);
Runnable replaced = fixture.search.get();
fixture.command.river("river", false);
replaced.run();
fixture.queries.verify(() -> GenerationSemanticQueries.nearestRiver(any(), eq(HydrologyFeatureType.POND), anyInt(), anyInt(),
anyInt(), any()), never());
fixture.search.get().run();
verify(fixture.sender).sendMessage(contains("Found river at 32, 63, 32."));
verify(fixture.sender, never()).sendMessage(contains("Found pond"));
verify(fixture.sender, never()).sendMessage(contains("Could not search"));
}
}
@Test
public void disabledTypeIsReportedWithItsReason() throws Exception {
try (Fixture fixture = new Fixture()) {
fixture.searchForReal();
when(fixture.runtime.unavailable(HydrologyFeatureType.LAKE)).thenReturn(Optional.of("hydrology.lakes is disabled"));
fixture.command.river("lake", true);
fixture.search.get().run();
verify(fixture.sender).sendMessage(contains("No lake forms in this dimension: hydrology.lakes is disabled."));
verify(fixture.runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any());
}
}
@Test
public void stoppedSearchReportsTheNearestWaterWithoutTeleporting() throws Exception {
try (Fixture fixture = new Fixture()) {
fixture.searchForReal();
IrisDimension dimension = mock(IrisDimension.class);
when(fixture.engine.getDimension()).thenReturn(dimension);
when(dimension.getMinHeight()).thenReturn(-64);
when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())).thenThrow(
new HydrologySearchTimeoutException(Duration.ofSeconds(30L), new HydrologyFeatureRef(1L, HydrologyFeatureType.RIVER, 32, 127, 32)));
fixture.command.river("river", true);
fixture.search.get().run();
verify(fixture.sender).sendMessage(contains("Stopped searching for the nearest river after 30 seconds. The nearest river found so "
+ "far is at 32, 63, 32; a nearer one may exist."));
fixture.platform.verify(() -> BukkitPlatform.chunkAtAsync(any(World.class), anyInt(), anyInt(), eq(true)), never());
fixture.platform.verify(() -> BukkitPlatform.teleportAsync(any(Player.class), any(Location.class)), never());
}
}
@Test
public void deliveryFailureIsReportedInsteadOfLost() {
try (Fixture fixture = new Fixture()) {
LinkageError failure = new LinkageError("sender gone");
doThrow(failure).when(fixture.sender).sendMessage(contains("Found river"));
fixture.command.river("river", false);
fixture.search.get().run();
fixture.logging.verify(() -> Iris.reportError(any(String.class), eq(failure)));
verify(fixture.sender).sendMessage(contains("Could not search for river: LinkageError - sender gone"));
}
}
@Test
public void missingCavePoolIsReportedAsNotFoundInGeneratedChunks() {
try (Fixture fixture = new Fixture()) {
fixture.queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(fixture.engine), any(), eq(0), eq(0), anyInt()))
.thenReturn(Optional.empty());
fixture.searchForReal();
fixture.command.river("cave_pool", true);
fixture.search.get().run();
@@ -162,8 +231,7 @@ public class CommandFindHydrologyTest {
@Test
public void missingFeatureIsReportedAsNotFound() {
try (Fixture fixture = new Fixture()) {
fixture.queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(fixture.engine), any(), eq(0), eq(0), anyInt()))
.thenReturn(Optional.empty());
fixture.searchForReal();
fixture.command.river("sea_inlet", true);
fixture.search.get().run();
@@ -176,7 +244,7 @@ public class CommandFindHydrologyTest {
public void plannerFailureIsReportedAsAnErrorNotAsNotFound() {
try (Fixture fixture = new Fixture()) {
IllegalStateException failure = new IllegalStateException("window planner exploded");
fixture.queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(fixture.engine), any(), eq(0), eq(0), anyInt()))
fixture.queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(fixture.engine), any(), eq(0), eq(0), anyInt(), any()))
.thenThrow(failure);
fixture.command.river("lake", true);
fixture.search.get().run();
@@ -191,6 +259,7 @@ public class CommandFindHydrologyTest {
private final CommandFind command = mock(CommandFind.class, CALLS_REAL_METHODS);
private final Engine engine = mock(Engine.class);
private final IrisComplex complex = mock(IrisComplex.class);
private final HydrologyRuntime runtime = mock(HydrologyRuntime.class);
private final Player player = mock(Player.class);
private final World world = mock(World.class);
private final VolmitSender sender = mock(VolmitSender.class);
@@ -208,6 +277,8 @@ public class CommandFindHydrologyTest {
doReturn(player).when(command).player();
doReturn(sender).when(command).sender();
when(engine.getComplex()).thenReturn(complex);
when(complex.getHydrologyRuntime()).thenReturn(runtime);
when(player.getUniqueId()).thenReturn(UUID.randomUUID());
when(player.getWorld()).thenReturn(world);
when(player.getLocation()).thenReturn(new Location(world, 0, 70, 0));
when(player.isOnline()).thenReturn(true);
@@ -227,12 +298,17 @@ public class CommandFindHydrologyTest {
});
platform.when(() -> BukkitPlatform.chunkAtAsync(any(World.class), anyInt(), anyInt(), eq(true))).thenReturn(chunk);
platform.when(() -> BukkitPlatform.teleportAsync(eq(player), any(Location.class))).thenReturn(teleport);
queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(engine), any(), eq(0), eq(0), anyInt()))
.thenReturn(Optional.of(new GenerationSemanticQueries.RiverResult(
queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(engine), any(), eq(0), eq(0), anyInt(), any()))
.thenReturn(new GenerationSemanticQueries.RiverSearch.Found(new GenerationSemanticQueries.RiverResult(
GenerationSemanticQueries.RiverSource.ACTIVE_PREDICTION,
HydrologyFeatureType.RIVER, 1L, 32, 63, 32, OptionalLong.empty())));
}
private void searchForReal() {
queries.when(() -> GenerationSemanticQueries.nearestRiver(eq(engine), any(), eq(0), eq(0), anyInt(), any()))
.thenCallRealMethod();
}
@Override
public void close() {
logging.close();
@@ -10,6 +10,7 @@ import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.runtime.BiomeEnvironment;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.stream.ProvisionalSampling;
import art.arcane.iris.generation.terrain.InferredType;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisRegion;
@@ -26,6 +27,7 @@ import org.bukkit.World;
import org.bukkit.generator.ChunkGenerator;
import org.junit.Test;
import org.mockito.MockedStatic;
import org.mockito.stubbing.Answer;
import java.lang.reflect.Field;
import java.util.ArrayList;
@@ -35,10 +37,12 @@ import java.util.Optional;
import java.util.OptionalInt;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.IntPredicate;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.mock;
@@ -143,6 +147,90 @@ public class IrisTerrainSVCTest {
assertEquals(List.of("LAND", "NONE", "NaN", "-1", "unavailable"), sampled(WaterRole.NONE, 50));
}
@Test
public void serverThreadUnplannedColumnsAreProvisional() throws Exception {
List<IrisColumnSample> samples = sampledRow(blockX -> blockX < 16, () -> {
});
assertEquals(32, samples.size());
for (IrisColumnSample sample : samples) {
assertEquals("column " + sample.blockX(), sample.blockX() < 16, sample.provisional());
}
}
@Test
public void plannedColumnsAreFinal() throws Exception {
ProvisionalSampling.mark();
List<IrisColumnSample> samples = sampledRow(blockX -> false, () -> {
});
assertEquals(32, samples.size());
for (IrisColumnSample sample : samples) {
assertFalse("column " + sample.blockX(), sample.provisional());
}
}
@Test
public void aSinkThatReadsProvisionallyDoesNotMarkLaterColumns() throws Exception {
List<IrisColumnSample> samples = sampledRow(blockX -> false, ProvisionalSampling::mark);
assertEquals(32, samples.size());
for (IrisColumnSample sample : samples) {
assertFalse("column " + sample.blockX(), sample.provisional());
}
}
@Test
public void surfaceHeightIsUnavailableUntilTheColumnIsPlanned() throws Exception {
World world = world(engine(blockX -> blockX >= 16));
IrisTerrainSVC service = enabledService();
assertEquals(OptionalInt.empty(), service.surfaceHeight(world, 16, 0));
assertEquals(OptionalInt.of(-4), service.surfaceHeight(world, 0, 0));
}
@Test
public void surfaceKindIsUnknownUntilTheColumnIsPlanned() throws Exception {
World world = world(engine(blockX -> blockX >= 16));
IrisTerrainSVC service = enabledService();
assertEquals(IrisSurfaceKind.UNKNOWN, service.surfaceKind(world, 16, 0));
assertEquals(IrisSurfaceKind.LAND, service.surfaceKind(world, 0, 0));
}
@Test
public void surfaceBiomeReadsAreEmptyUntilTheColumnIsPlanned() throws Exception {
World world = world(engine(blockX -> blockX >= 16));
IrisTerrainSVC service = enabledService();
assertTrue(service.surfaceBiomeKey(world, 16, 0).isEmpty());
assertTrue(service.surfaceBiomeName(world, 16, 0).isEmpty());
assertTrue(service.surfaceBiomeInfo(world, 16, 0).isEmpty());
assertEquals(Optional.of("plains"), service.surfaceBiomeKey(world, 0, 0));
assertEquals(Optional.of("Plains"), service.surfaceBiomeName(world, 0, 0));
assertEquals("plains", service.surfaceBiomeInfo(world, 0, 0).orElseThrow().key());
}
@Test
public void biomeKeyIsEmptyUntilTheColumnIsPlanned() throws Exception {
World world = world(engine(blockX -> blockX >= 16));
IrisTerrainSVC service = enabledService();
assertTrue(service.biomeKey(world, 16, 64, 0).isEmpty());
assertEquals(Optional.of("plains"), service.biomeKey(world, 0, 64, 0));
}
@Test
public void regionReadsAreEmptyUntilTheColumnIsPlanned() throws Exception {
World world = world(engine(blockX -> blockX >= 16));
IrisTerrainSVC service = enabledService();
assertTrue(service.regionKey(world, 16, 0).isEmpty());
assertTrue(service.regionName(world, 16, 0).isEmpty());
assertEquals(Optional.of("temperate"), service.regionKey(world, 0, 0));
assertEquals(Optional.of("Temperate"), service.regionName(world, 0, 0));
}
@Test
public void pendingBiomeMetadataReturnsAbsenceAndResolvesOnRetryWithoutLogging() throws Exception {
Engine engine = mock(Engine.class);
@@ -271,6 +359,64 @@ public class IrisTerrainSVCTest {
sample.riverWaterSurfaceY() == IrisColumnSample.UNAVAILABLE_HEIGHT ? "unavailable" : String.valueOf(sample.riverWaterSurfaceY()));
}
private static List<IrisColumnSample> sampledRow(IntPredicate unplanned, Runnable afterAccept) throws Exception {
Engine engine = engine(unplanned);
IrisColumnQuery query = IrisColumnQuery.rect(0, 0, 31, 0, 1, EnumSet.of(IrisColumnField.SURFACE_HEIGHT,
IrisColumnField.SURFACE_KIND, IrisColumnField.BIOME_KEY, IrisColumnField.RIVER_STATE));
List<IrisColumnSample> samples = new ArrayList<>();
try (MockedStatic<IrisSettings> settings = mockStatic(IrisSettings.class)) {
settings.when(IrisSettings::get).thenReturn(new IrisSettings());
assertTrue(enabledService().sampleColumns(world(engine), query, sample -> {
samples.add(sample);
afterAccept.run();
}));
}
return samples;
}
private static Engine engine(IntPredicate unplanned) {
Engine engine = mock(Engine.class);
IrisComplex complex = mock(IrisComplex.class);
IrisBiome biome = mock(IrisBiome.class);
IrisRegion region = mock(IrisRegion.class);
when(biome.getInferredType()).thenReturn(InferredType.LAND);
when(biome.getLoadKey()).thenReturn("plains");
when(biome.getName()).thenReturn("Plains");
when(region.getLoadKey()).thenReturn("temperate");
when(region.getName()).thenReturn("Temperate");
BiomeEnvironment environment = new BiomeEnvironment(1L, biome, region, mock(IrisDimension.class), mock(IrisData.class));
when(engine.getComplex()).thenReturn(complex);
when(engine.getDimension()).thenReturn(mock(IrisDimension.class));
when(engine.getMinHeight()).thenReturn(-64);
when(engine.getHeight(anyInt(), anyInt())).thenAnswer(serverThreadAnswer(unplanned, 60));
when(engine.getSurfaceBiome(anyInt(), anyInt())).thenAnswer(serverThreadAnswer(unplanned, biome));
when(engine.getSurfaceBiomeEnvironment(anyInt(), anyInt())).thenAnswer(serverThreadAnswer(unplanned, environment));
when(engine.getBiome(anyInt(), anyInt(), anyInt())).thenAnswer(serverThreadAnswer(unplanned, biome));
when(engine.getRegion(anyInt(), anyInt())).thenAnswer(serverThreadAnswer(unplanned, region));
when(complex.getWaterRoleStream()).thenReturn(ProceduralStream.of((Double x, Double z) -> {
serverThreadRead(unplanned, x.intValue());
return WaterRole.NONE;
}, Interpolated.of(value -> 0D, value -> WaterRole.NONE)));
when(complex.getWaterHeadStream()).thenReturn(ProceduralStream.ofDouble((double x, double z) -> {
serverThreadRead(unplanned, (int) x);
return 50D;
}));
return engine;
}
private static <T> Answer<T> serverThreadAnswer(IntPredicate unplanned, T value) {
return invocation -> {
serverThreadRead(unplanned, (int) invocation.getArgument(0));
return value;
};
}
private static void serverThreadRead(IntPredicate unplanned, int blockX) {
if (unplanned.test(blockX)) {
ProvisionalSampling.mark();
}
}
private static World world(Engine engine) {
World world = mock(World.class);
ChunkGenerator generator = mock(ChunkGenerator.class, withSettings().extraInterfaces(PlatformChunkGenerator.class));
@@ -21,6 +21,7 @@ import art.arcane.volmlib.nativelib.terrain.structure.StructureLocateSearchAcces
import art.arcane.volmlib.nativelib.terrain.structure.StructurePalette;
import art.arcane.volmlib.nativelib.terrain.structure.StructurePlacementDecision;
import art.arcane.volmlib.nativelib.terrain.structure.StructureReferencePolicy;
import art.arcane.volmlib.nativelib.terrain.structure.StructureSeaSurface;
import art.arcane.volmlib.nativelib.terrain.structure.StructureVolumePolicy;
import art.arcane.volmlib.util.math.RNG;
@@ -124,6 +125,11 @@ final class ModdedNativeStructurePolicy implements NativeModdedStructureStage.Po
return (x, z) -> Engine.hostHeight(context, x, z, true) + context.getMinHeight();
}
@Override
public StructureSeaSurface seaSurface(Engine context) {
return GenerationWritePolicy.seaSurface(context);
}
@Override
public IntBinaryOperator worldgenHeight(Engine context, int runtimeMinY, boolean floor) {
return (x, z) -> Engine.hostHeight(context, x, z, floor) + runtimeMinY + 1;
@@ -149,39 +149,50 @@ final class ModdedLocateCommands {
IrisModdedCommands.fail(source, error.getMessage());
return 0;
}
String label = featureType.key().replace('_', ' ');
int originX = player.blockX();
int originZ = player.blockZ();
int maximumDistance = GenerationSemanticQueries.RIVER_SEARCH_DISTANCE;
NativeModdedServer server = source.server();
IrisModdedCommands.ok(source, GenerationSemanticQueries.riverSearchMessage(featureType, maximumDistance));
MultiBurst.burst.completeValueAsync(() -> GenerationSemanticQueries.nearestRiver(
engine, featureType, originX, originZ, maximumDistance).orElse(null))
.whenComplete((GenerationSemanticQueries.RiverResult feature, Throwable error) -> server.execute(() -> {
if (error != null) {
Throwable cause = error instanceof CompletionException && error.getCause() != null ? error.getCause() : error;
ModdedIrisLog.error("Hydrology locate failed for {}", featureType.key(), cause);
IrisModdedCommands.fail(source, "Could not search for " + label + ": " + cause.getClass().getSimpleName()
+ (cause.getMessage() == null ? "" : " - " + cause.getMessage()));
return;
}
if (feature == null) {
IrisModdedCommands.fail(source, GenerationSemanticQueries.riverNotFoundMessage(featureType, maximumDistance));
return;
}
teleportToStructure(
source,
level,
player,
feature.x(),
feature.y() + 2,
feature.z(),
label
);
}));
RiverRequest request = new RiverRequest(source, level, player, featureType);
IrisModdedCommands.ok(source, GenerationSemanticQueries.riverSearchMessage(featureType, GenerationSemanticQueries.RIVER_SEARCH_DISTANCE));
GenerationSemanticQueries.startRiverSearch(player.id(), MultiBurst.burst, engine, featureType, player.blockX(), player.blockZ())
.whenComplete((GenerationSemanticQueries.RiverSearch search, Throwable error) ->
deliverRiverSearch(server, request, search, error));
return 1;
}
private static void deliverRiverSearch(NativeModdedServer server, RiverRequest request, GenerationSemanticQueries.RiverSearch search,
Throwable error) {
if (error instanceof CancellationException) {
return;
}
try {
server.execute(() -> finishRiverSearch(request, search, error));
} catch (Throwable rejected) {
ModdedIrisLog.error("Hydrology locate result for {} could not reach the server thread", request.type().key(), rejected);
}
}
private static void finishRiverSearch(RiverRequest request, GenerationSemanticQueries.RiverSearch search, Throwable error) {
if (error != null) {
reportRiverFailure(request, error);
return;
}
try {
switch (search) {
case GenerationSemanticQueries.RiverSearch.Missing missing -> IrisModdedCommands.fail(request.source(), missing.message());
case GenerationSemanticQueries.RiverSearch.Stopped stopped -> IrisModdedCommands.fail(request.source(), stopped.message());
case GenerationSemanticQueries.RiverSearch.Found found -> teleportToStructure(request.source(), request.level(),
request.player(), found.feature().x(), found.feature().y() + 2, found.feature().z(), request.label());
}
} catch (Throwable failure) {
reportRiverFailure(request, failure);
}
}
private static void reportRiverFailure(RiverRequest request, Throwable error) {
ModdedIrisLog.error("Hydrology locate failed for {}", request.type().key(), error);
IrisModdedCommands.fail(request.source(), "Could not search for " + request.label() + ": " + error.getClass().getSimpleName()
+ (error.getMessage() == null ? "" : " - " + error.getMessage()));
}
static int gotoStructure(NativeCommandSource source, String keyRaw) {
NativeWorld level = source.world();
Engine engine = IrisModdedCommands.engineFor(level);
@@ -706,6 +717,12 @@ final class ModdedLocateCommands {
record CaveDestination(SubterrainPosition target, Optional<SavedBiomeRuntime.ReadSession> read) {
}
private record RiverRequest(NativeCommandSource source, NativeWorld level, NativeProtocolPlayer player, HydrologyFeatureType type) {
private String label() {
return type.key().replace('_', ' ');
}
}
private record CaveLocateRequest(NativeCommandSource source, NativeWorld level, Engine engine,
NativeProtocolPlayer player, String label, NativeModdedServer server,
UUID playerId, CompletableFuture<Position2> search, BiomeLocator locator, Position2 at) {
@@ -998,11 +998,6 @@ public final class ModdedStudioCommands {
if (region == null) {
continue;
}
region.getAllBiomes(() -> dm).forEach((IrisBiome biome) -> {
if (biome != null && biome.getLoadKey() != null) {
biomeKeys.add(biome.getLoadKey());
}
});
lootKeys.addAll(region.getLoot().getTables());
spawnerKeys.addAll(region.getEntitySpawners());
collectStructureKeys(structureKeys, region.getStructures());
@@ -4,6 +4,7 @@ import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType;
import art.arcane.iris.generation.hydrology.query.HydrologySearchTimeoutException;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.terrain.IrisDimension;
@@ -18,7 +19,9 @@ import org.mockito.ArgumentCaptor;
import org.mockito.MockedConstruction;
import org.mockito.MockedStatic;
import java.time.Duration;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
@@ -41,7 +44,7 @@ public class ModdedLocateRiverTest {
private static final int DISTANCE = GenerationSemanticQueries.RIVER_SEARCH_DISTANCE;
@Test
public void unknownTypeFailsBeforeSearching() {
public void unknownTypeFailsBeforeSearching() throws Exception {
Fixture fixture = new Fixture();
try (MockedStatic<IrisModdedCommands> commands = fixture.commands()) {
assertEquals(0, ModdedLocateCommands.gotoRiver(fixture.source, "ocean_trench"));
@@ -49,14 +52,14 @@ public class ModdedLocateRiverTest {
commands.verify(() -> IrisModdedCommands.fail(eq(fixture.source), anyString()));
commands.verify(() -> IrisModdedCommands.ok(eq(fixture.source), anyString()), never());
verify(fixture.server, never()).execute(any());
verify(fixture.runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any());
verify(fixture.runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any());
}
}
@Test
public void missingFeatureReportsNotFound() throws Exception {
Fixture fixture = new Fixture();
when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any())).thenReturn(Optional.empty());
when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())).thenReturn(Optional.empty());
try (MockedStatic<IrisModdedCommands> commands = fixture.commands()) {
assertEquals(1, ModdedLocateCommands.gotoRiver(fixture.source, "river"));
fixture.finishOnServerThread();
@@ -66,10 +69,53 @@ public class ModdedLocateRiverTest {
}
}
@Test
public void disabledTypeReportsItsReasonWithoutSearching() throws Exception {
Fixture fixture = new Fixture();
when(fixture.runtime.unavailable(HydrologyFeatureType.DAM)).thenReturn(Optional.of("hydrology.ponds.dams is disabled"));
try (MockedStatic<IrisModdedCommands> commands = fixture.commands()) {
assertEquals(1, ModdedLocateCommands.gotoRiver(fixture.source, "dam"));
fixture.finishOnServerThread();
commands.verify(() -> IrisModdedCommands.fail(fixture.source, "No dam forms in this dimension: hydrology.ponds.dams is disabled."));
verify(fixture.runtime, never()).nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any());
verify(fixture.player, never()).teleport(any(), anyDouble(), anyDouble(), anyDouble());
}
}
@Test
public void stoppedSearchReportsTheNearestWaterWithoutTeleporting() throws Exception {
Fixture fixture = new Fixture();
when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())).thenThrow(new HydrologySearchTimeoutException(
Duration.ofSeconds(30L), new HydrologyFeatureRef(9L, HydrologyFeatureType.WATERFALL, 400, 130, -250)));
try (MockedStatic<IrisModdedCommands> commands = fixture.commands()) {
assertEquals(1, ModdedLocateCommands.gotoRiver(fixture.source, "waterfall"));
fixture.finishOnServerThread();
commands.verify(() -> IrisModdedCommands.fail(fixture.source, "Stopped searching for the nearest waterfall after 30 seconds. "
+ "The nearest waterfall found so far is at 400, 66, -250; a nearer one may exist."));
verify(fixture.player, never()).teleport(any(), anyDouble(), anyDouble(), anyDouble());
}
}
@Test
public void deliveryFailureIsReportedInsteadOfLost() throws Exception {
Fixture fixture = new Fixture();
when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any())).thenReturn(Optional.empty());
try (MockedStatic<IrisModdedCommands> commands = fixture.commands()) {
commands.when(() -> IrisModdedCommands.fail(fixture.source, "No river found within " + DISTANCE + " blocks."))
.thenThrow(new LinkageError("source gone"));
assertEquals(1, ModdedLocateCommands.gotoRiver(fixture.source, "river"));
fixture.finishOnServerThread();
commands.verify(() -> IrisModdedCommands.fail(fixture.source, "Could not search for river: LinkageError - source gone"));
}
}
@Test
public void plannerFailureIsReportedAsAnErrorNotAsNotFound() throws Exception {
Fixture fixture = new Fixture();
when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any()))
when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()))
.thenThrow(new IllegalStateException("window planner exploded"));
try (MockedStatic<IrisModdedCommands> commands = fixture.commands()) {
assertEquals(1, ModdedLocateCommands.gotoRiver(fixture.source, "major_river"));
@@ -86,7 +132,7 @@ public class ModdedLocateRiverTest {
@Test
public void foundFeatureTeleportsAboveItFromThePlayersPosition() throws Exception {
Fixture fixture = new Fixture();
when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any()))
when(fixture.runtime.nearestFeature(anyInt(), anyInt(), any(), anyInt(), any(), any()))
.thenReturn(Optional.of(new HydrologyFeatureRef(9L, HydrologyFeatureType.WATERFALL, 400, 130, -250)));
when(fixture.player.teleport(fixture.world, 400.5D, 68D, -249.5D)).thenReturn(true);
try (MockedStatic<IrisModdedCommands> commands = fixture.commands();
@@ -95,7 +141,7 @@ public class ModdedLocateRiverTest {
fixture.finishOnServerThread();
ArgumentCaptor<HydrologyFeatureQuery> query = ArgumentCaptor.forClass(HydrologyFeatureQuery.class);
verify(fixture.runtime).nearestFeature(eq(120), eq(-75), query.capture(), eq(DISTANCE), any());
verify(fixture.runtime).nearestFeature(eq(120), eq(-75), query.capture(), eq(DISTANCE), any(), any());
assertEquals(HydrologyFeatureQuery.of(HydrologyFeatureType.WATERFALL), query.getValue());
verify(queries.constructed().getFirst()).loadChunk(400 >> 4, -250 >> 4);
verify(fixture.player).teleport(fixture.world, 400.5D, 68D, -249.5D);
@@ -119,6 +165,7 @@ public class ModdedLocateRiverTest {
when(source.player()).thenReturn(player);
when(source.world()).thenReturn(world);
when(source.server()).thenReturn(server);
when(player.id()).thenReturn(UUID.randomUUID());
when(player.blockX()).thenReturn(120);
when(player.blockZ()).thenReturn(-75);
when(player.connected()).thenReturn(true);
@@ -92,6 +92,7 @@ import java.util.Objects;
@Data
@EqualsAndHashCode(callSuper = false)
public class IrisBiome extends IrisRegistrant implements Rarity {
public static final int CHILD_HOPS = 4;
private static final int BIOME_GENERATOR_CACHE_SIZE = 8;
private static final int CHILDREN_SEED_SALT = 2137;
@@ -39,7 +39,7 @@ final class IrisBiomeColorRenderer {
static Color getColor(IrisBiome biome, Engine engine, RenderType type) {
switch (type) {
case BIOME, HEIGHT, CAVE_LAND, REGION, BIOME_SEA, BIOME_LAND, RIVER -> {
case BIOME, HEIGHT, CAVE_LAND, REGION, BIOME_SEA, BIOME_LAND -> {
return biome.getCacheColor().aquire(() -> {
if (biome.getColor() == null) {
RandomColor randomColor = new RandomColor(biome.getName().hashCode());
@@ -0,0 +1,48 @@
package art.arcane.iris.generation.hydrology;
import java.util.Arrays;
import java.util.function.ToIntFunction;
public final class PersistedCodes<E extends Enum<E>> {
private static final int MAX_CODE = 255;
private final String type;
private final E[] byCode;
private PersistedCodes(String type, E[] byCode) {
this.type = type;
this.byCode = byCode;
}
public static <E extends Enum<E>> PersistedCodes<E> of(Class<E> type, ToIntFunction<E> code) {
E[] constants = type.getEnumConstants();
int size = 0;
for (E constant : constants) {
int value = code.applyAsInt(constant);
if (value < 0 || value > MAX_CODE) {
throw new IllegalStateException(type.getSimpleName() + "." + constant.name() + " has code " + value
+ ", outside 0.." + MAX_CODE);
}
size = Math.max(size, value + 1);
}
E[] byCode = Arrays.copyOf(constants, size);
Arrays.fill(byCode, null);
for (E constant : constants) {
int value = code.applyAsInt(constant);
if (byCode[value] != null) {
throw new IllegalStateException(type.getSimpleName() + "." + constant.name() + " reuses code " + value + " of "
+ type.getSimpleName() + "." + byCode[value].name());
}
byCode[value] = constant;
}
return new PersistedCodes<>(type.getSimpleName(), byCode);
}
public E decode(int code) {
E constant = code >= 0 && code < byCode.length ? byCode[code] : null;
if (constant == null) {
throw new IllegalStateException("Unknown " + type + " code " + code);
}
return constant;
}
}
@@ -2,7 +2,6 @@ package art.arcane.iris.generation.hydrology.cave;
public enum HydrologyCaveAction {
WET_SOURCE,
FALLING_FLUID,
DRY_AIR,
SEAL_GUARD,
POOL_SOURCE
@@ -6,56 +6,32 @@ import java.util.Objects;
public final class HydrologyCaveCell {
public static final String SEA_FLUID = "@sea";
private static final String DEFAULT_FLUID_PROFILE_KEY = "default";
private static final byte LIQUID_FLUID = 1;
private static final byte LIQUID_FORCED_AIR = 3;
private final HydrologyCaveAction action;
private final String fluidProfileKey;
private final String floodedBiomeKey;
private final MatterCavern cavern;
public HydrologyCaveCell(
HydrologyCaveAction action,
String fluidProfileKey,
String floodedBiomeKey
) {
public HydrologyCaveCell(HydrologyCaveAction action, String fluidProfileKey) {
this.action = Objects.requireNonNull(action);
if (fluidProfileKey == null || fluidProfileKey.isBlank()) {
throw new IllegalArgumentException("fluidProfileKey must not be blank");
}
this.fluidProfileKey = fluidProfileKey.trim();
this.floodedBiomeKey = floodedBiomeKey == null ? "" : floodedBiomeKey.trim();
this.cavern = switch (action) {
case WET_SOURCE, FALLING_FLUID, POOL_SOURCE -> new MatterCavern(true, this.floodedBiomeKey, LIQUID_FLUID);
case DRY_AIR -> new MatterCavern(true, this.floodedBiomeKey, LIQUID_FORCED_AIR);
case WET_SOURCE, POOL_SOURCE -> new MatterCavern(true, "", LIQUID_FLUID);
case DRY_AIR -> new MatterCavern(true, "", LIQUID_FORCED_AIR);
case SEAL_GUARD -> null;
};
}
public static HydrologyCaveCell of(HydrologyCaveAction action) {
return new HydrologyCaveCell(action, DEFAULT_FLUID_PROFILE_KEY, "");
}
public static HydrologyCaveCell of(HydrologyCaveAction action, String fluidProfileKey) {
return new HydrologyCaveCell(action, fluidProfileKey, "");
}
public boolean carves() {
return action != HydrologyCaveAction.SEAL_GUARD;
}
public boolean isWet() {
return action == HydrologyCaveAction.WET_SOURCE || action == HydrologyCaveAction.FALLING_FLUID
|| action == HydrologyCaveAction.POOL_SOURCE;
}
public boolean isFalling() {
return action == HydrologyCaveAction.FALLING_FLUID;
}
public boolean protectsPlacement() {
return true;
return action == HydrologyCaveAction.WET_SOURCE || action == HydrologyCaveAction.POOL_SOURCE;
}
public MatterCavern asCavern() {
@@ -66,10 +42,6 @@ public final class HydrologyCaveCell {
return action;
}
public String floodedBiomeKey() {
return floodedBiomeKey;
}
public String fluidProfileKey() {
return fluidProfileKey;
}
@@ -82,19 +54,16 @@ public final class HydrologyCaveCell {
if (!(object instanceof HydrologyCaveCell hydrology)) {
return false;
}
return action == hydrology.action
&& fluidProfileKey.equals(hydrology.fluidProfileKey)
&& floodedBiomeKey.equals(hydrology.floodedBiomeKey);
return action == hydrology.action && fluidProfileKey.equals(hydrology.fluidProfileKey);
}
@Override
public int hashCode() {
return (31 * ((31 * action.hashCode()) + fluidProfileKey.hashCode())) + floodedBiomeKey.hashCode();
return (31 * action.hashCode()) + fluidProfileKey.hashCode();
}
@Override
public String toString() {
return "HydrologyCaveCell[action=" + action + ", fluidProfileKey=" + fluidProfileKey
+ ", floodedBiomeKey=" + floodedBiomeKey + "]";
return "HydrologyCaveCell[action=" + action + ", fluidProfileKey=" + fluidProfileKey + "]";
}
}
@@ -24,12 +24,12 @@ public class IrisCavePools {
private double density = 0.15D;
@MinNumber(1)
@MaxNumber(4096)
@MaxNumber(961)
@Description("Smallest pool surface in square blocks.")
private int minArea = 6;
@MinNumber(1)
@MaxNumber(65536)
@MaxNumber(961)
@Description("Largest pool surface in square blocks.")
private int maxArea = 400;
@@ -40,7 +40,7 @@ public class IrisCavePools {
@MinNumber(1)
@MaxNumber(15)
@Description("Distance in blocks a pool may spread from its site, at most 15.")
@Description("Half-size in blocks of the square box, centered on the site column, inside which a pool settles and spreads, at most 15, so a pool stays within one chunk of the chunk that holds its site.")
private int radius = 15;
@ArrayType(type = Integer.class, min = 2)
@@ -48,6 +48,6 @@ public class IrisCavePools {
private KList<Integer> freeboard = new KList<>(0, 1);
@Required
@Description("Name of the fluid profile that fills cave pools. A cave biome's hydrology policy fluid replaces it.")
@Description("Name of the fluid profile that fills cave pools. The hydrology policy fluid of the cave biome at the pool replaces it, then that of its region, then that of the dimension. A surface biome's policy never fills cave pools.")
private String fluid = "water";
}
@@ -9,19 +9,19 @@ 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.")
@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.")
@Data
public class IrisHydrologyLakes {
@Description("Turns large hollows into lakes.")
private boolean enabled = true;
@MinNumber(1024)
@MaxNumber(134217728)
@MaxNumber(4194304)
@Description("Smallest lake surface in square blocks.")
private int minArea = 65536;
@MinNumber(1024)
@MaxNumber(134217728)
@MaxNumber(4194304)
@Description("Largest lake surface in square blocks. Larger hollows are drained by a cut through their rim.")
private int maxArea = 4194304;
}
@@ -14,38 +14,44 @@ import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.util.List;
import java.util.function.Function;
@Accessors(chain = true)
@NoArgsConstructor
@Description("Hydrology settings for a dimension, region or biome. A value left unset is inherited from the region, then from the dimension.")
@Description("Hydrology settings for a dimension, region or biome. A value a biome leaves unset is inherited from the biome it grows inside as a child, up through that biome's own parents, then from the region, then from the dimension, and a value a region leaves unset is inherited from the dimension. wetness is inherited whole: a bound it leaves out is 0 for min and 1 for max. Cave pools take fluid from the cave biome at the pool, then its region, then the dimension, and never from the surface biome above.")
@Data
public class IrisHydrologyPolicy {
public static final double MAX_MULTIPLIER = 16D;
@MinNumber(0)
@MaxNumber(16)
@Description("Multiplier on the water that falls in this area. Higher values grow more and larger streams and keep ponds fuller. With no value set anywhere it is 1.")
@MaxNumber(MAX_MULTIPLIER)
@Description("Multiplier on the water that falls in this area. Higher values grow more and larger streams. Where the wet and dry zones do not apply, values below 1 also lower pond and lake surfaces. With no value set anywhere it is 1.")
private Double rainfall = null;
@MinNumber(0)
@MaxNumber(16)
@MaxNumber(MAX_MULTIPLIER)
@Description("Multiplier on how many ponds form in this area. With no value set anywhere it is 1.")
private Double pondDensity = null;
@Description("Whether the dimension's wet and dry zones apply in this area. false keeps this area's full rainfall and pond density even inside a dry zone. With no value set anywhere they apply.")
private Boolean climateZones = null;
@Description("Bounds on the wetness of the dimension's wet and dry zones in this area: min keeps a swamp wet inside a dry zone, max keeps a desert mostly dry inside a wet zone. The bounded wetness scales the area's rainfall and pond density and sets how far ponds and lakes whose floor lies here drop below their freeboard. It has no effect where the wet and dry zones are off or climateZones is false. A scope that sets it replaces both bounds, and a bound it leaves out is 0 for min and 1 for max. With no value set anywhere the zone wetness applies unchanged.")
private IrisHydrologyWetness wetness = null;
@Description("Whether streams and rivers may form in this area. With no value set anywhere they are allowed.")
private IrisHydrologyPermission streams = null;
@Description("Whether ponds may form in this area. With no value set anywhere they are allowed.")
private IrisHydrologyPermission ponds = null;
@Description("Name of a fluid profile that fills the water in this area instead of its usual fluid: ponds and lakes whose floor lies here, and every stretch of stream or river that flows through here.")
@Description("Name of a fluid profile that fills the water in this area instead of its usual fluid: ponds and lakes whose floor lies here, and every stretch of stream or river whose upstream end lies here, for the whole stretch. A stretch that starts elsewhere keeps its own fluid while it crosses this area. Set on a cave biome, a region or the dimension, it also fills the cave pools there. It cannot name a seam profile.")
private String fluid = null;
@RegistryListResource(IrisBiome.class)
@ArrayType(type = String.class)
@Description("Biomes placed along the water's edge in this area. An empty list clears the inherited biomes.")
@Description("Biomes placed along the water's edge in this area, in a band as wide as shoreBiomeWidth. Without a shoreBiomeWidth above 0 the list places nothing. An empty list clears the inherited biomes.")
private KList<String> shoreBiomes = null;
@MinNumber(0)
@@ -57,15 +63,31 @@ public class IrisHydrologyPolicy {
@Description("Plants for the rivers, streams, ponds and lakes in this area, replacing the decorators of the tiers and ponds there. Written like the tier and pond decorators: partOf SEA_FLOOR, SEA_SURFACE or SHORE_LINE. An empty list grows no plants here. With no value set anywhere, the tiers and ponds use their own decorators.")
private KList<IrisDecorator> decorators = null;
public static <T> T inherited(IrisBiome biome, IrisRegion region, IrisDimension dimension, Function<IrisHydrologyPolicy, T> field) {
T value = value(biome == null ? null : biome.getHydrologyPolicy(), field);
if (value == null) {
value = value(region == null ? null : region.getHydrologyPolicy(), field);
public static boolean validMultiplier(double value) {
return value >= 0D && value <= MAX_MULTIPLIER;
}
public static ShoreBand shoreBand(List<IrisBiome> biomes, IrisRegion region, IrisDimension dimension) {
Integer width = inherited(biomes, region, dimension, IrisHydrologyPolicy::getShoreBiomeWidth);
KList<String> keys = inherited(biomes, region, dimension, IrisHydrologyPolicy::getShoreBiomes);
return width == null || width <= 0 || keys == null || keys.isEmpty() ? null : new ShoreBand(width, keys);
}
public static <T> T inherited(List<IrisBiome> biomes, IrisRegion region, IrisDimension dimension, Function<IrisHydrologyPolicy, T> field) {
for (int index = 0; index < biomes.size(); index++) {
T value = value(biomes.get(index).getHydrologyPolicy(), field);
if (value != null) {
return value;
}
}
T value = value(region == null ? null : region.getHydrologyPolicy(), field);
return value != null ? value : value(dimension == null ? null : dimension.getHydrologyPolicy(), field);
}
private static <T> T value(IrisHydrologyPolicy policy, Function<IrisHydrologyPolicy, T> field) {
return policy == null ? null : field.apply(policy);
}
public record ShoreBand(int width, List<String> biomes) {
}
}
@@ -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.")
@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.")
@Data
public class IrisHydrologyPonds {
@Description("Ponds that fill hollows already present in the terrain.")
@@ -26,18 +26,18 @@ public class IrisHydrologyPonds {
private IrisPondDams dams = new IrisPondDams();
@ArrayType(type = Integer.class, min = 2)
@Description("Blocks the pond surface sits below its spill point, written as [min, max]. Each pond picks a value in this range.")
@Description("Blocks the pond or lake surface sits below its spill point, written as [min, max]. Each pond and lake picks a value in this range.")
private KList<Integer> freeboard = new KList<>(1, 3);
@MinNumber(0)
@MaxNumber(32)
@Description("Extra blocks a pond surface drops in the driest climate. Ponds in wet areas stay full.")
@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;
@Description("Shape of pond shores and floors.")
@Description("Shape of pond shores and floors. Lakes take only its roundness.")
private IrisPondShore shore = new IrisPondShore();
@Description("Blocks painted on pond floors and shores.")
@Description("Blocks painted on pond and lake floors and shores.")
private IrisHydrologyMaterials materials = new IrisHydrologyMaterials();
@ArrayType(type = IrisDecorator.class)
@@ -17,7 +17,7 @@ import lombok.experimental.Accessors;
@Data
public class IrisHydrologyTier {
@Required
@Description("Label for this tier in configuration error messages. Locate, maps and history do not use it: they rank tiers by minCatchment, so the lowest tier is a stream, the highest a major river and any between are rivers.")
@Description("Channel type of this tier for locate, maps and history: stream, river or major (also major_river). Any other name takes the type of its rank by minCatchment instead: the lowest tier is a stream, the highest a major river and any between are rivers. Configuration error messages also use the name.")
private String name = "stream";
@MinNumber(0)
@@ -0,0 +1,24 @@
package art.arcane.iris.generation.hydrology.config;
import art.arcane.iris.pack.schema.annotation.MaxNumber;
import art.arcane.iris.pack.schema.annotation.MinNumber;
import art.arcane.volmlib.util.documentation.Description;
import lombok.Data;
import lombok.NoArgsConstructor;
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.")
@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.")
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.")
private double max = 1D;
}
@@ -32,6 +32,6 @@ public class IrisPondNatural {
@MinNumber(0.5)
@MaxNumber(64)
@Description("Smallest hollow depth in blocks that holds a pond.")
@Description("Smallest hollow depth in blocks that holds a pond or a lake.")
private double minDepth = 2D;
}
@@ -9,12 +9,12 @@ import lombok.experimental.Accessors;
@Accessors(chain = true)
@NoArgsConstructor
@Description("Shape of pond and lake shores and floors.")
@Description("Shape of pond shores and floors. Lakes take only roundness.")
@Data
public class IrisPondShore {
@MinNumber(0)
@MaxNumber(4)
@Description("Strength of the noise that rounds and roughens pond outlines. 0 follows the terrain exactly.")
@Description("Strength of the noise that rounds and roughens pond and lake outlines. 0 follows the terrain exactly.")
private double roundness = 0.5D;
@MinNumber(0)
@@ -10,6 +10,7 @@ import art.arcane.iris.generation.hydrology.plan.WindowPlan;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType;
import art.arcane.iris.generation.hydrology.query.HydrologySearchTimeoutException;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.water.HydrologyTier;
import art.arcane.iris.generation.hydrology.water.Pond;
@@ -18,14 +19,21 @@ import art.arcane.iris.generation.hydrology.water.PondMask;
import art.arcane.iris.generation.hydrology.water.Reach;
import art.arcane.iris.generation.hydrology.water.ReachStyle;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.BooleanSupplier;
import java.util.function.Predicate;
final class HydrologyFeatureSearch {
@@ -33,12 +41,15 @@ final class HydrologyFeatureSearch {
private static final Set<HydrologyFeatureType> WINDOW_TYPES = EnumSet.of(HydrologyFeatureType.STREAM, HydrologyFeatureType.RIVER,
HydrologyFeatureType.MAJOR_RIVER, HydrologyFeatureType.CASCADE, HydrologyFeatureType.WATERFALL, HydrologyFeatureType.MOUTH,
HydrologyFeatureType.POND, HydrologyFeatureType.DAM, HydrologyFeatureType.SEA_INLET);
private static final long POLL_NANOS = TimeUnit.MILLISECONDS.toNanos(50L);
static final String OFF = "hydrology is off";
private static final String PONDS_OFF = "hydrology.ponds.natural and hydrology.ponds.seeded are disabled";
private final HydrologySettings settings;
private final HydrologyPlanCache cache;
private final int originX;
private final int originZ;
private final HydrologyFeatureQuery query;
private final Set<HydrologyFeatureType> types;
private final Predicate<HydrologyFeatureRef> eligible;
private final int radius;
private final long radiusSquared;
@@ -51,29 +62,70 @@ final class HydrologyFeatureSearch {
this.cache = cache;
this.originX = originX;
this.originZ = originZ;
this.query = query;
this.types = enabledTypes(settings, query);
this.eligible = eligible;
this.radius = radius;
this.radiusSquared = (long) radius * radius;
}
Optional<HydrologyFeatureRef> nearest() {
Optional<HydrologyFeatureRef> nearest(Duration timeout, BooleanSupplier running) throws HydrologySearchTimeoutException {
Objects.requireNonNull(timeout, "timeout");
Objects.requireNonNull(running, "running");
int rings = Math.ceilDiv(radius, WindowKey.SIZE) + 1;
long windows = (2L * rings + 1L) * (2L * rings + 1L);
if (windows > MAX_WINDOWS) {
throw new IllegalArgumentException("Hydrology feature search radius " + radius + " covers " + windows + " windows, above "
+ MAX_WINDOWS);
}
if (query.matches(HydrologyFeatureType.LAKE)) {
searchLakes();
if (types.isEmpty()) {
return Optional.empty();
}
if (!Collections.disjoint(query.types(), WINDOW_TYPES)) {
searchWindows(rings);
Budget budget = new Budget(System.nanoTime() + timeout.toNanos(), timeout, running);
if (types.contains(HydrologyFeatureType.LAKE)) {
searchLakes(budget);
}
if (!Collections.disjoint(types, WINDOW_TYPES)) {
searchWindows(rings, budget);
}
return Optional.ofNullable(best);
}
private void searchLakes() {
static Optional<String> disabledReason(HydrologySettings settings, HydrologyFeatureType type) {
HydrologySettings.Ponds ponds = settings.ponds();
boolean anyPonds = ponds.natural().enabled() || ponds.seeded().enabled();
String reason = switch (type) {
case STREAM, RIVER, MAJOR_RIVER -> hasTier(settings, type) ? null : "it has no " + type.key().replace('_', ' ') + " tier";
case CASCADE, WATERFALL, MOUTH -> null;
case POND -> anyPonds ? null : PONDS_OFF;
case DAM -> !anyPonds ? PONDS_OFF : ponds.dams().enabled() ? null : "hydrology.ponds.dams is disabled";
case LAKE -> settings.lakes().enabled() ? null : "hydrology.lakes is disabled";
case SEA_INLET -> settings.underground().seaInlets().enabled() ? null : "hydrology.underground.seaInlets is disabled";
case CAVE_POOL -> settings.underground().cavePools().enabled() ? null : "hydrology.underground.cavePools is disabled";
};
return Optional.ofNullable(reason);
}
private static Set<HydrologyFeatureType> enabledTypes(HydrologySettings settings, HydrologyFeatureQuery query) {
Set<HydrologyFeatureType> enabled = EnumSet.noneOf(HydrologyFeatureType.class);
for (HydrologyFeatureType type : query.types()) {
if (disabledReason(settings, type).isEmpty()) {
enabled.add(type);
}
}
return enabled;
}
private static boolean hasTier(HydrologySettings settings, HydrologyFeatureType type) {
List<HydrologyTier> tiers = settings.tiers();
for (int index = 0; index < tiers.size(); index++) {
if (channelType(tiers.get(index).name(), index, tiers.size()) == type) {
return true;
}
}
return false;
}
private void searchLakes(Budget budget) throws HydrologySearchTimeoutException {
long minX = (long) originX - radius;
long minZ = (long) originZ - radius;
long maxX = (long) originX + radius;
@@ -85,7 +137,7 @@ final class HydrologyFeatureSearch {
plans.add(cache.demandRegion(key));
}
for (CompletableFuture<RegionPlan> plan : plans) {
for (Pond lake : cache.awaitPlan(plan).lakes()) {
for (Pond lake : await(plan, budget).lakes()) {
if (seen.add(lake.id())) {
pond(lake, HydrologyFeatureType.LAKE);
}
@@ -93,7 +145,7 @@ final class HydrologyFeatureSearch {
}
}
private void searchWindows(int rings) {
private void searchWindows(int rings, Budget budget) throws HydrologySearchTimeoutException {
WindowKey origin = WindowKey.containing(originX, originZ);
for (int ring = 0; ring <= rings; ring++) {
long bound = Math.max(0L, (long) (ring - 2) * WindowKey.SIZE);
@@ -105,11 +157,43 @@ final class HydrologyFeatureSearch {
plans.add(cache.demandWindow(key));
}
for (CompletableFuture<IndexedWindow> plan : plans) {
window(cache.awaitPlan(plan).plan());
window(await(plan, budget).plan());
}
}
}
private <T> T await(CompletableFuture<T> plan, Budget budget) throws HydrologySearchTimeoutException {
CountDownLatch settled = new CountDownLatch(1);
plan.whenComplete((value, failure) -> settled.countDown());
boolean ready = false;
while (!ready) {
ready = settle(settled, slice(budget));
}
return cache.awaitPlan(plan);
}
private long slice(Budget budget) throws HydrologySearchTimeoutException {
if (!budget.running().getAsBoolean()) {
throw new CancellationException("The hydrology feature search was cancelled.");
}
long remaining = budget.deadline() - System.nanoTime();
if (remaining <= 0L) {
throw new HydrologySearchTimeoutException(budget.timeout(), best);
}
return Math.min(remaining, POLL_NANOS);
}
private static boolean settle(CountDownLatch settled, long nanos) {
try {
return settled.await(nanos, TimeUnit.NANOSECONDS);
} catch (InterruptedException interruption) {
Thread.currentThread().interrupt();
CancellationException cancelled = new CancellationException("The hydrology feature search was interrupted.");
cancelled.initCause(interruption);
throw cancelled;
}
}
private static List<WindowKey> ring(WindowKey origin, int ring) {
if (ring == 0) {
return List.of(origin);
@@ -135,7 +219,7 @@ final class HydrologyFeatureSearch {
pond(pond, type);
}
}
if (query.matches(HydrologyFeatureType.SEA_INLET)) {
if (types.contains(HydrologyFeatureType.SEA_INLET)) {
for (SeaInlet inlet : plan.inlets()) {
inlet(inlet);
}
@@ -151,22 +235,22 @@ final class HydrologyFeatureSearch {
private HydrologyFeatureType pondType(Pond pond) {
if (pond.kind() == PondKind.LAKE) {
return query.matches(HydrologyFeatureType.LAKE) ? HydrologyFeatureType.LAKE : null;
return types.contains(HydrologyFeatureType.LAKE) ? HydrologyFeatureType.LAKE : null;
}
if (pond.damRaise() > 0 && query.matches(HydrologyFeatureType.DAM)) {
if (pond.damRaise() > 0 && types.contains(HydrologyFeatureType.DAM)) {
return HydrologyFeatureType.DAM;
}
return query.matches(HydrologyFeatureType.POND) ? HydrologyFeatureType.POND : null;
return types.contains(HydrologyFeatureType.POND) ? HydrologyFeatureType.POND : null;
}
private void reach(Reach reach) {
HydrologyFeatureType channel = channelType(settings, reach.tier());
boolean whole = query.matches(channel);
boolean whole = types.contains(channel);
float[] xs = reach.xs();
float[] zs = reach.zs();
for (int index = 0; index < xs.length; index++) {
HydrologyFeatureType point = pointType(reach.style()[index]);
HydrologyFeatureType type = point != null && query.matches(point) ? point : whole ? channel : null;
HydrologyFeatureType type = point != null && types.contains(point) ? point : whole ? channel : null;
if (type != null) {
offer(reach.id(), type, (int) Math.floor(xs[index]), reach.grade()[index], (int) Math.floor(zs[index]));
}
@@ -197,10 +281,24 @@ final class HydrologyFeatureSearch {
if (index < 0) {
throw new IllegalStateException("Reach tier '" + tier.name() + "' is not one of the hydrology tiers");
}
if (tier.equals(settings.majorTier())) {
return HydrologyFeatureType.MAJOR_RIVER;
return channelType(tier.name(), index, tiers.size());
}
private static HydrologyFeatureType channelType(String name, int index, int count) {
String normalized = name == null ? "" : name.trim().toLowerCase(Locale.ROOT).replace('-', '_').replace(' ', '_');
return switch (normalized) {
case "stream" -> HydrologyFeatureType.STREAM;
case "river" -> HydrologyFeatureType.RIVER;
case "major", "major_river" -> HydrologyFeatureType.MAJOR_RIVER;
default -> rankType(index, count);
};
}
private static HydrologyFeatureType rankType(int index, int count) {
if (index == 0) {
return HydrologyFeatureType.STREAM;
}
return index == 0 ? HydrologyFeatureType.STREAM : HydrologyFeatureType.RIVER;
return index == count - 1 ? HydrologyFeatureType.MAJOR_RIVER : HydrologyFeatureType.RIVER;
}
private static HydrologyFeatureType pointType(ReachStyle style) {
@@ -239,4 +337,7 @@ final class HydrologyFeatureSearch {
}
return x != best.x() ? x < best.x() : z < best.z();
}
private record Budget(long deadline, Duration timeout, BooleanSupplier running) {
}
}
@@ -14,6 +14,7 @@ import art.arcane.iris.generation.hydrology.plan.WindowKey;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType;
import art.arcane.iris.generation.hydrology.query.HydrologySearchTimeoutException;
import art.arcane.iris.generation.hydrology.raster.ChannelFluids;
import art.arcane.iris.generation.hydrology.raster.ChunkRasterizer;
import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster;
@@ -30,12 +31,14 @@ import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.runtime.IrisEngine;
import art.arcane.iris.generation.runtime.PreparedHydrologyCacheIdentity;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.world.IrisWorld;
import java.io.File;
import java.io.UncheckedIOException;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
@@ -64,6 +67,7 @@ public final class HydrologyRuntime {
public static final int MAX_PREGENERATION_REGIONS = 4096;
private static final int MAX_PREVIEW_REQUESTS = 64;
private static final int PREFETCH_CAPACITY = 16;
public static final Duration FEATURE_SEARCH_TIMEOUT = Duration.ofSeconds(30L);
private static final HydrologyRuntime DISABLED = new HydrologyRuntime();
private final HydrologySettings settings;
@@ -150,8 +154,9 @@ public final class HydrologyRuntime {
Objects.requireNonNull(complex, "Hydrology needs the engine's terrain complex");
HydrologySettings settings = HydrologySettings.compile(config, engine.getSeedManager().getBodies(), dimension.getFluidHeight(), 0,
engine.getHeight());
boolean caveFluidPolicies = settings.underground().cavePools().enabled()
&& requireBiomeFluids(dimension.getReachableBiomes(engine), settings);
requireBiomeFluids(dimension.getReachableBiomes(engine), settings);
boolean caveFluidPolicies = requireCaveFluids(dimension, dimension.getAllRegions(engine), dimension.getReachableCaveBiomes(engine), settings)
&& settings.underground().cavePools().enabled();
if (settings.density() == 0D) {
return DISABLED;
}
@@ -168,20 +173,33 @@ public final class HydrologyRuntime {
identity -> store(world, dimensionKey, settings, identity), caveFluidPolicies);
}
static boolean requireBiomeFluids(Collection<IrisBiome> biomes, HydrologySettings settings) {
boolean named = false;
private static void requireBiomeFluids(Collection<IrisBiome> biomes, HydrologySettings settings) {
for (IrisBiome biome : biomes) {
IrisHydrologyPolicy policy = biome == null ? null : biome.getHydrologyPolicy();
String fluid = policy == null ? null : policy.getFluid();
if (fluid == null) {
continue;
}
settings.requireFillingFluid(fluid, "biome '" + biome.getLoadKey() + "' hydrologyPolicy.fluid");
named = true;
requireFluid(biome.getHydrologyPolicy(), "biome '" + biome.getLoadKey() + "'", settings);
}
}
static boolean requireCaveFluids(IrisDimension dimension, Collection<IrisRegion> regions, Collection<IrisBiome> caveBiomes,
HydrologySettings settings) {
boolean named = requireFluid(dimension.getHydrologyPolicy(), "dimension '" + dimension.getLoadKey() + "'", settings);
for (IrisRegion region : regions) {
named |= requireFluid(region.getHydrologyPolicy(), "region '" + region.getLoadKey() + "'", settings);
}
for (IrisBiome biome : caveBiomes) {
named |= requireFluid(biome.getHydrologyPolicy(), "biome '" + biome.getLoadKey() + "'", settings);
}
return named;
}
private static boolean requireFluid(IrisHydrologyPolicy policy, String owner, HydrologySettings settings) {
String fluid = policy == null ? null : policy.getFluid();
if (fluid == null) {
return false;
}
settings.requireFillingFluid(fluid, owner + " hydrologyPolicy.fluid");
return true;
}
public boolean caveFluidPolicies() {
return caveFluidPolicies;
}
@@ -388,14 +406,12 @@ public final class HydrologyRuntime {
}
}
public Optional<HydrologyFeatureRef> nearestFeature(int blockX, int blockZ, HydrologyFeatureQuery query, int radius) {
return nearestFeature(blockX, blockZ, query, radius, feature -> true);
}
public Optional<HydrologyFeatureRef> nearestFeature(int blockX, int blockZ, HydrologyFeatureQuery query, int radius,
Predicate<HydrologyFeatureRef> eligible) {
Predicate<HydrologyFeatureRef> eligible, BooleanSupplier running)
throws HydrologySearchTimeoutException {
Objects.requireNonNull(query, "query");
Objects.requireNonNull(eligible, "eligible");
Objects.requireNonNull(running, "running");
if (radius < 0) {
throw new IllegalArgumentException("Hydrology feature search radius must not be negative, got " + radius);
}
@@ -406,7 +422,15 @@ public final class HydrologyRuntime {
throw new IllegalStateException("Hydrology feature search was requested on the main thread.");
}
requireOpen();
return new HydrologyFeatureSearch(settings, cache, blockX, blockZ, query, eligible, radius).nearest();
return new HydrologyFeatureSearch(settings, cache, blockX, blockZ, query, eligible, radius).nearest(FEATURE_SEARCH_TIMEOUT, running);
}
public Optional<String> unavailable(HydrologyFeatureType type) {
Objects.requireNonNull(type, "type");
if (settings == null) {
return Optional.of(HydrologyFeatureSearch.OFF);
}
return HydrologyFeatureSearch.disabledReason(settings, type);
}
public HydrologyFeatureType channelType(HydrologyTier tier) {
@@ -4,6 +4,7 @@ import art.arcane.iris.generation.bake.ChunkBakeCache;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyPermission;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyWetness;
import art.arcane.iris.generation.hydrology.grid.HydrologySampleBuffer;
import art.arcane.iris.generation.hydrology.grid.HydrologyTerrainSource;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
@@ -38,7 +39,6 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource,
private final ExecutorService pool;
private final int parallelism;
private final ProceduralStream<IrisRegion> regions;
private final ProceduralStream<IrisBiome> biomes;
private final ProceduralStream<InferredType> continents;
private final BiomeBuffetLayout buffet;
private final IrisBiome focus;
@@ -55,7 +55,6 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource,
this.pool = pool;
this.parallelism = Math.max(1, parallelism);
this.regions = Objects.requireNonNull(complex.getRegionStream(), "region stream");
this.biomes = Objects.requireNonNull(complex.getBaseBiomeStream(), "base biome stream");
this.continents = Objects.requireNonNull(complex.getBridgeStream(), "continent stream");
this.buffet = complex.getBiomeBuffet();
this.focus = complex.getFocusBiome();
@@ -88,7 +87,7 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource,
public String channelFluid(int x, int z) {
ChunkBakeCache.enterSparse();
try {
return policy(biomes.get(x, z), regions.get(x, z)).fluid();
return policy(complex.baseBiomeLineage(x, z), regions.get(x, z)).fluid();
} finally {
ChunkBakeCache.exitSparse();
}
@@ -164,20 +163,19 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource,
if (!Double.isFinite(height)) {
throw new IllegalStateException("Hydrology " + (baseOnly ? "base" : "natural") + " height at " + x + "," + z + " is " + height);
}
Policy policy = policy(biomes.get(x, z), regions.get(x, z));
Policy policy = policy(complex.baseBiomeLineage(x, z), regions.get(x, z));
out.height()[index] = (float) height;
out.ocean()[index] = StrictMath.round(height) < settings.seaLevel() && oceanIntent(x, z);
float wet = policy.climateZones() ? wetness(x, z) : 1f;
boolean zoned = wetness != null && policy.climateZones();
float wet = zoned ? (float) Math.clamp(climate.wetness(wetness.noise(x, z)), policy.minWetness(), policy.maxWetness()) : 1f;
out.rainfall()[index] = policy.rainfall() * wet;
out.pondDensity()[index] = policy.pondDensity() * wet;
out.wetness()[index] = wet;
out.climateZoned()[index] = zoned;
out.permission()[index] = policy.permission();
out.fluidProfile()[index] = policy.fluid();
}
private float wetness(int x, int z) {
return wetness == null ? 1f : (float) climate.wetness(wetness.noise(x, z));
}
private boolean oceanIntent(int x, int z) {
BiomeBuffetLayout.Cell cell = buffet == null ? null : buffet.terrain(x, z);
IrisBiome focused = cell == null ? focus : cell.biome();
@@ -185,13 +183,13 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource,
return type == InferredType.SEA;
}
private Policy policy(IrisBiome biome, IrisRegion region) {
PolicyKey key = new PolicyKey(biome, region);
private Policy policy(List<IrisBiome> biomes, IrisRegion region) {
PolicyKey key = new PolicyKey(biomes, region);
Policy known = policies.get(key);
if (known != null) {
return known;
}
Policy resolved = resolve(biome, region);
Policy resolved = resolve(biomes, region);
if (policies.size() >= POLICY_CAPACITY) {
policies.clear();
}
@@ -199,23 +197,28 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource,
return raced == null ? resolved : raced;
}
private Policy resolve(IrisBiome biome, IrisRegion region) {
double rainfall = inherited(biome, region, IrisHydrologyPolicy::getRainfall, 1D);
double pondDensity = inherited(biome, region, IrisHydrologyPolicy::getPondDensity, 1D);
IrisHydrologyPermission streams = inherited(biome, region, IrisHydrologyPolicy::getStreams, IrisHydrologyPermission.ALLOW);
IrisHydrologyPermission ponds = inherited(biome, region, IrisHydrologyPolicy::getPonds, IrisHydrologyPermission.ALLOW);
String fluid = inherited(biome, region, IrisHydrologyPolicy::getFluid, null);
boolean climateZones = inherited(biome, region, IrisHydrologyPolicy::getClimateZones, Boolean.TRUE);
requireMultiplier("rainfall", rainfall, biome, region);
requireMultiplier("pondDensity", pondDensity, biome, region);
private Policy resolve(List<IrisBiome> biomes, IrisRegion region) {
double rainfall = inherited(biomes, region, IrisHydrologyPolicy::getRainfall, 1D);
double pondDensity = inherited(biomes, region, IrisHydrologyPolicy::getPondDensity, 1D);
IrisHydrologyPermission streams = inherited(biomes, region, IrisHydrologyPolicy::getStreams, IrisHydrologyPermission.ALLOW);
IrisHydrologyPermission ponds = inherited(biomes, region, IrisHydrologyPolicy::getPonds, IrisHydrologyPermission.ALLOW);
String fluid = inherited(biomes, region, IrisHydrologyPolicy::getFluid, null);
boolean climateZones = inherited(biomes, region, IrisHydrologyPolicy::getClimateZones, Boolean.TRUE);
IrisHydrologyWetness wetness = inherited(biomes, region, IrisHydrologyPolicy::getWetness, null);
requireMultiplier("rainfall", rainfall, biomes, region);
requireMultiplier("pondDensity", pondDensity, biomes, region);
if (fluid != null) {
settings.requireFillingFluid(fluid, "the hydrology policy for " + where(biome, region));
settings.requireFillingFluid(fluid, "the hydrology policy for " + where(biomes, region));
}
return new Policy((float) rainfall, (float) pondDensity, permission(streams, ponds), fluid, climateZones);
double minWetness = wetness == null ? 0D : wetness.getMin();
double maxWetness = wetness == null ? 1D : wetness.getMax();
requireWetness(minWetness, maxWetness, biomes, region);
return new Policy((float) rainfall, (float) pondDensity, permission(streams, ponds), fluid, climateZones, (float) minWetness,
(float) maxWetness);
}
private <T> T inherited(IrisBiome biome, IrisRegion region, Function<IrisHydrologyPolicy, T> field, T fallback) {
T value = IrisHydrologyPolicy.inherited(biome, region, dimension, field);
private <T> T inherited(List<IrisBiome> biomes, IrisRegion region, Function<IrisHydrologyPolicy, T> field, T fallback) {
T value = IrisHydrologyPolicy.inherited(biomes, region, dimension, field);
return value == null ? fallback : value;
}
@@ -225,29 +228,41 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource,
return (byte) bits;
}
private static void requireMultiplier(String field, double value, IrisBiome biome, IrisRegion region) {
if (!Double.isFinite(value) || value < 0D) {
throw new IllegalArgumentException("Hydrology policy " + field + " for " + where(biome, region) + " must be a finite value of 0 or more, got "
+ value);
private static void requireMultiplier(String field, double value, List<IrisBiome> biomes, IrisRegion region) {
if (!IrisHydrologyPolicy.validMultiplier(value)) {
throw new IllegalArgumentException("Hydrology policy " + field + " for " + where(biomes, region) + " must be a finite value from 0 to "
+ (int) IrisHydrologyPolicy.MAX_MULTIPLIER + ", got " + value);
}
}
private static String where(IrisBiome biome, IrisRegion region) {
return "biome " + (biome == null ? "none" : biome.getLoadKey()) + " in region " + (region == null ? "none" : region.getLoadKey());
private static void requireWetness(double min, double max, List<IrisBiome> biomes, IrisRegion region) {
if (!(min >= 0D && min <= max && max <= 1D)) {
throw new IllegalArgumentException("Hydrology policy wetness for " + where(biomes, region) + " must have 0 <= min <= max <= 1, got min "
+ min + " and max " + max);
}
}
private record Policy(float rainfall, float pondDensity, byte permission, String fluid, boolean climateZones) {
private static String where(List<IrisBiome> biomes, IrisRegion region) {
StringBuilder where = new StringBuilder("biome ").append(biomes.isEmpty() ? "none" : biomes.getFirst().getLoadKey());
for (int index = 1; index < biomes.size(); index++) {
where.append(" inside ").append(biomes.get(index).getLoadKey());
}
return where.append(" in region ").append(region == null ? "none" : region.getLoadKey()).toString();
}
private record PolicyKey(IrisBiome biome, IrisRegion region) {
private record Policy(float rainfall, float pondDensity, byte permission, String fluid, boolean climateZones, float minWetness,
float maxWetness) {
}
private record PolicyKey(List<IrisBiome> biomes, IrisRegion region) {
@Override
public boolean equals(Object other) {
return other instanceof PolicyKey key && key.biome == biome && key.region == region;
return other instanceof PolicyKey key && key.biomes == biomes && key.region == region;
}
@Override
public int hashCode() {
return 31 * System.identityHashCode(biome) + System.identityHashCode(region);
return 31 * System.identityHashCode(biomes) + System.identityHashCode(region);
}
}
@@ -184,6 +184,8 @@ public final class HeightLattice {
out.ocean()[index] = samples.ocean()[sample];
out.rainfall()[index] = samples.rainfall()[sample];
out.pondDensity()[index] = samples.pondDensity()[sample];
out.wetness()[index] = samples.wetness()[sample];
out.climateZoned()[index] = samples.climateZoned()[sample];
out.permission()[index] = samples.permission()[sample];
out.fluidProfile()[index] = samples.fluidProfile()[sample];
}
@@ -345,6 +347,8 @@ public final class HeightLattice {
private final boolean[] ocean;
private final float[] rainfall;
private final float[] pondDensity;
private final float[] wetness;
private final boolean[] climateZoned;
private final byte[] permission;
private final String[] fluidProfile;
private final AtomicReferenceArray<CompletableFuture<Void>> marks;
@@ -356,6 +360,8 @@ public final class HeightLattice {
this.ocean = new boolean[cells];
this.rainfall = new float[cells];
this.pondDensity = new float[cells];
this.wetness = new float[cells];
this.climateZoned = new boolean[cells];
this.permission = new byte[cells];
this.fluidProfile = new String[cells];
this.marks = new AtomicReferenceArray<>(cells);
@@ -366,6 +372,8 @@ public final class HeightLattice {
ocean[local] = samples.ocean()[sample];
rainfall[local] = samples.rainfall()[sample];
pondDensity[local] = samples.pondDensity()[sample];
wetness[local] = samples.wetness()[sample];
climateZoned[local] = samples.climateZoned()[sample];
permission[local] = samples.permission()[sample];
fluidProfile[local] = samples.fluidProfile()[sample];
}
@@ -375,6 +383,8 @@ public final class HeightLattice {
out.ocean()[index] = ocean[local];
out.rainfall()[index] = rainfall[local];
out.pondDensity()[index] = pondDensity[local];
out.wetness()[index] = wetness[local];
out.climateZoned()[index] = climateZoned[local];
out.permission()[index] = permission[local];
out.fluidProfile()[index] = fluidProfile[local];
}
@@ -8,6 +8,8 @@ public final class HydrologySampleBuffer {
private final boolean[] ocean;
private final float[] rainfall;
private final float[] pondDensity;
private final float[] wetness;
private final boolean[] climateZoned;
private final byte[] permission;
private final String[] fluidProfile;
@@ -19,6 +21,8 @@ public final class HydrologySampleBuffer {
this.ocean = new boolean[capacity];
this.rainfall = new float[capacity];
this.pondDensity = new float[capacity];
this.wetness = new float[capacity];
this.climateZoned = new boolean[capacity];
this.permission = new byte[capacity];
this.fluidProfile = new String[capacity];
}
@@ -39,6 +43,14 @@ public final class HydrologySampleBuffer {
return pondDensity;
}
public float[] wetness() {
return wetness;
}
public boolean[] climateZoned() {
return climateZoned;
}
public byte[] permission() {
return permission;
}
@@ -28,8 +28,6 @@ public final class HydrologyPlanCodec {
private static final int POND_BYTES = 2 * Long.BYTES + 1 + 15 * Integer.BYTES;
private static final int STATION_BYTES = 5 * Integer.BYTES;
private static final int INLET_BYTES = Long.BYTES + 5 * Integer.BYTES + 2 * STATION_BYTES;
private static final ReachStyle[] STYLES = ReachStyle.values();
private static final PondKind[] KINDS = PondKind.values();
private HydrologyPlanCodec() {
}
@@ -102,13 +100,13 @@ public final class HydrologyPlanCodec {
writeFloats(out, reach.halfWidth());
writeFloats(out, reach.depth());
for (ReachStyle style : reach.style()) {
out.writeByte(style.ordinal());
out.writeByte(style.code());
}
}
private static void writePond(DataOutputStream out, Pond pond) throws IOException {
out.writeLong(pond.id());
out.writeByte(pond.kind().ordinal());
out.writeByte(pond.kind().code());
out.writeInt(pond.level());
out.writeInt(pond.floor());
out.writeInt(pond.spillX());
@@ -190,7 +188,7 @@ public final class HydrologyPlanCodec {
return Optional.empty();
}
return Optional.of(new Body(x, z, reaches, ponds, inlets));
} catch (BufferUnderflowException | IllegalArgumentException malformed) {
} catch (BufferUnderflowException | IllegalArgumentException | IllegalStateException malformed) {
return Optional.empty();
}
}
@@ -211,14 +209,14 @@ public final class HydrologyPlanCodec {
float[] depth = readFloats(in, points);
ReachStyle[] style = new ReachStyle[points];
for (int point = 0; point < points; point++) {
style[point] = STYLES[index(in.get(), STYLES.length)];
style[point] = ReachStyle.fromCode(Byte.toUnsignedInt(in.get()));
}
return new Reach(id, tier, downstreamId, xs, zs, grade, halfWidth, depth, style, catchment);
}
private static Pond readPond(ByteBuffer in) {
long id = in.getLong();
PondKind kind = KINDS[index(in.get(), KINDS.length)];
PondKind kind = PondKind.fromCode(Byte.toUnsignedInt(in.get()));
int level = in.getInt();
int floor = in.getInt();
int spillX = in.getInt();
@@ -21,8 +21,10 @@ import art.arcane.iris.generation.hydrology.config.IrisPondNatural;
import art.arcane.iris.generation.hydrology.config.IrisPondSeeded;
import art.arcane.iris.generation.hydrology.config.IrisPondShore;
import art.arcane.iris.generation.hydrology.config.IrisSeaInlets;
import art.arcane.iris.generation.hydrology.underground.SeaInletPlanner;
import art.arcane.iris.generation.hydrology.underground.SeaInletRasterizer;
import art.arcane.iris.generation.hydrology.water.HydrologyTier;
import art.arcane.iris.generation.hydrology.water.LakeCandidate;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
import com.google.gson.Gson;
@@ -57,6 +59,12 @@ public final class HydrologySettings {
private static final int INLET_LAST_STEP = (int) Math.ceil(WindowPlanner.CELL * Math.sqrt(2D));
private static final int INLET_SHELL = SeaInletRasterizer.SHELL;
public static final int MAX_CAVE_POOL_RADIUS = 15;
private static final int CAVE_POOL_SPAN = 2 * MAX_CAVE_POOL_RADIUS + 1;
private static final int MAX_CAVE_POOL_AREA = CAVE_POOL_SPAN * CAVE_POOL_SPAN;
private static final int MAX_LAKE_AREA = LakeCandidate.MAX_EXTENT * LakeCandidate.MAX_EXTENT;
private static final int MAX_PREFETCH_RINGS = 4;
private static final int MAX_SEEDED_DENSITY = 64;
private static final int MIN_WATERFALL_DROP = 2;
private final long seed;
private final int seaLevel;
@@ -98,6 +106,7 @@ public final class HydrologySettings {
this.seams = seams(config.getFluids());
this.prefetchRings = config.getPrefetchRings();
this.persist = config.isPersist();
requireBounds(config);
requireFluidReferences();
this.fingerprint = computeFingerprint();
}
@@ -362,6 +371,12 @@ public final class HydrologySettings {
+ inlets.length().max() + " + " + INLET_LAST_STEP + " for the last step + the wider of halfWidth max and chamberRadius max"
+ " + " + (1 + INLET_SHELL) + " for the seal); an inlet must stay within " + WindowKey.SIZE + " blocks");
}
long lookups = SeaInletPlanner.lookupReach(inlets.length().max(), inlets.chamberRadius().max());
if (lookups > WindowKey.SIZE) {
throw new IllegalArgumentException("Hydrology underground.seaInlets planning looks " + lookups
+ " blocks from the coast (length max " + inlets.length().max() + ", chamberRadius max " + inlets.chamberRadius().max()
+ "); it must stay within " + WindowKey.SIZE + " blocks");
}
return inlets;
}
@@ -544,6 +559,77 @@ public final class HydrologySettings {
}
}
private void requireBounds(IrisHydrology config) {
requireWithin(prefetchRings, 0, MAX_PREFETCH_RINGS, "prefetchRings");
requirePositive(drainage.fillEpsilon(), "drainage.fillEpsilon");
for (int index = 0; index < config.getTiers().size(); index++) {
requireTierBounds(config.getTiers().get(index), "tiers[" + index + "]");
}
double seeded = config.getPonds().getSeeded().getDensity();
if (!(seeded >= 0D && seeded <= MAX_SEEDED_DENSITY)) {
throw new IllegalArgumentException("Hydrology ponds.seeded.density must stay within 0.." + MAX_SEEDED_DENSITY + ", got " + seeded);
}
requireShoreDepth(ponds.materials(), "ponds.materials");
requireAtLeast(deformation.maxFill(), 0, "deformation.maxFill");
if (lakes.maxArea() > MAX_LAKE_AREA) {
throw new IllegalArgumentException("Hydrology lakes.maxArea must not go above " + MAX_LAKE_AREA + " (" + LakeCandidate.MAX_EXTENT
+ " by " + LakeCandidate.MAX_EXTENT + " blocks, the widest a lake can span), got " + lakes.maxArea());
}
requireAtLeast(underground.seaInlets().spacing(), 1, "underground.seaInlets.spacing");
requireCavePoolBounds(underground.cavePools());
}
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");
requireShoreDepth(config.getMaterials(), field + ".materials");
}
private static void requireShoreDepth(IrisHydrologyMaterials materials, String field) {
if (materials != null) {
requireAtLeast(materials.getShoreDepth(), 1, field + ".shoreDepth");
}
}
private static void requireCavePoolBounds(CavePools pools) {
if (!pools.enabled()) {
return;
}
if (pools.freeboard().max() >= pools.maxDepth()) {
throw new IllegalArgumentException("Hydrology underground.cavePools.freeboard max " + pools.freeboard().max()
+ " must stay below maxDepth " + pools.maxDepth());
}
if (pools.maxArea() > MAX_CAVE_POOL_AREA) {
throw new IllegalArgumentException("Hydrology underground.cavePools.maxArea must not go above " + MAX_CAVE_POOL_AREA + " ("
+ CAVE_POOL_SPAN + " by " + CAVE_POOL_SPAN + " blocks, the widest a pool can spread), got " + pools.maxArea());
}
}
private static void requireWithin(int value, int min, int max, String field) {
if (value < min || value > max) {
throw new IllegalArgumentException("Hydrology " + field + " must stay within " + min + ".." + max + ", got " + value);
}
}
private static void requireAtLeast(int value, int min, String field) {
if (value < min) {
throw new IllegalArgumentException("Hydrology " + field + " must be at least " + min + ", got " + value);
}
}
private static void requireNonNegative(double value, String field) {
if (!(Double.isFinite(value) && value >= 0D)) {
throw new IllegalArgumentException("Hydrology " + field + " must be a finite value of at least 0, got " + value);
}
}
private static void requirePositive(float value, String field) {
if (!(Float.isFinite(value) && value > 0f)) {
throw new IllegalArgumentException("Hydrology " + field + " must be a finite value above 0, got " + value);
}
}
private void requireFluidReferences() {
for (Map.Entry<String, String> seam : seams.entrySet()) {
requireFluid(seam.getValue(), "the seam of fluid '" + seam.getKey() + "'");
@@ -574,8 +660,7 @@ public final class HydrologySettings {
}
private long computeFingerprint() {
Fingerprint hash = new Fingerprint().add(seed).add(seaLevel).add(minY).add(maxY).add(enabled)
.add(density).add(prefetchRings).add(persist);
Fingerprint hash = new Fingerprint().add(seed).add(seaLevel).add(minY).add(maxY).add(enabled).add(density);
addClimate(hash);
addDrainage(hash);
addTiers(hash);
@@ -130,7 +130,7 @@ public final class WindowPlanner {
}
List<Reach> reaches = network.reaches();
List<Pond> windowPonds = windowPonds(network.ponds());
List<SeaInlet> planned = inlets.plan(raw, samples, drainage.receivers(), drainage.accumulation(), network, settings.seed());
List<SeaInlet> planned = inlets.plan(key, raw, samples, drainage.receivers(), drainage.accumulation(), network, settings.seed());
WindowPlan owned = new WindowPlan(key, ownedReaches(key, reaches), ownedPonds(key, windowPonds), ownedInlets(key, planned));
requireSeaConnectedHeads(owned, settings.seaLevel());
return new WindowComputation(owned, reaches, windowPonds);
@@ -1,23 +1,41 @@
package art.arcane.iris.generation.hydrology.query;
import art.arcane.iris.generation.hydrology.PersistedCodes;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public enum HydrologyFeatureType {
STREAM,
RIVER,
MAJOR_RIVER,
CASCADE,
WATERFALL,
MOUTH,
POND,
LAKE,
DAM,
SEA_INLET,
CAVE_POOL;
STREAM(0),
RIVER(1),
MAJOR_RIVER(2),
CASCADE(3),
WATERFALL(4),
MOUTH(5),
POND(6),
LAKE(7),
DAM(8),
SEA_INLET(9),
CAVE_POOL(10);
private static final List<String> KEYS = keyList();
private static final PersistedCodes<HydrologyFeatureType> CODES =
PersistedCodes.of(HydrologyFeatureType.class, HydrologyFeatureType::code);
private final int code;
HydrologyFeatureType(int code) {
this.code = code;
}
public int code() {
return code;
}
public static HydrologyFeatureType fromCode(int code) {
return CODES.decode(code);
}
public String key() {
return name().toLowerCase(Locale.ROOT);
@@ -0,0 +1,18 @@
package art.arcane.iris.generation.hydrology.query;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.TimeoutException;
public final class HydrologySearchTimeoutException extends TimeoutException {
private final HydrologyFeatureRef nearestSoFar;
public HydrologySearchTimeoutException(Duration timeout, HydrologyFeatureRef nearestSoFar) {
super("The hydrology feature search ran past its " + timeout.toMillis() + " ms limit.");
this.nearestSoFar = nearestSoFar;
}
public Optional<HydrologyFeatureRef> nearestSoFar() {
return Optional.ofNullable(nearestSoFar);
}
}
@@ -21,7 +21,6 @@ public final class CavePoolFiller {
private static final long SALT_FLOOR = 0x4341564652L << 20;
private static final long SALT_FREEBOARD = 0x43415646524244L;
private static final long SALT_DENSITY = 0x43415644454e53L;
private static final HydrologyCaveCell GUARD = HydrologyCaveCell.of(HydrologyCaveAction.SEAL_GUARD);
private static final CaveVoxel[] VOXELS = CaveVoxel.values();
private static final int[] DX = {1, -1, 0, 0, 0, 0};
private static final int[] DY = {0, 0, 0, 0, 1, -1};
@@ -143,7 +142,8 @@ public final class CavePoolFiller {
}
private static void write(int chunkX, int chunkZ, Pool pool, MantleWriter writer) {
HydrologyCaveCell wet = new HydrologyCaveCell(HydrologyCaveAction.POOL_SOURCE, pool.fluid(), "");
HydrologyCaveCell wet = new HydrologyCaveCell(HydrologyCaveAction.POOL_SOURCE, pool.fluid());
HydrologyCaveCell wall = new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, pool.fluid());
for (int offsetX = -1; offsetX <= 1; offsetX++) {
for (int offsetZ = -1; offsetZ <= 1; offsetZ++) {
int targetX = chunkX + offsetX;
@@ -151,7 +151,7 @@ public final class CavePoolFiller {
if (pool.touches(targetX, targetZ)) {
writer.withChunkFence(targetX, targetZ, () -> {
writeCells(targetX, targetZ, pool.cells(), wet, writer);
writeCells(targetX, targetZ, pool.walls(), GUARD, writer);
writeCells(targetX, targetZ, pool.walls(), wall, writer);
});
}
}
@@ -166,12 +166,18 @@ public final class CavePoolFiller {
continue;
}
int y = unpackY(cell);
if (writer.getDataIfPresent(x, y, z, HydrologyCaveCell.class) == null) {
HydrologyCaveCell existing = writer.getDataIfPresent(x, y, z, HydrologyCaveCell.class);
if (existing == null || replacesSharedWall(existing, value)) {
writer.setData(x, y, z, value);
}
}
}
private static boolean replacesSharedWall(HydrologyCaveCell existing, HydrologyCaveCell value) {
return existing.action() == HydrologyCaveAction.SEAL_GUARD && value.action() == HydrologyCaveAction.SEAL_GUARD
&& value.fluidProfileKey().compareTo(existing.fluidProfileKey()) < 0;
}
private String fluid(CarvedTerrain carved, int x, int y, int z) {
String policy = carved.caveFluid(x, y, z);
return policy != null ? policy : pools.fluid();
@@ -5,6 +5,7 @@ import art.arcane.iris.generation.hydrology.grid.DemGrid;
import art.arcane.iris.generation.hydrology.grid.HydrologySampleBuffer;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.hydrology.plan.WindowKey;
import art.arcane.iris.generation.hydrology.plan.WindowPlanner;
import art.arcane.iris.generation.hydrology.water.Pond;
import art.arcane.iris.generation.hydrology.water.PondMask;
import art.arcane.iris.generation.hydrology.water.Reach;
@@ -20,6 +21,7 @@ import java.util.TreeMap;
public final class SeaInletPlanner {
private static final int ROOF_MARGIN = 2;
private static final int OPEN_LAND_STATIONS = 2;
private static final int STEP_LOOKUP_CELLS = 2;
private static final float NOISE_STEP = 32f;
private static final int CONTAINMENT = 2;
private static final float WET_SLACK = CONTAINMENT + 1 + 6f;
@@ -41,8 +43,15 @@ public final class SeaInletPlanner {
this.settings = Objects.requireNonNull(settings, "settings");
}
public List<SeaInlet> plan(DemGrid raw, HydrologySampleBuffer samples, int[] receivers, float[] accumulation, ShapedNetwork network,
long seed) {
public static long lookupReach(int lengthMax, int chamberRadiusMax) {
int cell = WindowPlanner.CELL;
long farthestStation = cell * (long) Math.floor((lengthMax + cell * Math.sqrt(2D) - cell) / cell);
return farthestStation + (long) cell * Math.max(STEP_LOOKUP_CELLS, chamberRing(chamberRadiusMax, cell));
}
public List<SeaInlet> plan(WindowKey window, DemGrid raw, HydrologySampleBuffer samples, int[] receivers, float[] accumulation,
ShapedNetwork network, long seed) {
Objects.requireNonNull(window, "window");
HydrologySettings.SeaInlets config = settings.underground().seaInlets();
if (!config.enabled() || settings.density() == 0f) {
return List.of();
@@ -53,31 +62,36 @@ public final class SeaInletPlanner {
+ " receivers=" + receivers.length + " accumulation=" + accumulation.length);
}
Terrain terrain = new Terrain(raw, samples, receivers, accumulation, cover(raw, samples.height(), network), seed);
List<SeaInlet> inlets = new ArrayList<>();
List<Traced> traced = new ArrayList<>();
for (Map.Entry<Long, List<Integer>> site : sites(terrain, config).entrySet()) {
SeaInlet inlet = site(terrain, config, site.getKey(), site.getValue());
if (inlet != null) {
inlets.add(inlet);
if (inlet == null) {
continue;
}
if (terrain.clipped && window.equals(owner(inlet))) {
throw new IllegalStateException("Sea inlet " + inlet.id() + " of window " + window
+ " reaches the edge of the window's planning span");
}
traced.add(new Traced(inlet, !terrain.clipped));
}
inlets.sort(Comparator.comparingLong(SeaInlet::id).thenComparingDouble(inlet -> inlet.xs()[0])
.thenComparingDouble(inlet -> inlet.zs()[0]));
return separated(inlets);
traced.sort(Comparator.comparingLong((Traced entry) -> entry.inlet().id()).thenComparingDouble(entry -> entry.inlet().xs()[0])
.thenComparingDouble(entry -> entry.inlet().zs()[0]));
return separated(traced);
}
private static List<SeaInlet> separated(List<SeaInlet> inlets) {
List<SeaInletFootprint> footprints = new ArrayList<>(inlets.size());
for (SeaInlet inlet : inlets) {
footprints.add(SeaInletFootprint.of(inlet));
private static List<SeaInlet> separated(List<Traced> traced) {
List<SeaInletFootprint> footprints = new ArrayList<>(traced.size());
for (Traced entry : traced) {
footprints.add(SeaInletFootprint.of(entry.inlet()));
}
List<SeaInlet> kept = new ArrayList<>(inlets.size());
for (int index = 0; index < inlets.size(); index++) {
List<SeaInlet> kept = new ArrayList<>(traced.size());
for (int index = 0; index < traced.size(); index++) {
boolean yields = false;
for (int earlier = 0; earlier < index && !yields; earlier++) {
yields = footprints.get(earlier).conflicts(footprints.get(index));
}
if (!yields) {
kept.add(inlets.get(index));
if (!yields && traced.get(index).whole()) {
kept.add(traced.get(index).inlet());
}
}
return List.copyOf(kept);
@@ -110,6 +124,7 @@ public final class SeaInletPlanner {
double targetZ = (siteZ + CellHash.unit(CellHash.mix(terrain.seed, SALT_SITE_Z, siteX, siteZ))) * config.spacing();
DemGrid grid = terrain.grid;
WindowKey owner = WindowKey.containing((int) Math.floor(targetX), (int) Math.floor(targetZ));
terrain.clipped = siteTouchesBorder(terrain, config, siteX, siteZ, owner);
List<Integer> ordered = new ArrayList<>(candidates.size());
for (int candidate : candidates) {
if (owner.equals(WindowKey.containing(grid.blockX(candidate), grid.blockZ(candidate)))) {
@@ -180,7 +195,7 @@ public final class SeaInletPlanner {
int radius = 0;
int preferred = Math.round(lerp(config.chamberRadius().min(), config.chamberRadius().max(), unit(terrain, SALT_RADIUS, end)));
for (int candidate : new int[]{preferred, config.chamberRadius().min()}) {
float capacity = capacity(terrain, config, end, (candidate + grid.cell() - 1) / grid.cell() + 1);
float capacity = capacity(terrain, config, end, chamberRing(candidate, grid.cell()));
if (capacity - water >= config.headroom().min()) {
radius = candidate;
chamberCapacity = capacity;
@@ -251,12 +266,14 @@ public final class SeaInletPlanner {
int i = cell % grid.width();
int j = cell / grid.width();
float lowest = Float.POSITIVE_INFINITY;
boolean outside = false;
for (int dj = -ring; dj <= ring; dj++) {
for (int di = -ring; di <= ring; di++) {
int ni = i + di;
int nj = j + dj;
if (ni < 0 || nj < 0 || ni >= grid.width() || nj >= grid.depth()) {
return Float.NEGATIVE_INFINITY;
outside = true;
continue;
}
int neighbour = grid.index(ni, nj);
if (terrain.ocean(neighbour)) {
@@ -265,6 +282,10 @@ public final class SeaInletPlanner {
lowest = Math.min(lowest, terrain.cover[neighbour]);
}
}
if (outside) {
terrain.clipped = true;
return Float.NEGATIVE_INFINITY;
}
return lowest - config.roofClearance() - ROOF_MARGIN;
}
@@ -272,16 +293,20 @@ public final class SeaInletPlanner {
DemGrid grid = terrain.grid;
int i = cell % grid.width();
int j = cell / grid.width();
boolean outside = false;
for (int dj = -1; dj <= 1; dj++) {
for (int di = -1; di <= 1; di++) {
int ni = i + di;
int nj = j + dj;
if (ni < 0 || nj < 0 || ni >= grid.width() || nj >= grid.depth() || terrain.wet(grid.index(ni, nj))) {
if (ni < 0 || nj < 0 || ni >= grid.width() || nj >= grid.depth()) {
outside = true;
} else if (terrain.wet(grid.index(ni, nj))) {
return false;
}
}
}
return true;
terrain.clipped |= outside;
return !outside;
}
private static int mouth(Terrain terrain, int land) {
@@ -310,14 +335,8 @@ public final class SeaInletPlanner {
int best = -1;
for (int dj = -1; dj <= 1; dj++) {
for (int di = -1; di <= 1; di++) {
int ni = i + di;
int nj = j + dj;
if ((di == 0 && dj == 0) || ni <= 0 || nj <= 0 || ni >= grid.width() - 1 || nj >= grid.depth() - 1) {
continue;
}
int neighbour = grid.index(ni, nj);
if (terrain.receivers[neighbour] != cell || terrain.ocean(neighbour) || path.contains(neighbour)
|| distanceSquared(grid, neighbour, grid.blockX(mouth), grid.blockZ(mouth)) <= away) {
int neighbour = onward(terrain, mouth, i + di, j + dj, away, path);
if (neighbour < 0 || terrain.receivers[neighbour] != cell) {
continue;
}
if (best < 0 || terrain.accumulation[neighbour] > terrain.accumulation[best]
@@ -339,16 +358,11 @@ public final class SeaInletPlanner {
double bestAway = 0D;
for (int dj = -1; dj <= 1; dj++) {
for (int di = -1; di <= 1; di++) {
int ni = i + di;
int nj = j + dj;
if ((di == 0 && dj == 0) || ni <= 0 || nj <= 0 || ni >= grid.width() - 1 || nj >= grid.depth() - 1) {
int neighbour = onward(terrain, mouth, i + di, j + dj, away, path);
if (neighbour < 0) {
continue;
}
int neighbour = grid.index(ni, nj);
double distance = distanceSquared(grid, neighbour, grid.blockX(mouth), grid.blockZ(mouth));
if (terrain.ocean(neighbour) || path.contains(neighbour) || distance <= away) {
continue;
}
boolean covers = canCover(terrain, config, neighbour);
if (best < 0 || covers && !bestCovers || covers == bestCovers && (distance > bestAway
|| distance == bestAway && terrain.cover[neighbour] > terrain.cover[best])) {
@@ -426,6 +440,67 @@ public final class SeaInletPlanner {
}
}
private static int onward(Terrain terrain, int mouth, int ni, int nj, double away, List<Integer> path) {
DemGrid grid = terrain.grid;
if (ni < 0 || nj < 0 || ni >= grid.width() || nj >= grid.depth()) {
terrain.clipped = true;
return -1;
}
int neighbour = grid.index(ni, nj);
if (terrain.ocean(neighbour) || path.contains(neighbour)
|| distanceSquared(grid, neighbour, grid.blockX(mouth), grid.blockZ(mouth)) <= away) {
return -1;
}
if (ni == 0 || nj == 0 || ni == grid.width() - 1 || nj == grid.depth() - 1) {
terrain.clipped = true;
return -1;
}
return neighbour;
}
private boolean siteTouchesBorder(Terrain terrain, HydrologySettings.SeaInlets config, int siteX, int siteZ, WindowKey owner) {
DemGrid grid = terrain.grid;
CellRange columns = siteCells(siteX, config.spacing(), owner.wx(), grid.originX(), grid.cell());
CellRange rows = siteCells(siteZ, config.spacing(), owner.wz(), grid.originZ(), grid.cell());
int lastColumn = grid.width() - 1;
int lastRow = grid.depth() - 1;
if (columns.first() < 0L || rows.first() < 0L || columns.last() > lastColumn || rows.last() > lastRow) {
return true;
}
float cliff = settings.seaLevel() + config.minimumCliffHeight();
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;
}
}
for (int j = (int) rows.first(); j <= rows.last(); j++) {
if (columns.first() == 0L && cliffLand(terrain, 0, j, cliff)
|| columns.last() == lastColumn && cliffLand(terrain, lastColumn, j, cliff)) {
return true;
}
}
return false;
}
private static CellRange siteCells(int site, int spacing, int window, int origin, int cell) {
long from = Math.max((long) site * spacing, (long) window * WindowKey.SIZE);
long to = Math.min(((long) site + 1L) * spacing, ((long) window + 1L) * WindowKey.SIZE);
return new CellRange(Math.ceilDiv(from - origin, cell), Math.ceilDiv(to - origin, cell) - 1L);
}
private static boolean cliffLand(Terrain terrain, int i, int j, float cliff) {
int cell = terrain.grid.index(i, j);
return !terrain.ocean(cell) && terrain.natural(cell) >= cliff;
}
private static int chamberRing(int radius, int cell) {
return (radius + cell - 1) / cell + 1;
}
private static WindowKey owner(SeaInlet inlet) {
return WindowKey.containing((int) Math.floor(inlet.xs()[1]), (int) Math.floor(inlet.zs()[1]));
}
private static double squaredAbove(float radius) {
return (double) radius * radius * (1D + SQUARED_MARGIN);
}
@@ -467,6 +542,12 @@ public final class SeaInletPlanner {
private record Cover(float[] cover, boolean[] wet) {
}
private record Traced(SeaInlet inlet, boolean whole) {
}
private record CellRange(long first, long last) {
}
private static final class Terrain {
private final DemGrid grid;
private final HydrologySampleBuffer samples;
@@ -475,6 +556,7 @@ public final class SeaInletPlanner {
private final float[] cover;
private final boolean[] wet;
private final long seed;
private boolean clipped;
private Terrain(DemGrid grid, HydrologySampleBuffer samples, int[] receivers, float[] accumulation, Cover cover, long seed) {
this.grid = grid;
@@ -13,7 +13,8 @@ public final class SeaInletRasterizer {
private static final int GRID = CHUNK + 2 * SHELL;
static final int NONE = Integer.MIN_VALUE;
public void write(SeaInlet inlet, int chunkX, int chunkZ, MantleWriter writer, String fluid, String floodedBiome, SubterrainFluid subterrain) {
public void write(SeaInlet inlet, int chunkX, int chunkZ, MantleWriter writer, String fluid, SubterrainFluid subterrain,
HistoricalChunks historical) {
if (!touches(inlet, chunkX, chunkZ)) {
return;
}
@@ -22,10 +23,11 @@ public final class SeaInletRasterizer {
if (!shape(inlet, (chunkX << 4) - SHELL, (chunkZ << 4) - SHELL, GRID, floors, ceilings)) {
return;
}
HydrologyCaveCell wet = new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, fluid, floodedBiome);
HydrologyCaveCell dry = new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, fluid, floodedBiome);
HydrologyCaveCell guard = new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, fluid, floodedBiome);
HydrologyCaveCell wet = new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, fluid);
HydrologyCaveCell dry = new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, fluid);
HydrologyCaveCell guard = new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, fluid);
int water = inlet.waterLevel();
boolean[] historicalAround = historicalAround(chunkX, chunkZ, historical);
for (int lz = 0; lz < CHUNK; lz++) {
for (int lx = 0; lx < CHUNK; lx++) {
int cell = (lz + SHELL) * GRID + lx + SHELL;
@@ -40,6 +42,8 @@ public final class SeaInletRasterizer {
guard(writer, x, low - SHELL, water, z, guard);
} else if (ceilings[cell] == SeaInlet.OPEN) {
guard(writer, x, low - SHELL, floor - 1, z, guard);
} else if (historicalAround != null && besideHistorical(historicalAround, lx, lz)) {
guard(writer, x, low - SHELL, ceilings[cell], z, guard);
} else {
for (int y = floor + 1; y <= water; y++) {
writer.setData(x, y, z, wet);
@@ -66,6 +70,12 @@ public final class SeaInletRasterizer {
boolean at(int x, int y, int z);
}
public interface HistoricalChunks {
HistoricalChunks NONE = (chunkX, chunkZ) -> false;
boolean at(int chunkX, int chunkZ);
}
public static boolean touches(SeaInlet inlet, int chunkX, int chunkZ) {
int[] bounds = bounds(inlet);
int minX = chunkX << 4;
@@ -182,6 +192,36 @@ public final class SeaInletRasterizer {
return roof;
}
private static boolean[] historicalAround(int chunkX, int chunkZ, HistoricalChunks historical) {
boolean[] around = null;
for (int dz = -1; dz <= 1; dz++) {
for (int dx = -1; dx <= 1; dx++) {
if ((dx != 0 || dz != 0) && historical.at(chunkX + dx, chunkZ + dz)) {
if (around == null) {
around = new boolean[9];
}
around[(dz + 1) * 3 + dx + 1] = true;
}
}
}
return around;
}
private static boolean besideHistorical(boolean[] historicalAround, int lx, int lz) {
int fromX = lx < SHELL ? -1 : 0;
int toX = lx >= CHUNK - SHELL ? 1 : 0;
int fromZ = lz < SHELL ? -1 : 0;
int toZ = lz >= CHUNK - SHELL ? 1 : 0;
for (int dz = fromZ; dz <= toZ; dz++) {
for (int dx = fromX; dx <= toX; dx++) {
if (historicalAround[(dz + 1) * 3 + dx + 1]) {
return true;
}
}
}
return false;
}
private static void guard(MantleWriter writer, int x, int fromY, int toY, int z, HydrologyCaveCell guard) {
for (int y = fromY; y <= toY; y++) {
if (writer.getDataIfPresent(x, y, z, HydrologyCaveCell.class) == null) {
@@ -13,6 +13,7 @@ import java.util.List;
final class CupCarver {
private static final long SALT_SITE = 0x43555053495445L;
private static final long SALT_SPLIT = 0x43555053504c54L;
private static final long SALT_SITE_X = 0x43555053495858L;
private static final long SALT_SITE_Z = 0x4355505349545aL;
private static final long SALT_RADIUS = 0x43555052414449L;
@@ -53,13 +54,14 @@ final class CupCarver {
private void windowCups(DemGrid raw, int wx, int wz, HydrologySampleBuffer samples, List<CupSet.Cup> out) {
float density = settings.ponds().seeded().density();
if (!(density > 0f)) {
double expected = (double) density * peakPondDensity(raw, wx, wz, samples);
if (!(expected > 0D)) {
return;
}
int split = (int) Math.ceil(Math.sqrt(density));
int split = (int) Math.ceil(Math.sqrt(expected));
double size = (double) WindowKey.SIZE / split;
double chance = density / ((double) split * split);
long seed = settings.seed();
long seed = CellHash.mix(settings.seed(), SALT_SPLIT, split, split);
for (int sz = 0; sz < split; sz++) {
for (int sx = 0; sx < split; sx++) {
int siteX = wx * split + sx;
@@ -74,12 +76,28 @@ final class CupCarver {
if (suitable(samples, cell, slope)
&& CellHash.unit(CellHash.mix(seed, SALT_SITE, siteX, siteZ))
< Math.clamp(chance * samples.pondDensity()[cell], 0D, 1D) * settings.density()) {
addCup(raw, samples, cell, slope, siteX, siteZ, false, out);
addCup(raw, samples, cell, slope, x, z, false, out);
}
}
}
}
private static float peakPondDensity(DemGrid raw, int wx, int wz, HydrologySampleBuffer samples) {
int cell = raw.cell();
int i0 = Math.max(0, Math.ceilDiv(wx * WindowKey.SIZE - raw.originX(), cell));
int i1 = Math.min(raw.width(), Math.ceilDiv((wx + 1) * WindowKey.SIZE - raw.originX(), cell));
int j0 = Math.max(0, Math.ceilDiv(wz * WindowKey.SIZE - raw.originZ(), cell));
int j1 = Math.min(raw.depth(), Math.ceilDiv((wz + 1) * WindowKey.SIZE - raw.originZ(), cell));
float[] pondDensity = samples.pondDensity();
float peak = 0f;
for (int j = j0; j < j1; j++) {
for (int i = i0; i < i1; i++) {
peak = Math.max(peak, pondDensity[raw.index(i, j)]);
}
}
return peak;
}
private void chainedCups(DemGrid raw, HydrologySampleBuffer samples, BitSet channels, List<CupSet.Cup> out) {
HydrologySettings.IntRange spacing = settings.ponds().seeded().channelSpacing();
double chance = Math.min(1D, 2D * raw.cell() / Math.max(1, spacing.max() - spacing.min()));
@@ -1,8 +1,26 @@
package art.arcane.iris.generation.hydrology.water;
import art.arcane.iris.generation.hydrology.PersistedCodes;
public enum PondKind {
NATURAL,
SEEDED,
CHAINED,
LAKE
NATURAL(0),
SEEDED(1),
CHAINED(2),
LAKE(3);
private static final PersistedCodes<PondKind> CODES = PersistedCodes.of(PondKind.class, PondKind::code);
private final int code;
PondKind(int code) {
this.code = code;
}
public int code() {
return code;
}
public static PondKind fromCode(int code) {
return CODES.decode(code);
}
}
@@ -230,7 +230,7 @@ public final class PondPlanner {
>= Math.clamp(settings.ponds().natural().keep() * floor.pondDensity()[0], 0f, 1f) * settings.density()) {
return null;
}
return new Candidate(basin, kind, floorX, floorZ, floor.rainfall()[0], fluid(floor));
return new Candidate(basin, kind, floorX, floorZ, dryness(floor), fluid(floor));
}
private Pond lake(LakeCandidate candidate, HeightLattice fine) {
@@ -241,13 +241,18 @@ public final class PondPlanner {
if ((floor.permission()[0] & HydrologySampleBuffer.ALLOW_PONDS) == 0) {
return null;
}
return measureLake(fine, new LakeSite(candidate, floor.rainfall()[0], fluid(floor)));
return measureLake(fine, new LakeSite(candidate, dryness(floor), fluid(floor)));
}
private String fluid(HydrologySampleBuffer floor) {
return floor.fluidProfile()[0] == null ? settings.ponds().fluid() : floor.fluidProfile()[0];
}
private static float dryness(HydrologySampleBuffer floor) {
float wetness = floor.climateZoned()[0] ? floor.wetness()[0] : floor.rainfall()[0];
return Math.clamp(1f - wetness, 0f, 1f);
}
private boolean qualifies(DemGrid raw, Basin basin, PondKind kind) {
long area = (long) basin.cells().length * raw.cell() * raw.cell();
HydrologySettings.NaturalPonds natural = settings.ponds().natural();
@@ -339,7 +344,7 @@ public final class PondPlanner {
return null;
}
int lowest = Math.max(settings.minY() + 1, settings.seaLevel());
int level = Math.min(Math.min(Math.max(lowest, (int) Math.floor(spill.height()) - freeboard(site) - drawdown(site.rainfall())),
int level = Math.min(Math.min(Math.max(lowest, (int) Math.floor(spill.height()) - freeboard(site) - drawdown(site.dryness())),
settings.maxY() - 1), levelCap);
int failures = 0;
for (int round = 0; round < LEVEL_ROUNDS && level >= lowest; round++) {
@@ -770,8 +775,8 @@ public final class PondPlanner {
CellHash.mix(settings.seed(), SALT_FREEBOARD, site.floorX(), site.floorZ()));
}
private int drawdown(float rainfall) {
return Math.round(settings.ponds().climateDrawdown() * Math.clamp(1f - rainfall, 0f, 1f));
private int drawdown(float dryness) {
return Math.round(settings.ponds().climateDrawdown() * dryness);
}
private static int radius(DemGrid raw, Basin basin) {
@@ -807,15 +812,15 @@ public final class PondPlanner {
int floorZ();
float rainfall();
float dryness();
String fluid();
}
private record Candidate(Basin basin, PondKind kind, int floorX, int floorZ, float rainfall, String fluid) implements Site {
private record Candidate(Basin basin, PondKind kind, int floorX, int floorZ, float dryness, String fluid) implements Site {
}
private record LakeSite(LakeCandidate lake, float rainfall, String fluid) implements Site {
private record LakeSite(LakeCandidate lake, float dryness, String fluid) implements Site {
@Override
public PondKind kind() {
return PondKind.LAKE;
@@ -1,10 +1,28 @@
package art.arcane.iris.generation.hydrology.water;
import art.arcane.iris.generation.hydrology.PersistedCodes;
public enum ReachStyle {
RUN,
RIFFLE,
CASCADE,
WATERFALL,
POND_OUTLET,
MOUTH
RUN(0),
RIFFLE(1),
CASCADE(2),
WATERFALL(3),
POND_OUTLET(4),
MOUTH(5);
private static final PersistedCodes<ReachStyle> CODES = PersistedCodes.of(ReachStyle.class, ReachStyle::code);
private final int code;
ReachStyle(int code) {
this.code = code;
}
public int code() {
return code;
}
public static ReachStyle fromCode(int code) {
return CODES.decode(code);
}
}
@@ -1,12 +1,10 @@
package art.arcane.iris.generation.locator;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy;
import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime;
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.generation.terrain.IrisRegion;
import art.arcane.iris.generation.terrain.ShoreBiomeLineages;
import java.util.Set;
@@ -31,28 +29,8 @@ final class HydrologyShoreTargets {
static boolean placesAny(Engine engine, Set<String> targets) {
IrisDimension dimension = engine.getDimension();
if (places(engine, dimension.getHydrologyPolicy(), targets)) {
return true;
}
for (IrisRegion region : dimension.getAllRegions(engine)) {
if (region != null && places(engine, region.getHydrologyPolicy(), targets)) {
return true;
}
}
for (IrisBiome biome : dimension.getReachableBiomes(engine)) {
if (biome != null && places(engine, biome.getHydrologyPolicy(), targets)) {
return true;
}
}
return false;
}
private static boolean places(Engine engine, IrisHydrologyPolicy policy, Set<String> targets) {
if (policy == null || policy.getShoreBiomes() == null) {
return false;
}
for (String key : policy.getShoreBiomes()) {
if (key != null && HintedLocator.closureContains(engine, key, targets)) {
for (String key : ShoreBiomeLineages.placed(dimension, dimension.getAllRegions(engine), engine)) {
if (HintedLocator.closureContains(engine, key, targets)) {
return true;
}
}
@@ -0,0 +1,51 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell;
import art.arcane.iris.generation.subterrain.SubterrainCell;
import art.arcane.iris.generation.subterrain.SubterrainRasterizer;
import art.arcane.iris.generation.terrain.Terrain3DColumn;
import java.util.function.BooleanSupplier;
public final class CarveOwnership {
private CarveOwnership() {
}
public static Owner resolve(boolean hydrology, boolean subterrain, boolean naturalOpening) {
if (hydrology) {
return Owner.HYDROLOGY;
}
if (subterrain) {
return Owner.SUBTERRAIN;
}
return naturalOpening ? Owner.NATURAL_OPENING : Owner.CAVERN;
}
public static boolean carved(Terrain3DColumn transformed, int y, HydrologyCaveCell hydrology, SubterrainCell subterrain,
BooleanSupplier naturalOpening, BooleanSupplier cavern) {
if (transformed != null) {
if (hydrology == null && SubterrainRasterizer.protectsPlacement(subterrain)) {
return subterrain.carve();
}
return y >= 0 && y < transformed.topY() && !transformed.isSolid(y);
}
boolean claims = subterrainClaims(subterrain);
return switch (resolve(hydrology != null, claims, hydrology == null && !claims && naturalOpening.getAsBoolean())) {
case HYDROLOGY -> hydrology.carves();
case SUBTERRAIN -> subterrain.carve();
case NATURAL_OPENING -> true;
case CAVERN -> cavern.getAsBoolean();
};
}
public static boolean subterrainClaims(SubterrainCell cell) {
return cell != null && cell.owned() && (!cell.solid() || cell.room().reservedSolid());
}
public enum Owner {
HYDROLOGY,
SUBTERRAIN,
NATURAL_OPENING,
CAVERN
}
}
@@ -1,8 +1,14 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime;
import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.underground.SeaInletRasterizer;
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
import java.util.Arrays;
import java.util.List;
public final class CaveCeilingMask {
static final int CONTAINMENT = 2;
static final int ROOF = 2;
@@ -53,6 +59,69 @@ public final class CaveCeilingMask {
return masked;
}
public static long[] headroom(int chunkX, int chunkZ, HydrologyRuntime runtime, long[] bands) {
List<SeaInlet> inlets = runtime.inlets(chunkX, chunkZ);
if (inlets.isEmpty()) {
return null;
}
int roofClearance = runtime.settings().underground().seaInlets().roofClearance();
return fillHeadroom(chunkX, chunkZ, inlets, roofClearance, bands) ? bands : null;
}
static boolean fillHeadroom(int chunkX, int chunkZ, List<SeaInlet> inlets, int roofClearance, long[] bands) {
if (inlets.isEmpty()) {
return false;
}
int originX = (chunkX << 4) - CONTAINMENT;
int originZ = (chunkZ << 4) - CONTAINMENT;
int[] bottoms = new int[FIELD * FIELD];
int[] tops = new int[FIELD * FIELD];
Arrays.fill(bottoms, Integer.MAX_VALUE);
Arrays.fill(tops, Integer.MIN_VALUE);
int[] column = new int[2];
boolean roofed = false;
for (SeaInlet inlet : inlets) {
int[] bounds = SeaInletRasterizer.bounds(inlet);
int fromX = Math.max(originX, bounds[0]);
int toX = Math.min(originX + FIELD - 1, bounds[2]);
int toZ = Math.min(originZ + FIELD - 1, bounds[3]);
for (int z = Math.max(originZ, bounds[1]); z <= toZ; z++) {
for (int x = fromX; x <= toX; x++) {
if (!SeaInletRasterizer.column(inlet, x, z, column) || column[1] == SeaInlet.OPEN) {
continue;
}
int index = (z - originZ) * FIELD + x - originX;
bottoms[index] = Math.min(bottoms[index], inlet.waterLevel() + 1);
tops[index] = Math.max(tops[index], column[1] + roofClearance);
roofed = true;
}
}
}
if (!roofed) {
return false;
}
boolean masked = false;
for (int lz = 0; lz < CHUNK; lz++) {
for (int lx = 0; lx < CHUNK; lx++) {
int bottom = Integer.MAX_VALUE;
int top = Integer.MIN_VALUE;
for (int fz = lz; fz <= lz + CONTAINMENT * 2; fz++) {
for (int fx = lx; fx <= lx + CONTAINMENT * 2; fx++) {
bottom = Math.min(bottom, bottoms[fz * FIELD + fx]);
top = Math.max(top, tops[fz * FIELD + fx]);
}
}
bands[PowerOfTwoCoordinates.packLocal16(lx, lz)] = SurfaceFluidBoundaryPlan.boundary(bottom, top);
masked |= bottom <= top;
}
}
return masked;
}
public static boolean masked(int[] ceilings, long[] headroom, int column, int y) {
return ceilings != null && y > ceilings[column] || SurfaceFluidBoundaryPlan.protects(headroom, column, y);
}
public static ChunkWaterRaster ready(ChunkWaterRaster raster, int chunkX, int chunkZ) {
if (raster.provisional()) {
throw new IllegalStateException("The water raster for chunk " + chunkX + "," + chunkZ
@@ -112,8 +112,7 @@ final class CaveObjectPlacementTransaction implements IObjectPlacer {
discard();
return CommitResult.REJECTED_SUBTERRAIN;
}
HydrologyCaveCell hydrology = delegate.getData(x, y, z, HydrologyCaveCell.class);
if (hydrology != null && hydrology.protectsPlacement()) {
if (delegate.getData(x, y, z, HydrologyCaveCell.class) != null) {
discard();
return CommitResult.REJECTED_HYDROLOGY;
}
@@ -85,7 +85,7 @@ public final class CaveTerrainSnapshot {
bytes += 16L + (long) section.length * 8L;
for (HydrologyCaveCell cell : section) {
if (cell != null) {
bytes += 208L + ((long) cell.fluidProfileKey().length() + cell.floodedBiomeKey().length()) * 2L;
bytes += 208L + (long) cell.fluidProfileKey().length() * 2L;
}
}
}
@@ -28,8 +28,6 @@ import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.EngineTarget;
import art.arcane.iris.generation.decoration.tree.TreeBlockMaterial;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.Terrain3DColumn;
import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell;
import art.arcane.iris.generation.hydrology.cave.HydrologyCaveStorage;
import art.arcane.iris.pack.value.IrisPosition;
import art.arcane.iris.generation.block.BoundBlockState;
@@ -123,16 +121,14 @@ public interface EngineMantle extends MatterGenerator {
}
default boolean isCarved(int x, int h, int z) {
Terrain3DColumn transformed = getComplex().transformedColumn(x, z);
if (transformed != null) {
return h >= 0 && h < transformed.topY() && !transformed.isSolid(h);
}
HydrologyCaveCell hydrology = HydrologyCaveStorage.getIfPresent(getMantle(), x, h, z);
if (hydrology != null) {
return hydrology.carves();
}
return getMantle().get(x, h, z, MatterCavern.class) != null
|| getComplex().isTerrain3DOpening(x, h, z);
return CarveOwnership.carved(
getComplex().transformedColumn(x, z),
h,
HydrologyCaveStorage.getIfPresent(getMantle(), x, h, z),
getEngine().getSubterrainCell(x, h, z),
() -> getComplex().isTerrain3DOpening(x, h, z),
() -> getMantle().get(x, h, z, MatterCavern.class) != null
);
}
default NativeBlockState get(int x, int y, int z) {
@@ -12,6 +12,8 @@ import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.stream.ProvisionalSampling;
import art.arcane.iris.generation.subterrain.SubterrainPlan;
import art.arcane.iris.generation.subterrain.SubterrainPlanner;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.generation.terrain.Terrain3DColumn;
import art.arcane.volmlib.util.mantle.flag.MantleFlag;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
@@ -31,6 +33,7 @@ final class MantleCarvedTerrain implements CarvedTerrain {
private final MantleWriter writer;
private final IrisComplex complex;
private final Engine engine;
private final IrisDimension dimension;
private final int chunkX;
private final int chunkZ;
private final int originX;
@@ -54,12 +57,13 @@ final class MantleCarvedTerrain implements CarvedTerrain {
this.writer = writer;
this.complex = complex;
this.engine = engine;
this.dimension = engine.getDimension();
this.chunkX = chunkX;
this.chunkZ = chunkZ;
this.originX = (chunkX - 1) << 4;
this.originZ = (chunkZ - 1) << 4;
this.height = writer.getMantle().getWorldHeight();
this.caveLavaHeight = engine.getDimension().getCaveLavaHeight();
this.caveLavaHeight = dimension.getCaveLavaHeight();
this.minimumY = engine.getWorld().minHeight();
HydrologyRuntime runtime = complex.getHydrologyRuntime();
this.caveFluids = runtime.caveFluidPolicies();
@@ -110,10 +114,10 @@ final class MantleCarvedTerrain implements CarvedTerrain {
return null;
}
long revision = ProvisionalSampling.revision();
IrisBiome biome = engine.getCaveBiome(x, y, z);
IrisBiome biome = engine.getCaveBiomeBelowSurface(x, y, z);
IrisRegion region = complex.getRegionStream().get(x, z);
requireFinal(revision, x, z);
IrisHydrologyPolicy policy = biome == null ? null : biome.getHydrologyPolicy();
return policy == null ? null : policy.getFluid();
return IrisHydrologyPolicy.inherited(biome == null ? List.of() : List.of(biome), region, dimension, IrisHydrologyPolicy::getFluid);
}
private static Collection<SeaInlet> inlets(HydrologyRuntime runtime, int chunkX, int chunkZ) {
@@ -169,6 +169,10 @@ public class MantleCarvingComponent extends IrisMantleComponent {
);
int[] caveCeilings = CaveCeilingMask.fill(x, z, complex.getHydrologyRuntime()::raster,
blendScratch.caveCeilingField, blendScratch.caveCeilings) ? blendScratch.caveCeilings : null;
long[] inletHeadroom = CaveCeilingMask.headroom(x, z, complex.getHydrologyRuntime(), blendScratch.inletHeadroom);
if (inletHeadroom != null) {
SurfaceFluidBoundaryPlan.join(surfaceFluidBoundaries, inletHeadroom);
}
CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan();
for (WeightedProfile weightedProfile : weightedProfiles) {
carveProfile(weightedProfile, writer, x, z, chunkSurfaceHeights, surfaceFluidBoundaries, caveCeilings, fluidSupportPlan);
@@ -190,10 +194,10 @@ public class MantleCarvingComponent extends IrisMantleComponent {
caveCeilings
);
}
rasterizeSubterrain(writer, x, z, complex, caveCeilings);
rasterizeSubterrain(writer, x, z, complex, caveCeilings, inletHeadroom);
}
private void rasterizeSubterrain(MantleWriter writer, int chunkX, int chunkZ, IrisComplex complex, int[] caveCeilings) {
private void rasterizeSubterrain(MantleWriter writer, int chunkX, int chunkZ, IrisComplex complex, int[] caveCeilings, long[] inletHeadroom) {
SubterrainPlanner planner = complex.getSubterrainPlanner();
if (planner == null || planner.isEmpty()) {
return;
@@ -207,7 +211,7 @@ public class MantleCarvingComponent extends IrisMantleComponent {
if (cell.solid() && !cell.room().reservedSolid()) {
return;
}
if (!cell.solid() && caveCeilings != null && y > caveCeilings[PowerOfTwoCoordinates.packLocal16(x & 15, z & 15)]) {
if (!cell.solid() && CaveCeilingMask.masked(caveCeilings, inletHeadroom, PowerOfTwoCoordinates.packLocal16(x & 15, z & 15), y)) {
return;
}
if (cell.solid()) {
@@ -763,6 +767,7 @@ public class MantleCarvingComponent extends IrisMantleComponent {
private final double[] chunkSurfaceHeightSamples = new double[CHUNK_AREA];
private final int[] caveCeilingField = new int[CaveCeilingMask.FIELD * CaveCeilingMask.FIELD];
private final int[] caveCeilings = new int[CHUNK_AREA];
private final long[] inletHeadroom = new long[CHUNK_AREA];
private final double[][] neighbourHeights = new double[NEIGHBOURS][CHUNK_AREA];
private final Object[][] neighbourObjects = new Object[NEIGHBOURS][CHUNK_AREA];
private final long[][] neighbourSubmerged = new long[NEIGHBOURS][4];
@@ -81,7 +81,7 @@ public final class MantleHydrologyComponent extends IrisMantleComponent {
if (!inlets.isEmpty()) {
SeaInletRasterizer.SubterrainFluid subterrain = subterrainFluid(writer, complex, chunkX, chunkZ);
for (SeaInlet inlet : inlets) {
INLETS.write(inlet, chunkX, chunkZ, writer, HydrologyCaveCell.SEA_FLUID, "", subterrain);
INLETS.write(inlet, chunkX, chunkZ, writer, HydrologyCaveCell.SEA_FLUID, subterrain, complex::isHistoricalChunk);
}
}
generateFalls(writer, complex, runtime, own, chunkX, chunkZ);
@@ -897,7 +897,7 @@ public class MantleObjectComponent extends IrisMantleComponent {
int y,
int lavaHeight
) {
if (hydrology != null && hydrology.protectsPlacement()) {
if (hydrology != null) {
return false;
}
if (cavern == null || !cavern.isCavern()) {
@@ -54,6 +54,7 @@ import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.iris.generation.block.B;
import java.util.LinkedHashMap;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
@@ -67,6 +68,8 @@ import static art.arcane.iris.generation.mantle.EngineMantle.AIR;
@Data
public class MantleWriter implements ObjectPassPlacer, AutoCloseable {
private static final int OBJECT_COMPONENT_PRIORITY = 2;
private static final BooleanSupplier ALWAYS = () -> true;
private static final BooleanSupplier NEVER = () -> false;
private final EngineMantle engineMantle;
private final Mantle<Matter> mantle;
@@ -460,34 +463,25 @@ public class MantleWriter implements ObjectPassPlacer, AutoCloseable {
}
public boolean isPrerequisiteCarved(int x, int y, int z) {
SubterrainCell feature = getEngine().getSubterrainCell(x, y, z);
if (feature != null && feature.owned()) {
return feature.carve();
}
Terrain3DColumn transformed = engineMantle.getComplex().transformedColumn(x, z);
if (transformed != null) {
return y >= 0 && y < transformed.topY() && !transformed.isSolid(y);
}
HydrologyCaveCell hydrology = getPrerequisiteDataIfPresent(x, y, z, HydrologyCaveCell.class);
if (hydrology != null) {
return hydrology.carves();
}
return getPrerequisiteDataIfPresent(x, y, z, MatterCavern.class) != null
|| engineMantle.getComplex().isTerrain3DOpening(x, y, z);
return CarveOwnership.carved(
engineMantle.getComplex().transformedColumn(x, z),
y,
getPrerequisiteDataIfPresent(x, y, z, HydrologyCaveCell.class),
getEngine().getSubterrainCell(x, y, z),
() -> engineMantle.getComplex().isTerrain3DOpening(x, y, z),
() -> getPrerequisiteDataIfPresent(x, y, z, MatterCavern.class) != null
);
}
public byte[] getPrerequisiteCarvedColumn(int x, int z, int height) {
int cappedHeight = Math.min(Math.max(height, 0), mantle.getWorldHeight());
Terrain3DColumn transformed = engineMantle.getComplex().transformedColumn(x, z);
if (transformed != null) {
return carvedColumn(transformed, cappedHeight);
}
byte[] carvedColumn = new byte[cappedHeight];
if (cappedHeight <= 0) {
return carvedColumn;
}
Terrain3DColumn terrainColumn = engineMantle.getComplex().terrainColumn(x, z);
Terrain3DColumn transformed = engineMantle.getComplex().transformedColumn(x, z);
Terrain3DColumn terrainColumn = transformed == null ? engineMantle.getComplex().terrainColumn(x, z) : null;
if (terrainColumn != null) {
int maximumY = Math.min(cappedHeight, terrainColumn.topY());
for (int y = Math.max(0, terrainColumn.minY()); y < maximumY; y++) {
@@ -499,46 +493,38 @@ public class MantleWriter implements ObjectPassPlacer, AutoCloseable {
}
MantleChunk<Matter> chunk = acquireChunk(x >> 4, z >> 4);
SubterrainCell[] subterrain = subterrainColumn(x, z, cappedHeight);
if (chunk == null) {
for (int y = 0; y < cappedHeight; y++) {
carvedColumn[y] = carvedByte(transformed, y, null, subterrain, carvedColumn[y] != 0, false);
}
return carvedColumn;
}
synchronized (chunk) {
int lastSection = (cappedHeight - 1) >> 4;
for (int section = 0; section <= lastSection; section++) {
if (!chunk.exists(section)) {
continue;
}
Matter matter = chunk.get(section);
if (matter == null) {
continue;
}
MatterSlice<PreObjectMatterCell> journalSlice = matter.getSlice(PreObjectMatterCell.class);
MatterSlice<MatterCavern> cavernSlice = matter.getSlice(MatterCavern.class);
MatterSlice<HydrologyCaveCell> hydrologySlice = matter.getSlice(HydrologyCaveCell.class);
int sectionBaseY = section << 4;
int sectionMaxY = Math.min(cappedHeight, sectionBaseY + 16);
for (int y = sectionBaseY; y < sectionMaxY; y++) {
int localY = y & 15;
PreObjectMatterCell cell = journalSlice == null
? null
: journalSlice.get(x & 15, localY, z & 15);
HydrologyCaveCell hydrology = cell != null && cell.hydrologyCaptured()
? cell.hydrology()
: hydrologySlice == null
? null
: hydrologySlice.get(x & 15, localY, z & 15);
if (hydrology != null) {
carvedColumn[y] = hydrology.carves() ? (byte) 1 : 0;
continue;
}
MatterCavern cavern = cell != null && cell.cavernCaptured()
? cell.cavern()
: cavernSlice == null ? null : cavernSlice.get(x & 15, localY, z & 15);
if (cavern != null) {
carvedColumn[y] = 1;
}
MatterSlice<PreObjectMatterCell> journalSlice = null;
MatterSlice<MatterCavern> cavernSlice = null;
MatterSlice<HydrologyCaveCell> hydrologySlice = null;
for (int y = 0; y < cappedHeight; y++) {
int localY = y & 15;
if (localY == 0) {
Matter matter = chunk.exists(y >> 4) ? chunk.get(y >> 4) : null;
journalSlice = matter == null ? null : matter.getSlice(PreObjectMatterCell.class);
cavernSlice = matter == null ? null : matter.getSlice(MatterCavern.class);
hydrologySlice = matter == null ? null : matter.getSlice(HydrologyCaveCell.class);
}
PreObjectMatterCell cell = journalSlice == null
? null
: journalSlice.get(x & 15, localY, z & 15);
HydrologyCaveCell hydrology = cell != null && cell.hydrologyCaptured()
? cell.hydrology()
: hydrologySlice == null
? null
: hydrologySlice.get(x & 15, localY, z & 15);
MatterCavern cavern = cell != null && cell.cavernCaptured()
? cell.cavern()
: cavernSlice == null ? null : cavernSlice.get(x & 15, localY, z & 15);
carvedColumn[y] = carvedByte(transformed, y, hydrology, subterrain, carvedColumn[y] != 0, cavern != null);
}
}
return carvedColumn;
@@ -599,8 +585,7 @@ public class MantleWriter implements ObjectPassPlacer, AutoCloseable {
if (slice == null) {
return false;
}
HydrologyCaveCell hydrology = slice.get(x & 15, y & 15, z & 15);
return hydrology != null && hydrology.protectsPlacement();
return slice.get(x & 15, y & 15, z & 15) != null;
}
private static void clearTile(Matter matter, int x, int y, int z) {
@@ -820,35 +805,26 @@ public class MantleWriter implements ObjectPassPlacer, AutoCloseable {
@Override
public boolean isCarved(int x, int y, int z) {
SubterrainCell feature = getEngine().getSubterrainCell(x, y, z);
if (feature != null && feature.owned()) {
return feature.carve();
}
Terrain3DColumn transformed = engineMantle.getComplex().transformedColumn(x, z);
if (transformed != null) {
return y >= 0 && y < transformed.topY() && !transformed.isSolid(y);
}
HydrologyCaveCell hydrology = getDataIfPresent(x, y, z, HydrologyCaveCell.class);
if (hydrology != null) {
return hydrology.carves();
}
return getDataIfPresent(x, y, z, MatterCavern.class) != null
|| engineMantle.getComplex().isTerrain3DOpening(x, y, z);
return CarveOwnership.carved(
engineMantle.getComplex().transformedColumn(x, z),
y,
getDataIfPresent(x, y, z, HydrologyCaveCell.class),
getEngine().getSubterrainCell(x, y, z),
() -> engineMantle.getComplex().isTerrain3DOpening(x, y, z),
() -> getDataIfPresent(x, y, z, MatterCavern.class) != null
);
}
public byte[] getCarvedColumn(int x, int z, int height) {
int cappedHeight = Math.min(Math.max(height, 0), mantle.getWorldHeight());
Terrain3DColumn transformed = engineMantle.getComplex().transformedColumn(x, z);
if (transformed != null) {
return carvedColumn(transformed, cappedHeight);
}
byte[] carvedColumn = new byte[cappedHeight];
if (cappedHeight <= 0) {
return carvedColumn;
}
Terrain3DColumn terrainColumn = engineMantle.getComplex().terrainColumn(x, z);
Terrain3DColumn transformed = engineMantle.getComplex().transformedColumn(x, z);
Terrain3DColumn terrainColumn = transformed == null ? engineMantle.getComplex().terrainColumn(x, z) : null;
if (terrainColumn != null) {
int maximumY = Math.min(cappedHeight, terrainColumn.topY());
for (int y = terrainColumn.minY(); y < maximumY; y++) {
@@ -859,44 +835,24 @@ public class MantleWriter implements ObjectPassPlacer, AutoCloseable {
}
MantleChunk<Matter> chunk = acquireChunk(x >> 4, z >> 4);
if (chunk == null) {
return carvedColumn;
}
SubterrainCell[] subterrain = subterrainColumn(x, z, cappedHeight);
int localX = x & 15;
int localZ = z & 15;
int lastSection = (cappedHeight - 1) >> 4;
for (int section = 0; section <= lastSection; section++) {
if (!chunk.exists(section)) {
continue;
}
Matter matter = chunk.get(section);
if (matter == null) {
continue;
}
MatterSlice<MatterCavern> cavernSlice = matter.getSlice(MatterCavern.class);
MatterSlice<HydrologyCaveCell> hydrologySlice = matter.hasSlice(HydrologyCaveCell.class)
? matter.getSlice(HydrologyCaveCell.class)
: null;
if (cavernSlice == null && hydrologySlice == null) {
continue;
}
int sectionBaseY = section << 4;
int sectionMaxY = Math.min(cappedHeight, sectionBaseY + 16);
for (int y = sectionBaseY; y < sectionMaxY; y++) {
HydrologyCaveCell hydrology = hydrologySlice == null
MatterSlice<MatterCavern> cavernSlice = null;
MatterSlice<HydrologyCaveCell> hydrologySlice = null;
for (int y = 0; y < cappedHeight; y++) {
int localY = y & 15;
if (localY == 0) {
Matter matter = chunk == null || !chunk.exists(y >> 4) ? null : chunk.get(y >> 4);
cavernSlice = matter == null ? null : matter.getSlice(MatterCavern.class);
hydrologySlice = matter == null || !matter.hasSlice(HydrologyCaveCell.class)
? null
: hydrologySlice.get(localX, y & 15, localZ);
if (hydrology != null) {
carvedColumn[y] = hydrology.carves() ? (byte) 1 : 0;
} else if (cavernSlice != null && cavernSlice.get(localX, y & 15, localZ) != null) {
carvedColumn[y] = 1;
}
: matter.getSlice(HydrologyCaveCell.class);
}
HydrologyCaveCell hydrology = hydrologySlice == null ? null : hydrologySlice.get(localX, localY, localZ);
boolean cavern = cavernSlice != null && cavernSlice.get(localX, localY, localZ) != null;
carvedColumn[y] = carvedByte(transformed, y, hydrology, subterrain, carvedColumn[y] != 0, cavern);
}
return carvedColumn;
}
@@ -1033,15 +989,22 @@ public class MantleWriter implements ObjectPassPlacer, AutoCloseable {
return blocks > 0 ? Math.ceilDiv(blocks, 16) : 0;
}
private static byte[] carvedColumn(Terrain3DColumn terrain, int height) {
byte[] result = new byte[height];
int maximumY = Math.min(height, terrain.topY());
for (int y = 0; y < maximumY; y++) {
if (!terrain.isSolid(y)) {
result[y] = 1;
}
private SubterrainCell[] subterrainColumn(int x, int z, int height) {
Engine engine = getEngine();
if (engine.subterrainAbsentInChunk(x >> 4, z >> 4)) {
return null;
}
return result;
SubterrainCell[] cells = new SubterrainCell[height];
for (int y = 0; y < height; y++) {
cells[y] = engine.getSubterrainCell(x, y, z);
}
return cells;
}
private static byte carvedByte(Terrain3DColumn transformed, int y, HydrologyCaveCell hydrology, SubterrainCell[] subterrain,
boolean naturalOpening, boolean cavern) {
return CarveOwnership.carved(transformed, y, hydrology, subterrain == null ? null : subterrain[y],
naturalOpening ? ALWAYS : NEVER, cavern ? ALWAYS : NEVER) ? (byte) 1 : 0;
}
public final class ObjectPlacementCapture implements AutoCloseable {
@@ -491,8 +491,7 @@ final class ObjectDestinationTransaction implements ObjectPassPlacer {
}
private boolean hasProtectedHydrology(int x, int y, int z) {
HydrologyCaveCell hydrology = getDataIfPresent(x, y, z, HydrologyCaveCell.class);
return hydrology != null && hydrology.protectsPlacement();
return getDataIfPresent(x, y, z, HydrologyCaveCell.class) != null;
}
private final class CommitJournal {
@@ -364,7 +364,7 @@ final class ObjectSourcePlan {
case Identifier identifier -> 24L + stringBytes(identifier.namespace()) + stringBytes(identifier.key());
case NativeBlockState ignored -> 0L;
case MatterCavern cavern -> 24L + stringBytes(cavern.getCustomBiome());
case HydrologyCaveCell cell -> 48L + stringBytes(cell.fluidProfileKey()) + stringBytes(cell.floodedBiomeKey());
case HydrologyCaveCell cell -> 48L + stringBytes(cell.fluidProfileKey());
case MatterMarker marker -> 16L + stringBytes(marker.getTag());
case TileWrapper ignored -> 4L * UNKNOWN_PAYLOAD_BYTES;
case Enum<?> ignored -> 0L;
@@ -73,6 +73,17 @@ final class SurfaceFluidBoundaryPlan {
}
}
static void join(long[] boundaries, long[] bands) {
for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) {
long band = bands[columnIndex];
if (startY(band) > endY(band)) {
continue;
}
long boundary = boundaries[columnIndex];
boundaries[columnIndex] = boundary(Math.min(startY(boundary), startY(band)), Math.max(endY(boundary), endY(band)));
}
}
static boolean protects(long[] boundaries, int columnIndex, int y) {
if (boundaries == null || columnIndex < 0 || columnIndex >= boundaries.length) {
return false;
@@ -0,0 +1,124 @@
package art.arcane.iris.generation.runtime;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.block.DataProvider;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
final class BiomeLineages {
private final Set<String> heirs;
private final Object lock = new Object();
private volatile IdentityHashMap<IrisBiome, List<IrisBiome>> roots = new IdentityHashMap<>();
private volatile Map<Chain, List<IrisBiome>> chains = new HashMap<>();
private BiomeLineages(Set<String> heirs) {
this.heirs = heirs;
}
static BiomeLineages compile(Collection<IrisBiome> biomes, DataProvider provider) {
Set<String> heirs = new HashSet<>();
for (IrisBiome biome : biomes) {
if (biome.getHydrologyPolicy() != null) {
addDescendants(biome, provider, heirs);
}
}
return new BiomeLineages(heirs);
}
boolean inherits(IrisBiome biome) {
return heirs.contains(biome.getLoadKey());
}
List<IrisBiome> root(IrisBiome biome) {
List<IrisBiome> known = roots.get(biome);
if (known != null) {
return known;
}
synchronized (lock) {
List<IrisBiome> raced = roots.get(biome);
if (raced != null) {
return raced;
}
List<IrisBiome> created = List.of(biome);
IdentityHashMap<IrisBiome, List<IrisBiome>> next = new IdentityHashMap<>(roots);
next.put(biome, created);
roots = next;
return created;
}
}
List<IrisBiome> chain(IrisBiome[] leafFirst) {
if (leafFirst.length == 1) {
return root(leafFirst[0]);
}
Chain key = new Chain(leafFirst);
List<IrisBiome> known = chains.get(key);
if (known != null) {
return known;
}
synchronized (lock) {
List<IrisBiome> raced = chains.get(key);
if (raced != null) {
return raced;
}
List<IrisBiome> created = List.of(leafFirst);
Map<Chain, List<IrisBiome>> next = new HashMap<>(chains);
next.put(key, created);
chains = next;
return created;
}
}
private static void addDescendants(IrisBiome parent, DataProvider provider, Set<String> heirs) {
Set<IrisBiome> visited = Collections.newSetFromMap(new IdentityHashMap<>());
ArrayDeque<IrisBiome> pending = new ArrayDeque<>();
addChildren(parent, provider, pending);
while (!pending.isEmpty()) {
IrisBiome child = pending.poll();
if (visited.add(child)) {
heirs.add(child.getLoadKey());
addChildren(child, provider, pending);
}
}
}
private static void addChildren(IrisBiome parent, DataProvider provider, ArrayDeque<IrisBiome> pending) {
for (IrisBiome child : parent.getRealChildren(provider)) {
if (child != null) {
pending.add(child);
}
}
}
private record Chain(IrisBiome[] biomes) {
@Override
public boolean equals(Object other) {
if (!(other instanceof Chain chain) || chain.biomes.length != biomes.length) {
return false;
}
for (int index = 0; index < biomes.length; index++) {
if (chain.biomes[index] != biomes[index]) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
int hash = 1;
for (IrisBiome biome : biomes) {
hash = 31 * hash + System.identityHashCode(biome);
}
return hash;
}
}
}
@@ -47,8 +47,6 @@ import art.arcane.iris.pack.value.IrisPosition;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.structure.placement.IrisStructure;
import art.arcane.iris.world.IrisWorld;
import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell;
import art.arcane.iris.generation.hydrology.cave.HydrologyCaveStorage;
import art.arcane.volmlib.nativelib.terrain.NativeBiome;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.volmlib.util.collection.KList;
@@ -367,24 +365,10 @@ public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer,
if (featureBiome != null) {
return featureBiome;
}
IrisBiome mantleBiome = mantleCaveBiome(x, y, z);
IrisBiome mantleBiome = customCaveBiome(getMantle().getMantle().get(x, y, z, MatterCavern.class));
return mantleBiome != null ? mantleBiome : getCaveBiome(x, y, z);
}
private IrisBiome mantleCaveBiome(int x, int y, int z) {
IrisBiome flooded = floodedCaveBiome(x, y, z);
return flooded != null ? flooded : customCaveBiome(getMantle().getMantle().get(x, y, z, MatterCavern.class));
}
private IrisBiome floodedCaveBiome(int x, int y, int z) {
HydrologyCaveCell hydrology = HydrologyCaveStorage.getIfPresent(
getMantle().getMantle(), x, y, z);
if (hydrology != null && !hydrology.floodedBiomeKey().isEmpty()) {
return getData().getBiomeLoader().load(hydrology.floodedBiomeKey());
}
return null;
}
private IrisBiome customCaveBiome(MatterCavern cavern) {
if (cavern != null && cavern.getCustomBiome() != null && !cavern.getCustomBiome().isEmpty()) {
return getData().getBiomeLoader().load(cavern.getCustomBiome());
@@ -439,15 +423,12 @@ public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer,
biomes[index] = surface;
continue;
}
IrisBiome biome = floodedCaveBiome(x, y, z);
if (biome == null) {
if (!cavernChunkResolved) {
cavernChunk = useCavernChunk(x, z);
cavernChunkResolved = true;
}
biome = cavernChunk == null || y < 0 || y >= getMantle().getMantle().getWorldHeight()
? null : customCaveBiome(cavernChunk.get(x & 15, y, z & 15, MatterCavern.class));
if (!cavernChunkResolved) {
cavernChunk = useCavernChunk(x, z);
cavernChunkResolved = true;
}
IrisBiome biome = cavernChunk == null || y < 0 || y >= getMantle().getMantle().getWorldHeight()
? null : customCaveBiome(cavernChunk.get(x & 15, y, z & 15, MatterCavern.class));
if (biome == null) {
biome = resolveConfiguredCaveBiome(x, y, z, null);
}
@@ -478,8 +459,8 @@ public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer,
@BlockCoordinates
default IrisBiome getCaveBiome(int x, int z) {
IrisBiome biome = getComplex().getCaveBiomeStream().get(x, z);
return biome == null || biome.getLoadKey() == null ? getSurfaceBiome(x, z) : biome;
IrisBiome biome = regionCaveBiome(x, z);
return biome == null ? getSurfaceBiome(x, z) : biome;
}
@BlockCoordinates
@@ -489,13 +470,9 @@ public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer,
@BlockCoordinates
default IrisBiome getCaveBiome(int x, int y, int z, IrisDimensionCarvingResolver.State state) {
IrisBiome featureBiome = getSubterrainBiome(x, y, z);
if (featureBiome != null) {
return featureBiome;
}
IrisBiome configuredBiome = resolveConfiguredCaveBiome(x, y, z, state);
if (configuredBiome != null) {
return configuredBiome;
IrisBiome placedBiome = placedCaveBiome(x, y, z, state);
if (placedBiome != null) {
return placedBiome;
}
boolean naturalFallback = answersFromNaturalTerrain(x, z);
IrisBiome surfaceBiome = caveDepthSurfaceBiome(x, z, naturalFallback);
@@ -503,6 +480,26 @@ public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer,
return resolveDepthCaveBiome(x, y, z, surfaceBiome, surfaceY);
}
@BlockCoordinates
default IrisBiome getCaveBiomeBelowSurface(int x, int y, int z) {
IrisBiome placedBiome = placedCaveBiome(x, y, z, null);
if (placedBiome != null) {
return placedBiome;
}
IrisBiome caveBiome = regionCaveBiome(x, z);
return caveBiome == null ? null : depthCaveBiome(caveBiome, y, null, caveDepthSurfaceY(x, z, answersFromNaturalTerrain(x, z)));
}
private IrisBiome regionCaveBiome(int x, int z) {
IrisBiome biome = getComplex().getCaveBiomeStream().get(x, z);
return biome == null || biome.getLoadKey() == null ? null : biome;
}
private IrisBiome placedCaveBiome(int x, int y, int z, IrisDimensionCarvingResolver.State state) {
IrisBiome featureBiome = getSubterrainBiome(x, y, z);
return featureBiome != null ? featureBiome : resolveConfiguredCaveBiome(x, y, z, state);
}
private IrisBiome caveDepthSurfaceBiome(int x, int z, boolean naturalFallback) {
if (naturalFallback) {
return getComplex().naturalSurfaceBiome(x, z);
@@ -525,15 +522,8 @@ public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer,
IrisBiome surfaceBiome,
int surfaceY
) {
IrisBiome featureBiome = getSubterrainBiome(x, y, z);
if (featureBiome != null) {
return featureBiome;
}
IrisBiome configuredBiome = resolveConfiguredCaveBiome(x, y, z, state);
if (configuredBiome != null) {
return configuredBiome;
}
return resolveDepthCaveBiome(x, y, z, surfaceBiome, surfaceY);
IrisBiome placedBiome = placedCaveBiome(x, y, z, state);
return placedBiome != null ? placedBiome : resolveDepthCaveBiome(x, y, z, surfaceBiome, surfaceY);
}
private IrisBiome resolveConfiguredCaveBiome(
@@ -907,7 +897,7 @@ public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer,
.map(IrisRegistrant::getLoadKey)
.collect(Collectors.toSet());
Set<String> regionKeys = getDimension().getAllRegions(this).stream()
.filter((i) -> i.getAllBiomeIds().stream().anyMatch(biomeKeys::contains)
.filter((i) -> i.getAllBiomeIds(getDimension(), this).stream().anyMatch(biomeKeys::contains)
|| containsObjectPlacement(i.getObjects(), normalizedObjectKey, data))
.map(IrisRegistrant::getLoadKey)
.collect(Collectors.toSet());
@@ -8,6 +8,7 @@ import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.pack.loading.IrisData;
import java.util.Collection;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Objects;
@@ -22,7 +23,7 @@ final class HydrologyShoreBiomes {
private final IrisData data;
private final long seed;
private final Object policyLock = new Object();
private volatile IdentityHashMap<IrisBiome, IdentityHashMap<IrisRegion, Policy>> policies = new IdentityHashMap<>();
private volatile IdentityHashMap<List<IrisBiome>, IdentityHashMap<IrisRegion, Policy>> policies = new IdentityHashMap<>();
private int policyCount;
HydrologyShoreBiomes(IrisDimension dimension, IrisData data, long seed) {
@@ -31,8 +32,25 @@ final class HydrologyShoreBiomes {
this.seed = seed;
}
IrisBiome select(IrisBiome biome, IrisRegion region, int x, int z, int shoreDistance) {
Policy policy = policy(biome, region);
static boolean banded(IrisDimension dimension, Collection<IrisRegion> regions, Collection<IrisBiome> biomes) {
if (banded(dimension.getHydrologyPolicy())) {
return true;
}
for (IrisRegion region : regions) {
if (region != null && banded(region.getHydrologyPolicy())) {
return true;
}
}
for (IrisBiome biome : biomes) {
if (biome != null && banded(biome.getHydrologyPolicy())) {
return true;
}
}
return false;
}
IrisBiome select(List<IrisBiome> lineage, IrisRegion region, int x, int z, int shoreDistance) {
Policy policy = policy(lineage, region);
IrisBiome[] biomes = policy.biomes();
if (shoreDistance > policy.width() || biomes.length == 0) {
return null;
@@ -44,52 +62,70 @@ final class HydrologyShoreBiomes {
return biomes[(int) Long.remainderUnsigned(patch, biomes.length)];
}
private Policy policy(IrisBiome biome, IrisRegion region) {
IdentityHashMap<IrisRegion, Policy> regions = policies.get(biome);
private Policy policy(List<IrisBiome> lineage, IrisRegion region) {
IdentityHashMap<IrisRegion, Policy> regions = policies.get(lineage);
Policy known = regions == null ? null : regions.get(region);
return known != null ? known : remember(biome, region, resolve(biome, region));
return known != null ? known : remember(lineage, region, resolve(lineage, region));
}
private Policy remember(IrisBiome biome, IrisRegion region, Policy resolved) {
private Policy remember(List<IrisBiome> lineage, IrisRegion region, Policy resolved) {
synchronized (policyLock) {
IdentityHashMap<IrisRegion, Policy> current = policies.get(biome);
IdentityHashMap<IrisRegion, Policy> current = policies.get(lineage);
Policy raced = current == null ? null : current.get(region);
if (raced != null) {
return raced;
}
boolean full = policyCount >= CAPACITY;
IdentityHashMap<IrisBiome, IdentityHashMap<IrisRegion, Policy>> next = full ? new IdentityHashMap<>() : new IdentityHashMap<>(policies);
IdentityHashMap<List<IrisBiome>, IdentityHashMap<IrisRegion, Policy>> next = full ? new IdentityHashMap<>() : new IdentityHashMap<>(policies);
IdentityHashMap<IrisRegion, Policy> regions = full || current == null ? new IdentityHashMap<>() : new IdentityHashMap<>(current);
regions.put(region, resolved);
next.put(biome, regions);
next.put(lineage, regions);
policyCount = full ? 1 : policyCount + 1;
policies = next;
return resolved;
}
}
private Policy resolve(IrisBiome biome, IrisRegion region) {
Integer width = IrisHydrologyPolicy.inherited(biome, region, dimension, IrisHydrologyPolicy::getShoreBiomeWidth);
List<String> keys = IrisHydrologyPolicy.inherited(biome, region, dimension, IrisHydrologyPolicy::getShoreBiomes);
if (width == null || width <= 0 || keys == null || keys.isEmpty()) {
private Policy resolve(List<IrisBiome> lineage, IrisRegion region) {
IrisHydrologyPolicy.ShoreBand band = IrisHydrologyPolicy.shoreBand(lineage, region, dimension);
if (band == null) {
return NONE;
}
List<String> keys = band.biomes();
IrisBiome[] biomes = new IrisBiome[keys.size()];
for (int index = 0; index < biomes.length; index++) {
biomes[index] = load(keys.get(index), biome, region).withInferredType(InferredType.SHORE);
biomes[index] = load(keys.get(index), lineage, region).withInferredType(InferredType.SHORE);
}
return new Policy(biomes, width);
return new Policy(biomes, band.width());
}
private IrisBiome load(String key, IrisBiome biome, IrisRegion region) {
private IrisBiome load(String key, List<IrisBiome> lineage, IrisRegion region) {
IrisBiome loaded = key == null || key.isBlank() || data == null ? null : data.getBiomeLoader().load(key);
if (loaded == null) {
throw new IllegalStateException("Hydrology shore biome '" + key + "' for biome " + (biome == null ? "none" : biome.getLoadKey())
+ " in region " + (region == null ? "none" : region.getLoadKey()) + " does not exist");
throw new IllegalStateException("Hydrology shore biome '" + key + "' listed by " + listedBy(lineage, region) + " for biome "
+ (lineage.isEmpty() ? "none" : lineage.getFirst().getLoadKey()) + " in region " + (region == null ? "none" : region.getLoadKey())
+ " does not exist");
}
return loaded;
}
private String listedBy(List<IrisBiome> lineage, IrisRegion region) {
for (IrisBiome biome : lineage) {
if (lists(biome.getHydrologyPolicy())) {
return "biome " + biome.getLoadKey();
}
}
return region != null && lists(region.getHydrologyPolicy()) ? "region " + region.getLoadKey() : "dimension " + dimension.getLoadKey();
}
private static boolean lists(IrisHydrologyPolicy policy) {
return policy != null && policy.getShoreBiomes() != null;
}
private static boolean banded(IrisHydrologyPolicy policy) {
return policy != null && policy.getShoreBiomeWidth() != null && policy.getShoreBiomeWidth() > 0;
}
private record Policy(IrisBiome[] biomes, int width) {
}
}
@@ -26,7 +26,7 @@ final class HydrologyVegetationSource {
private final Object lock = new Object();
private boolean planted;
private volatile IdentityHashMap<List<IrisDecorator>, HydrologyVegetation.Decorators> compiled = new IdentityHashMap<>();
private volatile IdentityHashMap<IrisBiome, IdentityHashMap<IrisRegion, Resolved>> overrides = new IdentityHashMap<>();
private volatile IdentityHashMap<List<IrisBiome>, IdentityHashMap<IrisRegion, Resolved>> overrides = new IdentityHashMap<>();
private HydrologyVegetationSource(IrisData data, IrisDimension dimension, Map<HydrologyTier, HydrologyVegetation.Decorators> tiers,
HydrologyVegetation.Decorators ponds) {
@@ -62,11 +62,11 @@ final class HydrologyVegetationSource {
return planted;
}
HydrologyVegetation.Decorators decorators(HydrologyTier tier, IrisBiome biome, IrisRegion region) {
HydrologyVegetation.Decorators decorators(HydrologyTier tier, List<IrisBiome> lineage, IrisRegion region) {
if (data == null) {
return HydrologyVegetation.Decorators.EMPTY;
}
Resolved override = override(biome, region);
Resolved override = override(lineage, region);
if (override.decorators() != null) {
return override.decorators();
}
@@ -80,28 +80,28 @@ final class HydrologyVegetationSource {
return known;
}
private Resolved override(IrisBiome biome, IrisRegion region) {
IdentityHashMap<IrisRegion, Resolved> regions = overrides.get(biome);
private Resolved override(List<IrisBiome> lineage, IrisRegion region) {
IdentityHashMap<IrisRegion, Resolved> regions = overrides.get(lineage);
Resolved known = regions == null ? null : regions.get(region);
return known != null ? known : remember(biome, region, resolve(biome, region));
return known != null ? known : remember(lineage, region, resolve(lineage, region));
}
private Resolved resolve(IrisBiome biome, IrisRegion region) {
List<IrisDecorator> decorators = IrisHydrologyPolicy.inherited(biome, region, dimension, IrisHydrologyPolicy::getDecorators);
private Resolved resolve(List<IrisBiome> lineage, IrisRegion region) {
List<IrisDecorator> decorators = IrisHydrologyPolicy.inherited(lineage, region, dimension, IrisHydrologyPolicy::getDecorators);
return decorators == null ? Resolved.INHERIT : new Resolved(compiled(decorators, LAZY_POLICY));
}
private Resolved remember(IrisBiome biome, IrisRegion region, Resolved resolved) {
private Resolved remember(List<IrisBiome> lineage, IrisRegion region, Resolved resolved) {
synchronized (lock) {
IdentityHashMap<IrisRegion, Resolved> current = overrides.get(biome);
IdentityHashMap<IrisRegion, Resolved> current = overrides.get(lineage);
Resolved raced = current == null ? null : current.get(region);
if (raced != null) {
return raced;
}
IdentityHashMap<IrisBiome, IdentityHashMap<IrisRegion, Resolved>> next = new IdentityHashMap<>(overrides);
IdentityHashMap<List<IrisBiome>, IdentityHashMap<IrisRegion, Resolved>> next = new IdentityHashMap<>(overrides);
IdentityHashMap<IrisRegion, Resolved> regions = current == null ? new IdentityHashMap<>() : new IdentityHashMap<>(current);
regions.put(region, resolved);
next.put(biome, regions);
next.put(lineage, regions);
overrides = next;
return resolved;
}
@@ -121,8 +121,8 @@ import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiFunction;
@Data
@EqualsAndHashCode(exclude = {"data", "gridBoundsCache", "sharedCornerBounds", "sharedBaseHeights", "sharedBoundsBiomes", "regionBounds", "contextRegionStream", "terrainProgram", "bakeCache", "regionSource", "baseBiomeSource", "caveSource", "rockSource", "fluidSource", "childStyleSeed", "inferredByType", "naturalHeightSource", "naturalTrueBiomeSource", "trueBiomeSource", "frozenInterpolators", "frozenGenerators", "inferredBiomeStreams", "imageMapRuntime", "terrainEngine", "terrain3D", "hydrologyRuntime", "shoreBiomes", "waterVegetation", "effectiveChunks"})
@ToString(exclude = {"data", "gridBoundsCache", "sharedCornerBounds", "sharedBaseHeights", "sharedBoundsBiomes", "regionBounds", "contextRegionStream", "terrainProgram", "bakeCache", "regionSource", "baseBiomeSource", "caveSource", "rockSource", "fluidSource", "childStyleSeed", "inferredByType", "naturalHeightSource", "naturalTrueBiomeSource", "trueBiomeSource", "frozenInterpolators", "frozenGenerators", "inferredBiomeStreams", "imageMapRuntime", "terrainEngine", "terrain3D", "hydrologyRuntime", "shoreBiomes", "waterVegetation", "effectiveChunks"})
@EqualsAndHashCode(exclude = {"data", "gridBoundsCache", "sharedCornerBounds", "sharedBaseHeights", "sharedBoundsBiomes", "regionBounds", "contextRegionStream", "terrainProgram", "bakeCache", "regionSource", "baseBiomeSource", "caveSource", "rockSource", "fluidSource", "childStyleSeed", "inferredByType", "naturalHeightSource", "naturalTrueBiomeSource", "trueBiomeSource", "frozenInterpolators", "frozenGenerators", "inferredBiomeStreams", "imageMapRuntime", "terrainEngine", "terrain3D", "hydrologyRuntime", "shoreBiomes", "waterVegetation", "effectiveChunks", "biomeLineages"})
@ToString(exclude = {"data", "gridBoundsCache", "sharedCornerBounds", "sharedBaseHeights", "sharedBoundsBiomes", "regionBounds", "contextRegionStream", "terrainProgram", "bakeCache", "regionSource", "baseBiomeSource", "caveSource", "rockSource", "fluidSource", "childStyleSeed", "inferredByType", "naturalHeightSource", "naturalTrueBiomeSource", "trueBiomeSource", "frozenInterpolators", "frozenGenerators", "inferredBiomeStreams", "imageMapRuntime", "terrainEngine", "terrain3D", "hydrologyRuntime", "shoreBiomes", "waterVegetation", "effectiveChunks", "biomeLineages"})
public class IrisComplex implements DataProvider {
private static final NoiseBounds ZERO_NOISE_BOUNDS = new NoiseBounds(0D, 0D);
private static final long NEGATIVE_ZERO_BITS = Double.doubleToRawLongBits(-0D);
@@ -277,6 +277,12 @@ public class IrisComplex implements DataProvider {
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient HydrologyShoreBiomes shoreBiomes;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient BiomeLineages biomeLineages;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient boolean shoreBands;
@Setter(AccessLevel.NONE)
private final transient SubterrainPlanner subterrainPlanner;
private transient IrisImageMapRuntime imageMapRuntime;
@@ -494,11 +500,15 @@ public class IrisComplex implements DataProvider {
Interpolated.of(value -> 0D, value -> null));
naturalTrueBiomeStream = new BakedStream<>(bakeCache, BakePlane.NATURAL_TRUE_BIOME, naturalTrueBiomeSource);
shoreBiomes = new HydrologyShoreBiomes(engine.getDimension(), data, engine.getSeedManager().getBodies());
biomeLineages = BiomeLineages.compile(focusedBiomes == null ? baseCapableBiomes(preparedRegions) : List.of(), this);
hydrologyRuntime = HydrologyRuntime.create(engine, this);
waterFluidStreams = hydrologyRuntime.enabled() ? createWaterFluidStreams(hydrologyRuntime.settings().fluids(), hydrologyRuntime.settings().seams().values()) : Map.of();
pondMaterials = hydrologyRuntime.enabled() ? hydrologyRuntime.settings().ponds().materials() : null;
KList<IrisRegion> policyRegions = hydrologyRuntime.enabled() ? engine.getDimension().getAllRegions(engine) : new KList<>();
KList<IrisBiome> policyBiomes = hydrologyRuntime.enabled() ? engine.getDimension().getReachableBiomes(engine) : new KList<>();
waterVegetation = hydrologyRuntime.enabled() ? HydrologyVegetationSource.create(engine.getDimension(), hydrologyRuntime.settings(), data,
engine.getDimension().getAllRegions(engine), engine.getDimension().getReachableBiomes(engine)) : HydrologyVegetationSource.NONE;
policyRegions, policyBiomes) : HydrologyVegetationSource.NONE;
shoreBands = hydrologyRuntime.enabled() && HydrologyShoreBiomes.banded(engine.getDimension(), policyRegions, policyBiomes);
heightStream = new BakedHeightStream(bakeCache, () -> terrainEngine.getPlatformHooks().isMainThread(),
this::resolveHydrologyTerrainHeight, this::resolveHydrologyTerrainHeight);
roundedHeighteightStream = GenerationStreams.contextInjecting(heightStream, engine, (c, x, z) -> c.getHeight().getDouble(x, z))
@@ -1400,7 +1410,16 @@ public class IrisComplex implements DataProvider {
return HydrologyVegetation.Decorators.EMPTY;
}
HydrologyTier tier = chunkRasterAt(x, z).tier(x & 15, z & 15);
return waterVegetation.decorators(tier, baseBiomeStream.get(x, z), regionStream.get(x, z));
return waterVegetation.decorators(tier, baseBiomeLineage(x, z), regionStream.get(x, z));
}
public List<IrisBiome> baseBiomeLineage(int x, int z) {
IrisBiome biome = baseBiomeStream.get(x, z);
if (!biomeLineages.inherits(biome)
|| imageMapRuntime.has(IrisImageMapApplication.BIOME) && imageMapRuntime.sampleBiome(x, z) != null) {
return biomeLineages.root(biome);
}
return childLineage(biome, x, z);
}
private ChunkWaterRaster chunkRasterAt(int blockX, int blockZ) {
@@ -1809,7 +1828,10 @@ public class IrisComplex implements DataProvider {
|| seamWeight(blockX, blockZ) == 0D) {
return null;
}
IrisBiome shore = shoreBiomes.select(baseBiomeStream.get(x, z), regionStream.get(x, z), blockX, blockZ, distance);
if (!shoreBands) {
return null;
}
IrisBiome shore = shoreBiomes.select(baseBiomeLineage(blockX, blockZ), regionStream.get(x, z), blockX, blockZ, distance);
return shore == null ? null : implode(shore, x, z);
}
@@ -2485,7 +2507,7 @@ public class IrisComplex implements DataProvider {
return b;
}
return implode(b, x, z, 3);
return implode(b, x, z, IrisBiome.CHILD_HOPS - 1);
}
private IrisBiome implode(IrisBiome b, double x, double z, int max) {
@@ -2497,15 +2519,42 @@ public class IrisComplex implements DataProvider {
return b;
}
CNG childCell = b.getChildrenGenerator(childStyleSeed, b.getChildShrinkFactor());
ChildSelectionPlan childSelectionPlan = resolveChildSelectionPlan(b);
IrisBiome biome = childSelectionPlan.select(childCell, x, z).withInferredType(b.getInferredType());
IrisBiome biome = pickChild(b, x, z);
if (biome == b && hasFixedNoise(b.getChildStyle())) {
return biome;
}
return implode(biome, x, z, max - 1);
}
private IrisBiome pickChild(IrisBiome parent, double x, double z) {
CNG childCell = parent.getChildrenGenerator(childStyleSeed, parent.getChildShrinkFactor());
return resolveChildSelectionPlan(parent).select(childCell, x, z).withInferredType(parent.getInferredType());
}
private List<IrisBiome> childLineage(IrisBiome biome, int x, int z) {
IrisBiome[] rootFirst = new IrisBiome[IrisBiome.CHILD_HOPS + 1];
IrisBiome current = inferredByType.get(bridgeStream.get(x, z)).get(x, z);
rootFirst[0] = current;
int size = 1;
for (int hop = 0; hop < IrisBiome.CHILD_HOPS && !current.getChildren().isEmpty(); hop++) {
IrisBiome picked = pickChild(current, x, z);
if (picked == current) {
break;
}
rootFirst[size++] = picked;
current = picked;
}
if (current != biome) {
throw new IllegalStateException("The child chain at " + x + "," + z + " ends at biome " + current.getLoadKey()
+ ", but the base biome there is " + biome.getLoadKey());
}
IrisBiome[] leafFirst = new IrisBiome[size];
for (int index = 0; index < size; index++) {
leafFirst[index] = rootFirst[size - 1 - index];
}
return biomeLineages.chain(leafFirst);
}
static boolean hasFixedNaturalBiomeNoise(IrisDimension dimension, Iterable<IrisBiome> biomes) {
if (!hasFixedNoise(dimension.getRegionStyle()) || !hasFixedNoise(dimension.getContinentalStyle())
|| !hasFixedNoise(dimension.getLandBiomeStyle()) || !hasFixedNoise(dimension.getSeaBiomeStyle())) {
@@ -34,6 +34,7 @@ import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.volmlib.util.stream.ProceduralStream;
import art.arcane.iris.generation.runtime.EngineAssignedModifier;
import art.arcane.iris.generation.mantle.CarveOwnership;
import art.arcane.iris.generation.mantle.CaveCeilingMask;
import art.arcane.iris.generation.mantle.CaveTerrainSnapshot;
import art.arcane.iris.generation.mantle.TerrainMatterView;
@@ -163,7 +164,8 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
getEngine().getWorld().minHeight(),
resolverState.complex,
subterrainPlanner == null ? null : subterrainPlanner.chunkSampler(x, z),
subterrain ? caveCeilings(resolverState.complex, x, z) : null
subterrain ? caveCeilings(resolverState.complex, x, z) : null,
subterrain ? inletHeadroom(resolverState.complex, x, z) : null
);
CarveResolver carveResolver = new CarveResolver(resolutionContext);
terrain.forEachCell(carveResolver::apply);
@@ -261,17 +263,18 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
int minimumY = getEngine().getWorld().minHeight();
SubterrainSurfaceMaterials materials = subterrainMaterials(planner, blockX >> 4, blockZ >> 4);
int[] caveCeilings = caveCeilings(getComplex(), blockX >> 4, blockZ >> 4);
long[] inletHeadroom = inletHeadroom(getComplex(), blockX >> 4, blockZ >> 4);
MantleChunk<Matter> chunk = getEngine().getMantle().getMantle().useChunk(blockX >> 4, blockZ >> 4);
try {
preserveSubterrain(planner, materials, caveCeilings, minimumY, blockX, blockZ, output,
preserveSubterrain(planner, materials, caveCeilings, inletHeadroom, minimumY, blockX, blockZ, output,
(worldX, y, worldZ) -> HydrologyCaveStorage.getIfPresent(chunk, worldX, y, worldZ));
} finally {
chunk.release();
}
}
private void preserveSubterrain(SubterrainPlanner planner, SubterrainSurfaceMaterials materials, int[] caveCeilings, int minimumY,
int blockX, int blockZ, Hunk<NativeBlockState> output, HydrologyCells hydrology) {
private void preserveSubterrain(SubterrainPlanner planner, SubterrainSurfaceMaterials materials, int[] caveCeilings, long[] inletHeadroom,
int minimumY, int blockX, int blockZ, Hunk<NativeBlockState> output, HydrologyCells hydrology) {
SubterrainRasterizer.rasterize(planner, blockX >> 4, blockZ >> 4, (worldX, worldY, worldZ, cell) -> {
int y = worldY - minimumY;
if (y <= 0 || y >= output.getHeight()) {
@@ -279,7 +282,7 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
}
int x = worldX & 15;
int z = worldZ & 15;
if (!cell.solid() && caveCeilings != null && y > caveCeilings[PowerOfTwoCoordinates.packLocal16(x, z)]) {
if (!cell.solid() && CaveCeilingMask.masked(caveCeilings, inletHeadroom, PowerOfTwoCoordinates.packLocal16(x, z), y)) {
return;
}
if (hydrology.at(worldX, y, worldZ) != null) {
@@ -307,6 +310,10 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
new int[CaveCeilingMask.FIELD * CaveCeilingMask.FIELD], ceilings) ? ceilings : null;
}
private static long[] inletHeadroom(IrisComplex complex, int chunkX, int chunkZ) {
return CaveCeilingMask.headroom(chunkX, chunkZ, complex.getHydrologyRuntime(), new long[256]);
}
private void restoreSubterrainSolids(Hunk<NativeBlockState> output, int chunkX, int chunkZ, boolean preserveFloorSupports,
HydrologyCells hydrology) {
SubterrainPlanner planner = getComplex().getSubterrainPlanner();
@@ -379,8 +386,12 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
return cavern.getLiquid() == 3 ? air : null;
}
static boolean subterrainOwns(SubterrainCell feature, HydrologyCaveCell hydrology) {
return hydrology == null && feature.owned() && (!feature.solid() || feature.room().reservedSolid());
static CarveOwnership.Owner carveOwner(HydrologyCaveCell hydrology, SubterrainCell feature, Terrain3DColumn naturalTerrain, int y) {
return CarveOwnership.resolve(
hydrology != null,
CarveOwnership.subterrainClaims(feature),
naturalTerrain != null && y >= naturalTerrain.minY() && y < naturalTerrain.topY() && !naturalTerrain.isSolid(y)
);
}
static NativeBlockState sealGuardState(NativeBlockState current, NativeBlockState rock) {
@@ -408,7 +419,6 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
}
return switch (hydrology.action()) {
case WET_SOURCE, POOL_SOURCE -> fluid;
case FALLING_FLUID -> fallingFluidState(fluid);
case DRY_AIR -> air;
case SEAL_GUARD -> normalizeWaterlogging(current, null);
};
@@ -439,16 +449,6 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
return normalizeWaterlogging(state, resultingFluid);
}
private static NativeBlockState fallingFluidState(NativeBlockState fluid) {
if (fluid == null || !IrisProceduralBlocks.hasProperty(fluid, "level")) {
return fluid;
}
if ("8".equals(IrisProceduralBlocks.propertyValue(fluid, "level"))) {
return fluid;
}
return fluid.withProperty("level", "8");
}
private final class CarveResolver {
private final CarveResolutionContext context;
@@ -473,8 +473,10 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
SubterrainCell feature = context.subterrainSampler() == null ? SubterrainCell.OUTSIDE
: context.subterrainSampler().sampleCandidates(context.chunkBlockX() + localX, y + context.minimumY(),
context.chunkBlockZ() + localZ);
if (subterrainOwns(feature, hydrology)) {
if (!feature.solid() && context.caveCeilings() != null && y > context.caveCeilings()[columnIndex]) {
CarveOwnership.Owner owner = carveOwner(hydrology, feature,
context.terrainColumns() == null ? null : context.terrainColumns()[columnIndex], y);
if (owner == CarveOwnership.Owner.SUBTERRAIN) {
if (!feature.solid() && CaveCeilingMask.masked(context.caveCeilings(), context.inletHeadroom(), columnIndex, y)) {
return;
}
context.output().setRaw(localX, y, localZ, SubterrainRasterizer.state(feature));
@@ -487,6 +489,14 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
return;
}
if (hydrology != null && hydrology.action() == HydrologyCaveAction.SEAL_GUARD) {
NativeBlockState unsealed = context.output().getRaw(localX, y, localZ);
NativeBlockState sealed = sealGuardState(unsealed, context.chunkContext().getRock().get(localX, localZ));
if (sealed != unsealed) {
context.output().setRaw(localX, y, localZ, sealed);
}
return;
}
if (context.upperSurfaceHeights() != null && y >= context.upperSurfaceHeights()[columnIndex]) {
return;
}
@@ -495,20 +505,10 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
return;
}
NativeBlockState current = context.output().getRaw(localX, y, localZ);
if (hydrology == null && context.terrainColumns() != null) {
Terrain3DColumn column = context.terrainColumns()[columnIndex];
if (column != null && y >= column.minY() && y < column.topY() && !column.isSolid(y)) {
return;
}
}
if (hydrology != null && hydrology.action() == HydrologyCaveAction.SEAL_GUARD) {
NativeBlockState sealed = sealGuardState(current, context.chunkContext().getRock().get(localX, localZ));
if (sealed != current) {
context.output().setRaw(localX, y, localZ, sealed);
}
if (owner == CarveOwnership.Owner.NATURAL_OPENING) {
return;
}
NativeBlockState current = context.output().getRaw(localX, y, localZ);
MatterCavern cavern = composeCavern(baseline, hydrology);
if (cavern == null || shouldPreserveExistingFluid(cavern, current)) {
@@ -566,7 +566,8 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
int minimumY,
IrisComplex complex,
SubterrainPlanner.ChunkSampler subterrainSampler,
int[] caveCeilings
int[] caveCeilings,
long[] inletHeadroom
) {
}
@@ -631,7 +632,7 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
HydrologyCaveCell hydrology = terrain.hydrology(rx, yy, rz);
int worldX = rx + chunkBlockX;
int worldZ = rz + chunkBlockZ;
if (hydrology != null && hydrology.protectsPlacement() || inputs.cells.cell(worldX, yy, worldZ).owned()
if (hydrology != null || inputs.cells.cell(worldX, yy, worldZ).owned()
|| yy >= surfaceHeights[PowerOfTwoCoordinates.packLocal16(rx, rz)] || !B.isSolid(output.getRaw(rx, yy, rz))) {
return;
}
@@ -880,9 +881,7 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
break;
}
HydrologyCaveCell hydrology = terrain.hydrology(rx, floorY, rz);
if (hydrology != null
&& hydrology.protectsPlacement()
&& hydrology.action() != HydrologyCaveAction.SEAL_GUARD) {
if (hydrology != null && hydrology.action() != HydrologyCaveAction.SEAL_GUARD) {
continue;
}
NativeBlockState existing = output.getRaw(rx, floorY, rz);
@@ -910,9 +909,7 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
break;
}
HydrologyCaveCell hydrology = terrain.hydrology(rx, ceilingY, rz);
if (hydrology != null
&& hydrology.protectsPlacement()
&& hydrology.action() != HydrologyCaveAction.SEAL_GUARD) {
if (hydrology != null && hydrology.action() != HydrologyCaveAction.SEAL_GUARD) {
continue;
}
NativeBlockState existing = output.getRaw(rx, ceilingY, rz);
@@ -976,9 +973,7 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
}
int y = zone.floor - i - 1;
HydrologyCaveCell hydrology = terrain.hydrology(rx, y, rz);
if (hydrology != null
&& hydrology.protectsPlacement()
&& hydrology.action() != HydrologyCaveAction.SEAL_GUARD) {
if (hydrology != null && hydrology.action() != HydrologyCaveAction.SEAL_GUARD) {
continue;
}
NativeBlockState block = resolveSubmergedCaveFloorLayer(
@@ -1005,9 +1000,7 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
break;
}
HydrologyCaveCell hydrology = terrain.hydrology(rx, cy, rz);
if (hydrology != null
&& hydrology.protectsPlacement()
&& hydrology.action() != HydrologyCaveAction.SEAL_GUARD) {
if (hydrology != null && hydrology.action() != HydrologyCaveAction.SEAL_GUARD) {
continue;
}
NativeBlockState block = ceilingBlocks.get(i);
@@ -1184,11 +1177,9 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
}
MatterCavern baseline = terrain.cavern(localX, y, localZ);
NativeBlockState current = output.getRaw(localX, y, localZ);
NativeBlockState columnFluid = getComplex().resolveCaveCellFluid(
hydrology.fluidProfileKey(),
worldX,
worldZ
);
NativeBlockState columnFluid = hydrology.isWet()
? getComplex().resolveCaveCellFluid(hydrology.fluidProfileKey(), worldX, worldZ)
: null;
NativeBlockState normalized = normalizeHydrologyWaterlogging(
current,
baseline,
@@ -441,8 +441,7 @@ public class IrisDepositModifier extends EngineAssignedModifier<NativeBlockState
}
private static boolean protectedHydrology(MantleChunk chunk, int x, int y, int z) {
Object cell = chunk.get(x, y, z, HydrologyCaveCell.class);
return cell instanceof HydrologyCaveCell hydrology && hydrology.protectsPlacement();
return chunk.get(x, y, z, HydrologyCaveCell.class) instanceof HydrologyCaveCell;
}
static boolean canReplaceDepositTarget(NativeBlockState state) {
@@ -24,7 +24,6 @@ import art.arcane.iris.generation.mantle.EngineMantle;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.decoration.IrisProceduralBlocks;
import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell;
import art.arcane.iris.generation.hydrology.cave.HydrologyCaveStorage;
import art.arcane.iris.generation.hydrology.raster.WaterRole;
import art.arcane.iris.generation.terrain.IrisSlopeClip;
@@ -358,8 +357,7 @@ public class IrisPostModifier extends EngineAssignedModifier<NativeBlockState> {
if (mantle == null) {
return false;
}
HydrologyCaveCell cell = HydrologyCaveStorage.getIfPresent(mantle.getMantle(), x, y, z);
return cell != null && cell.protectsPlacement();
return HydrologyCaveStorage.getIfPresent(mantle.getMantle(), x, y, z) != null;
}
public void setPostBlock(int x, int y, int z, NativeBlockState d, int originX, int originZ, Hunk<NativeBlockState> currentData) {
@@ -113,6 +113,7 @@ import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
@@ -581,12 +582,12 @@ public class IrisDimension extends IrisRegistrant {
String biomeKey = Objects.requireNonNull(biome, "focus biome").getLoadKey();
KList<IrisRegion> available = getAllRegions(provider);
for (IrisRegion region : available) {
if (region.getAllBiomeIds().contains(biomeKey)) {
if (region.getAllBiomeIds(this, provider).contains(biomeKey)) {
return region;
}
}
for (IrisRegion region : available) {
for (IrisBiome member : region.getAllBiomes(provider)) {
for (IrisBiome member : region.getAllBiomes(this, provider)) {
if (biomeKey.equals(member.getLoadKey())) {
return region;
}
@@ -697,29 +698,15 @@ public class IrisDimension extends IrisRegistrant {
Deque<String> pending = new ArrayDeque<>();
addReachableBiomeKey(pending, getFocus());
boolean hydrologyPoliciesActive = hydrology != null && hydrology.isEnabled();
if (hydrologyPoliciesActive && hydrologyPolicy != null) {
addReachableBiomeKeys(pending, hydrologyPolicy.getShoreBiomes());
}
for (IrisRegion region : getAllRegions(g)) {
KList<IrisRegion> regions = getAllRegions(g);
for (IrisRegion region : regions) {
if (region == null) {
continue;
}
addReachableBiomeKeys(pending,
hydrologyPoliciesActive ? region.getAllBiomeIds() : region.getNaturalBiomeIds());
}
for (IrisImageMapBinding binding : getImageMaps()) {
if (binding == null || binding.getApplication() != IrisImageMapApplication.BIOME) {
continue;
}
IrisImageMap map = data.getImageMapLoader().load(binding.getMap());
if (map == null) {
continue;
}
for (String target : imageMapTargets(map)) {
addReachableBiomeKey(pending, localImageMapTarget(target));
}
addReachableBiomeKeys(pending, region.getNaturalBiomeIds());
}
addReachableBiomeKeys(pending, ShoreBiomeLineages.placed(this, regions, g));
addReachableBiomeKeys(pending, getImageMapBiomeKeys(g));
KList<IrisDimensionCarvingEntry> carvingEntries = getCarving();
if (carvingEntries != null) {
@@ -763,9 +750,6 @@ public class IrisDimension extends IrisRegistrant {
biomes.put(loadKey, biome);
addReachableBiomeKeys(pending, biome.getChildren());
addReachableBiomeKey(pending, biome.getCarvingBiome());
if (hydrologyPoliciesActive && biome.getHydrologyPolicy() != null) {
addReachableBiomeKeys(pending, biome.getHydrologyPolicy().getShoreBiomes());
}
KList<IrisFloatingChildBiomes> floatingChildren = biome.getFloatingChildBiomes();
if (floatingChildren == null) {
@@ -785,6 +769,50 @@ public class IrisDimension extends IrisRegistrant {
return biomes.v();
}
public KList<IrisBiome> getReachableCaveBiomes(DataProvider g) {
IrisData data = g == null ? null : g.getData();
if (data == null || data.getBiomeLoader() == null) {
return new KList<>();
}
Map<String, IrisBiome> biomes = new LinkedHashMap<>();
for (IrisRegion region : getAllRegions(g)) {
for (IrisBiome biome : region.getRealCaveBiomes(g)) {
biomes.putIfAbsent(biome.getLoadKey(), biome);
}
}
KList<IrisDimensionCarvingEntry> carvingEntries = getCarving();
if (carvingEntries != null) {
for (IrisDimensionCarvingEntry entry : carvingEntries) {
IrisBiome biome = entry == null || !entry.isEnabled() ? null : entry.getRealBiome(data);
if (biome != null) {
biomes.putIfAbsent(biome.getLoadKey(), biome);
}
}
}
return new KList<>(biomes.values());
}
public Set<String> getImageMapBiomeKeys(DataProvider g) {
Set<String> keys = new LinkedHashSet<>();
IrisData data = g == null ? null : g.getData();
if (data == null) {
return keys;
}
for (IrisImageMapBinding binding : getImageMaps()) {
if (binding == null || binding.getApplication() != IrisImageMapApplication.BIOME) {
continue;
}
IrisImageMap map = data.getImageMapLoader().load(binding.getMap());
if (map == null) {
continue;
}
for (String target : imageMapTargets(map)) {
keys.add(localImageMapTarget(target));
}
}
return keys;
}
private Set<String> imageMapTargets(IrisImageMap map) {
Set<String> targets = new LinkedHashSet<>();
if (map.getColors() != null) {
@@ -297,11 +297,9 @@ public class IrisRegion extends IrisRegistrant implements Rarity {
return getShoreHeightGenerator().fitDouble(shoreHeightMin, shoreHeightMax, x / shoreHeightZoom, z / shoreHeightZoom);
}
public KSet<String> getAllBiomeIds() {
public KSet<String> getAllBiomeIds(IrisDimension dimension, DataProvider g) {
KSet<String> names = getNaturalBiomeIds();
if (hydrologyPolicy != null && hydrologyPolicy.getShoreBiomes() != null) {
names.addAll(hydrologyPolicy.getShoreBiomes());
}
names.addAll(ShoreBiomeLineages.placedIn(dimension, this, g));
return names;
}
@@ -314,15 +312,15 @@ public class IrisRegion extends IrisRegistrant implements Rarity {
return names;
}
public KList<IrisBiome> getAllBiomes(DataProvider g) {
return resolveBiomes(g, getAllBiomeIds(), true);
public KList<IrisBiome> getAllBiomes(IrisDimension dimension, DataProvider g) {
return resolveBiomes(g, getAllBiomeIds(dimension, g));
}
public KList<IrisBiome> getNaturalBiomes(DataProvider g) {
return resolveBiomes(g, getNaturalBiomeIds(), false);
return resolveBiomes(g, getNaturalBiomeIds());
}
private KList<IrisBiome> resolveBiomes(DataProvider g, KSet<String> biomeIds, boolean includeShoreBiomes) {
private KList<IrisBiome> resolveBiomes(DataProvider g, KSet<String> biomeIds) {
KMap<String, IrisBiome> b = new KMap<>();
KSet<String> names = biomeIds.copy();
@@ -348,9 +346,6 @@ public class IrisRegion extends IrisRegistrant implements Rarity {
names.add(biome.getCarvingBiome());
b.put(biome.getLoadKey(), biome);
names.addAll(biome.getChildren());
if (includeShoreBiomes && biome.getHydrologyPolicy() != null && biome.getHydrologyPolicy().getShoreBiomes() != null) {
names.addAll(biome.getHydrologyPolicy().getShoreBiomes());
}
}
}
@@ -428,7 +423,7 @@ public class IrisRegion extends IrisRegistrant implements Rarity {
public Color getColor(DataProvider dataProvider, RenderType type) {
return this.cacheColor.aquire(() -> {
if (this.color == null) {
Random rand = new Random(getName().hashCode() + getAllBiomeIds().hashCode());
Random rand = new Random(getName().hashCode() + getNaturalBiomeIds().hashCode());
RandomColor randomColor = new RandomColor(rand);
KList<IrisBiome> biomes = getRealLandBiomes(dataProvider);
@@ -0,0 +1,119 @@
package art.arcane.iris.generation.terrain;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.block.DataProvider;
import art.arcane.iris.generation.hydrology.config.IrisHydrology;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.collection.KSet;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.BiConsumer;
public final class ShoreBiomeLineages {
private ShoreBiomeLineages() {
}
public static KSet<String> placed(IrisDimension dimension, Collection<IrisRegion> regions, DataProvider provider) {
KSet<String> keys = new KSet<>();
if (enabled(dimension)) {
visit(dimension, regions, provider, (lineage, region) -> addPlaced(keys, lineage, region, dimension));
}
return keys;
}
static KSet<String> placedIn(IrisDimension dimension, IrisRegion region, DataProvider provider) {
KSet<String> keys = new KSet<>();
IrisData data = provider == null ? null : provider.getData();
if (enabled(dimension) && data != null && data.getBiomeLoader() != null) {
visitRegion(region, data, (lineage, area) -> addPlaced(keys, lineage, area, dimension));
}
return keys;
}
public static void visit(IrisDimension dimension, Collection<IrisRegion> regions, DataProvider provider,
BiConsumer<List<IrisBiome>, IrisRegion> visitor) {
IrisData data = provider == null ? null : provider.getData();
if (data == null || data.getBiomeLoader() == null) {
return;
}
for (IrisRegion region : regions) {
if (region != null) {
visitRegion(region, data, visitor);
}
}
List<IrisBiome> direct = new ArrayList<>();
for (String key : dimension.getImageMapBiomeKeys(provider)) {
addLoaded(direct, data, key);
}
addLoaded(direct, data, dimension.getFocus());
for (IrisBiome biome : direct) {
List<IrisBiome> lineage = List.of(biome);
for (IrisRegion region : regions) {
if (region != null) {
visitor.accept(lineage, region);
}
}
visitor.accept(lineage, null);
}
}
private static boolean enabled(IrisDimension dimension) {
IrisHydrology hydrology = dimension.getHydrology();
return hydrology != null && hydrology.isEnabled();
}
private static void visitRegion(IrisRegion region, IrisData data, BiConsumer<List<IrisBiome>, IrisRegion> visitor) {
List<IrisBiome> roots = new ArrayList<>();
for (String key : region.getLandBiomes()) {
addLoaded(roots, data, key);
}
for (String key : region.getSeaBiomes()) {
addLoaded(roots, data, key);
}
ArrayDeque<IrisBiome> chain = new ArrayDeque<>();
for (IrisBiome root : roots) {
descend(root, chain, region, data, visitor);
}
}
private static void descend(IrisBiome biome, ArrayDeque<IrisBiome> chain, IrisRegion region, IrisData data,
BiConsumer<List<IrisBiome>, IrisRegion> visitor) {
chain.addFirst(biome);
visitor.accept(List.copyOf(chain), region);
if (chain.size() <= IrisBiome.CHILD_HOPS) {
List<IrisBiome> children = new ArrayList<>();
for (String key : biome.getChildren()) {
addLoaded(children, data, key);
}
for (IrisBiome child : children) {
if (child != biome) {
descend(child, chain, region, data, visitor);
}
}
}
chain.removeFirst();
}
private static void addLoaded(List<IrisBiome> biomes, IrisData data, String key) {
IrisBiome biome = key == null || key.isBlank() ? null : data.getBiomeLoader().load(key);
if (biome != null && !biome.isCompatExcluded()) {
biomes.add(biome);
}
}
private static void addPlaced(KSet<String> keys, List<IrisBiome> lineage, IrisRegion region, IrisDimension dimension) {
IrisHydrologyPolicy.ShoreBand band = IrisHydrologyPolicy.shoreBand(lineage, region, dimension);
if (band == null) {
return;
}
for (String key : band.biomes()) {
if (key != null && !key.isBlank()) {
keys.add(key);
}
}
}
}
@@ -5,21 +5,29 @@ import art.arcane.iris.generation.decoration.HydrologyVegetation;
import art.arcane.iris.generation.decoration.IrisDecorator;
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.IrisRegion;
import art.arcane.iris.generation.terrain.ShoreBiomeLineages;
import art.arcane.iris.pack.loading.IrisData;
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 java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.IdentityHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
final class PackHydrologyValidator {
private static final String CONFIG = "hydrology";
@@ -38,31 +46,36 @@ final class PackHydrologyValidator {
new RangeField("underground.cavePools.freeboard", Floor.NON_NEGATIVE, true)
);
private static final List<String> FLUID_REFERENCES = List.of("ponds.fluid", "underground.cavePools.fluid");
private static final IrisHydrologyTier DEFAULT_TIER = new IrisHydrologyTier();
private static final String MANTLE_WATER = "the falling water at waterfalls and cascades, sea inlets and cave pools";
private PackHydrologyValidator() {
}
static Validation validate(File packFolder, File[] dimensionFiles) {
List<String> errors = new ArrayList<>();
List<String> warnings = new ArrayList<>();
if (packFolder == null || !packFolder.isDirectory() || dimensionFiles == null) {
return new Validation(errors, List.of());
return new Validation(errors, warnings);
}
List<File> sortedDimensions = new ArrayList<>(List.of(dimensionFiles));
sortedDimensions.sort(Comparator.comparing(File::getPath));
File dimensionsFolder = new File(packFolder, PackValidator.DIMENSIONS_FOLDER);
Findings findings = new Findings(errors, warnings);
IrisData data = null;
try {
for (File dimensionFile : sortedDimensions) {
data = validateDimension(packFolder, dimensionsFolder, dimensionFile, data, errors);
data = validateDimension(packFolder, dimensionsFolder, dimensionFile, data, findings);
}
} finally {
close(packFolder, data, errors);
}
return new Validation(errors, List.of());
return new Validation(errors, warnings);
}
private static IrisData validateDimension(File packFolder, File dimensionsFolder, File dimensionFile, IrisData data,
List<String> errors) {
Findings findings) {
List<String> errors = findings.errors();
JSONObject dimension = PackValidationIo.readJson(dimensionFile);
if (dimension == null || !dimension.has(CONFIG)) {
return data;
@@ -78,6 +91,7 @@ final class PackHydrologyValidator {
}
int reported = errors.size();
validateRanges(path, hydrology, errors);
warnPartialTiers(path, hydrology, findings.warnings());
Set<String> fluids = fluidNames(hydrology);
Set<String> seams = seamNames(hydrology);
validateFluidReferences(path, hydrology, fluids, errors);
@@ -86,7 +100,9 @@ final class PackHydrologyValidator {
if (loadedDimension == null) {
return loaded;
}
warnMantleOff("Dimension '" + dimensionKey + "'", loadedDimension, findings.warnings());
validatePolicies(path, dimensionKey, loaded, loadedDimension, new PolicyFluids(fluids, seams), errors);
warnShoreBiomesWithoutWidth(dimensionKey, loaded, loadedDimension, findings.warnings());
if (errors.size() == reported && validateCompile(path, loadedDimension, errors)) {
validateDecoratorBlocks(path, loaded, loadedDimension.getHydrology(), errors);
}
@@ -149,6 +165,37 @@ final class PackHydrologyValidator {
}
}
private static void warnPartialTiers(String path, JSONObject hydrology, List<String> warnings) {
JSONArray tiers = hydrology.optJSONArray("tiers");
if (tiers == null) {
return;
}
for (int index = 0; index < tiers.length(); index++) {
JSONObject tier = tiers.optJSONObject(index);
if (tier == null) {
continue;
}
String field = path + ".tiers[" + index + "] ('" + tier.optString("name", DEFAULT_TIER.getName()) + "')";
if (!tier.has("halfWidth")) {
warnings.add(field + " does not set halfWidth, so it takes the default " + DEFAULT_TIER.getHalfWidth() + ".");
}
if (!tier.has("bankBand")) {
warnings.add(field + " does not set bankBand, so it takes the default " + DEFAULT_TIER.getBankBand()
+ " and leaves the ground beside its channels as it is.");
}
}
}
private static void warnMantleOff(String path, IrisDimension dimension, List<String> warnings) {
if (!dimension.isUseMantle()) {
warnings.add(path + " sets useMantle to false while hydrology is enabled, so " + MANTLE_WATER + " are not generated.");
}
if (dimension.getDisabledComponents() != null && dimension.getDisabledComponents().contains(ReservedFlag.RIVER_HYDROLOGY)) {
warnings.add(path + " disables the " + ReservedFlag.RIVER_HYDROLOGY + " component while hydrology is enabled, so " + MANTLE_WATER
+ " are not generated.");
}
}
private static double[] range(String field, Object value, Floor floor, boolean whole, List<String> errors) {
if (!(value instanceof JSONArray pair) || pair.length() != 2 || !(pair.opt(0) instanceof Number first)
|| !(pair.opt(1) instanceof Number second)) {
@@ -259,6 +306,58 @@ final class PackHydrologyValidator {
if (policy.getDecorators() != null) {
validateDecorators(field + ".decorators", policy.getDecorators(), data, errors);
}
requireMultiplier(field + ".rainfall", policy.getRainfall(), errors);
requireMultiplier(field + ".pondDensity", policy.getPondDensity(), errors);
IrisHydrologyWetness wetness = policy.getWetness();
if (wetness != null && !(wetness.getMin() >= 0D && wetness.getMin() <= wetness.getMax() && wetness.getMax() <= 1D)) {
errors.add(field + ".wetness must have 0 <= min <= max <= 1, got min " + wetness.getMin() + " and max " + wetness.getMax() + ".");
}
}
private static void warnShoreBiomesWithoutWidth(String dimensionKey, IrisData data, IrisDimension dimension, List<String> warnings) {
List<IrisRegion> regions = new ArrayList<>(dimension.getAllRegions(() -> data));
regions.sort(Comparator.comparing(IrisRegion::getLoadKey, Comparator.nullsFirst(Comparator.naturalOrder())));
Set<IrisHydrologyPolicy> widened = Collections.newSetFromMap(new IdentityHashMap<>());
Map<String, IrisBiome> lineageBiomes = new TreeMap<>();
ShoreBiomeLineages.visit(dimension, regions, () -> data, (lineage, region) -> {
Integer width = IrisHydrologyPolicy.inherited(lineage, region, dimension, IrisHydrologyPolicy::getShoreBiomeWidth);
boolean wide = width != null && width > 0;
for (IrisBiome biome : lineage) {
if (biome.getLoadKey() != null) {
lineageBiomes.putIfAbsent(biome.getLoadKey(), biome);
}
if (wide && biome.getHydrologyPolicy() != null) {
widened.add(biome.getHydrologyPolicy());
}
}
if (wide && region != null && region.getHydrologyPolicy() != null) {
widened.add(region.getHydrologyPolicy());
}
if (wide && dimension.getHydrologyPolicy() != null) {
widened.add(dimension.getHydrologyPolicy());
}
});
warnShoreBiomesWithoutWidth("Dimension '" + dimensionKey + "'", dimension.getHydrologyPolicy(), widened, warnings);
for (IrisRegion region : regions) {
warnShoreBiomesWithoutWidth("Region '" + region.getLoadKey() + "'", region.getHydrologyPolicy(), widened, warnings);
}
for (IrisBiome biome : lineageBiomes.values()) {
warnShoreBiomesWithoutWidth("Biome '" + biome.getLoadKey() + "'", biome.getHydrologyPolicy(), widened, warnings);
}
}
private static void warnShoreBiomesWithoutWidth(String scope, IrisHydrologyPolicy policy, Set<IrisHydrologyPolicy> widened,
List<String> warnings) {
if (policy != null && policy.getShoreBiomes() != null && !policy.getShoreBiomes().isEmpty() && !widened.contains(policy)) {
warnings.add(scope + "." + POLICY + ".shoreBiomes lists shore biomes, but no shoreBiomeWidth above 0 applies to them,"
+ " so none are placed.");
}
}
private static void requireMultiplier(String field, Double value, List<String> errors) {
if (value != null && !IrisHydrologyPolicy.validMultiplier(value)) {
errors.add(field + " must be a finite value from 0 to " + (int) IrisHydrologyPolicy.MAX_MULTIPLIER + ", got " + value + ".");
}
}
private static void close(File packFolder, IrisData data, List<String> errors) {
@@ -307,4 +406,7 @@ final class PackHydrologyValidator {
private record PolicyFluids(Set<String> defined, Set<String> seams) {
}
private record Findings(List<String> errors, List<String> warnings) {
}
}
@@ -34,7 +34,7 @@ public final class DimensionStage implements CompileStage {
dimension.getLogicalHeight(),
dimension.getFluidHeight() + minY,
paletteBlock(dimension.getRockPalette(), DEFAULT_ROCK, "rock"),
paletteBlock(dimension.getFluidPalette(), DEFAULT_FLUID, "fluid"),
fluidBlock(dimension),
new JsonObject(),
context.diagnostics());
IrisDimensionType type = new IrisDimensionType(
@@ -55,6 +55,17 @@ public final class DimensionStage implements CompileStage {
typeJson));
}
public static String fluidBlock(IrisDimension dimension) {
return paletteBlock(dimension.getFluidPalette(), DEFAULT_FLUID, "fluid");
}
public static String blockId(String raw) {
String block = raw == null ? "" : raw.trim().toLowerCase(Locale.ROOT);
int properties = block.indexOf('[');
String id = properties < 0 ? block : block.substring(0, properties);
return id.indexOf(':') < 0 ? "minecraft:" + id : id;
}
private static IrisDimensionTypeOptions typeOptions(IrisDimension dimension) {
IrisDimensionTypeOptions options = dimension.getDimensionOptions();
return dimension.isFullbright() ? options.copy().ambientLight(FULLBRIGHT_AMBIENT_LIGHT) : options;
@@ -65,11 +76,6 @@ public final class DimensionStage implements CompileStage {
if (entries == null || entries.isEmpty() || entries.getFirst() == null) {
return fallback;
}
String raw = entries.getFirst().getBlock();
String block = raw == null ? "" : raw.trim().toLowerCase(Locale.ROOT);
int properties = block.indexOf('[');
String id = properties < 0 ? block : block.substring(0, properties);
String namespaced = id.indexOf(':') < 0 ? "minecraft:" + id : id;
return VanillaResourceIdentifier.requireIdentifier(namespaced, "dimension " + role + " block");
return VanillaResourceIdentifier.requireIdentifier(blockId(entries.getFirst().getBlock()), "dimension " + role + " block");
}
}
@@ -104,7 +104,7 @@ public final class ExportedBiomes {
if (region == null) {
continue;
}
for (IrisBiome biome : region.getAllBiomes(() -> context.data())) {
for (IrisBiome biome : region.getAllBiomes(context.dimension(), () -> context.data())) {
if (biome != null && biome.getLoadKey() != null) {
regions.putIfAbsent(biome.getLoadKey(), region);
}
@@ -1,10 +1,12 @@
package art.arcane.iris.pack.datapack.export.compile.terrain;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.hydrology.config.IrisBankStyle;
import art.arcane.iris.generation.hydrology.config.IrisHydrology;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.hydrology.water.HydrologyTier;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.pack.datapack.export.compile.noise.NoiseRegistry;
import art.arcane.iris.pack.datapack.export.ir.CostClass;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
@@ -17,6 +19,7 @@ import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;
public final class RiverCompiler {
public static final String CARVED_HEIGHT = "height/carved";
@@ -59,8 +62,9 @@ public final class RiverCompiler {
this.diagnostics = Objects.requireNonNull(diagnostics, "diagnostics");
}
public Field compile(Field height, IrisDimension dimension, NoiseRegistry registry, ExportCapabilities capabilities) {
public Field compile(Field height, IrisDimension dimension, Supplier<List<Area>> areas, NoiseRegistry registry, ExportCapabilities capabilities) {
Objects.requireNonNull(height, "height");
Objects.requireNonNull(areas, "areas");
IrisHydrology hydrology = dimension.getHydrology();
if (hydrology == null || !hydrology.isEnabled()) {
return height;
@@ -73,6 +77,7 @@ public final class RiverCompiler {
return height;
}
report(ExportLimit.RIVER_DRAINAGE, resource, "Rivers follow seeded noise channels instead of drainage: tributaries cross instead of joining and widths follow elevation");
diagnostics.addAll(RiverLimits.diagnostics(dimension, settings, areas.get(), resource));
Field elevation = FieldMacros.sum(List.of(height, new Field.Const(-fluidHeight)));
Carving carving = new Carving(elevation, variation(registry), bankNoise(settings.deformation(), registry), settings.deformation(), registry, capabilities);
List<HydrologyTier> tiers = settings.tiers();
@@ -287,6 +292,16 @@ public final class RiverCompiler {
return new Field.Binary(Field.BinaryOp.MAX, first, second);
}
public record Area(IrisRegion region, List<IrisBiome> biomes) {
public Area {
Objects.requireNonNull(region, "region");
biomes = List.copyOf(biomes);
if (biomes.isEmpty()) {
throw new IllegalArgumentException("A river area in region " + region.getLoadKey() + " needs a biome");
}
}
}
private record Carving(Field elevation, Field variation, Field bankNoise, HydrologySettings.Deformation deformation,
NoiseRegistry registry, ExportCapabilities capabilities) {
}
@@ -0,0 +1,207 @@
package art.arcane.iris.pack.datapack.export.compile.terrain;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.block.IrisBlockData;
import art.arcane.iris.generation.decoration.IrisDecorator;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyPermission;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyWetness;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.hydrology.water.HydrologyTier;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
import art.arcane.iris.pack.datapack.export.compile.DimensionStage;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.function.Function;
final class RiverLimits {
private static final double NEUTRAL_RAINFALL = 1.0;
private static final Comparator<Finding> ORDER = Comparator.comparing(Finding::limit)
.thenComparingInt(finding -> finding.owner().rank())
.thenComparing(finding -> finding.owner().resource())
.thenComparing(Finding::subject);
private final IrisDimension dimension;
private final HydrologySettings settings;
private final Owner hydrology;
private final Owner dimensionPolicy;
private final String exportFluid;
private final SortedMap<Finding, String> findings = new TreeMap<>(ORDER);
private RiverLimits(IrisDimension dimension, HydrologySettings settings, String resource) {
this.dimension = dimension;
this.settings = settings;
this.hydrology = new Owner(Owner.HYDROLOGY, resource);
this.dimensionPolicy = new Owner(Owner.DIMENSION, "dimensions/" + dimension.getLoadKey());
this.exportFluid = DimensionStage.fluidBlock(dimension);
}
static List<ExportDiagnostic> diagnostics(IrisDimension dimension, HydrologySettings settings, List<RiverCompiler.Area> areas, String resource) {
RiverLimits limits = new RiverLimits(dimension, settings, resource);
for (RiverCompiler.Area area : areas) {
limits.inspect(area);
}
limits.inspectUnderground();
List<ExportDiagnostic> diagnostics = new ArrayList<>(limits.findings.size());
for (Map.Entry<Finding, String> entry : limits.findings.entrySet()) {
Finding finding = entry.getKey();
diagnostics.add(new ExportDiagnostic(ExportDiagnostic.Severity.WARNING, finding.limit(), finding.owner().resource(), entry.getValue()));
}
return diagnostics;
}
private void inspect(RiverCompiler.Area area) {
inspectFluid(area);
inspectPolicy(area);
inspectClimate(area);
inspectShore(area);
inspectDecorators(area);
}
private void inspectUnderground() {
if (settings.underground().seaInlets().enabled()) {
add(ExportLimit.SEA_INLET, hydrology, "", "Sea inlets are not exported: coastal cliffs have no flooded passages");
}
if (settings.underground().cavePools().enabled() && settings.underground().cavePools().density() > 0.0F) {
add(ExportLimit.CAVE_POOL, hydrology, "", "Cave pools are not exported: cave floors hold no standing water of their own");
}
}
private void inspectFluid(RiverCompiler.Area area) {
Sourced<String> fluid = sourced(area, IrisHydrologyPolicy::getFluid);
if (fluid != null) {
settings.requireFillingFluid(fluid.value(), "the hydrology policy of " + fluid.owner().resource());
fluid(fluid.owner(), fluid.value());
return;
}
for (HydrologyTier tier : settings.tiers()) {
fluid(hydrology, tier.fluid());
}
}
private void inspectPolicy(RiverCompiler.Area area) {
Sourced<Double> rainfall = sourced(area, IrisHydrologyPolicy::getRainfall);
if (rainfall != null && rainfall.value() != NEUTRAL_RAINFALL) {
add(ExportLimit.RIVER_POLICY, rainfall.owner(), "rainfall",
"Hydrology policy rainfall is not exported: rivers form at the dimension density here");
}
Sourced<IrisHydrologyPermission> streams = sourced(area, IrisHydrologyPolicy::getStreams);
if (streams != null && streams.value() == IrisHydrologyPermission.BLOCK) {
add(ExportLimit.RIVER_POLICY, streams.owner(), "streams",
"Hydrology policy streams BLOCK is not exported: rivers start here as they do elsewhere");
}
}
private void inspectClimate(RiverCompiler.Area area) {
HydrologySettings.Climate climate = settings.climate();
Sourced<Boolean> zones = sourced(area, IrisHydrologyPolicy::getClimateZones);
if (!climate.enabled() || zones != null && !zones.value()) {
return;
}
boolean zoned = climate.dryness() > 0.0F && climate.dryRainfall() < 1.0F;
if (zoned) {
add(ExportLimit.RIVER_CLIMATE, hydrology, "", "Wet and dry zones are not exported: rivers start in dry zones as they do in wet ones");
}
Sourced<IrisHydrologyWetness> wetness = sourced(area, IrisHydrologyPolicy::getWetness);
double driest = zoned ? climate.dryRainfall() : 1.0;
if (wetness != null && (wetness.value().getMin() > driest || wetness.value().getMax() < 1.0)) {
add(ExportLimit.RIVER_CLIMATE, wetness.owner(), "wetness",
"Hydrology policy wetness is not exported: rivers form at the dimension density here");
}
}
private void inspectShore(RiverCompiler.Area area) {
Sourced<Integer> width = sourced(area, IrisHydrologyPolicy::getShoreBiomeWidth);
Sourced<List<String>> biomes = sourced(area, IrisHydrologyPolicy::getShoreBiomes);
if (width == null || width.value() <= 0 || biomes == null || biomes.value().isEmpty()) {
return;
}
add(ExportLimit.RIVER_SHORE_BIOME, biomes.owner(), "",
"Hydrology shore biomes are not exported: the water's edge keeps the biome around it");
}
private void inspectDecorators(RiverCompiler.Area area) {
Sourced<List<IrisDecorator>> decorators = sourced(area, IrisHydrologyPolicy::getDecorators);
if (decorators != null) {
if (!decorators.value().isEmpty()) {
decorators(decorators.owner());
}
return;
}
for (HydrologyTier tier : settings.tiers()) {
if (tier.decorators() != null && !tier.decorators().isEmpty()) {
decorators(hydrology);
return;
}
}
}
private void decorators(Owner owner) {
add(ExportLimit.RIVER_DECORATOR, owner, "", "Hydrology decorators are not exported: rivers grow no water plants of their own");
}
private void fluid(Owner owner, String name) {
String seam = settings.seams().get(name);
if (!exported(settings.fluids().get(name))) {
String subject = seam == null ? "Fluid '" + name + "' is" : "Fluid '" + name + "' and its seam '" + seam + "' are";
add(ExportLimit.RIVER_FLUID, owner, name, subject + " not exported: rivers fill with " + exportFluid + " up to fluidHeight");
return;
}
if (seam != null) {
add(ExportLimit.RIVER_FLUID, owner, name, "Seam '" + seam + "' of fluid '" + name + "' is not exported: rivers have no seam band at their edges");
}
}
private boolean exported(IrisMaterialPalette palette) {
for (IrisBlockData block : palette.getPalette()) {
if (!exportFluid.equals(DimensionStage.blockId(block.getBlock()))) {
return false;
}
}
return true;
}
private void add(ExportLimit limit, Owner owner, String subject, String message) {
findings.putIfAbsent(new Finding(limit, owner, subject), message);
}
private <T> Sourced<T> sourced(RiverCompiler.Area area, Function<IrisHydrologyPolicy, T> field) {
for (IrisBiome biome : area.biomes()) {
T value = value(biome.getHydrologyPolicy(), field);
if (value != null) {
return new Sourced<>(new Owner(Owner.BIOME, "biomes/" + biome.getLoadKey()), value);
}
}
T region = value(area.region().getHydrologyPolicy(), field);
if (region != null) {
return new Sourced<>(new Owner(Owner.REGION, "regions/" + area.region().getLoadKey()), region);
}
T inherited = value(dimension.getHydrologyPolicy(), field);
return inherited == null ? null : new Sourced<>(dimensionPolicy, inherited);
}
private static <T> T value(IrisHydrologyPolicy policy, Function<IrisHydrologyPolicy, T> field) {
return policy == null ? null : field.apply(policy);
}
private record Owner(int rank, String resource) {
private static final int HYDROLOGY = 0;
private static final int DIMENSION = 1;
private static final int REGION = 2;
private static final int BIOME = 3;
}
private record Finding(ExportLimit limit, Owner owner, String subject) {
}
private record Sourced<T>(Owner owner, T value) {
}
}
@@ -1,8 +1,20 @@
package art.arcane.iris.pack.datapack.export.compile.terrain;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.pack.datapack.export.compile.CompileStage;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.loading.IrisData;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
public final class RiverStage implements CompileStage {
private static final String ESTIMATE_TAG = "estimate";
@@ -15,8 +27,68 @@ public final class RiverStage implements CompileStage {
@Override
public void apply(PackCompileContext context) {
Field natural = context.naturalHeight();
Field carved = new RiverCompiler(context.diagnostics()).compile(natural, context.dimension(), context.noises(), context.capabilities());
Field carved = new RiverCompiler(context.diagnostics()).compile(natural, context.dimension(), () -> areas(context), context.noises(), context.capabilities());
context.setCarvedHeight(carved);
context.setSurfaceEstimate(FieldMacros.substitute(carved, natural, context.climateHeight(), ESTIMATE_TAG));
}
private static List<RiverCompiler.Area> areas(PackCompileContext context) {
IrisData data = context.data();
Set<String> exported = new HashSet<>(context.baseBiomeCodes().loadKeyByBiomeId().values());
List<IrisRegion> regions = new ArrayList<>();
for (IrisRegion region : data.getRegionLoader().loadAll(context.dimension().getRegions())) {
if (!region.isCompatExcluded()) {
regions.add(region);
}
}
regions.sort(Comparator.comparing(IrisRegion::getLoadKey));
List<RiverCompiler.Area> areas = new ArrayList<>();
for (IrisRegion region : regions) {
for (List<IrisBiome> lineage : lineages(region, data, exported)) {
areas.add(new RiverCompiler.Area(region, lineage));
}
}
return areas;
}
private static Collection<List<IrisBiome>> lineages(IrisRegion region, IrisData data, Set<String> exported) {
List<String> roots = new ArrayList<>();
roots.addAll(region.getLandBiomes());
roots.addAll(region.getSeaBiomes());
roots.addAll(region.getShoreBiomes());
SortedMap<String, List<IrisBiome>> lineages = new TreeMap<>();
for (String key : roots) {
IrisBiome root = exportedBiome(key, data, exported);
if (root != null) {
addLineages(List.of(root), data, exported, lineages);
}
}
return lineages.values();
}
private static void addLineages(List<IrisBiome> leafFirst, IrisData data, Set<String> exported, SortedMap<String, List<IrisBiome>> lineages) {
StringBuilder key = new StringBuilder(leafFirst.getFirst().getLoadKey());
for (int index = 1; index < leafFirst.size(); index++) {
key.append('<').append(leafFirst.get(index).getLoadKey());
}
if (lineages.putIfAbsent(key.toString(), leafFirst) != null || leafFirst.size() > IrisBiome.CHILD_HOPS) {
return;
}
IrisBiome leaf = leafFirst.getFirst();
for (String childKey : leaf.getChildren()) {
IrisBiome child = exportedBiome(childKey, data, exported);
if (child == null || child.getLoadKey().equals(leaf.getLoadKey())) {
continue;
}
List<IrisBiome> lineage = new ArrayList<>(leafFirst.size() + 1);
lineage.add(child);
lineage.addAll(leafFirst);
addLineages(List.copyOf(lineage), data, exported, lineages);
}
}
private static IrisBiome exportedBiome(String key, IrisData data, Set<String> exported) {
IrisBiome biome = key == null ? null : data.getBiomeLoader().load(key);
return biome == null || biome.isCompatExcluded() || !exported.contains(biome.getLoadKey()) ? null : biome;
}
}
@@ -31,6 +31,13 @@ public enum ExportLimit {
OBJECT_BOUNDS,
RIVER_DRAINAGE,
ELEVATED_WATER,
RIVER_FLUID,
RIVER_POLICY,
RIVER_CLIMATE,
RIVER_SHORE_BIOME,
RIVER_DECORATOR,
SEA_INLET,
CAVE_POOL,
DATAPACK_VERSION,
DATAPACK_COLLISION,
DATAPACK_FILE,
@@ -21,6 +21,7 @@ import art.arcane.volmlib.nativelib.terrain.structure.StructureLocateSearchAcces
import art.arcane.volmlib.nativelib.terrain.structure.StructurePalette;
import art.arcane.volmlib.nativelib.terrain.structure.StructurePlacementDecision;
import art.arcane.volmlib.nativelib.terrain.structure.StructureReferencePolicy;
import art.arcane.volmlib.nativelib.terrain.structure.StructureSeaSurface;
import art.arcane.volmlib.nativelib.terrain.structure.StructureVolumePolicy;
import art.arcane.volmlib.util.math.RNG;
@@ -120,6 +121,11 @@ public final class BukkitStructureStagePolicy implements StructureStagePolicy<
return (x, z) -> Engine.hostHeight(context, x, z, true) + context.getMinHeight();
}
@Override
public StructureSeaSurface seaSurface(Engine context) {
return GenerationWritePolicy.seaSurface(context);
}
@Override
public IntBinaryOperator worldgenHeight(Engine context, int runtimeMinY, boolean floor) {
return (x, z) -> Engine.hostHeight(context, x, z, floor) + runtimeMinY + 1;
@@ -4,9 +4,12 @@ import art.arcane.iris.generation.runtime.DimensionStackContext;
import art.arcane.iris.generation.runtime.DimensionStackLayout;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.IrisEngine;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.world.history.GenerationHistoryRuntimeRouter;
import art.arcane.iris.structure.object.IrisStaticObjectLayer;
import art.arcane.volmlib.nativelib.terrain.NativeBlockPositionPredicate;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.volmlib.nativelib.terrain.structure.StructureSeaSurface;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -23,6 +26,20 @@ public final class GenerationWritePolicy {
return router != null && activation < router.history().activeActivation().activationId();
}
public static StructureSeaSurface seaSurface(Engine engine) {
IrisDimension dimension = engine.getDimension();
int fluidHeight = dimension.getFluidHeight();
if (fluidHeight <= 0) {
return StructureSeaSurface.NONE;
}
for (NativeBlockState fluid : dimension.getFluidPalette().getBlockData(engine.getData())) {
if (fluid.isFluid()) {
return new StructureSeaSurface(engine.getMinHeight() + fluidHeight, fluid);
}
}
return StructureSeaSurface.NONE;
}
public static NativeBlockPositionPredicate protectedPositions(
IrisStaticObjectLayer staticObjects,
DimensionStackContext stackContext,
@@ -58,7 +58,7 @@ public class IrisVanillaStructureAdjustment {
@Description("Optional foundation columns placed beneath the native structure piece bases after placement.")
private IrisStructureStiltSettings stilt = null;
@Description("Optional terrain integration override. FLATTEN cuts and fills exposed surface foundations within flattenRange, blending across horizontalPadding blocks while preserving buried and submerged structures. VACUUM raises processed rigid-template foundations with a fixed 12-block falloff without lowering ground. BORE and FORCE_CARVE clear every intersecting chunk before native placement, while ENCASE fills it. Left unset, SOURCE replays the registered structure's authored terrain adaptation.")
@Description("Optional terrain integration override. FLATTEN cuts and fills exposed surface foundations within flattenRange, blending across horizontalPadding blocks while preserving buried and submerged structures. It never lowers dry ground outside a structure footprint below the dimension fluidHeight. A cut beneath water or lava, such as a riverbed, fills with that fluid, and other cuts at or below fluidHeight fill with the dimension sea fluid instead of air. VACUUM raises processed rigid-template foundations with a fixed 12-block falloff without lowering ground. BORE and FORCE_CARVE clear every intersecting chunk before native placement, while ENCASE fills it. Left unset, SOURCE replays the registered structure's authored terrain adaptation.")
private IrisStructureTerrain terrain = null;
public boolean matches(String key) {
@@ -30,7 +30,7 @@ public class IrisStructureTerrain implements StructureTerrainSettings {
private static final double MAX_EROSION_FREQUENCY = 1D;
private static final double MAX_LOBE_FREQUENCY = 1D;
@Description("Terrain operation. SOURCE applies the registered native structure's authored terrain adaptation and is a no-op for editable Iris structures. PRESERVE disables terrain integration. FLATTEN cuts and fills exposed native structure terrain within flattenRange, blending across horizontalPadding blocks. VACUUM raises terrain from processed rigid-template foundations with a fixed 12-block falloff without lowering ground. BORE and FORCE_CARVE clear the requested envelope, while ENCASE fills it before placement.")
@Description("Terrain operation. SOURCE applies the registered native structure's authored terrain adaptation and is a no-op for editable Iris structures. PRESERVE disables terrain integration. FLATTEN cuts and fills exposed native structure terrain within flattenRange, blending across horizontalPadding blocks, and never lowers dry ground outside a structure footprint below the dimension fluidHeight. SOURCE and FLATTEN surface cuts beneath water or lava, such as a riverbed, fill with that fluid, and other cuts at or below fluidHeight fill with the dimension sea fluid instead of air. VACUUM raises terrain from processed rigid-template foundations with a fixed 12-block falloff without lowering ground. BORE and FORCE_CARVE clear the requested envelope, while ENCASE fills it before placement.")
private StructureTerrainMode mode = StructureTerrainMode.SOURCE;
@MinNumber(0)
@@ -274,7 +274,7 @@ public final class StructureCaveAnchorResolver {
int blockZ
) {
HydrologyCaveCell hydrology = hydrologyAt(engine, blockX, mantleY, blockZ);
if (hydrology != null && hydrology.protectsPlacement()) {
if (hydrology != null) {
return false;
}
MatterCavern cavern = engine.getMantle().getMantle()
@@ -303,7 +303,7 @@ public final class StructureCaveAnchorResolver {
int mantleY,
int defaultLavaHeight
) {
if (hydrology != null && hydrology.protectsPlacement()) {
if (hydrology != null) {
return false;
}
if (cavern == null || !cavern.isCavern()) {
@@ -30,7 +30,7 @@ enum MapView {
REGIONS("Regions", "The region each spot belongs to; pick one to see the biomes it places",
Group.WORLD, TileType.REGION, KeyEvent.VK_2),
HEIGHT("Height", "Terrain height, from deep water to snowy peaks", Group.WORLD, TileType.HEIGHT, KeyEvent.VK_3),
RIVERS("Rivers", "Rivers, falls, grottos and the rest of the hydrology the engine plans",
RIVERS("Rivers", "Streams, rivers, falls, ponds, lakes, sea inlets and cave pools from the hydrology",
Group.WORLD, TileType.RIVER, KeyEvent.VK_4),
WORLD_3D("3D world", "The terrain in 3D, coloured by biome or region", Group.WORLD, null, KeyEvent.VK_5),
LAND_BIOMES("Land biomes", "The land biome each spot would get, also where the sea is",
@@ -339,7 +339,8 @@ final class VisionRenderController implements AutoCloseable {
tilesInFlight.remove(key);
Frame frame = currentFrame;
VisibleTile visible = frame == null ? null : frame.tile(key);
if (cancelled && visible != null && visible.needsRender(nanoTime.getAsLong(), frame.spec().renderer().previewRevision())) {
if (cancelled && visible != null && visible.needsRender(nanoTime.getAsLong(), frame.spec().renderer().previewRevision(),
frame.spec().renderer().riverRevision())) {
frame.nextCandidate = 0;
}
}
@@ -349,6 +350,7 @@ final class VisionRenderController implements AutoCloseable {
boolean cancelled = false;
try {
long previewRevision = job.renderer().previewRevision();
long riverRevision = job.renderer().riverRevision();
double tileSpan = TILE_PIXELS * key.blocksPerPixel();
MapTileRenderer.TileRender work = job.work();
if (work == null) {
@@ -364,13 +366,14 @@ final class VisionRenderController implements AutoCloseable {
? FIRST_RETRY_NANOS : Math.min(LAST_RETRY_NANOS, previous.retryDelay() * 2L);
}
long completedAt = nanoTime.getAsLong();
boolean retained = work.retainsWater();
TileState state = new TileState(tile, provisional, delay, completedAt + delay,
completedAt + FIRST_RETRY_NANOS, previewRevision);
completedAt + FIRST_RETRY_NANOS, previewRevision, riverRevision, retained);
synchronized (this) {
if (closed.get()) {
return;
}
cache.put(key, state, provisional ? work : null);
cache.put(key, state, provisional || retained ? work : null);
if (isWanted(key)) {
currentFrame.tile(key).state = state;
}
@@ -573,9 +576,10 @@ final class VisionRenderController implements AutoCloseable {
// Tiles are sorted centre first, and everything before the cursor is drawn or claimed, so each search resumes there.
private VisibleTile nextMissing(Set<TileKey> inFlight, boolean advance, long now) {
long previewRevision = spec.renderer().previewRevision();
long riverRevision = spec.renderer().riverRevision();
for (int index = nextCandidate; index < tiles.size(); index++) {
VisibleTile tile = tiles.get(index);
if (tile.needsRender(now, previewRevision) && !inFlight.contains(tile.key())) {
if (tile.needsRender(now, previewRevision, riverRevision) && !inFlight.contains(tile.key())) {
if (advance) {
nextCandidate = index + 1;
}
@@ -625,10 +629,16 @@ final class VisionRenderController implements AutoCloseable {
return current != null && current.provisional();
}
private boolean needsRender(long now, long previewRevision) {
private boolean needsRender(long now, long previewRevision, long riverRevision) {
TileState current = state;
return current == null || current.provisional() && (now - current.retryAt() >= 0L
|| previewRevision != current.previewRevision() && now - current.earliestRetryAt() >= 0L);
if (current == null) {
return true;
}
if (current.provisional()) {
return now - current.retryAt() >= 0L
|| previewRevision != current.previewRevision() && now - current.earliestRetryAt() >= 0L;
}
return current.retained() && riverRevision != current.riverRevision() && now - current.earliestRetryAt() >= 0L;
}
}
@@ -681,7 +691,7 @@ final class VisionRenderController implements AutoCloseable {
}
private record TileState(MapTile tile, boolean provisional, long retryDelay, long retryAt, long earliestRetryAt,
long previewRevision) {
long previewRevision, long riverRevision, boolean retained) {
}
private static final class WeightedTileCache {
@@ -28,6 +28,7 @@ import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.studio.render.IrisRenderer;
import art.arcane.iris.studio.render.RenderType;
import art.arcane.iris.world.history.GenerationSemanticQueries;
import art.arcane.volmlib.util.stream.ProceduralStream;
import java.awt.Color;
@@ -58,6 +59,7 @@ public final class MapTileRenderer {
private static final int NOISE_LOW = rgb(5, 5, 5);
private static final int NOISE_HIGH = rgb(255, 255, 255);
private static final double DARKEST_PICK_SHADE = 0.3D;
private static final double POOL_REFRESH_BLOCKS_PER_PIXEL = 4D;
private final Engine engine;
private final IrisRenderer hydrologyRenderer;
@@ -78,6 +80,10 @@ public final class MapTileRenderer {
return runtime == null ? 0L : runtime.previewRevision();
}
public long riverRevision() {
return GenerationSemanticQueries.recordedRiverRevision(engine);
}
/**
* Renders the square of {@code size} pixels whose top left pixel samples the given world position.
*
@@ -351,6 +357,7 @@ public final class MapTileRenderer {
public final class TileRender {
private final TileRequest request;
private final boolean retainsWater;
private short[] subjects;
private short[] regions;
private int[] baseColors;
@@ -367,18 +374,22 @@ public final class MapTileRenderer {
private TileRender(TileRequest request) {
this.request = request;
boolean drawsWater = request.layer().type() == TileType.RIVER || request.layer().waterOverlay();
this.retainsWater = drawsWater && request.blocksPerPixel() <= POOL_REFRESH_BLOCKS_PER_PIXEL;
heightsComplete = !request.withHeights() && request.layer().type() != TileType.HEIGHT;
waterComplete = request.layer().type() != TileType.RIVER && !request.layer().waterOverlay();
waterComplete = !drawsWater;
}
public MapTile render(BooleanSupplier cancelled) {
Objects.requireNonNull(cancelled, "cancelled");
checkCancelled(cancelled);
TileGrid grid = new TileGrid(request.size() + 2, request.startX() - request.blocksPerPixel(),
request.startZ() - request.blocksPerPixel(), request.blocksPerPixel(), cancelled);
sampleSubjects(grid);
sampleBaseColors(grid);
sampleTerrain(grid, cancelled);
if (!identitiesComplete || !baseComplete || !heightsComplete) {
TileGrid grid = new TileGrid(request.size() + 2, request.startX() - request.blocksPerPixel(),
request.startZ() - request.blocksPerPixel(), request.blocksPerPixel(), cancelled);
sampleSubjects(grid);
sampleBaseColors(grid);
sampleTerrain(grid, cancelled);
}
int[] colors = sampleWater(cancelled);
checkCancelled(cancelled);
complete = baseComplete && heightsComplete && waterComplete;
@@ -396,6 +407,10 @@ public final class MapTileRenderer {
return complete;
}
public boolean retainsWater() {
return retainsWater;
}
public long bytes() {
return bytes;
}
@@ -445,19 +460,21 @@ public final class MapTileRenderer {
}
private int[] sampleWater(BooleanSupplier cancelled) {
if (waterComplete) {
return finalColors == null ? baseColors : finalColors;
}
if (water == null) {
if (waterComplete) {
return finalColors == null ? baseColors : finalColors;
}
water = hydrologyRenderer.prepareStudioWater(request.startX(), request.startZ(), request.blocksPerPixel(),
request.size());
}
int[] colors = water.render(baseColors, request.layer().waterOverlay(), cancelled);
if (baseComplete && water.complete()) {
finalColors = colors;
baseColors = null;
waterComplete = true;
water = null;
if (!retainsWater) {
finalColors = colors;
baseColors = null;
water = null;
}
}
return colors;
}
@@ -88,64 +88,6 @@ public final class IrisRenderer {
int resolution,
RenderType currentType,
BooleanSupplier cancelled
) {
return render(sx, sz, size, resolution, currentType, cancelled, false, false);
}
public BufferedImage renderStudio(
double sx,
double sz,
double size,
int resolution,
RenderType currentType,
BooleanSupplier cancelled
) {
return render(sx, sz, size, resolution, currentType, cancelled, true, true);
}
public BufferedImage renderStudioBase(
double sx,
double sz,
double size,
int resolution,
RenderType currentType,
BooleanSupplier cancelled
) {
return render(sx, sz, size, resolution, currentType, cancelled, true, false);
}
public BufferedImage refineStudioBiome(
double sx,
double sz,
double size,
BufferedImage base,
BooleanSupplier cancelled
) {
Objects.requireNonNull(base, "base");
Objects.requireNonNull(cancelled, "cancelled");
checkCancelled(cancelled);
if (!Double.isFinite(sx) || !Double.isFinite(sz) || !Double.isFinite(size) || size <= 0D
|| base.getWidth() != base.getHeight()) {
throw new IllegalArgumentException("Vision biome refinement requires finite coordinates and a square base image");
}
int resolution = base.getWidth();
BufferedImage image = new BufferedImage(resolution, resolution, BufferedImage.TYPE_INT_RGB);
base.copyData(image.getRaster());
int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
renderRiverAtlas(pixels, resolution, sx, sz, size / resolution, renderer, cancelled, true);
checkCancelled(cancelled);
return image;
}
private BufferedImage render(
double sx,
double sz,
double size,
int resolution,
RenderType currentType,
BooleanSupplier cancelled,
boolean studio,
boolean riverOverlay
) {
if (!Double.isFinite(sx) || !Double.isFinite(sz) || !Double.isFinite(size) || size <= 0D) {
throw new IllegalArgumentException("Vision render coordinates and size must be finite");
@@ -160,23 +102,7 @@ public final class IrisRenderer {
BufferedImage image = new BufferedImage(resolution, resolution, BufferedImage.TYPE_INT_RGB);
int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
double step = size / resolution;
if (studio && currentType == RenderType.HEIGHT) {
renderHeightAtlas(pixels, resolution, sx, sz, step, renderer, cancelled);
return image;
}
if (currentType == RenderType.RIVER) {
Arrays.fill(pixels, NO_RIVER);
renderRiverAtlas(pixels, resolution, sx, sz, step, renderer, cancelled, false);
return image;
}
PixelShader shader = shader(currentType, studio);
if (studio && adaptiveStudioType(currentType)) {
renderAdaptiveAtlas(pixels, resolution, sx, sz, step, shader, cancelled);
if (currentType == RenderType.BIOME && riverOverlay) {
renderRiverAtlas(pixels, resolution, sx, sz, step, renderer, cancelled, true);
}
return image;
}
PixelShader shader = shader(currentType);
int groupSize = sampleGroup(step, resolution);
for (int groupZ = 0; groupZ < resolution; groupZ += groupSize) {
@@ -248,118 +174,19 @@ public final class IrisRenderer {
return Math.max(1, Math.min(resolution, (int) Math.floor(16D / absoluteStep)));
}
private PixelShader shader(RenderType currentType, boolean studio) {
private PixelShader shader(RenderType currentType) {
IrisComplex complex = renderer.getComplex();
return switch (currentType) {
case BIOME, DECORATOR_LOAD, OBJECT_LOAD, LAYER_LOAD -> biomeShader(
studio ? complex.getBaseBiomeStream() : complex.getTrueBiomeStream(), currentType);
case BIOME, DECORATOR_LOAD, OBJECT_LOAD, LAYER_LOAD -> biomeShader(complex.getTrueBiomeStream(), currentType);
case BIOME_LAND -> biomeShader(complex.getLandBiomeStream(), currentType);
case BIOME_SEA -> biomeShader(complex.getSeaBiomeStream(), currentType);
case REGION -> regionShader(complex, currentType);
case CAVE_LAND -> biomeShader(complex.getCaveBiomeStream(), currentType);
case HEIGHT -> heightShader(studio ? complex.getNaturalHeightStream() : complex.getHeightStream());
case RIVER -> throw new IllegalArgumentException("River maps render from the water raster atlas, not a pixel shader");
case CONTINENT -> studio
? continentShader(complex.getBaseBiomeStream())
: this::continentColor;
case HEIGHT -> heightShader(complex.getHeightStream());
case CONTINENT -> this::continentColor;
};
}
private static boolean adaptiveStudioType(RenderType type) {
return switch (type) {
case BIOME, DECORATOR_LOAD, OBJECT_LOAD, LAYER_LOAD, BIOME_LAND, BIOME_SEA, REGION, CAVE_LAND,
CONTINENT -> true;
case HEIGHT, RIVER -> false;
};
}
private static void renderAdaptiveAtlas(
int[] pixels,
int resolution,
double startX,
double startZ,
double step,
PixelShader shader,
BooleanSupplier cancelled
) {
int maximumPixels = Math.max(1, Math.min(16, (int) Math.floor(64D / step)));
int blockPixels = Integer.highestOneBit(maximumPixels);
AdaptiveSampler sampler = new AdaptiveSampler(pixels, resolution, startX, startZ, step, shader, cancelled);
for (int pixelZ = 0; pixelZ < resolution; pixelZ += blockPixels) {
int height = Math.min(blockPixels, resolution - pixelZ);
for (int pixelX = 0; pixelX < resolution; pixelX += blockPixels) {
sampler.render(pixelX, pixelZ, Math.min(blockPixels, resolution - pixelX), height);
}
}
}
private static void renderHeightAtlas(
int[] pixels,
int resolution,
double startX,
double startZ,
double step,
Engine engine,
BooleanSupplier cancelled
) {
IrisComplex complex = engine.getComplex();
IrisDimension dimension = engine.getDimension();
double fluidHeight = dimension == null ? 0D : dimension.getFluidHeight();
int maximumPixels = Math.max(1, Math.min(16, (int) Math.floor(64D / step)));
int blockPixels = Integer.highestOneBit(maximumPixels);
HeightSampler sampler = new HeightSampler(
pixels,
resolution,
startX,
startZ,
step,
complex.getNaturalHeightStream(),
engine.getHeight(),
fluidHeight,
cancelled
);
for (int pixelZ = 0; pixelZ < resolution; pixelZ += blockPixels) {
int height = Math.min(blockPixels, resolution - pixelZ);
for (int pixelX = 0; pixelX < resolution; pixelX += blockPixels) {
sampler.render(pixelX, pixelZ, Math.min(blockPixels, resolution - pixelX), height);
}
}
}
private static void renderRiverAtlas(
int[] pixels,
int resolution,
double startX,
double startZ,
double step,
Engine engine,
BooleanSupplier cancelled,
boolean composite
) {
HydrologyRuntime runtime = engine.getComplex().getHydrologyRuntime();
if (runtime == null || !runtime.enabled() || step > WaterMap.MAX_STEP) {
return;
}
WaterMap map = WaterMap.draw(runtime, resolution, startX, startZ, step, cancelled);
map.drawCavePools(GenerationSemanticQueries.recordedCavePools(engine, Math.floorDiv((int) Math.floor(startX), 16),
Math.floorDiv((int) Math.floor(startZ), 16), Math.floorDiv((int) Math.ceil(startX + resolution * step) - 1, 16),
Math.floorDiv((int) Math.ceil(startZ + resolution * step) - 1, 16)));
for (int pixelZ = 0; pixelZ < resolution; pixelZ++) {
for (int pixelX = 0; pixelX < resolution; pixelX++) {
HydrologyFeatureType type = map.at(pixelX, pixelZ);
if (type == null) {
continue;
}
int index = pixelZ * resolution + pixelX;
int color = hydrologyFeatureColor(type);
pixels[index] = composite ? blend(pixels[index], color, RIVER_OVERLAY) : color;
}
}
if (map.provisional()) {
ProvisionalSampling.mark();
}
}
private PixelShader biomeShader(ProceduralStream<IrisBiome> stream, RenderType currentType) {
IdentityHashMap<IrisBiome, Integer> colors = new IdentityHashMap<>();
return (double x, double z) -> {
@@ -403,19 +230,6 @@ public final class IrisRenderer {
return continentColor(biome);
}
private PixelShader continentShader(ProceduralStream<IrisBiome> stream) {
IdentityHashMap<IrisBiome, Integer> colors = new IdentityHashMap<>();
return (double x, double z) -> {
IrisBiome biome = stream.get(x, z);
Integer color = colors.get(biome);
if (color == null) {
color = continentColor(biome);
colors.put(biome, color);
}
return color;
};
}
private int continentColor(IrisBiome biome) {
if (biome == null) {
return GREEN;
@@ -459,6 +273,7 @@ public final class IrisRenderer {
private final int resolution;
private final WaterMap map;
private boolean complete;
private long poolRevision;
private WaterTile(double startX, double startZ, double step, int resolution) {
this.startX = startX;
@@ -477,13 +292,8 @@ public final class IrisRenderer {
if (composite && (base == null || base.length != resolution * resolution)) {
throw new IllegalArgumentException("Water overlay requires matching base pixels");
}
if (!complete) {
map.advance(cancelled);
map.drawCavePools(GenerationSemanticQueries.recordedCavePools(renderer,
Math.floorDiv((int) Math.floor(startX), 16), Math.floorDiv((int) Math.floor(startZ), 16),
Math.floorDiv((int) Math.ceil(startX + resolution * step) - 1, 16),
Math.floorDiv((int) Math.ceil(startZ + resolution * step) - 1, 16)));
complete = !map.provisional();
if (map != null) {
draw(cancelled);
}
int[] colors = composite ? base.clone() : new int[resolution * resolution];
if (!composite) {
@@ -515,260 +325,27 @@ public final class IrisRenderer {
public long bytes() {
return map == null ? 0L : map.bytes();
}
private void draw(BooleanSupplier cancelled) {
long revision = GenerationSemanticQueries.recordedRiverRevision(renderer);
boolean advanced = !complete;
if (advanced) {
map.advance(cancelled);
complete = !map.provisional();
}
if (!advanced && revision == poolRevision) {
return;
}
map.drawCavePools(GenerationSemanticQueries.recordedCavePools(renderer,
Math.floorDiv((int) Math.floor(startX), 16), Math.floorDiv((int) Math.floor(startZ), 16),
Math.floorDiv((int) Math.ceil(startX + resolution * step) - 1, 16),
Math.floorDiv((int) Math.ceil(startZ + resolution * step) - 1, 16)));
poolRevision = revision;
}
}
@FunctionalInterface
private interface PixelShader {
int color(double x, double z);
}
private static final class AdaptiveSampler {
private final int[] pixels;
private final boolean[] sampled;
private final int resolution;
private final double startX;
private final double startZ;
private final double step;
private final PixelShader shader;
private final BooleanSupplier cancelled;
private AdaptiveSampler(
int[] pixels,
int resolution,
double startX,
double startZ,
double step,
PixelShader shader,
BooleanSupplier cancelled
) {
this.pixels = pixels;
this.sampled = new boolean[pixels.length];
this.resolution = resolution;
this.startX = startX;
this.startZ = startZ;
this.step = step;
this.shader = shader;
this.cancelled = cancelled;
}
private void render(int pixelX, int pixelZ, int width, int height) {
checkCancelled(cancelled);
if (width == 1 && height == 1) {
sample(pixelX, pixelZ);
return;
}
int maximumX = pixelX + width - 1;
int maximumZ = pixelZ + height - 1;
int centerX = pixelX + width / 2;
int centerZ = pixelZ + height / 2;
int color = sample(pixelX, pixelZ);
if (sample(maximumX, pixelZ) == color
&& sample(pixelX, maximumZ) == color
&& sample(maximumX, maximumZ) == color
&& sample(centerX, centerZ) == color) {
fill(pixelX, pixelZ, width, height, color);
return;
}
int leftWidth = Math.max(1, width / 2);
int rightWidth = width - leftWidth;
int topHeight = Math.max(1, height / 2);
int bottomHeight = height - topHeight;
render(pixelX, pixelZ, leftWidth, topHeight);
if (rightWidth > 0) {
render(pixelX + leftWidth, pixelZ, rightWidth, topHeight);
}
if (bottomHeight > 0) {
render(pixelX, pixelZ + topHeight, leftWidth, bottomHeight);
if (rightWidth > 0) {
render(pixelX + leftWidth, pixelZ + topHeight, rightWidth, bottomHeight);
}
}
}
private int sample(int pixelX, int pixelZ) {
int index = pixelZ * resolution + pixelX;
if (!sampled[index]) {
pixels[index] = shader.color(startX + pixelX * step, startZ + pixelZ * step);
sampled[index] = true;
}
return pixels[index];
}
private void fill(int pixelX, int pixelZ, int width, int height, int color) {
for (int row = pixelZ; row < pixelZ + height; row++) {
int start = row * resolution + pixelX;
Arrays.fill(pixels, start, start + width, color);
Arrays.fill(sampled, start, start + width, true);
}
}
}
private static final class HeightSampler {
private static final double MAXIMUM_INTERPOLATION_ERROR = 1.5D;
private final int[] pixels;
private final double[] heights;
private final boolean[] sampled;
private final int resolution;
private final double startX;
private final double startZ;
private final double step;
private final ProceduralStream<Double> stream;
private final double maximumHeight;
private final double fluidHeight;
private final BooleanSupplier cancelled;
private HeightSampler(
int[] pixels,
int resolution,
double startX,
double startZ,
double step,
ProceduralStream<Double> stream,
double maximumHeight,
double fluidHeight,
BooleanSupplier cancelled
) {
this.pixels = pixels;
this.heights = new double[pixels.length];
this.sampled = new boolean[pixels.length];
this.resolution = resolution;
this.startX = startX;
this.startZ = startZ;
this.step = step;
this.stream = stream;
this.maximumHeight = maximumHeight;
this.fluidHeight = fluidHeight;
this.cancelled = cancelled;
}
private void render(int pixelX, int pixelZ, int width, int height) {
checkCancelled(cancelled);
if (width == 1 && height == 1) {
pixels[pixelZ * resolution + pixelX] = heightColor(
sample(pixelX, pixelZ), maximumHeight, fluidHeight);
return;
}
int maximumX = pixelX + width - 1;
int maximumZ = pixelZ + height - 1;
int centerX = pixelX + width / 2;
int centerZ = pixelZ + height / 2;
double topLeft = sample(pixelX, pixelZ);
double topRight = sample(maximumX, pixelZ);
double bottomLeft = sample(pixelX, maximumZ);
double bottomRight = sample(maximumX, maximumZ);
if (matchesPlane(pixelX, pixelZ, width, height, topLeft, topRight, bottomLeft, bottomRight,
centerX, pixelZ)
&& matchesPlane(pixelX, pixelZ, width, height, topLeft, topRight, bottomLeft, bottomRight,
pixelX, centerZ)
&& matchesPlane(pixelX, pixelZ, width, height, topLeft, topRight, bottomLeft, bottomRight,
maximumX, centerZ)
&& matchesPlane(pixelX, pixelZ, width, height, topLeft, topRight, bottomLeft, bottomRight,
centerX, maximumZ)
&& matchesPlane(pixelX, pixelZ, width, height, topLeft, topRight, bottomLeft, bottomRight,
centerX, centerZ)) {
fillPlane(pixelX, pixelZ, width, height, topLeft, topRight, bottomLeft, bottomRight);
return;
}
int leftWidth = Math.max(1, width / 2);
int rightWidth = width - leftWidth;
int topHeight = Math.max(1, height / 2);
int bottomHeight = height - topHeight;
render(pixelX, pixelZ, leftWidth, topHeight);
if (rightWidth > 0) {
render(pixelX + leftWidth, pixelZ, rightWidth, topHeight);
}
if (bottomHeight > 0) {
render(pixelX, pixelZ + topHeight, leftWidth, bottomHeight);
if (rightWidth > 0) {
render(pixelX + leftWidth, pixelZ + topHeight, rightWidth, bottomHeight);
}
}
}
private boolean matchesPlane(
int pixelX,
int pixelZ,
int width,
int height,
double topLeft,
double topRight,
double bottomLeft,
double bottomRight,
int sampleX,
int sampleZ
) {
double predicted = interpolate(
pixelX,
pixelZ,
width,
height,
topLeft,
topRight,
bottomLeft,
bottomRight,
sampleX,
sampleZ
);
return Math.abs(sample(sampleX, sampleZ) - predicted) <= MAXIMUM_INTERPOLATION_ERROR;
}
private void fillPlane(
int pixelX,
int pixelZ,
int width,
int height,
double topLeft,
double topRight,
double bottomLeft,
double bottomRight
) {
for (int row = pixelZ; row < pixelZ + height; row++) {
int offset = row * resolution;
for (int column = pixelX; column < pixelX + width; column++) {
double value = interpolate(
pixelX,
pixelZ,
width,
height,
topLeft,
topRight,
bottomLeft,
bottomRight,
column,
row
);
pixels[offset + column] = heightColor(value, maximumHeight, fluidHeight);
}
}
}
private double sample(int pixelX, int pixelZ) {
int index = pixelZ * resolution + pixelX;
if (!sampled[index]) {
heights[index] = stream.getDouble(startX + pixelX * step, startZ + pixelZ * step);
sampled[index] = true;
}
return heights[index];
}
private static double interpolate(
int pixelX,
int pixelZ,
int width,
int height,
double topLeft,
double topRight,
double bottomLeft,
double bottomRight,
int sampleX,
int sampleZ
) {
double x = width <= 1 ? 0D : (sampleX - pixelX) / (double) (width - 1);
double z = height <= 1 ? 0D : (sampleZ - pixelZ) / (double) (height - 1);
double top = topLeft + (topRight - topLeft) * x;
double bottom = bottomLeft + (bottomRight - bottomLeft) * x;
return top + (bottom - top) * z;
}
}
}
@@ -19,5 +19,5 @@
package art.arcane.iris.studio.render;
public enum RenderType {
BIOME, BIOME_LAND, BIOME_SEA, REGION, CAVE_LAND, RIVER, HEIGHT, OBJECT_LOAD, DECORATOR_LOAD, CONTINENT, LAYER_LOAD
BIOME, BIOME_LAND, BIOME_SEA, REGION, CAVE_LAND, HEIGHT, OBJECT_LOAD, DECORATOR_LOAD, CONTINENT, LAYER_LOAD
}
@@ -24,12 +24,8 @@ import java.util.function.BooleanSupplier;
final class WaterMap {
static final double RASTER_STEP = 2D;
static final double MAX_STEP = 16D;
static final List<HydrologyFeatureType> DRAWN = List.of(HydrologyFeatureType.WATERFALL, HydrologyFeatureType.CASCADE,
HydrologyFeatureType.MOUTH, HydrologyFeatureType.MAJOR_RIVER, HydrologyFeatureType.RIVER, HydrologyFeatureType.STREAM,
HydrologyFeatureType.SEA_INLET, HydrologyFeatureType.LAKE, HydrologyFeatureType.POND, HydrologyFeatureType.DAM,
HydrologyFeatureType.CAVE_POOL);
static final List<HydrologyFeatureType> DRAWN = drawn();
private static final int DRY = Integer.MAX_VALUE;
private static final int[] RANK = ranks();
private final HydrologyRuntime runtime;
private final int resolution;
@@ -57,12 +53,6 @@ final class WaterMap {
provisional = true;
}
static WaterMap draw(HydrologyRuntime runtime, int resolution, double startX, double startZ, double step, BooleanSupplier cancelled) {
WaterMap map = new WaterMap(runtime, resolution, startX, startZ, step);
map.advance(cancelled);
return map;
}
void advance(BooleanSupplier cancelled) {
if (!provisional) {
return;
@@ -280,7 +270,7 @@ final class WaterMap {
int lastX = Math.min(resolution - 1, (int) Math.floor((centreX + half - 1 - startX) / step));
for (int pixelZ = firstZ; pixelZ <= lastZ; pixelZ++) {
for (int pixelX = firstX; pixelX <= lastX; pixelX++) {
ranks[pixelZ * resolution + pixelX] = RANK[type.ordinal()];
stamp(pixelX, pixelZ, type);
}
}
}
@@ -296,7 +286,7 @@ final class WaterMap {
return;
}
int index = pixelZ * resolution + pixelX;
int rank = RANK[type.ordinal()];
int rank = rank(type);
if (rank < ranks[index]) {
ranks[index] = rank;
}
@@ -308,12 +298,31 @@ final class WaterMap {
}
}
private static int[] ranks() {
int[] ranks = new int[HydrologyFeatureType.values().length];
Arrays.fill(ranks, DRY);
for (int index = 0; index < DRAWN.size(); index++) {
ranks[DRAWN.get(index).ordinal()] = index;
private static int rank(HydrologyFeatureType type) {
return switch (type) {
case WATERFALL -> 0;
case CASCADE -> 1;
case MOUTH -> 2;
case MAJOR_RIVER -> 3;
case RIVER -> 4;
case STREAM -> 5;
case SEA_INLET -> 6;
case POND -> 7;
case LAKE -> 8;
case DAM -> 9;
case CAVE_POOL -> 10;
};
}
private static List<HydrologyFeatureType> drawn() {
HydrologyFeatureType[] drawn = new HydrologyFeatureType[HydrologyFeatureType.values().length];
for (HydrologyFeatureType type : HydrologyFeatureType.values()) {
int rank = rank(type);
if (drawn[rank] != null) {
throw new IllegalStateException("Water map ranks " + drawn[rank] + " and " + type + " equally");
}
drawn[rank] = type;
}
return ranks;
return List.of(drawn);
}
}
@@ -139,7 +139,6 @@ public class IrisPackageCompiler {
exportedDimension.getEntitySpawners().forEach((sp) ->
addIfPresent(spawners, dm.getSpawnerLoader().load(sp)));
}
regions.forEach((i) -> biomes.addAll(i.getAllBiomes(() -> dm)));
regions.forEach((r) -> r.getLoot().getTables().forEach((i) -> addIfPresent(loot, dm.getLootLoader().load(i))));
regions.forEach((r) -> r.getEntitySpawners().forEach((sp) -> addIfPresent(spawners, dm.getSpawnerLoader().load(sp))));
biomes.forEach((i) -> i.getGenerators().forEach((j) -> addIfPresent(generators, j.getCachedGenerator(() -> dm))));
@@ -28,7 +28,7 @@ public final class ChunkGenerationSemantics {
.thenComparingInt(point -> point.position().y());
private static final Comparator<RiverFeatureOccurrence> RIVER_FEATURE_COMPARATOR = Comparator
.comparing(RiverFeatureOccurrence::profileKey)
.thenComparing(RiverFeatureOccurrence::type)
.thenComparingInt(occurrence -> occurrence.type().code())
.thenComparingInt(occurrence -> occurrence.position().x())
.thenComparingInt(occurrence -> occurrence.position().z())
.thenComparingInt(occurrence -> occurrence.position().y())
@@ -866,6 +866,10 @@ public final class GenerationHistory {
return semantics.get(chunkX, chunkZ);
}
public long riverRevision() {
return semantics.riverRevision();
}
public synchronized Optional<GenerationSemanticIndex.Match> findRecorded(
GenerationSemanticIndex.Query query
) {
@@ -277,7 +277,7 @@ public final class GenerationSemanticCapture {
blockX,
y,
blockZ,
cell == null ? null : cell.floodedBiomeKey()
null
);
if (cell != null && cell.isWet() && cell.fluidProfileKey() != null && !cell.fluidProfileKey().isBlank()
&& !HydrologyCaveCell.SEA_FLUID.equals(cell.fluidProfileKey())) {
@@ -45,6 +45,7 @@ import java.util.Optional;
import java.util.OptionalLong;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Predicate;
@@ -96,6 +97,7 @@ public final class GenerationSemanticIndex {
private final CatalogPublisher catalogPublisher;
private final boolean unpublished;
private final DeferredDurability durability;
private final AtomicLong riverRevision = new AtomicLong();
private long regionDecodeCount;
private volatile IOException journalFailure;
private long appendingRegionKey;
@@ -245,6 +247,7 @@ public final class GenerationSemanticIndex {
RegionShard baseRegion = loadRegionLocked(regionKey, regionX, regionZ);
RegionShard nextRegion = baseRegion;
List<ChunkGenerationSemantics> updates = new ArrayList<>(claims.size());
boolean water = false;
for (Claim pending : claims) {
ChunkGenerationSemantics update = pending.update;
ChunkGenerationSemantics existing = nextRegion.get(update.chunkX(), update.chunkZ());
@@ -261,6 +264,7 @@ public final class GenerationSemanticIndex {
}
nextRegion = nextRegion.withRecord(merged);
updates.add(merged);
water |= waterChanged(existing, merged);
pending.persisted = true;
}
if (updates.isEmpty()) {
@@ -286,6 +290,9 @@ public final class GenerationSemanticIndex {
cacheRegion(regionKey, nextRegion);
regionRecordCounts.put(regionKey, nextRegion.recordCount());
journalEntries.addTo(regionKey, updates.size());
if (water) {
riverRevision.incrementAndGet();
}
for (Claim pending : claims) {
pending.completed = true;
}
@@ -452,6 +459,9 @@ public final class GenerationSemanticIndex {
if (existing == null) {
regionRecordCounts.addTo(regionKey, 1);
}
if (waterChanged(existing, merged)) {
riverRevision.incrementAndGet();
}
shardHashes.put(regionKey, shardHash);
deleteUnreferencedShard(regionX, regionZ, previousHash, shardHash);
return true;
@@ -473,6 +483,10 @@ public final class GenerationSemanticIndex {
}
}
public long riverRevision() {
return riverRevision.get();
}
public int recordCount() {
lock.readLock().lock();
publicationLock.lock();
@@ -1153,6 +1167,10 @@ public final class GenerationSemanticIndex {
}
}
private static boolean waterChanged(ChunkGenerationSemantics existing, ChunkGenerationSemantics merged) {
return existing == null ? !merged.riverFeatures().isEmpty() : !existing.riverFeatures().equals(merged.riverFeatures());
}
private static Set<String> keys(ChunkGenerationSemantics semantics, SemanticKind kind) {
return switch (kind) {
case SURFACE_BIOME -> semantics.surfaceBiomeKeys();
@@ -1750,14 +1768,14 @@ public final class GenerationSemanticIndex {
} else if (riverTypeCount > HydrologyFeatureType.values().length) {
throw invalid(source, "invalid summary river type count " + riverTypeCount);
}
int previousOrdinal = -1;
int previousCode = -1;
for (int index = 0; index < riverTypeCount; index++) {
int ordinal = input.readUnsignedByte();
if (ordinal <= previousOrdinal || ordinal >= HydrologyFeatureType.values().length) {
throw invalid(source, "invalid summary river type ordinal " + ordinal);
int code = input.readUnsignedByte();
if (code <= previousCode) {
throw invalid(source, "summary river type codes are not in canonical order");
}
riverTypes.add(HydrologyFeatureType.values()[ordinal]);
previousOrdinal = ordinal;
riverTypes.add(RegionShard.riverFeatureType(source, code));
previousCode = code;
}
LongOpenHashSet activations = readActivations(source, input, "summary activation");
LongOpenHashSet sealedActivations = readActivations(source, input, "sealed summary activation");
@@ -1791,8 +1809,8 @@ public final class GenerationSemanticIndex {
}
}
output.writeByte(riverTypes.size());
for (HydrologyFeatureType type : riverTypes) {
output.writeByte(type.ordinal());
for (int code : riverTypes.stream().mapToInt(HydrologyFeatureType::code).sorted().toArray()) {
output.writeByte(code);
}
writeActivations(output, activations);
writeActivations(output, sealedActivations);
@@ -2707,7 +2725,7 @@ public final class GenerationSemanticIndex {
output.writeShort(semantics.riverFeatures().size());
for (ChunkGenerationSemantics.RiverFeatureOccurrence occurrence : semantics.riverFeatures()) {
output.writeShort(paletteIndexes.get(occurrence.profileKey()));
output.writeByte(occurrence.type().ordinal());
output.writeByte(occurrence.type().code());
output.writeLong(occurrence.featureId());
output.writeInt(occurrence.position().x());
output.writeInt(occurrence.position().y());
@@ -2916,21 +2934,17 @@ public final class GenerationSemanticIndex {
return;
}
ChunkGenerationSemantics.RiverFeatureOccurrence previous = null;
HydrologyFeatureType[] types = HydrologyFeatureType.values();
for (int index = 0; index < count; index++) {
int paletteIndex = input.readUnsignedShort();
if (paletteIndex >= palette.length) {
throw invalid(file, "river profile key palette index is out of range");
}
int typeOrdinal = input.readUnsignedByte();
if (typeOrdinal >= types.length) {
throw invalid(file, "river feature type ordinal is out of range");
}
HydrologyFeatureType type = riverFeatureType(file, input.readUnsignedByte());
paletteUsed[paletteIndex] = true;
ChunkGenerationSemantics.RiverFeatureOccurrence occurrence =
new ChunkGenerationSemantics.RiverFeatureOccurrence(
palette[paletteIndex],
types[typeOrdinal],
type,
input.readLong(),
new ChunkGenerationSemantics.BlockPosition(
input.readInt(),
@@ -2948,6 +2962,14 @@ public final class GenerationSemanticIndex {
}
}
private static HydrologyFeatureType riverFeatureType(Path file, int code) throws IOException {
try {
return HydrologyFeatureType.fromCode(code);
} catch (IllegalStateException unknown) {
throw invalid(file, unknown.getMessage(), unknown);
}
}
private static void skipLegacyRiverFeatures(
Path file,
DataInputStream input,
@@ -9,6 +9,7 @@ import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType;
import art.arcane.iris.generation.hydrology.query.HydrologySearchTimeoutException;
import java.math.BigInteger;
import java.io.IOException;
@@ -21,11 +22,18 @@ import java.util.Objects;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.function.Predicate;
import java.util.function.BooleanSupplier;
public final class GenerationSemanticQueries {
public static final int RIVER_SEARCH_DISTANCE = 7168;
private static final ConcurrentHashMap<UUID, CompletableFuture<RiverSearch>> RIVER_SEARCHES = new ConcurrentHashMap<>();
private GenerationSemanticQueries() {
}
@@ -153,15 +161,41 @@ public final class GenerationSemanticQueries {
IrisStructureLocator.LocateStatus.FOUND, position.x(), position.y(), position.z());
}
public static Optional<RiverResult> nearestRiver(
public static CompletableFuture<RiverSearch> startRiverSearch(
UUID searcher,
Executor executor,
Engine engine,
HydrologyFeatureType type,
int blockX,
int blockZ
) {
UUID requiredSearcher = Objects.requireNonNull(searcher, "searcher");
Executor requiredExecutor = Objects.requireNonNull(executor, "executor");
CompletableFuture<RiverSearch> search = new CompletableFuture<>();
CompletableFuture<RiverSearch> previous = RIVER_SEARCHES.put(requiredSearcher, search);
if (previous != null) {
previous.cancel(false);
}
search.whenComplete((result, failure) -> RIVER_SEARCHES.remove(requiredSearcher, search));
try {
requiredExecutor.execute(() -> runRiverSearch(search, engine, type, blockX, blockZ));
} catch (RejectedExecutionException rejected) {
search.completeExceptionally(rejected);
}
return search;
}
public static RiverSearch nearestRiver(
Engine engine,
HydrologyFeatureType type,
int blockX,
int blockZ,
int maximumDistance
int maximumDistance,
BooleanSupplier running
) {
Engine requiredEngine = Objects.requireNonNull(engine, "engine");
HydrologyFeatureType requiredType = Objects.requireNonNull(type, "type");
Objects.requireNonNull(running, "running");
if (maximumDistance < 0) {
throw new IllegalArgumentException("Maximum river search distance cannot be negative.");
}
@@ -173,23 +207,63 @@ public final class GenerationSemanticQueries {
blockZ,
maximumDistance
);
RiverResult active = recordedOnly(requiredType) ? null : activeRiver(
requiredEngine,
history,
requiredType,
blockX,
blockZ,
maximumDistance
);
Optional<String> unavailable = requiredEngine.getComplex().getHydrologyRuntime().unavailable(requiredType);
if (recordedOnly(requiredType) || unavailable.isPresent()) {
if (recorded != null) {
return new RiverSearch.Found(recorded);
}
return new RiverSearch.Missing(unavailable.map(reason -> riverUnavailableMessage(requiredType, reason))
.orElseGet(() -> riverNotFoundMessage(requiredType, maximumDistance)));
}
int activeDistance = recorded == null ? maximumDistance : Math.min(maximumDistance, distanceCeiling(blockX, blockZ, recorded));
RiverResult active;
try {
active = activeRiver(requiredEngine, history, requiredType, blockX, blockZ, activeDistance, running);
} catch (HydrologySearchTimeoutException timedOut) {
RiverResult planned = timedOut.nearestSoFar().map(feature -> activeResult(requiredEngine, history, feature)).orElse(null);
return stoppedSearch(requiredType, nearer(blockX, blockZ, recorded, planned));
}
RiverResult nearest = nearer(blockX, blockZ, recorded, active);
return nearest == null
? new RiverSearch.Missing(riverNotFoundMessage(requiredType, maximumDistance))
: new RiverSearch.Found(nearest);
}
private static void runRiverSearch(
CompletableFuture<RiverSearch> search,
Engine engine,
HydrologyFeatureType type,
int blockX,
int blockZ
) {
if (search.isDone()) {
return;
}
try {
search.complete(nearestRiver(engine, type, blockX, blockZ, RIVER_SEARCH_DISTANCE, () -> !search.isDone()));
} catch (CancellationException stopped) {
search.completeExceptionally(new IllegalStateException(stopped.getMessage(), stopped));
} catch (Throwable failure) {
search.completeExceptionally(failure);
}
}
private static int distanceCeiling(int blockX, int blockZ, RiverResult feature) {
BigInteger squared = horizontalDistanceSquared(blockX, blockZ, feature.x(), feature.z());
BigInteger root = squared.sqrt();
return (root.multiply(root).equals(squared) ? root : root.add(BigInteger.ONE)).intValueExact();
}
private static RiverResult nearer(int blockX, int blockZ, RiverResult recorded, RiverResult active) {
if (recorded == null) {
return Optional.ofNullable(active);
return active;
}
if (active == null) {
return Optional.of(recorded);
return recorded;
}
int comparison = horizontalDistanceSquared(blockX, blockZ, recorded.x(), recorded.z())
.compareTo(horizontalDistanceSquared(blockX, blockZ, active.x(), active.z()));
return Optional.of(comparison <= 0 ? recorded : active);
return comparison <= 0 ? recorded : active;
}
private static boolean recordedOnly(HydrologyFeatureType type) {
@@ -197,14 +271,32 @@ public final class GenerationSemanticQueries {
}
public static String riverSearchMessage(HydrologyFeatureType type, int maximumDistance) {
String label = type.key().replace('_', ' ');
String label = label(type);
return recordedOnly(type)
? "Searching generated chunks for the nearest " + label + " within " + maximumDistance + " blocks..."
: "Searching for the nearest " + label + " within " + maximumDistance + " blocks...";
}
public static String riverNotFoundMessage(HydrologyFeatureType type, int maximumDistance) {
String label = type.key().replace('_', ' ');
private static String riverUnavailableMessage(HydrologyFeatureType type, String reason) {
return "No " + label(type) + " forms in this dimension: " + reason + ".";
}
private static RiverSearch stoppedSearch(HydrologyFeatureType type, RiverResult nearestSoFar) {
String stopped = "Stopped searching for the nearest " + label(type) + " after "
+ HydrologyRuntime.FEATURE_SEARCH_TIMEOUT.toSeconds() + " seconds";
if (nearestSoFar == null) {
return new RiverSearch.Stopped(Optional.empty(), stopped + " without finding one.");
}
return new RiverSearch.Stopped(Optional.of(nearestSoFar), stopped + ". The nearest " + label(type) + " found so far is at "
+ nearestSoFar.x() + ", " + nearestSoFar.y() + ", " + nearestSoFar.z() + "; a nearer one may exist.");
}
private static String label(HydrologyFeatureType type) {
return type.key().replace('_', ' ');
}
private static String riverNotFoundMessage(HydrologyFeatureType type, int maximumDistance) {
String label = label(type);
return recordedOnly(type)
? "No " + label + " found in generated chunks within " + maximumDistance + " blocks. Cave pools form in carved caves, so "
+ "only chunks that have already generated can hold one."
@@ -239,6 +331,11 @@ public final class GenerationSemanticQueries {
return pools;
}
public static long recordedRiverRevision(Engine engine) {
GenerationHistory history = history(Objects.requireNonNull(engine, "engine")).orElse(null);
return history == null ? 0L : history.riverRevision();
}
public static boolean allowsActivePrediction(Engine engine, int chunkX, int chunkZ) {
Engine requiredEngine = Objects.requireNonNull(engine, "engine");
if (!requiredEngine.getComplex().allowsNewGenerationChunk(chunkX, chunkZ)) {
@@ -300,12 +397,10 @@ public final class GenerationSemanticQueries {
HydrologyFeatureType type,
int blockX,
int blockZ,
int maximumDistance
) {
int maximumDistance,
BooleanSupplier running
) throws HydrologySearchTimeoutException {
HydrologyRuntime runtime = engine.getComplex().getHydrologyRuntime();
if (runtime == null || !runtime.enabled()) {
return null;
}
Map<Long, Boolean> eligibleChunks = new HashMap<>();
TransitionDisplacementField displacement = engine.getComplex().getTransitionDisplacement();
Predicate<HydrologyFeatureRef> eligibility = feature -> (displacement == null
@@ -317,11 +412,13 @@ public final class GenerationSemanticQueries {
blockZ,
HydrologyFeatureQuery.of(type),
maximumDistance,
eligibility
eligibility,
running
).orElse(null);
if (feature == null) {
return null;
}
return feature == null ? null : activeResult(engine, history, feature);
}
private static RiverResult activeResult(Engine engine, GenerationHistory history, HydrologyFeatureRef feature) {
OptionalLong activationId = history == null
? OptionalLong.empty()
: OptionalLong.of(history.activeActivation().activationId());
@@ -379,4 +476,25 @@ public final class GenerationSemanticQueries {
activationId = Objects.requireNonNull(activationId, "activationId");
}
}
public sealed interface RiverSearch {
record Found(RiverResult feature) implements RiverSearch {
public Found {
Objects.requireNonNull(feature, "feature");
}
}
record Missing(String message) implements RiverSearch {
public Missing {
Objects.requireNonNull(message, "message");
}
}
record Stopped(Optional<RiverResult> nearestSoFar, String message) implements RiverSearch {
public Stopped {
Objects.requireNonNull(nearestSoFar, "nearestSoFar");
Objects.requireNonNull(message, "message");
}
}
}
}
@@ -114,11 +114,9 @@ final class TransitionBoundarySampler {
Math.min(distance, terrainWidth),
terrainWidth
);
double hydrologyWeight = newEpochWeight;
return new TransitionGenerationPlan.TerrainSample(
Math.min(distance, searchWidth),
newEpochWeight,
hydrologyWeight,
nearest.signatures[0],
weightedHeight(nearest, true),
weightedHeight(nearest, false),
@@ -88,10 +88,6 @@ public final class TransitionGenerationPlan {
return terrainSampleAt(blockX, blockZ).newEpochWeight();
}
public double hydrologyWeightAt(int blockX, int blockZ) {
return terrainSampleAt(blockX, blockZ).hydrologyWeight();
}
public boolean allowsNewDiscreteContentAt(int blockX, int blockZ) {
return !boundary.isHistoricalBlock(blockX, blockZ);
}
@@ -191,7 +187,6 @@ public final class TransitionGenerationPlan {
public record TerrainSample(
double distanceToHistoricalTerrain,
double newEpochWeight,
double hydrologyWeight,
TerrainBoundarySignature nearestSignature,
double historicalSurfaceHeight,
double historicalOceanFloorHeight,
@@ -204,9 +199,6 @@ public final class TransitionGenerationPlan {
if (!Double.isFinite(newEpochWeight) || newEpochWeight < 0D || newEpochWeight > 1D) {
throw new IllegalArgumentException("New epoch weight must be between zero and one");
}
if (!Double.isFinite(hydrologyWeight) || hydrologyWeight < 0D || hydrologyWeight > 1D) {
throw new IllegalArgumentException("Hydrology weight must be between zero and one");
}
if (nearestSignature != null
&& (!Double.isFinite(historicalSurfaceHeight)
|| !Double.isFinite(historicalOceanFloorHeight)
@@ -217,11 +209,11 @@ public final class TransitionGenerationPlan {
}
static TerrainSample newTerrain(double distance) {
return new TerrainSample(distance, 1D, 1D, null, 0D, 0D, 0D);
return new TerrainSample(distance, 1D, null, 0D, 0D, 0D);
}
static TerrainSample historicalTerrain() {
return new TerrainSample(0D, 0D, 0D, null, 0D, 0D, 0D);
return new TerrainSample(0D, 0D, null, 0D, 0D, 0D);
}
public boolean hasHistoricalSignature() {
@@ -62,7 +62,6 @@ public class MedievalPregenMethod implements PregeneratorMethod {
private final Executor chunkIoExecutor;
private final PregenSerialWorker chunkFlush;
private volatile Engine cachedEngine;
private volatile boolean engineResolutionAttempted;
private final AtomicBoolean closing = new AtomicBoolean();
private final PregenHydrology hydrology = new PregenHydrology(this::resolveEngine);
@@ -99,10 +98,6 @@ public class MedievalPregenMethod implements PregeneratorMethod {
if (cached != null) {
return cached;
}
if (engineResolutionAttempted) {
return null;
}
engineResolutionAttempted = true;
try {
if (!IrisToolbelt.isIrisWorld(world)) {
return null;
@@ -29,19 +29,20 @@ public final class HydrologyCaveMatter extends RawMatter<HydrologyCaveCell> {
public void writeNode(HydrologyCaveCell hydrology, DataOutputStream output) throws IOException {
output.writeByte(actionCode(hydrology.action()));
output.writeUTF(hydrology.fluidProfileKey());
output.writeUTF(hydrology.floodedBiomeKey());
output.writeUTF("");
}
@Override
public HydrologyCaveCell readNode(DataInputStream input) throws IOException {
HydrologyCaveAction action = actionFromCode(input.readUnsignedByte());
return new HydrologyCaveCell(action, input.readUTF(), input.readUTF());
String fluidProfileKey = input.readUTF();
input.readUTF();
return new HydrologyCaveCell(action, fluidProfileKey);
}
private int actionCode(HydrologyCaveAction action) {
return switch (action) {
case WET_SOURCE -> 1;
case FALLING_FLUID -> 2;
case DRY_AIR -> 3;
case SEAL_GUARD -> 4;
case POOL_SOURCE -> 5;
@@ -50,8 +51,7 @@ public final class HydrologyCaveMatter extends RawMatter<HydrologyCaveCell> {
private HydrologyCaveAction actionFromCode(int code) throws IOException {
return switch (code) {
case 1 -> HydrologyCaveAction.WET_SOURCE;
case 2 -> HydrologyCaveAction.FALLING_FLUID;
case 1, 2 -> HydrologyCaveAction.WET_SOURCE;
case 3 -> HydrologyCaveAction.DRY_AIR;
case 4 -> HydrologyCaveAction.SEAL_GUARD;
case 5 -> HydrologyCaveAction.POOL_SOURCE;
@@ -0,0 +1,129 @@
package art.arcane.iris.generation.hydrology;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType;
import art.arcane.iris.generation.hydrology.water.PondKind;
import art.arcane.iris.generation.hydrology.water.ReachStyle;
import org.junit.Test;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.IntFunction;
import java.util.function.ToIntFunction;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class PersistedCodesTest {
private static final Map<HydrologyFeatureType, Integer> FEATURE_TYPE_CODES = Map.ofEntries(
Map.entry(HydrologyFeatureType.STREAM, 0),
Map.entry(HydrologyFeatureType.RIVER, 1),
Map.entry(HydrologyFeatureType.MAJOR_RIVER, 2),
Map.entry(HydrologyFeatureType.CASCADE, 3),
Map.entry(HydrologyFeatureType.WATERFALL, 4),
Map.entry(HydrologyFeatureType.MOUTH, 5),
Map.entry(HydrologyFeatureType.POND, 6),
Map.entry(HydrologyFeatureType.LAKE, 7),
Map.entry(HydrologyFeatureType.DAM, 8),
Map.entry(HydrologyFeatureType.SEA_INLET, 9),
Map.entry(HydrologyFeatureType.CAVE_POOL, 10));
private static final Map<ReachStyle, Integer> REACH_STYLE_CODES = Map.of(
ReachStyle.RUN, 0,
ReachStyle.RIFFLE, 1,
ReachStyle.CASCADE, 2,
ReachStyle.WATERFALL, 3,
ReachStyle.POND_OUTLET, 4,
ReachStyle.MOUTH, 5);
private static final Map<PondKind, Integer> POND_KIND_CODES = Map.of(
PondKind.NATURAL, 0,
PondKind.SEEDED, 1,
PondKind.CHAINED, 2,
PondKind.LAKE, 3);
@Test
public void codesAreUniqueAndPinned() {
assertPinned(HydrologyFeatureType.class, FEATURE_TYPE_CODES, HydrologyFeatureType::code, HydrologyFeatureType::fromCode);
assertPinned(ReachStyle.class, REACH_STYLE_CODES, ReachStyle::code, ReachStyle::fromCode);
assertPinned(PondKind.class, POND_KIND_CODES, PondKind::code, PondKind::fromCode);
}
@Test
public void unknownCodesFailClosed() {
assertUnknown("HydrologyFeatureType", FEATURE_TYPE_CODES, HydrologyFeatureType::fromCode);
assertUnknown("ReachStyle", REACH_STYLE_CODES, ReachStyle::fromCode);
assertUnknown("PondKind", POND_KIND_CODES, PondKind::fromCode);
}
@Test
public void conflictingCodesAreRejected() {
try {
PersistedCodes.of(SharedCode.class, SharedCode::code);
fail("two constants share code 7");
} catch (IllegalStateException expected) {
assertTrue(expected.getMessage(), expected.getMessage().contains("SharedCode") && expected.getMessage().contains("7"));
}
try {
PersistedCodes.of(WideCode.class, WideCode::code);
fail("code 256 does not fit one byte");
} catch (IllegalStateException expected) {
assertTrue(expected.getMessage(), expected.getMessage().contains("WideCode") && expected.getMessage().contains("256"));
}
}
private static <E extends Enum<E>> void assertPinned(Class<E> type, Map<E, Integer> pins, ToIntFunction<E> code,
IntFunction<E> fromCode) {
assertEquals(type.getSimpleName() + " constants need a pinned code", EnumSet.allOf(type), pins.keySet());
Set<Integer> seen = new HashSet<>();
for (E constant : type.getEnumConstants()) {
int pinned = pins.get(constant);
assertEquals(type.getSimpleName() + "." + constant.name(), pinned, code.applyAsInt(constant));
assertTrue(type.getSimpleName() + " reuses code " + pinned, seen.add(pinned));
assertSame(constant, fromCode.apply(pinned));
}
}
private static <E extends Enum<E>> void assertUnknown(String name, Map<E, Integer> pins, IntFunction<E> fromCode) {
int unused = Collections.max(pins.values()) + 1;
for (int code : new int[]{-1, unused, 256}) {
try {
fromCode.apply(code);
fail(name + " decoded unknown code " + code);
} catch (IllegalStateException expected) {
assertTrue(expected.getMessage(), expected.getMessage().contains(name) && expected.getMessage().contains(Integer.toString(code)));
}
}
}
private enum SharedCode {
FIRST(7),
SECOND(7);
private final int code;
SharedCode(int code) {
this.code = code;
}
private int code() {
return code;
}
}
private enum WideCode {
ONLY(256);
private final int code;
WideCode(int code) {
this.code = code;
}
private int code() {
return code;
}
}
}
@@ -19,7 +19,7 @@ public class HydrologyCaveStorageTest {
MantleChunk<Matter> chunk = mock(MantleChunk.class);
Matter matter = mock(Matter.class);
MatterSlice<HydrologyCaveCell> slice = mock(MatterSlice.class);
HydrologyCaveCell expected = HydrologyCaveCell.of(HydrologyCaveAction.WET_SOURCE);
HydrologyCaveCell expected = new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "water");
when(chunk.exists(2)).thenReturn(true);
when(chunk.get(2)).thenReturn(matter);
when(matter.hasSlice(HydrologyCaveCell.class)).thenReturn(true);
@@ -83,6 +83,7 @@ public class IrisHydrologyDefaultsTest {
assertNull(policy.getDecorators());
assertNull(policy.getShoreBiomes());
assertNull(policy.getShoreBiomeWidth());
assertNull(policy.getWetness());
}
@Test
Loaded 100 of 171 files, more files were not shown because too many files have changed in this diff. Show more