Carve port tests: CarveTestWorld/Terrain fixtures, carving resolver parity against Iris's generators, cave carving, applying and mantle facade tests; the jar test lists carve; mantle stages see 16 blocks of terrain

This commit is contained in:
piexel committed 2026-10-12 02:19:37 +02:00
1 parent d15c3480ab
commit 4f69881e1f
20 files changed
+1290 -930

No files matched your search

@@ -24,7 +24,9 @@ import art.arcane.iris.builtin.carve.CarvingEnabledSettings;
import art.arcane.iris.builtin.carve.CarvingEntry;
import art.arcane.iris.builtin.carve.CarvingSettings;
import art.arcane.iris.builtin.carve.CaveDepthSettings;
import art.arcane.iris.builtin.carve.CaveLavaHeightSettings;
import art.arcane.iris.builtin.carve.CaveProfile;
import art.arcane.iris.builtin.carve.UpperDimensionCarvingSettings;
import art.arcane.volmlib.util.json.JSONObject;
import com.google.gson.Gson;
import com.volmit.FeatureAttachment.Target;
@@ -188,9 +190,21 @@ public class CarveSettingsDecodingTest {
assertEquals(Set.of(), settings.usedBiomes(ModuleSettings.NONE));
}
@Test
public void theOverworldReadsItsUpperDimensionCarvingAndANumberIsTheCaveLavaHeight() throws IOException {
ModuleSettings overworld = decoder.decode(Target.DIMENSION, file("dimensions/overworld.json"), "dimension overworld");
assertFalse(overworld.find(UpperDimensionCarvingSettings.class).orElseThrow().enabled());
assertTrue("the overworld writes no cave lava height", overworld.find(CaveLavaHeightSettings.class).isEmpty());
ModuleSettings written = decoder.decode(Target.DIMENSION, new JSONObject("{\"caveLavaHeight\": 18, \"upperDimensionCarving\": true}"), "dimension test");
assertEquals(18, written.find(CaveLavaHeightSettings.class).orElseThrow().height());
assertTrue(written.find(UpperDimensionCarvingSettings.class).orElseThrow().enabled());
assertEquals(8, CaveLavaHeightSettings.DEFAULT_HEIGHT);
}
@Test
public void everyKeyIsOnlyReadAtTheLevelsTheOldFieldExistedAt() {
assertTrue(decoder.keys(Target.DIMENSION).containsAll(List.of("caveProfile", "carving", "carvingEnabled")));
assertTrue(decoder.keys(Target.DIMENSION).containsAll(List.of("caveProfile", "carving", "carvingEnabled", "caveLavaHeight", "upperDimensionCarving")));
assertTrue(decoder.keys(Target.REGION).contains("caveProfile"));
assertTrue(decoder.keys(Target.BIOME).containsAll(List.of("caveProfile", "carvingBiome", "caveMinDepthBelowSurface")));
assertFalse(decoder.keys(Target.REGION).contains("carving"));
@@ -0,0 +1,111 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.modules;
import com.volmit.mantle.BlockBox;
import com.volmit.resource.ResourceId;
import com.volmit.world.BiomeSample;
import com.volmit.world.TerrainSample;
import com.volmit.world.TerrainSampler;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.function.IntBinaryOperator;
/** Terrain for the tests of the carve module: a surface height per column, a biome sample per block and an optional dimension above. */
public final class CarveTestTerrain implements TerrainSampler {
private static final int MARGIN = 16;
/** The biome sample of a block. */
@FunctionalInterface
public interface Biomes {
BiomeSample at(int x, int y, int z);
}
private final int originX;
private final int originZ;
private final int height;
private final int fluidHeight;
private final IntBinaryOperator surface;
private Biomes biomes = (x, y, z) -> new BiomeSample(CarveTestWorld.id("region"), CarveTestWorld.id("plains"), Optional.empty());
private IntBinaryOperator upper;
public CarveTestTerrain(int originX, int originZ, int height, int fluidHeight, IntBinaryOperator surface) {
this.originX = originX;
this.originZ = originZ;
this.height = height;
this.fluidHeight = fluidHeight;
this.surface = surface;
}
public CarveTestTerrain biomes(Biomes biomes) {
this.biomes = biomes;
return this;
}
public CarveTestTerrain upperDimension(IntBinaryOperator upper) {
this.upper = upper;
return this;
}
@Override
public BlockBox bounds() {
return new BlockBox(originX - MARGIN, 0, originZ - MARGIN, originX + 16 + MARGIN, height, originZ + 16 + MARGIN);
}
@Override
public TerrainSample column(int worldX, int worldZ) {
int surfaceY = surface.applyAsInt(worldX, worldZ);
return new TerrainSample(surfaceY, surfaceY < fluidHeight ? OptionalInt.of(fluidHeight) : OptionalInt.empty(), 0D);
}
@Override
public double surfaceY(int worldX, int worldZ) {
require(worldX, 0, worldZ);
return surface.applyAsInt(worldX, worldZ);
}
@Override
public BiomeSample biome(int worldX, int y, int worldZ) {
require(worldX, y, worldZ);
return biomes.at(worldX, y, worldZ);
}
@Override
public Optional<ResourceId> caveBiome(int worldX, int y, int worldZ) {
return biome(worldX, y, worldZ).caveBiome();
}
@Override
public int fluidHeight() {
return fluidHeight;
}
@Override
public OptionalInt upperDimensionY(int worldX, int worldZ) {
require(worldX, 0, worldZ);
return upper == null ? OptionalInt.empty() : OptionalInt.of(upper.applyAsInt(worldX, worldZ));
}
private void require(int worldX, int y, int worldZ) {
if (!bounds().contains(worldX, y, worldZ)) {
throw new IndexOutOfBoundsException(worldX + ", " + y + ", " + worldZ + " is outside " + bounds());
}
}
}
@@ -0,0 +1,281 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.modules;
import art.arcane.iris.builtin.CaveDressing;
import art.arcane.iris.builtin.IrisSeed;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.loader.ResourceLoader;
import art.arcane.iris.engine.object.material.IrisBlockData;
import com.volmit.FeatureAttachment.Target;
import com.volmit.IrisFeature;
import com.volmit.ModuleLog;
import com.volmit.block.BlockFace;
import com.volmit.block.BlockSpec;
import com.volmit.block.BlockState;
import com.volmit.block.BlockTrait;
import com.volmit.block.BlockRegistry;
import com.volmit.block.PaletteSampler;
import com.volmit.block.PaletteSpec;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.config.PackSettings;
import com.volmit.host.ModuleLogs;
import com.volmit.item.ItemRegistry;
import com.volmit.noise.NoiseFactory;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKey;
import com.volmit.world.PackBiome;
import com.volmit.world.PackWorld;
import com.volmit.object.BlockEntityData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* A world for the tests of the carve module: the settings its dimension, regions and biomes declare, the biomes its pack has, Iris's
* own noise over an empty pack, a few blocks by name and the world's seeds, all in memory, so the module is tested through IrisApi alone.
* Biomes and regions have the ids {@code test:<key>}; a declaration made for {@code <key>} has the source {@code test:<kind>/<key>}.
*/
public final class CarveTestWorld implements PackWorld, IrisSeed.Source, CaveDressing.Source {
public static final String NAMESPACE = "test";
public static final int MIN_HEIGHT = -64;
private static final Set<String> AIRS = Set.of("minecraft:air", "minecraft:cave_air", "minecraft:void_air");
private static final Set<String> FLUIDS = Set.of("minecraft:water", "minecraft:lava");
private static final Set<String> DECORATIONS = Set.of("minecraft:short_grass", "minecraft:poppy", "minecraft:glow_lichen");
private static final Set<String> FALLING = Set.of("minecraft:sand", "minecraft:gravel");
private final Map<Class<?>, Object> states = new HashMap<>();
private final List<Entry<?>> declared = new ArrayList<>();
private final Map<ResourceId, PackBiome> biomes = new HashMap<>();
private final IrisData data = packData();
private final Resources resources = new Resources();
private long carveSeed = 1337L;
private CaveDressing dressing;
public CarveTestWorld declare(Target level, String key, IrisFeature value) {
String kind = level.name().toLowerCase();
declared.add(new Entry<>(level, new ResourceId(NAMESPACE, kind + "/" + key), value));
return this;
}
public CarveTestWorld dimension(IrisFeature value) {
return declare(Target.DIMENSION, "overworld", value);
}
public CarveTestWorld biome(String key, int rarity) {
ResourceId id = new ResourceId(NAMESPACE, key);
biomes.put(id, new PackBiome(id, key, ResourceId.parse("minecraft:plains"), rarity, List.of()));
return this;
}
public CarveTestWorld carveSeed(long seed) {
this.carveSeed = seed;
return this;
}
public CarveTestWorld dressing(CaveDressing dressing) {
this.dressing = dressing;
return this;
}
/** The pack data under the noise: nothing in it, as the tests of Iris's value types have it. */
public IrisData data() {
return data;
}
public static ResourceId id(String key) {
return new ResourceId(NAMESPACE, key);
}
@Override
public long seed() {
return carveSeed;
}
@Override
public PackResources resources() {
return resources;
}
@Override
public PackSettings settings() {
return new PackSettings() {
@Override
@SuppressWarnings("unchecked")
public <F extends IrisFeature> List<Entry<F>> declared(Class<F> featureType) {
return declared.stream().filter(entry -> featureType.isInstance(entry.value())).map(entry -> (Entry<F>) entry).toList();
}
};
}
@Override
public int minHeight() {
return MIN_HEIGHT;
}
@Override
public synchronized <T> T state(Class<T> type, Function<? super PackWorld, ? extends T> create) {
Object known = states.get(type);
if (known == null) {
known = create.apply(this);
states.put(type, known);
}
return type.cast(known);
}
@Override
public ModuleLog log() {
return ModuleLogs.discarding();
}
@Override
public PackWorld withLog(ModuleLog log) {
return this;
}
@Override
public long seed(IrisSeed seed) {
return seed == IrisSeed.CARVE ? carveSeed : carveSeed + seed.ordinal();
}
@Override
public CaveDressing caveDressing() {
if (dressing == null) {
throw new UnsupportedOperationException("This world has no cave dressing");
}
return dressing;
}
@SuppressWarnings("unchecked")
private static IrisData packData() {
IrisData pack = mock(IrisData.class);
ResourceLoader<IrisBlockData> blocks = mock(ResourceLoader.class);
when(pack.getBlockLoader()).thenReturn(blocks);
return pack;
}
private final class Resources implements PackResources {
private final UUID snapshot = UUID.randomUUID();
private final NoiseFactory noise = new IrisNoiseFactory(data);
@Override
public ResourceId packId() {
return new ResourceId(NAMESPACE, "pack");
}
@Override
public UUID snapshotId() {
return snapshot;
}
@Override
public BlockRegistry blocks() {
return new Blocks();
}
@Override
public ItemRegistry items() {
throw new UnsupportedOperationException("No items here");
}
@Override
public NoiseFactory noise() {
return noise;
}
@Override
@SuppressWarnings("unchecked")
public <T> Optional<T> find(ResourceKey<T> key) {
if (key.type() != PackBiome.class) {
return Optional.empty();
}
return Optional.ofNullable((T) biomes.get(key.id()));
}
@Override
public List<ResourceId> ids(Class<?> type) {
return type == PackBiome.class ? biomes.keySet().stream().sorted().toList() : List.of();
}
}
/** Blocks by name: air, water and lava, a few decorations, falling blocks and ores (named {@code *_ore}); everything else is a solid cube. */
public static final class Blocks implements BlockRegistry {
@Override
public BlockState resolve(String key) {
return BlockState.parse(key.contains(":") ? key : "minecraft:" + key);
}
@Override
public BlockState resolve(BlockSpec spec) {
return resolve(spec.block());
}
@Override
public Optional<BlockEntityData> blockEntity(BlockSpec spec) {
return Optional.empty();
}
@Override
public PaletteSampler palette(PaletteSpec spec, long seed) {
throw new UnsupportedOperationException("No palettes here");
}
@Override
public boolean hasTrait(BlockState state, BlockTrait trait) {
String material = state.material().toString();
boolean air = AIRS.contains(material);
boolean fluid = FLUIDS.contains(material);
boolean decoration = DECORATIONS.contains(material);
return switch (trait) {
case AIR -> air;
case FLUID -> fluid;
case SOLID -> !air && !fluid && !decoration;
case ORE -> material.endsWith("_ore");
case DECORATION -> decoration;
case GRAVITY -> FALLING.contains(material);
default -> false;
};
}
@Override
public boolean inTag(BlockState state, ResourceId tag) {
return false;
}
@Override
public boolean canAttach(BlockState state, BlockState support, BlockFace face) {
return hasTrait(support, BlockTrait.SOLID);
}
@Override
public boolean canPlaceOn(BlockState state, BlockState below) {
return hasTrait(below, BlockTrait.SOLID);
}
}
}
@@ -213,8 +213,8 @@ public class DimensionBottomTest {
}
private void assertSamplesAndBoundsAgree() {
assertEquals(List.of(WHOLE_HEIGHT_OF_ONE_CHUNK), terrainBounds);
assertEquals("the mantle view covers the same heights as the terrain", terrainBounds, viewBounds);
assertEquals("a mantle stage sees the terrain around its chunk, as a chunk stage does", List.of(WHOLE_HEIGHT_AROUND_ONE_CHUNK), terrainBounds);
assertEquals(List.of(WHOLE_HEIGHT_OF_ONE_CHUNK), viewBounds);
assertEquals("the terrain samples count from the same bottom", List.of(Double.valueOf(SURFACE_HEIGHT)), surfaces);
assertTrue(terrainBounds.getFirst().contains(0, SURFACE_HEIGHT, 0));
}
@@ -18,6 +18,7 @@
package art.arcane.iris.core.modules;
import art.arcane.iris.builtin.MatterMantle;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.SeedManager;
@@ -34,6 +35,7 @@ import art.arcane.volmlib.util.matter.IrisMatter;
import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.MatterSlice;
import com.volmit.FeatureRegistry;
import com.volmit.block.BlockState;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.host.LoadedPack;
@@ -114,6 +116,16 @@ public class IrisModuleMantleTest {
return new IrisModuleMantle(bounds, this::chunk, LAYERS, PlannedBlocks.none(bounds));
}
@Test
public void theMatterSideGivesTheMantleChunksTheInvocationReachesAndNoOthers() {
IrisModuleMantle mantle = mantle(new BlockBox(0, 0, 0, 16, HEIGHT, 16));
MatterMantle matter = MatterMantle.of(mantle);
org.junit.Assert.assertSame(chunk(3, 4), matter.chunk(3, 4));
org.junit.Assert.assertNull("nothing is loaded that the host did not say is", matter.loadedChunk(3, 4));
org.junit.Assert.assertThrows(IllegalArgumentException.class, () -> MatterMantle.of(new InMemoryOnly()));
}
@Test
public void layersShareABlockAndReadInWorldCoordinatesAcrossChunks() {
IrisModuleMantle mantle = mantle(new BlockBox(-16, 0, -16, 32, HEIGHT, 32));
@@ -335,4 +347,27 @@ public class IrisModuleMantleTest {
private static DataInputStream input(byte[] bytes) {
return new DataInputStream(new ByteArrayInputStream(bytes));
}
/** A mantle that is none of Iris's. */
private static final class InMemoryOnly implements com.volmit.mantle.Mantle {
@Override
public BlockBox bounds() {
return new BlockBox(0, 0, 0, 0, 0, 0);
}
@Override
public <T> MantleLayer<T> layer(MantleKey<T> key) {
throw new UnsupportedOperationException();
}
@Override
public MantleLayer<BlockState> blocks() {
throw new UnsupportedOperationException();
}
@Override
public MantleEdit edit() {
throw new UnsupportedOperationException();
}
}
}
@@ -19,7 +19,7 @@
package art.arcane.iris.core.modules;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.modifier.CarveModule;
import art.arcane.iris.engine.actuator.TerrainModule;
import com.volmit.host.LoadedPack;
import org.junit.Rule;
import org.junit.Test;
@@ -79,7 +79,7 @@ public class PackModuleJarNextToBuiltInsTest {
@Test
public void aJarModuleWithTheIdOfACompiledInBuiltInFailsAsADuplicate() throws IOException {
String builtInId = new CarveModule().info().id().toString();
String builtInId = new TerrainModule().info().id().toString();
Path packFolder = BuiltInPack.newPackFolder(folder);
PackModuleJar.write(packFolder, "carve.jar", "pack.ported.Ported",
Map.of("pack.ported.Ported", module("ported", "Ported", builtInId)));
@@ -88,7 +88,7 @@ public class PackModuleJarNextToBuiltInsTest {
() -> BuiltInPack.serve(mock(IrisData.class), folder, packFolder, List.of()));
assertEquals("Duplicate module " + builtInId + " from " + Path.of("modules", "carve.jar") + " (pack.ported.Ported); already loaded from host classpath ("
+ CarveModule.class.getName() + ")", failure.getMessage());
+ TerrainModule.class.getName() + ")", failure.getMessage());
}
private static String module(String packageName, String className, String moduleId) {
@@ -27,7 +27,6 @@ import art.arcane.iris.engine.IrisComplex;
import art.arcane.iris.engine.decorator.DecoratorTestEngines;
import art.arcane.iris.engine.object.world.IrisWorld;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.modifier.CaveBiomeBands;
import art.arcane.iris.util.project.stream.ProceduralStream;
import com.volmit.FeatureRegistry;
import com.volmit.IrisModule;
@@ -196,15 +195,4 @@ public class EngineCaveBiomeTest {
assertEquals(1, depthQuestions.get());
verify(data.getBiomeLoader(), times(1)).load("band/deep");
}
@Test
public void theCarveModulesProviderReadsTheDepthFromTheBiomesSettings() {
IrisBiome deep = mock(IrisBiome.class);
when(deep.getModuleSettings()).thenReturn(BuiltInPack.settings(new CaveDepthSettings(25)));
IrisBiome plain = mock(IrisBiome.class);
when(plain.getModuleSettings()).thenReturn(BuiltInPack.settings());
org.junit.Assert.assertEquals(25, CaveBiomeBands.minDepthBelowSurface(deep));
org.junit.Assert.assertEquals(0, CaveBiomeBands.minDepthBelowSurface(plain));
}
}
@@ -1,5 +1,7 @@
package art.arcane.iris.engine.framework;
import art.arcane.iris.builtin.carve.CaveLavaHeightSettings;
import art.arcane.iris.core.modules.BuiltInPack;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.structure.IrisStructureAnchorMode;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement;
@@ -164,7 +166,7 @@ public class StructureCaveAnchorResolverTest {
when(engine.getHeight(anyInt(), anyInt(), eq(true))).thenReturn(surfaceHeight);
when(engine.getDimension()).thenReturn(dimension);
when(dimension.getFluidHeight()).thenReturn(127);
when(dimension.getCaveLavaHeight()).thenReturn(8);
when(dimension.getModuleSettings()).thenReturn(BuiltInPack.settings(new CaveLavaHeightSettings(8)));
when(engine.getMantle().getMantle().get(
anyInt(), anyInt(), anyInt(), eq(MatterCavern.class)))
.thenAnswer(invocation -> {
@@ -0,0 +1,131 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.MatterMantle;
import art.arcane.iris.builtin.carve.CaveProfile;
import art.arcane.iris.core.modules.CarveTestTerrain;
import art.arcane.iris.core.modules.CarveTestWorld;
import art.arcane.iris.core.modules.InMemoryMantle;
import art.arcane.iris.engine.modifier.RecordingCaveDressing;
import art.arcane.iris.engine.object.TestSettings;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.MatterCavern;
import com.volmit.FeatureAttachment.Target;
import com.volmit.config.Range;
import com.volmit.noise.NoiseStyle;
import com.volmit.noise.StyledRange;
import com.volmit.world.BiomeSample;
import org.junit.Before;
import org.junit.Test;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** The caves a chunk gets: the profile its dimension, region, surface biome and cave biome declare, the last enabled one winning, carved into the mantle. */
public class CaveCarvingTest {
private static final int HEIGHT = 128;
private static final int SURFACE = 100;
private static final int FLUID_HEIGHT = 30;
private static final int LAVA_HEIGHT = 8;
private static final double EVERYTHING_BELOW = 2D;
private InMemoryMantle mantle;
private CarveTestWorld world;
@Before
public void setUp() {
world = newWorld();
}
private static CarveTestWorld newWorld() {
return new CarveTestWorld().biome("cave/lush", 1).biome("plains", 1).dressing(new RecordingCaveDressing());
}
@Test
public void theDimensionsProfileCarvesWhereNothingNarrowerDeclaresOne() {
world.dimension(profile(true));
assertTrue(carvedBlocks(BiomeSample::surfaceBiome) > 0);
}
@Test
public void aDisabledProfileDeclaresNothingAndTheDimensionsStillCarves() {
world.dimension(profile(true));
int dimensionOnly = carvedBlocks(BiomeSample::surfaceBiome);
world = newWorld().dimension(profile(true)).declare(Target.REGION, "region", profile(false));
assertTrue(dimensionOnly > 0);
assertEquals(dimensionOnly, carvedBlocks(BiomeSample::surfaceBiome));
}
@Test
public void anEnabledProfileOfARegionReplacesTheDimensionsWithinItsOwnBounds() {
world.dimension(profile(true)).declare(Target.REGION, "region", TestSettings.with(profile(true), "verticalRange", Range.of(50D, 60D)));
int carved = carvedBlocks(BiomeSample::surfaceBiome);
assertTrue(carved > 0);
mantle.chunk(0, 0).iterate(MatterCavern.class, (x, y, z, cavern) -> assertTrue("y=" + y, y >= 50 && y <= 60));
}
@Test
public void theCaveBiomeOfAColumnCarvesWithItsOwnProfileWhereTheDimensionDeclaresNone() {
world.declare(Target.BIOME, "cave/lush", profile(true));
assertEquals("the surface biome declares none", 0, carvedBlocks(BiomeSample::surfaceBiome));
assertTrue(carvedBlocks(sample -> sample.caveBiome().orElseThrow()) > 0);
}
/** Carves chunk 0, 0 with the cave biome of every block {@code caveBiomeOf} says, and counts the blocks of the chunk's mantle that became cave. */
private int carvedBlocks(java.util.function.Function<BiomeSample, com.volmit.resource.ResourceId> caveBiomeOf) {
mantle = new InMemoryMantle(HEIGHT / 16);
CarveTestTerrain terrain = new CarveTestTerrain(0, 0, HEIGHT, FLUID_HEIGHT, (x, z) -> SURFACE).biomes((x, y, z) -> {
BiomeSample sample = new BiomeSample(CarveTestWorld.id("region"), CarveTestWorld.id("plains"), Optional.of(CarveTestWorld.id("cave/lush")));
return new BiomeSample(sample.region(), sample.surfaceBiome(), Optional.of(caveBiomeOf.apply(sample)));
});
MatterMantle matter = new MatterMantle() {
@Override
public MantleChunk<Matter> chunk(int chunkX, int chunkZ) {
return mantle.chunk(chunkX, chunkZ);
}
@Override
public MantleChunk<Matter> loadedChunk(int chunkX, int chunkZ) {
return null;
}
};
CarveWorld carveWorld = new CarveWorld(world.resources().noise(), 1337L, HEIGHT, FLUID_HEIGHT, LAVA_HEIGHT, CarveTestWorld.MIN_HEIGHT);
new CaveCarving(world, carveWorld, false).carve(matter, terrain, 0, 0);
int[] count = new int[1];
mantle.chunk(0, 0).iterate(MatterCavern.class, (x, y, z, cavern) -> count[0]++);
return count[0];
}
private static CaveProfile profile(boolean enabled) {
return TestSettings.with(new CaveProfile(), "enabled", enabled, "verticalRange", Range.of(20D, 90D),
"densityThreshold", StyledRange.of(EVERYTHING_BELOW, EVERYTHING_BELOW, NoiseStyle.of(NoiseStyle.FLAT)),
"allowSurfaceBreak", false, "allowFluid", false, "adaptiveSampling", false, "sampleStep", 1);
}
}
@@ -2,7 +2,6 @@ package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.carve.CaveProfile;
import art.arcane.iris.engine.object.TestSettings;
import art.arcane.iris.engine.object.value.IrisRange;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -25,7 +24,7 @@ public class CaveCarvingTop2BlendTest {
@BeforeClass
public static void setup() throws Exception {
Class<?> weightedProfileClass = Class.forName("art.arcane.iris.engine.mantle.components.CaveCarving$WeightedProfile");
weightedProfileConstructor = weightedProfileClass.getDeclaredConstructor(CaveProfile.class, double[].class, double.class, Class.forName("art.arcane.iris.engine.object.value.IrisRange"), int.class);
weightedProfileConstructor = weightedProfileClass.getDeclaredConstructor(CaveProfile.class, double[].class, double.class, com.volmit.config.Range.class, int.class);
weightedProfileConstructor.setAccessible(true);
limitMethod = CaveCarving.class.getDeclaredMethod("limitAndMergeBlendedProfiles", List.class, int.class, int.class);
limitMethod.setAccessible(true);
@@ -1,29 +1,18 @@
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.MatterMantle;
import art.arcane.iris.builtin.carve.CaveFieldModule;
import art.arcane.iris.builtin.carve.CaveProfile;
import art.arcane.iris.engine.object.TestSettings;
import art.arcane.iris.engine.object.noise.IrisGeneratorStyle;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.modules.CarveTestWorld;
import art.arcane.iris.builtin.terrain.FluidPaletteSettings;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineMetrics;
import art.arcane.iris.engine.framework.SeedManager;
import art.arcane.iris.engine.mantle.MantleWriter;
import art.arcane.iris.engine.object.terrain.carving.ResolvedCaveProfile;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.value.IrisRange;
import art.arcane.iris.engine.object.noise.IrisStyledRange;
import art.arcane.iris.engine.object.world.IrisWorld;
import art.arcane.iris.engine.object.noise.NoiseStyle;
import art.arcane.iris.util.project.noise.CNG;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.mantle.runtime.Mantle;
import art.arcane.iris.engine.object.TestSettings;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.MatterCavern;
import art.arcane.volmlib.util.matter.MatterSlice;
import com.volmit.config.Range;
import com.volmit.noise.NoiseSampler;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -53,11 +42,14 @@ public class IrisCaveCarver3DNearParityTest {
private static Method sampleDensityMethod;
private static Method aquiferCandidateMethod;
private static Field engineField;
private static Field dataField;
private static final int MIN_HEIGHT = 0;
private static final int FLUID_HEIGHT = 64;
private static final int LAVA_HEIGHT = 18;
private static final long CARVE_SEED = new SeedManager(942_337_445L).getCarve();
private static Field profileField;
private static Field surfaceBreakDensityField;
private static Field thresholdRngField;
private static Field thresholdNoiseField;
private static Field carveAirField;
private static Field carveFluidField;
private static Field carveLavaField;
@@ -69,16 +61,12 @@ public class IrisCaveCarver3DNearParityTest {
sampleDensityMethod.setAccessible(true);
aquiferCandidateMethod = IrisCaveCarver3D.class.getDeclaredMethod("isAquiferCandidate", int.class, int.class, int.class, double.class);
aquiferCandidateMethod.setAccessible(true);
engineField = IrisCaveCarver3D.class.getDeclaredField("engine");
engineField.setAccessible(true);
dataField = IrisCaveCarver3D.class.getDeclaredField("data");
dataField.setAccessible(true);
profileField = IrisCaveCarver3D.class.getDeclaredField("profile");
profileField.setAccessible(true);
surfaceBreakDensityField = IrisCaveCarver3D.class.getDeclaredField("surfaceBreakDensity");
surfaceBreakDensityField.setAccessible(true);
thresholdRngField = IrisCaveCarver3D.class.getDeclaredField("thresholdRng");
thresholdRngField.setAccessible(true);
thresholdNoiseField = IrisCaveCarver3D.class.getDeclaredField("thresholdNoise");
thresholdNoiseField.setAccessible(true);
carveAirField = IrisCaveCarver3D.class.getDeclaredField("carveAir");
carveAirField.setAccessible(true);
carveFluidField = IrisCaveCarver3D.class.getDeclaredField("carveFluid");
@@ -100,15 +88,15 @@ public class IrisCaveCarver3DNearParityTest {
@Test
public void carvedCellDistributionStableAcrossEquivalentCarvers() {
Engine engine = createEngine(128, 92);
CarveWorld engine = createEngine(128, 92);
IrisCaveCarver3D firstCarver = new IrisCaveCarver3D(engine, createProfile(true, true));
WriterCapture firstCapture = createWriterCapture(128);
int firstCarved = firstCarver.carve(firstCapture.writer, 7, -3);
int firstCarved = firstCarver.carve(firstCapture.writer, 7, -3, fullWeights(), 0D, 0D, null, filledHeights(92));
IrisCaveCarver3D secondCarver = new IrisCaveCarver3D(engine, createProfile(true, true));
WriterCapture secondCapture = createWriterCapture(128);
int secondCarved = secondCarver.carve(secondCapture.writer, 7, -3);
int secondCarved = secondCarver.carve(secondCapture.writer, 7, -3, fullWeights(), 0D, 0D, null, filledHeights(92));
assertTrue(firstCarved > 0);
assertEquals(firstCarved, secondCarved);
@@ -118,7 +106,7 @@ public class IrisCaveCarver3DNearParityTest {
@Test
public void warpCacheDoesNotCrossContaminateCarverInstancesOnSameThread() throws Exception {
Engine engine = createEngine(128, 92);
CarveWorld engine = createEngine(128, 92);
CaveProfile firstProfile = createProfile(true, false);
TestSettings.with(firstProfile, "warpStyle", com.volmit.noise.NoiseStyle.of("SIMPLEX").withZoom(0.12D));
CaveProfile secondProfile = createProfile(true, false);
@@ -155,13 +143,13 @@ public class IrisCaveCarver3DNearParityTest {
@Test
public void exactPathCarvesChunkEdgesAndRespectsWorldHeightClipping() {
Engine engine = createEngine(48, 46);
CarveWorld engine = createEngine(48, 46);
IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, createProfile(true, true));
WriterCapture capture = createWriterCapture(48);
double[] columnWeights = fullWeights();
int[] precomputedSurfaceHeights = filledHeights(46);
int carved = carver.carve(capture.writer, 0, 0, columnWeights, 0D, 0D, new IrisRange(0D, 80D), precomputedSurfaceHeights);
int carved = carver.carve(capture.writer, 0, 0, columnWeights, 0D, 0D, Range.of(0D, 80D), precomputedSurfaceHeights);
assertTrue(carved > 0);
assertTrue(hasX(capture.carvedCells, 14));
@@ -190,10 +178,10 @@ public class IrisCaveCarver3DNearParityTest {
@Test
public void legacySampleStepTwoMatchesExactReference() throws Exception {
Engine engine = createEngine(96, 90);
CarveWorld engine = createEngine(96, 90);
double[] columnWeights = fullWeights();
int[] precomputedSurfaceHeights = filledHeights(90);
IrisRange worldYRange = new IrisRange(0D, 88D);
Range worldYRange = Range.of(0D, 88D);
CaveProfile exactProfile = TestSettings.with(createProfile(true, true), "sampleStep", 1, "adaptiveSampling", false);
IrisCaveCarver3D exactCarver = new IrisCaveCarver3D(engine, exactProfile);
@@ -212,19 +200,19 @@ public class IrisCaveCarver3DNearParityTest {
@Test
public void exactPathUsesExpectedLavaAndForcedAirBands() {
Engine engine = createEngine(48, 46);
CarveWorld engine = createEngine(48, 46);
double[] columnWeights = fullWeights();
int[] precomputedSurfaceHeights = filledHeights(46);
CaveProfile lavaProfile = TestSettings.with(createProfile(false, false), "allowLava", true, "allowFluid", false);
IrisCaveCarver3D lavaCarver = new IrisCaveCarver3D(engine, lavaProfile);
WriterCapture lavaCapture = createWriterCapture(48);
lavaCarver.carve(lavaCapture.writer, 0, 0, columnWeights, 0D, 0D, new IrisRange(0D, 80D), precomputedSurfaceHeights);
lavaCarver.carve(lavaCapture.writer, 0, 0, columnWeights, 0D, 0D, Range.of(0D, 80D), precomputedSurfaceHeights);
CaveProfile forcedAirProfile = TestSettings.with(createProfile(false, false), "allowLava", false, "allowFluid", false);
IrisCaveCarver3D forcedAirCarver = new IrisCaveCarver3D(engine, forcedAirProfile);
WriterCapture forcedAirCapture = createWriterCapture(48);
forcedAirCarver.carve(forcedAirCapture.writer, 0, 0, columnWeights, 0D, 0D, new IrisRange(0D, 80D), precomputedSurfaceHeights);
forcedAirCarver.carve(forcedAirCapture.writer, 0, 0, columnWeights, 0D, 0D, Range.of(0D, 80D), precomputedSurfaceHeights);
assertTrue(containsLiquidInRange(lavaCapture.carvedLiquids, 0, 18, (byte) 2));
assertTrue(containsLiquidInRange(forcedAirCapture.carvedLiquids, 0, 18, (byte) 3));
@@ -234,7 +222,7 @@ public class IrisCaveCarver3DNearParityTest {
@Test
public void fluidPrecedesForcedAirWhenLavaIsDisabled() {
Engine engine = createEngine(48, 46);
CarveWorld engine = createEngine(48, 46);
int[] surfaceHeights = filledHeights(46);
CaveProfile wetProfile = TestSettings.with(createFluidProfile(), "verticalRange", com.volmit.config.Range.of(2D, 18D), "allowLava", false, "fluidRequiresFloor", false);
WriterCapture wetCapture = createWriterCapture(48);
@@ -255,7 +243,7 @@ public class IrisCaveCarver3DNearParityTest {
@Test
public void fluidToggleAndMinimumDepthUseEachColumnsTerrainSurface() {
Engine engine = createEngine(80, 70);
CarveWorld engine = createEngine(80, 70);
int[] surfaceHeights = splitSurfaceHeights(40, 70);
CaveProfile enabledProfile = TestSettings.with(createFluidProfile(), "allowFluid", true, "fluidMinDepthBelowSurface", 10);
@@ -278,7 +266,7 @@ public class IrisCaveCarver3DNearParityTest {
@Test
public void dimensionFluidHeightCapsFluidIntent() {
Engine engine = createEngine(80, 70);
CarveWorld engine = createEngine(80, 70);
CaveProfile profile = TestSettings.with(createFluidProfile(), "fluidMinDepthBelowSurface", 0);
WriterCapture capture = createWriterCapture(80);
@@ -299,7 +287,7 @@ public class IrisCaveCarver3DNearParityTest {
@Test
public void floorRequiredFluidResolvesAfterTheCompleteCarveMask() {
Engine engine = createEngine(80, 70);
CarveWorld engine = createEngine(80, 70);
int[] surfaceHeights = filledHeights(70);
int chunkX = -8;
int chunkZ = -1;
@@ -311,7 +299,7 @@ public class IrisCaveCarver3DNearParityTest {
new IrisCaveCarver3D(engine, supportedProfile).carve(
firstCapture.writer, chunkX, chunkZ, fullWeights(), 0D, 0D, null, surfaceHeights, null, null, supportPlan);
int candidateCount = countLiquid(firstCapture, (byte) 1);
supportPlan.resolve(firstCapture.writer.acquireChunk(chunkX, chunkZ));
supportPlan.resolve(firstCapture.writer.chunk(chunkX, chunkZ));
CaveProfile repeatedProfile = TestSettings.with(createFluidProfile(), "densityThreshold", cupThreshold, "fluidMinDepthBelowSurface", 0, "fluidRequiresFloor", true);
WriterCapture secondCapture = createWriterCapture(80);
@@ -333,7 +321,7 @@ public class IrisCaveCarver3DNearParityTest {
@Test
public void finalFluidSupportRejectsUnknownNeighborChunkEdges() {
WriterCapture capture = createWriterCapture(80);
MantleChunk<Matter> chunk = capture.writer.acquireChunk(0, 0);
MantleChunk<Matter> chunk = capture.writer.chunk(0, 0);
MatterSlice<MatterCavern> slice = chunk.getOrCreate(3).slice(MatterCavern.class);
MatterCavern fluid = new MatterCavern(true, "", (byte) 1);
MatterCavern air = new MatterCavern(true, "", (byte) 0);
@@ -353,36 +341,38 @@ public class IrisCaveCarver3DNearParityTest {
@Test
public void floorRequiredFluidSeesLaterProfileCarvePasses() {
Engine engine = createEngine(80, 70);
CarveWorld engine = createEngine(80, 70);
int[] surfaceHeights = filledHeights(70);
int chunkX = -8;
int chunkZ = -1;
WriterCapture capture = createWriterCapture(80);
CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan();
CaveProfile fluidProfile = TestSettings.with(createFluidProfile(), "densityThreshold", com.volmit.noise.StyledRange.of(0.15D, 0.15D, com.volmit.noise.NoiseStyle.of("FLAT")), "fluidRequiresFloor", true);
CaveProfile fluidProfile = TestSettings.with(createFluidProfile(), "densityThreshold", com.volmit.noise.StyledRange.of(0.15D, 0.15D, com.volmit.noise.NoiseStyle.of("FLAT")), "fluidMinDepthBelowSurface", 0, "fluidRequiresFloor", true);
CaveProfile airProfile = TestSettings.with(createFluidProfile(), "allowFluid", false);
new IrisCaveCarver3D(engine, fluidProfile).carve(
capture.writer, 0, 0, fullWeights(), 0D, 0D, null, surfaceHeights,
null, new IrisRange(20D, 64D), fluidSupportPlan);
capture.writer, chunkX, chunkZ, fullWeights(), 0D, 0D, null, surfaceHeights,
null, Range.of(20D, 64D), fluidSupportPlan);
String fluidCell = firstCellWithLiquid(capture, (byte) 1);
assertTrue(fluidCell != null);
int fluidY = coordinate(fluidCell, 1);
new IrisCaveCarver3D(engine, airProfile).carve(
capture.writer, 0, 0, fullWeights(), 0D, 0D, null, surfaceHeights,
null, new IrisRange(fluidY - 1D, fluidY - 1D), fluidSupportPlan);
capture.writer, chunkX, chunkZ, fullWeights(), 0D, 0D, null, surfaceHeights,
null, Range.of(fluidY - 1D, fluidY - 1D), fluidSupportPlan);
assertEquals(Byte.valueOf((byte) 1), capture.carvedLiquids.get(fluidCell));
fluidSupportPlan.resolve(capture.writer.acquireChunk(0, 0));
fluidSupportPlan.resolve(capture.writer.chunk(chunkX, chunkZ));
assertEquals(Byte.valueOf((byte) 0), capture.carvedLiquids.get(fluidCell));
}
@Test
public void optimizedExactPathOutperformsNaiveReference() throws Exception {
Engine engine = createEngine(128, 92);
CarveWorld engine = createEngine(128, 92);
IrisCaveCarver3D optimizedCarver = new IrisCaveCarver3D(engine, TestSettings.with(createProfile(true, true), "adaptiveSampling", false));
IrisCaveCarver3D naiveCarver = new IrisCaveCarver3D(engine, TestSettings.with(createProfile(true, true), "adaptiveSampling", false));
double[] columnWeights = fullWeights();
int[] precomputedSurfaceHeights = filledHeights(92);
IrisRange worldYRange = new IrisRange(0D, 96D);
Range worldYRange = Range.of(0D, 96D);
for (int warmup = 0; warmup < 4; warmup++) {
runOptimizedOnce(optimizedCarver, 3, -2, columnWeights, worldYRange, precomputedSurfaceHeights, 128);
@@ -411,10 +401,10 @@ public class IrisCaveCarver3DNearParityTest {
@Test
public void adaptivePathStaysNearExactReferenceWithWarpAndModules() throws Exception {
Engine engine = createEngine(96, 90);
CarveWorld engine = createEngine(96, 90);
double[] columnWeights = fullWeights();
int[] precomputedSurfaceHeights = filledHeights(90);
IrisRange worldYRange = new IrisRange(0D, 88D);
Range worldYRange = Range.of(0D, 88D);
IrisCaveCarver3D adaptiveCarver = new IrisCaveCarver3D(engine, TestSettings.with(createProfile(true, true), "adaptiveSampling", true));
WriterCapture adaptiveCapture = createWriterCapture(96);
@@ -438,7 +428,7 @@ public class IrisCaveCarver3DNearParityTest {
}
private void assertFlatSurfaceCeiling(CaveProfile profile) {
Engine engine = createEngine(96, 72);
CarveWorld engine = createEngine(96, 72);
WriterCapture capture = createWriterCapture(96);
new IrisCaveCarver3D(engine, profile).carve(
@@ -470,10 +460,10 @@ public class IrisCaveCarver3DNearParityTest {
}
private void assertExactParity(boolean warp, boolean modules, boolean adaptiveSampling) throws Exception {
Engine engine = createEngine(96, 90);
CarveWorld engine = createEngine(96, 90);
double[] columnWeights = fullWeights();
int[] precomputedSurfaceHeights = filledHeights(90);
IrisRange worldYRange = new IrisRange(0D, 88D);
Range worldYRange = Range.of(0D, 88D);
IrisCaveCarver3D optimizedCarver = new IrisCaveCarver3D(engine, TestSettings.with(createProfile(warp, modules), "adaptiveSampling", adaptiveSampling));
WriterCapture optimizedCapture = createWriterCapture(96);
@@ -481,14 +471,14 @@ public class IrisCaveCarver3DNearParityTest {
IrisCaveCarver3D naiveCarver = new IrisCaveCarver3D(engine, TestSettings.with(createProfile(warp, modules), "adaptiveSampling", false));
WriterCapture naiveCapture = createWriterCapture(96);
int naiveCarved = carveNaiveExact(naiveCarver, naiveCapture.writer, 5, -1, columnWeights, worldYRange, precomputedSurfaceHeights);
int naiveCarved = carveNaiveExact(naiveCarver, naiveCapture.writer, 96, 5, -1, columnWeights, worldYRange, precomputedSurfaceHeights);
assertEquals(optimizedCarved, naiveCarved);
assertEquals(optimizedCapture.carvedCells, naiveCapture.carvedCells);
assertEquals(optimizedCapture.carvedLiquids, naiveCapture.carvedLiquids);
}
private long runOptimizedOnce(IrisCaveCarver3D carver, int chunkX, int chunkZ, double[] columnWeights, IrisRange worldYRange, int[] precomputedSurfaceHeights, int worldHeight) {
private long runOptimizedOnce(IrisCaveCarver3D carver, int chunkX, int chunkZ, double[] columnWeights, Range worldYRange, int[] precomputedSurfaceHeights, int worldHeight) {
WriterCapture capture = createWriterCapture(worldHeight);
long start = System.nanoTime();
carver.carve(capture.writer, chunkX, chunkZ, columnWeights, 0D, 0D, worldYRange, precomputedSurfaceHeights);
@@ -501,21 +491,19 @@ public class IrisCaveCarver3DNearParityTest {
return (double) sampleDensityMethod.invoke(carver, x, y, z);
}
private long runNaiveOnce(IrisCaveCarver3D carver, int chunkX, int chunkZ, double[] columnWeights, IrisRange worldYRange, int[] precomputedSurfaceHeights, int worldHeight) throws Exception {
private long runNaiveOnce(IrisCaveCarver3D carver, int chunkX, int chunkZ, double[] columnWeights, Range worldYRange, int[] precomputedSurfaceHeights, int worldHeight) throws Exception {
WriterCapture capture = createWriterCapture(worldHeight);
long start = System.nanoTime();
int carved = carveNaiveExact(carver, capture.writer, chunkX, chunkZ, columnWeights, worldYRange, precomputedSurfaceHeights);
int carved = carveNaiveExact(carver, capture.writer, worldHeight, chunkX, chunkZ, columnWeights, worldYRange, precomputedSurfaceHeights);
long elapsed = System.nanoTime() - start;
assertTrue(carved > 0);
return elapsed;
}
private int carveNaiveExact(IrisCaveCarver3D carver, MantleWriter writer, int chunkX, int chunkZ, double[] columnWeights, IrisRange worldYRange, int[] precomputedSurfaceHeights) throws Exception {
Engine engine = (Engine) engineField.get(carver);
IrisData data = (IrisData) dataField.get(carver);
private int carveNaiveExact(IrisCaveCarver3D carver, MatterMantle writer, int worldHeight, int chunkX, int chunkZ, double[] columnWeights, Range worldYRange, int[] precomputedSurfaceHeights) throws Exception {
CaveProfile profile = (CaveProfile) profileField.get(carver);
CNG surfaceBreakDensity = (CNG) surfaceBreakDensityField.get(carver);
RNG thresholdRng = (RNG) thresholdRngField.get(carver);
NoiseSampler surfaceBreakDensity = (NoiseSampler) surfaceBreakDensityField.get(carver);
NoiseSampler thresholdNoise = (NoiseSampler) thresholdNoiseField.get(carver);
MatterCavern carveAir = (MatterCavern) carveAirField.get(carver);
MatterCavern carveFluid = (MatterCavern) carveFluidField.get(carver);
MatterCavern carveLava = (MatterCavern) carveLavaField.get(carver);
@@ -526,13 +514,11 @@ public class IrisCaveCarver3DNearParityTest {
resolvedWeights = fullWeights();
}
int worldHeight = writer.getMantle().getWorldHeight();
int minY = Math.max(0, (int) Math.floor(profile.verticalRange().min()));
int maxY = Math.min(worldHeight - 1, (int) Math.ceil(profile.verticalRange().max()));
if (worldYRange != null) {
int worldMinHeight = engine.getWorld().minHeight();
int rangeMinY = (int) Math.floor(worldYRange.getMin() - worldMinHeight);
int rangeMaxY = (int) Math.ceil(worldYRange.getMax() - worldMinHeight);
int rangeMinY = (int) Math.floor(worldYRange.min() - MIN_HEIGHT);
int rangeMaxY = (int) Math.ceil(worldYRange.max() - MIN_HEIGHT);
minY = Math.max(minY, rangeMinY);
maxY = Math.min(maxY, rangeMaxY);
}
@@ -553,7 +539,7 @@ public class IrisCaveCarver3DNearParityTest {
double[] passThreshold = new double[256];
double[] verticalEdgeFade = computeVerticalEdgeFade(profile, minY, maxY);
double[] surfaceClosureThreshold = computeSurfaceClosureThresholds(profile, minY, maxY);
MatterCavern[] matterByY = computeMatterByY(engine, profile, carveAir, carveLava, carveForcedAir, minY, maxY);
MatterCavern[] matterByY = computeMatterByY(profile, carveAir, carveLava, carveForcedAir, minY, maxY);
int x0 = chunkX << 4;
int z0 = chunkZ << 4;
@@ -562,20 +548,15 @@ public class IrisCaveCarver3DNearParityTest {
for (int localZ = 0; localZ < 16; localZ++) {
int z = z0 + localZ;
int columnIndex = (localX << 4) | localZ;
int columnSurfaceY;
if (precomputedSurfaceHeights != null && precomputedSurfaceHeights.length > columnIndex) {
columnSurfaceY = precomputedSurfaceHeights[columnIndex];
} else {
columnSurfaceY = engine.getHeight(x, z);
}
int columnSurfaceY = precomputedSurfaceHeights[columnIndex];
int unclampedClearanceTopY = columnSurfaceY - surfaceClearance;
int clearanceTopY = Math.min(maxY, Math.max(minY, unclampedClearanceTopY));
boolean breakColumn = allowSurfaceBreak && signed(surfaceBreakDensity.noiseFast2D(x, z)) >= surfaceBreakNoiseThreshold;
boolean breakColumn = allowSurfaceBreak && surfaceBreakDensity.signed(x, z) >= surfaceBreakNoiseThreshold;
int resolvedTopY = breakColumn ? Math.min(maxY, Math.max(minY, columnSurfaceY)) : clearanceTopY;
columnTopY[columnIndex] = resolvedTopY;
fluidMaxY[columnIndex] = profile.allowFluid()
? Math.min(engine.getDimension().getFluidHeight(), columnSurfaceY - Math.max(0, profile.fluidMinDepthBelowSurface()))
? Math.min(FLUID_HEIGHT, columnSurfaceY - Math.max(0, profile.fluidMinDepthBelowSurface()))
: Integer.MIN_VALUE;
surfaceBreakFloorY[columnIndex] = Math.max(minY, columnSurfaceY - surfaceBreakDepth);
surfaceBreakColumn[columnIndex] = breakColumn;
@@ -586,12 +567,12 @@ public class IrisCaveCarver3DNearParityTest {
continue;
}
passThreshold[columnIndex] = ResolvedCaveProfile.of(profile).densityThreshold().get(thresholdRng, x, z, data) - profile.thresholdBias();
passThreshold[columnIndex] = thresholdAt(profile, thresholdNoise, x, z) - profile.thresholdBias();
}
}
@SuppressWarnings("unchecked")
MantleChunk<Matter> chunk = writer.acquireChunk(chunkX, chunkZ);
MantleChunk<Matter> chunk = writer.chunk(chunkX, chunkZ);
if (chunk == null) {
return 0;
}
@@ -643,6 +624,18 @@ public class IrisCaveCarver3DNearParityTest {
return carved;
}
/** The density threshold at the column the way a styled range picks it. */
private double thresholdAt(CaveProfile profile, NoiseSampler thresholdNoise, int x, int z) {
com.volmit.noise.StyledRange range = profile.densityThreshold();
if (range.min() == range.max()) {
return range.min();
}
if (com.volmit.noise.NoiseStyle.FLAT.equals(range.style().style())) {
return art.arcane.volmlib.util.math.M.lerp(range.min(), range.max(), 0.5);
}
return range.min() + (thresholdNoise.sample(x, z) * (range.max() - range.min()));
}
private double applySurfaceCeilingFade(
double threshold,
boolean surfaceCeilingColumn,
@@ -672,7 +665,7 @@ public class IrisCaveCarver3DNearParityTest {
private double[] computeSurfaceClosureThresholds(CaveProfile profile, int minY, int maxY) {
double normalization = Math.abs(profile.baseWeight()) + Math.abs(profile.detailWeight());
for (ResolvedCaveProfile.Module module : ResolvedCaveProfile.of(profile).modules()) {
for (CaveFieldModule module : profile.modules()) {
normalization += Math.abs(module.weight());
}
if (normalization <= 0D) {
@@ -683,9 +676,9 @@ public class IrisCaveCarver3DNearParityTest {
double baseMinimum = -Math.abs(profile.baseWeight()) - Math.abs(profile.detailWeight());
for (int y = minY; y <= maxY; y++) {
double minimumDensity = baseMinimum;
for (ResolvedCaveProfile.Module module : ResolvedCaveProfile.of(profile).modules()) {
IrisRange range = module.verticalRange();
if (y < Math.floor(range.getMin()) || y > Math.ceil(range.getMax())) {
for (CaveFieldModule module : profile.modules()) {
Range range = module.verticalRange();
if (y < Math.floor(range.min()) || y > Math.ceil(range.max())) {
continue;
}
double rawMinimum = module.invert()
@@ -727,10 +720,10 @@ public class IrisCaveCarver3DNearParityTest {
return verticalEdgeFade;
}
private MatterCavern[] computeMatterByY(Engine engine, CaveProfile profile, MatterCavern carveAir, MatterCavern carveLava, MatterCavern carveForcedAir, int minY, int maxY) {
private MatterCavern[] computeMatterByY(CaveProfile profile, MatterCavern carveAir, MatterCavern carveLava, MatterCavern carveForcedAir, int minY, int maxY) {
MatterCavern[] matterByY = new MatterCavern[Math.max(0, maxY - minY + 1)];
boolean allowLava = profile.allowLava();
int lavaHeight = engine.getDimension().getCaveLavaHeight();
int lavaHeight = LAVA_HEIGHT;
for (int y = minY; y <= maxY; y++) {
int offset = y - minY;
@@ -749,25 +742,9 @@ public class IrisCaveCarver3DNearParityTest {
return matterByY;
}
private Engine createEngine(int worldHeight, int sampledHeight) {
Engine engine = mock(Engine.class);
IrisData data = mock(IrisData.class);
IrisDimension dimension = mock(IrisDimension.class);
SeedManager seedManager = new SeedManager(942_337_445L);
EngineMetrics metrics = new EngineMetrics(16);
IrisWorld world = IrisWorld.builder().minHeight(0).maxHeight(worldHeight).build();
doReturn(data).when(engine).getData();
doReturn(dimension).when(engine).getDimension();
doReturn(seedManager).when(engine).getSeedManager();
doReturn(metrics).when(engine).getMetrics();
doReturn(world).when(engine).getWorld();
doReturn(sampledHeight).when(engine).getHeight(anyInt(), anyInt());
doReturn(18).when(dimension).getCaveLavaHeight();
doReturn(64).when(dimension).getFluidHeight();
return engine;
private CarveWorld createEngine(int worldHeight, int sampledHeight) {
CarveTestWorld world = new CarveTestWorld();
return new CarveWorld(world.resources().noise(), CARVE_SEED, worldHeight, FLUID_HEIGHT, LAVA_HEIGHT, MIN_HEIGHT);
}
private CaveProfile createProfile(boolean warp, boolean modules) {
@@ -812,7 +789,7 @@ public class IrisCaveCarver3DNearParityTest {
}
private void assertSurfaceFluidBoundaryForProfile(CaveProfile profile) {
Engine engine = createEngine(80, 70);
CarveWorld engine = createEngine(80, 70);
int[] surfaceHeights = filledHeights(70);
surfaceHeights[0] = 60;
int[] boundaryStartY = new int[256];
@@ -849,9 +826,6 @@ public class IrisCaveCarver3DNearParityTest {
}
private WriterCapture createWriterCapture(int worldHeight) {
MantleWriter writer = mock(MantleWriter.class);
@SuppressWarnings("unchecked")
Mantle<Matter> mantle = mock(Mantle.class);
@SuppressWarnings("unchecked")
MantleChunk<Matter> chunk = mock(MantleChunk.class);
Map<Integer, Matter> sections = new HashMap<>();
@@ -859,9 +833,6 @@ public class IrisCaveCarver3DNearParityTest {
Set<String> carvedCells = new HashSet<>();
Map<String, Byte> carvedLiquids = new HashMap<>();
doReturn(mantle).when(writer).getMantle();
doReturn(worldHeight).when(mantle).getWorldHeight();
doReturn(chunk).when(writer).acquireChunk(anyInt(), anyInt());
doAnswer(invocation -> sections.get(invocation.getArgument(0, Integer.class))).when(chunk).get(anyInt());
doAnswer(invocation -> {
int sectionIndex = invocation.getArgument(0);
@@ -875,7 +846,18 @@ public class IrisCaveCarver3DNearParityTest {
return created;
}).when(chunk).getOrCreate(anyInt());
return new WriterCapture(writer, carvedCells, carvedLiquids);
MatterMantle mantle = new MatterMantle() {
@Override
public MantleChunk<Matter> chunk(int chunkX, int chunkZ) {
return chunk;
}
@Override
public MantleChunk<Matter> loadedChunk(int chunkX, int chunkZ) {
return null;
}
};
return new WriterCapture(mantle, carvedCells, carvedLiquids);
}
private Matter createSection(int sectionIndex, Map<Integer, Map<Integer, MatterCavern>> sectionCells, Set<String> carvedCells, Map<String, Byte> carvedLiquids) {
@@ -1101,11 +1083,11 @@ public class IrisCaveCarver3DNearParityTest {
}
private static final class WriterCapture {
private final MantleWriter writer;
private final MatterMantle writer;
private final Set<String> carvedCells;
private final Map<String, Byte> carvedLiquids;
private WriterCapture(MantleWriter writer, Set<String> carvedCells, Map<String, Byte> carvedLiquids) {
private WriterCapture(MatterMantle writer, Set<String> carvedCells, Map<String, Byte> carvedLiquids) {
this.writer = writer;
this.carvedCells = carvedCells;
this.carvedLiquids = carvedLiquids;
@@ -18,6 +18,11 @@
package art.arcane.iris.engine.modifier;
import art.arcane.iris.builtin.CaveDressing;
import art.arcane.iris.builtin.MatterMantle;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.matter.Matter;
import com.volmit.noise.NoiseSampler;
import art.arcane.iris.builtin.IrisStages;
import art.arcane.iris.builtin.IrisSeed;
import art.arcane.iris.builtin.post.PostProcessingSlabsSettings;
@@ -82,6 +87,7 @@ import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
import java.util.function.IntBinaryOperator;
import static org.mockito.Mockito.mock;
/**
* One chunk as IrisApi shows it to a chunk stage, held in memory, so the ported built-ins are tested through the surface
@@ -96,6 +102,7 @@ public final class ApiChunk implements GenerationContext {
private static final ResourceId DIMENSION = ResourceId.parse("test:dimension/overworld");
private static final ResourceId BIOME = ResourceId.parse("test:biome/plains");
private static final int TERRAIN_MARGIN = 16;
private static final double FLAT_NOISE = 0.5D;
private static final Set<String> AIRS = Set.of("minecraft:air", "minecraft:cave_air", "minecraft:void_air");
private static final Set<String> FLUIDS = Set.of("minecraft:water", "minecraft:lava");
private static final Set<String> DECORATIONS = Set.of("minecraft:short_grass", "minecraft:poppy", "minecraft:tall_grass",
@@ -197,9 +204,9 @@ public final class ApiChunk implements GenerationContext {
return TestSettings.with(new PaletteLayer(), "palette", List.of(BlockSpec.of(block.key())), "slopeCondition", slope);
}
/** Empty stand-ins for the built-in stages the ported modules order after: carving and floating islands. */
/** Empty stand-ins for the built-in stages the ported modules order after or require: terrain and floating islands. */
public static List<IrisModule> standIns() {
return List.of(new CarveStandIn(), new FloatingStandIn());
return List.of(new TerrainStandIn(), new FloatingStandIn());
}
/** Runs {@code modules} as a pack's chunk graph, with the {@link #standIns()}. */
@@ -323,7 +330,20 @@ public final class ApiChunk implements GenerationContext {
}
}
private final class ChunkMantle implements Mantle {
private final class ChunkMantle implements Mantle, MatterMantle {
private final MantleChunk<Matter> noCaves = mock(MantleChunk.class);
/** The matter of the chunk: none; a test of caves brings its own mantle. */
@Override
public MantleChunk<Matter> chunk(int chunkX, int chunkZ) {
return noCaves;
}
@Override
public MantleChunk<Matter> loadedChunk(int chunkX, int chunkZ) {
return null;
}
@Override
public BlockBox bounds() {
return chunkColumns();
@@ -382,7 +402,7 @@ public final class ApiChunk implements GenerationContext {
}
/** A world of the chunk: its pack's blocks, a state store and Iris's seeds, each the world seed plus its place. */
private static final class World implements PackWorld, IrisSeed.Source {
private static final class World implements PackWorld, IrisSeed.Source, CaveDressing.Source {
private final Resources resources = new Resources();
private final Map<Class<?>, Object> states = new HashMap<>();
@@ -398,7 +418,17 @@ public final class ApiChunk implements GenerationContext {
@Override
public PackSettings settings() {
throw new UnsupportedOperationException("No pack settings here");
return new PackSettings() {
@Override
public <F extends IrisFeature> List<Entry<F>> declared(Class<F> featureType) {
return List.of();
}
};
}
@Override
public CaveDressing caveDressing() {
return new RecordingCaveDressing();
}
@Override
@@ -452,7 +482,17 @@ public final class ApiChunk implements GenerationContext {
@Override
public NoiseFactory noise() {
throw new UnsupportedOperationException("No noise here");
return (style, seed) -> new NoiseSampler() {
@Override
public double sample(double worldX, double worldZ) {
return FLAT_NOISE;
}
@Override
public double sample(double worldX, double y, double worldZ) {
return FLAT_NOISE;
}
};
}
@Override
@@ -535,15 +575,15 @@ public final class ApiChunk implements GenerationContext {
}
}
private static final class CarveStandIn implements IrisModule {
private static final class TerrainStandIn implements IrisModule {
@Override
public ModuleInfo info() {
return ModuleInfo.of("iris:carve", "Carving stand-in", "test");
return ModuleInfo.of("iris:terrain", "Terrain stand-in", "test");
}
@Override
public void install(StageGraph graph) {
graph.define(IrisStages.Carve.APPLY).run(context -> {
graph.define(IrisStages.Terrain.SHAPE).run(context -> {
});
}
}
@@ -1,64 +1,47 @@
package art.arcane.iris.engine.modifier;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.loader.ResourceLoader;
import art.arcane.iris.engine.UsableBlockPlatform;
import art.arcane.iris.engine.decorator.DecoratorTestEngines;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.SeedManager;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.util.project.hunk.Hunk;
import art.arcane.iris.builtin.MatterMantle;
import art.arcane.iris.core.modules.CarveTestWorld;
import art.arcane.iris.engine.mantle.components.CarveWorld;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.MatterCavern;
import art.arcane.volmlib.util.matter.MatterSlice;
import com.volmit.host.ModuleLogs;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import org.junit.After;
import org.junit.Before;
import com.volmit.block.BlockState;
import com.volmit.host.ArrayHunk;
import com.volmit.hunk.Hunk;
import com.volmit.mantle.BlockBox;
import com.volmit.resource.ResourceId;
import com.volmit.world.BiomeSample;
import com.volmit.world.TerrainSample;
import com.volmit.world.TerrainSampler;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
public class CaveApplyingBoundarySupportTest {
@Before
public void bindPlatform() {
UsableBlockPlatform.bind();
}
private static final int CEILING_Y = 42;
private static final BlockState AIR = new BlockState("minecraft:cave_air");
private static final BlockState STONE = new BlockState("minecraft:stone");
private static final BlockState SAND = new BlockState("minecraft:sand");
@After
public void unbindPlatform() {
UsableBlockPlatform.unbind();
}
private final CarveTestWorld world = new CarveTestWorld().biome("custom/floor", 1).dressing(new RecordingCaveDressing());
private final CaveBlockClasses classes = new CaveBlockClasses(new CarveTestWorld.Blocks());
@Test
@SuppressWarnings("unchecked")
public void boundaryBiomeUsesCustomMatterAtItsOwnY() {
IrisBiome customFloor = mock(IrisBiome.class);
IrisBiome resolvedCeiling = mock(IrisBiome.class);
IrisData data = mock(IrisData.class);
ResourceLoader<IrisBiome> biomeLoader = mock(ResourceLoader.class);
doReturn(biomeLoader).when(data).getBiomeLoader();
doReturn(customFloor).when(biomeLoader).load("custom/floor");
Engine engine = mock(Engine.class);
doReturn(data).when(engine).getData();
doReturn(resolvedCeiling).when(engine).getCaveBiome(anyInt(), eq(42), anyInt());
doReturn(mock(SeedManager.class)).when(engine).getSeedManager();
DecoratorTestEngines.withGeneration(engine);
CaveApplying modifier = new CaveApplying(engine, ModuleLogs.discarding());
ResourceId resolvedCeiling = CarveTestWorld.id("cave/ceiling");
CaveApplying modifier = new CaveApplying(world, new CarveWorld(world.resources().noise(), 1L, 384, 127, 8, CarveTestWorld.MIN_HEIGHT), false);
MantleChunk<Matter> mantleChunk = mock(MantleChunk.class);
Matter floorMatter = mock(Matter.class);
Matter ceilingMatter = mock(Matter.class);
@@ -73,58 +56,86 @@ public class CaveApplyingBoundarySupportTest {
doReturn(floorSlice).when(floorMatter).getSlice(MatterCavern.class);
doReturn(ceilingSlice).when(ceilingMatter).getSlice(MatterCavern.class);
doReturn(new MatterCavern(true, "custom/floor", (byte) 0)).when(floorSlice).get(1, 6, 2);
doReturn(null).when(ceilingSlice).get(1, 10, 2);
doReturn(null).when(ceilingSlice).get(1, CEILING_Y & 15, 2);
TerrainSampler terrain = new CaveBiomeTerrain((x, y, z) -> y == CEILING_Y ? Optional.of(resolvedCeiling) : Optional.empty());
CaveApplying.Application application = modifier.new Application(chunkOnly(mantleChunk), mantleChunk, terrain, 2, 2, new ArrayHunk<>(BlockState.class, 16, 64, 16, AIR));
Map<String, ResourceId> customBiomeCache = new HashMap<>();
Long2ObjectOpenHashMap<IrisBiome> caveBiomeCache = new Long2ObjectOpenHashMap<>();
Map<String, IrisBiome> customBiomeCache = new HashMap<>();
ResourceId floor = application.resolveCaveBoundaryBiome(1, 6, 2, 40, 44, customBiomeCache);
ResourceId ceiling = application.resolveCaveBoundaryBiome(1, CEILING_Y, 2, 40, 44, customBiomeCache);
IrisBiome floor = modifier.resolveCaveBoundaryBiome(
mantleChunk, 1, 6, 2, 40, 44, caveBiomeCache, customBiomeCache);
IrisBiome ceiling = modifier.resolveCaveBoundaryBiome(
mantleChunk, 1, 42, 2, 40, 44, caveBiomeCache, customBiomeCache);
assertSame(customFloor, floor);
assertSame(resolvedCeiling, ceiling);
assertEquals(CarveTestWorld.id("custom/floor"), floor);
assertEquals(resolvedCeiling, ceiling);
}
@Test
@SuppressWarnings("unchecked")
public void gravityFloorLayerRequiresSolidSupportBelowItsTarget() {
Hunk<PlatformBlockState> output = mock(Hunk.class);
PlatformBlockState air = state("minecraft:cave_air", false);
PlatformBlockState solid = state("minecraft:stone", true);
PlatformBlockState sand = state("minecraft:sand", true);
PlatformBlockState stone = state("minecraft:stone", true);
doReturn(air).when(output).getRaw(0, 4, 0);
assertFalse(CaveApplying.canReplaceCaveFloorLayer(output, 0, 5, 0, sand));
assertTrue(CaveApplying.canReplaceCaveFloorLayer(output, 0, 5, 0, stone));
doReturn(solid).when(output).getRaw(0, 4, 0);
assertTrue(CaveApplying.canReplaceCaveFloorLayer(output, 0, 5, 0, sand));
Hunk<BlockState> output = new ArrayHunk<>(BlockState.class, 1, 8, 1, AIR);
output.set(0, 4, 0, AIR);
assertFalse(CaveApplying.canReplaceCaveFloorLayer(output, 0, 5, 0, SAND, classes));
assertTrue(CaveApplying.canReplaceCaveFloorLayer(output, 0, 5, 0, STONE, classes));
output.set(0, 4, 0, STONE);
assertTrue(CaveApplying.canReplaceCaveFloorLayer(output, 0, 5, 0, SAND, classes));
}
@Test
@SuppressWarnings("unchecked")
public void gravityFloorDoesNotReceiveDecoratorsOverLowerCaveAir() {
Hunk<PlatformBlockState> output = mock(Hunk.class);
PlatformBlockState air = state("minecraft:cave_air", false);
PlatformBlockState sand = state("minecraft:sand", true);
PlatformBlockState stone = state("minecraft:stone", true);
doReturn(sand).when(output).getRaw(0, 5, 0);
doReturn(air).when(output).getRaw(0, 4, 0);
assertFalse(CaveApplying.hasStableCaveFloorSupport(output, 0, 6, 0));
doReturn(stone).when(output).getRaw(0, 4, 0);
assertTrue(CaveApplying.hasStableCaveFloorSupport(output, 0, 6, 0));
Hunk<BlockState> output = new ArrayHunk<>(BlockState.class, 1, 8, 1, AIR);
output.set(0, 5, 0, SAND);
output.set(0, 4, 0, AIR);
assertFalse(CaveApplying.hasStableCaveFloorSupport(output, 0, 6, 0, classes));
output.set(0, 4, 0, STONE);
assertTrue(CaveApplying.hasStableCaveFloorSupport(output, 0, 6, 0, classes));
}
private PlatformBlockState state(String key, boolean solid) {
PlatformBlockState state = mock(PlatformBlockState.class);
doReturn(key).when(state).key();
doReturn(solid).when(state).isSolid();
doReturn(key.equals("minecraft:sand")).when(state).hasGravity();
return state;
private static MatterMantle chunkOnly(MantleChunk<Matter> chunk) {
return new MatterMantle() {
@Override
public MantleChunk<Matter> chunk(int chunkX, int chunkZ) {
return chunk;
}
@Override
public MantleChunk<Matter> loadedChunk(int chunkX, int chunkZ) {
return null;
}
};
}
/** Terrain that knows cave biomes only. */
private record CaveBiomeTerrain(CaveBiomeAt biomes) implements TerrainSampler {
interface CaveBiomeAt {
Optional<ResourceId> at(int x, int y, int z);
}
@Override
public Optional<ResourceId> caveBiome(int worldX, int y, int worldZ) {
return biomes.at(worldX, y, worldZ);
}
@Override
public BlockBox bounds() {
throw new UnsupportedOperationException();
}
@Override
public TerrainSample column(int worldX, int worldZ) {
throw new UnsupportedOperationException();
}
@Override
public BiomeSample biome(int worldX, int y, int worldZ) {
throw new UnsupportedOperationException();
}
@Override
public int fluidHeight() {
throw new UnsupportedOperationException();
}
@Override
public OptionalInt upperDimensionY(int worldX, int worldZ) {
throw new UnsupportedOperationException();
}
}
}
@@ -1,15 +1,13 @@
package art.arcane.iris.engine.modifier;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.volmlib.util.matter.MatterCavern;
import com.volmit.block.BlockState;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class CaveApplyingFluidIntentTest {
@Test
@@ -18,18 +16,17 @@ public class CaveApplyingFluidIntentTest {
MatterCavern fluidIntent = new MatterCavern(true, "", (byte) 1);
MatterCavern lavaIntent = new MatterCavern(true, "", (byte) 2);
MatterCavern forcedAirIntent = new MatterCavern(true, "", (byte) 3);
PlatformBlockState existingFluid = mock(PlatformBlockState.class);
PlatformBlockState fluid = mock(PlatformBlockState.class);
PlatformBlockState lava = mock(PlatformBlockState.class);
PlatformBlockState air = mock(PlatformBlockState.class);
when(existingFluid.isFluid()).thenReturn(true);
BlockState fluid = new BlockState("minecraft:water");
BlockState lava = new BlockState("minecraft:lava");
BlockState air = new BlockState("minecraft:cave_air");
assertFalse(CaveApplying.hasExplicitCarveIntent(null));
assertTrue(CaveApplying.shouldPreserveExistingFluid(airIntent, existingFluid));
assertTrue(CaveApplying.shouldPreserveExistingFluid(airIntent, true));
assertTrue(CaveApplying.isFluidIntent(fluidIntent));
assertFalse(CaveApplying.shouldPreserveExistingFluid(fluidIntent, existingFluid));
assertFalse(CaveApplying.shouldPreserveExistingFluid(lavaIntent, existingFluid));
assertFalse(CaveApplying.shouldPreserveExistingFluid(forcedAirIntent, existingFluid));
assertFalse(CaveApplying.shouldPreserveExistingFluid(fluidIntent, true));
assertFalse(CaveApplying.shouldPreserveExistingFluid(lavaIntent, true));
assertFalse(CaveApplying.shouldPreserveExistingFluid(forcedAirIntent, true));
assertFalse("nothing to preserve where there is no fluid", CaveApplying.shouldPreserveExistingFluid(airIntent, false));
assertNull(CaveApplying.resolveExplicitCarveState(null, fluid, lava, air));
assertSame(fluid, CaveApplying.resolveExplicitCarveState(fluidIntent, fluid, lava, air));
assertSame(lava, CaveApplying.resolveExplicitCarveState(lavaIntent, fluid, lava, air));
@@ -46,17 +43,8 @@ public class CaveApplyingFluidIntentTest {
@Test
public void unsupportedSurfaceOreIsRemovedOnlyOverCarvedAir() {
PlatformBlockState ore = mock(PlatformBlockState.class);
PlatformBlockState ordinarySurface = mock(PlatformBlockState.class);
PlatformBlockState air = mock(PlatformBlockState.class);
PlatformBlockState solid = mock(PlatformBlockState.class);
when(ore.isOre()).thenReturn(true);
when(ordinarySurface.isOre()).thenReturn(false);
when(air.isSolid()).thenReturn(false);
when(solid.isSolid()).thenReturn(true);
assertTrue(CaveApplying.isUnsupportedSurfaceOre(ore, air));
assertFalse(CaveApplying.isUnsupportedSurfaceOre(ore, solid));
assertFalse(CaveApplying.isUnsupportedSurfaceOre(ordinarySurface, air));
assertTrue(CaveApplying.isUnsupportedSurfaceOre(true, false));
assertFalse(CaveApplying.isUnsupportedSurfaceOre(true, true));
assertFalse(CaveApplying.isUnsupportedSurfaceOre(false, false));
}
}
@@ -1,129 +0,0 @@
package art.arcane.iris.engine.modifier;
import art.arcane.iris.builtin.terrain.LayersSettings;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.modules.BuiltInPack;
import art.arcane.iris.engine.IrisComplex;
import art.arcane.iris.engine.decorator.DecoratorTestEngines;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.SeedManager;
import art.arcane.iris.engine.object.world.biome.InferredType;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.world.IrisWorld;
import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.spi.PlatformRegistries;
import art.arcane.iris.util.project.hunk.Hunk;
import art.arcane.iris.util.project.stream.ProceduralStream;
import art.arcane.volmlib.util.matter.MatterCavern;
import com.google.gson.Gson;
import com.volmit.host.ModuleLogs;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.mockito.ArgumentMatchers.anyDouble;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
public class CaveApplyingInferenceIsolationTest {
@BeforeClass
public static void bindPlatform() {
IrisPlatforms.unbind();
PlatformBlockState block = mock(PlatformBlockState.class);
PlatformRegistries registries = mock(PlatformRegistries.class);
doReturn(block).when(registries).block(anyString());
IrisPlatform platform = mock(IrisPlatform.class);
doReturn(registries).when(platform).registries();
IrisPlatforms.bind(platform);
}
@AfterClass
public static void unbindPlatform() {
IrisPlatforms.unbind();
}
@Test
@SuppressWarnings("unchecked")
public void cavePaintingDoesNotMutateSharedBiomeInference() throws Exception {
IrisBiome biome = new IrisBiome().setInferredType(InferredType.LAND);
biome.setModuleSettings(BuiltInPack.settings(new Gson().fromJson("{\"layers\": []}", LayersSettings.class)));
Engine engine = mock(Engine.class);
doReturn(mock(IrisData.class)).when(engine).getData();
doReturn(mock(IrisDimension.class)).when(engine).getDimension();
doReturn(mock(IrisComplex.class)).when(engine).getComplex();
doReturn(IrisWorld.builder().minHeight(-256).maxHeight(512).build()).when(engine).getWorld();
doReturn(mock(SeedManager.class)).when(engine).getSeedManager();
DecoratorTestEngines.withGeneration(engine);
CaveApplying modifier = new CaveApplying(engine, ModuleLogs.discarding());
Map<String, IrisBiome> customBiomes = new HashMap<>();
customBiomes.put("shared", biome);
CarveWallBuffer walls = new CarveWallBuffer(1);
walls.put(0, 1, 0, new MatterCavern(true, "shared", (byte) 0));
Method paintBoundaryZone = CaveApplying.class.getDeclaredMethod(
"paintBoundaryZone",
Hunk.class,
CarveWallBuffer.class,
int.class,
int.class,
int.class,
int.class,
int.class,
int.class,
Long2ObjectOpenHashMap.class,
Map.class
);
paintBoundaryZone.setAccessible(true);
paintBoundaryZone.invoke(
modifier,
mock(Hunk.class),
walls,
0,
0,
0,
0,
1,
1,
new Long2ObjectOpenHashMap<IrisBiome>(),
customBiomes
);
IrisBiome fallback = new IrisBiome();
ProceduralStream<IrisBiome> landStream = mock(ProceduralStream.class);
doReturn(fallback).when(landStream).get(anyDouble(), anyDouble());
IrisComplex complex = mock(IrisComplex.class, CALLS_REAL_METHODS);
Field landBiomeStream = IrisComplex.class.getDeclaredField("landBiomeStream");
landBiomeStream.setAccessible(true);
landBiomeStream.set(complex, landStream);
IrisRegion region = mock(IrisRegion.class);
doReturn(0D).when(region).getShoreHeight(anyDouble(), anyDouble());
Method fixBiomeType = IrisComplex.class.getDeclaredMethod(
"fixBiomeType",
Double.class,
IrisBiome.class,
IrisRegion.class,
Double.class,
Double.class,
double.class
);
fixBiomeType.setAccessible(true);
IrisBiome resolved = (IrisBiome) fixBiomeType.invoke(complex, 10D, biome, region, 0D, 0D, 0D);
assertSame(biome, resolved);
assertEquals(InferredType.LAND, biome.getInferredType());
}
}
@@ -0,0 +1,168 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.modifier;
import art.arcane.iris.builtin.MatterMantle;
import art.arcane.iris.core.modules.CarveTestTerrain;
import art.arcane.iris.core.modules.CarveTestWorld;
import art.arcane.iris.core.modules.InMemoryMantle;
import art.arcane.iris.engine.mantle.components.CarveWorld;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.MatterCavern;
import art.arcane.volmlib.util.matter.MatterMarker;
import com.volmit.block.BlockState;
import com.volmit.host.ArrayHunk;
import com.volmit.hunk.Hunk;
import com.volmit.resource.ResourceId;
import com.volmit.world.BiomeSample;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** The caves the mantle planned become the chunk's blocks: air, lava low down, the biome's wall, floor and ceiling, and the markers cave spawning reads. */
public class CaveApplyingTest {
private static final int HEIGHT = 64;
private static final int FLUID_HEIGHT = 20;
private static final int LAVA_HEIGHT = 4;
private static final int SURFACE = 40;
private static final BlockState STONE = new BlockState("minecraft:stone");
private static final BlockState CAVE_AIR = new BlockState("minecraft:cave_air");
private static final BlockState LAVA = new BlockState("minecraft:lava");
private static final BlockState WALL = new BlockState("minecraft:mossy_cobblestone");
private static final BlockState FLOOR = new BlockState("minecraft:moss_block");
private static final BlockState CEILING = new BlockState("minecraft:dripstone_block");
private static final ResourceId LUSH = CarveTestWorld.id("cave/lush");
private static final MatterCavern AIR_CAVERN = new MatterCavern(true, "", (byte) 0);
private static final MatterCavern FLUID_CAVERN = new MatterCavern(true, "", (byte) 1);
private static final int CAVE_X = 5;
private static final int CAVE_Z = 5;
private static final int CAVE_FLOOR_Y = 10;
private static final int CAVE_CEILING_Y = 13;
private final InMemoryMantle mantle = new InMemoryMantle(HEIGHT / 16);
private final RecordingCaveDressing dressing = new RecordingCaveDressing();
private CarveTestWorld world;
private Hunk<BlockState> blocks;
private CarveTestTerrain terrain;
@Before
public void setUp() {
world = new CarveTestWorld().biome("cave/lush", 1).dressing(dressing);
dressing.walls.put(LUSH, WALL);
dressing.floors.put(LUSH, List.of(FLOOR));
dressing.ceilings.put(LUSH, List.of(CEILING));
blocks = new ArrayHunk<>(BlockState.class, 16, HEIGHT, 16, STONE);
terrain = new CarveTestTerrain(0, 0, HEIGHT, FLUID_HEIGHT, (x, z) -> SURFACE)
.biomes((x, y, z) -> new BiomeSample(CarveTestWorld.id("region"), CarveTestWorld.id("plains"), Optional.of(LUSH)));
}
@Test
public void aPlannedCaveBecomesCaveAirWithTheBiomesWallFloorAndCeiling() {
carve(CAVE_X, CAVE_Z, CAVE_FLOOR_Y, CAVE_CEILING_Y, AIR_CAVERN);
apply(false);
for (int y = CAVE_FLOOR_Y; y <= CAVE_CEILING_Y; y++) {
assertEquals("y=" + y, CAVE_AIR, blocks.get(CAVE_X, y, CAVE_Z));
}
assertEquals("the wall beside the cave", WALL, blocks.get(CAVE_X + 1, CAVE_FLOOR_Y + 1, CAVE_Z));
assertEquals("the floor layer under it", FLOOR, blocks.get(CAVE_X, CAVE_FLOOR_Y - 1, CAVE_Z));
assertEquals("the ceiling layer over it", CEILING, blocks.get(CAVE_X, CAVE_CEILING_Y + 1, CAVE_Z));
assertEquals("rock the cave did not touch", STONE, blocks.get(CAVE_X + 3, CAVE_FLOOR_Y + 1, CAVE_Z));
}
@Test
public void lowCavesFillWithLavaAndFluidCavernsWithTheDimensionsFluid() {
dressing.fluid = new BlockState("minecraft:water");
carve(CAVE_X, CAVE_Z, LAVA_HEIGHT - 2, LAVA_HEIGHT, AIR_CAVERN);
carve(CAVE_X + 4, CAVE_Z, CAVE_FLOOR_Y, CAVE_CEILING_Y, FLUID_CAVERN);
apply(false);
assertEquals(LAVA, blocks.get(CAVE_X, LAVA_HEIGHT, CAVE_Z));
assertEquals(LAVA, blocks.get(CAVE_X, LAVA_HEIGHT - 1, CAVE_Z));
assertEquals(new BlockState("minecraft:water"), blocks.get(CAVE_X + 4, CAVE_FLOOR_Y + 1, CAVE_Z));
}
@Test
public void aDimensionAboveIsLeftAloneUnlessCarvingIsAllowedThroughIt() {
carve(CAVE_X, CAVE_Z, CAVE_FLOOR_Y, CAVE_CEILING_Y, AIR_CAVERN);
terrain.upperDimension((x, z) -> CAVE_FLOOR_Y + 1);
apply(false);
assertEquals("the first block of the upper dimension stays", STONE, blocks.get(CAVE_X, CAVE_FLOOR_Y + 1, CAVE_Z));
assertEquals("what lies below it is carved", CAVE_AIR, blocks.get(CAVE_X, CAVE_FLOOR_Y, CAVE_Z));
blocks = new ArrayHunk<>(BlockState.class, 16, HEIGHT, 16, STONE);
apply(true);
assertEquals("carving through it", CAVE_AIR, blocks.get(CAVE_X, CAVE_FLOOR_Y + 1, CAVE_Z));
}
@Test
public void markersAreStampedFromTheSeedAndPositionAlone() {
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
carve(x, z, CAVE_FLOOR_Y, CAVE_CEILING_Y, AIR_CAVERN);
}
}
apply(false);
int first = markers();
blocks = new ArrayHunk<>(BlockState.class, 16, HEIGHT, 16, STONE);
apply(false);
assertTrue("about one in sixteen of the 512 floors and ceilings", first > 0 && first < 128);
assertEquals(first, markers());
}
private void carve(int x, int z, int floorY, int ceilingY, MatterCavern cavern) {
MantleChunk<Matter> chunk = mantle.chunk(0, 0);
for (int y = floorY; y <= ceilingY; y++) {
chunk.getOrCreate(y >> 4).<MatterCavern>slice(MatterCavern.class).set(x, y & 15, z, cavern);
}
}
private void apply(boolean upperDimensionCarving) {
MatterMantle matter = new MatterMantle() {
@Override
public MantleChunk<Matter> chunk(int chunkX, int chunkZ) {
return mantle.chunk(chunkX, chunkZ);
}
@Override
public MantleChunk<Matter> loadedChunk(int chunkX, int chunkZ) {
return null;
}
};
CarveWorld carveWorld = new CarveWorld(world.resources().noise(), 1337L, HEIGHT, FLUID_HEIGHT, LAVA_HEIGHT, CarveTestWorld.MIN_HEIGHT);
new CaveApplying(world, carveWorld, upperDimensionCarving).apply(matter, terrain, 0, 0, blocks);
}
private int markers() {
int[] count = new int[1];
mantle.chunk(0, 0).iterate(MatterMarker.class, (x, y, z, marker) -> count[0]++);
return count[0];
}
}
@@ -21,16 +21,9 @@ package art.arcane.iris.engine.modifier;
import art.arcane.iris.builtin.carve.CarvingEntry;
import art.arcane.iris.builtin.carve.CarvingSettings;
import art.arcane.iris.builtin.carve.CaveDepthSettings;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.loader.ResourceLoader;
import art.arcane.iris.core.modules.BuiltInPack;
import art.arcane.iris.core.modules.IrisPackWorld;
import art.arcane.iris.engine.decorator.DecoratorTestEngines;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.object.world.IrisWorld;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.core.modules.CarveTestWorld;
import com.google.gson.Gson;
import com.volmit.FeatureAttachment.Target;
import org.junit.Before;
import org.junit.Test;
@@ -38,12 +31,10 @@ import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** What the carve module answers the host about cave biomes: the biome of the dimension's band at a height above the dimension's bottom, and the minimum depths. */
public class CaveBiomeBandsTest {
private static final int MIN_HEIGHT = -64;
private static final int MIN_HEIGHT = CarveTestWorld.MIN_HEIGHT;
private static final String BANDS = """
[{"id": "shallow", "biome": "band/shallow", "worldYRange": {"min": -64, "max": 0}},
{"id": "disabled", "enabled": false, "biome": "band/disabled", "worldYRange": {"min": 100, "max": 200}},
@@ -51,46 +42,32 @@ public class CaveBiomeBandsTest {
{"id": "padded", "biome": " band/padded ", "worldYRange": {"min": 500, "max": 600}}]
""";
private Engine engine;
private final IrisBiome shallow = mock(IrisBiome.class);
private CarveTestWorld world;
@Before
@SuppressWarnings("unchecked")
public void mockEngine() {
IrisData data = mock(IrisData.class);
ResourceLoader<IrisBiome> biomes = mock(ResourceLoader.class);
when(data.getBiomeLoader()).thenReturn(biomes);
when(biomes.load("band/shallow")).thenReturn(shallow);
when(biomes.load("band/padded")).thenReturn(mock(IrisBiome.class));
when(biomes.load("band/disabled")).thenReturn(mock(IrisBiome.class));
when(shallow.getModuleSettings()).thenReturn(BuiltInPack.settings(new CaveDepthSettings(30)));
public void declareBands() {
List<CarvingEntry> entries = new Gson().fromJson(BANDS, new com.google.gson.reflect.TypeToken<List<CarvingEntry>>() { }.getType());
IrisDimension dimension = mock(IrisDimension.class);
when(dimension.getModuleSettings()).thenReturn(BuiltInPack.settings(new CarvingSettings(entries)));
engine = mock(Engine.class);
when(engine.getData()).thenReturn(data);
when(engine.getDimension()).thenReturn(dimension);
when(engine.getWorld()).thenReturn(IrisWorld.builder().minHeight(MIN_HEIGHT).maxHeight(320).build());
DecoratorTestEngines.withGeneration(engine);
world = new CarveTestWorld()
.biome("band/shallow", 1).biome("band/padded", 1).biome("band/disabled", 1)
.dimension(new CarvingSettings(entries))
.declare(Target.BIOME, "band/shallow", new CaveDepthSettings(30));
}
@Test
public void aPositionInsideAnEnabledBandGetsTheBandsBiomeKey() {
CaveBiomeBands bands = new CaveBiomeBands();
IrisPackWorld world = engine.getGeneration().world();
assertEquals("world Y -54 is in the band from -64 to 0", Optional.of("band/shallow"), bands.overriddenBiome(world, 5, 10, 5));
assertEquals("the band's end is in it", Optional.of("band/shallow"), bands.overriddenBiome(world, 5, 64, 5));
assertEquals("above it", Optional.empty(), bands.overriddenBiome(world, 5, 65, 5));
assertEquals("a disabled band overrides nothing", Optional.empty(), bands.overriddenBiome(world, 5, 200 - MIN_HEIGHT - 50, 5));
assertEquals("a band whose biome the pack lacks overrides nothing", Optional.empty(), bands.overriddenBiome(world, 5, 305 - MIN_HEIGHT, 5));
assertEquals("the key is trimmed as the loader is asked for it", Optional.of("band/padded"), bands.overriddenBiome(world, 5, 550 - MIN_HEIGHT, 5));
assertEquals("the key is trimmed as the pack is asked for it", Optional.of("band/padded"), bands.overriddenBiome(world, 5, 550 - MIN_HEIGHT, 5));
}
@Test
public void aBiomeKeyHasTheMinimumDepthItsSettingsDeclareAndZeroWhenTheKeyIsUnknown() {
CaveBiomeBands bands = new CaveBiomeBands();
IrisPackWorld world = engine.getGeneration().world();
assertEquals(30, bands.minDepthBelowSurface(world, "band/shallow"));
assertEquals(0, bands.minDepthBelowSurface(world, "band/unknown"));
@@ -0,0 +1,85 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.modifier;
import art.arcane.iris.builtin.CaveDressing;
import art.arcane.iris.builtin.decorant.DecorationPart;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.block.BlockState;
import com.volmit.hunk.Hunk;
import com.volmit.resource.ResourceId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** A cave dressing the tests of the carve module set up by biome: the wall block, the floor and ceiling layers and the fluid, with a record of what was decorated. */
public final class RecordingCaveDressing implements CaveDressing {
public final Map<ResourceId, BlockState> walls = new HashMap<>();
public final Map<ResourceId, List<BlockState>> floors = new HashMap<>();
public final Map<ResourceId, List<BlockState>> ceilings = new HashMap<>();
public final List<String> decorated = new ArrayList<>();
public BlockState fluid;
@Override
public boolean fluidPresentAt(int x, int z) {
return fluid != null;
}
@Override
public BlockState fluidAt(Hunk<BlockState> chunk, int x, int z) {
return fluid;
}
@Override
public BlockState wall(Hunk<BlockState> chunk, ResourceId biome, RNG rng, int x, int y, int z) {
return walls.get(biome);
}
@Override
public List<BlockState> floorLayers(Hunk<BlockState> chunk, ResourceId biome, int x, int z, RNG rng, int depth, int floorY) {
return floors.getOrDefault(biome, List.of());
}
@Override
public List<BlockState> ceilingLayers(Hunk<BlockState> chunk, ResourceId biome, int x, int z, RNG rng, int depth, int ceilingY) {
return ceilings.getOrDefault(biome, List.of());
}
@Override
public boolean hasDecorators(ResourceId biome, DecorationPart part) {
return false;
}
@Override
public void decorateFloor(Hunk<BlockState> chunk, int localX, int localZ, int x, int z, ResourceId biome, int floorY, int airThickness) {
decorated.add("floor " + localX + "," + floorY + "," + localZ);
}
@Override
public void decorateCeiling(Hunk<BlockState> chunk, int localX, int localZ, int x, int z, ResourceId biome, int ceilingY, int airThickness) {
decorated.add("ceiling " + localX + "," + ceilingY + "," + localZ);
}
@Override
public BlockState deepSlateOre(Hunk<BlockState> chunk, BlockState existing, BlockState layer) {
return new BlockState("minecraft:deepslate_" + layer.material().path());
}
}
@@ -1,120 +1,70 @@
package art.arcane.iris.engine.object.terrain.carving;
import art.arcane.iris.engine.object.value.IRare;
import com.volmit.config.Range;
import art.arcane.iris.builtin.carve.CarvingEntry;
import art.arcane.iris.engine.decorator.DecoratorTestEngines;
import art.arcane.iris.engine.object.world.IrisWorld;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.loader.ResourceLoader;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineGeneration;
import art.arcane.iris.engine.framework.SeedManager;
import art.arcane.iris.builtin.carve.CarvingSettings;
import art.arcane.iris.core.modules.CarveTestWorld;
import art.arcane.iris.core.modules.IrisValues;
import art.arcane.iris.engine.object.value.IRare;
import art.arcane.iris.util.project.noise.CNG;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.block.data.BlockData;
import org.junit.BeforeClass;
import com.volmit.config.Range;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Logger;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Answers.CALLS_REAL_METHODS;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.junit.Assert.assertNotSame;
/**
* The module's pick of a cave biome band is the pick the band code made with Iris's own generators: the root by world Y, then the
* child a rarity-weighted draw of the generator's noise selects. The reference below is that code, written out again.
*/
public class CarvingResolverParityTest {
private static final int MAX_CHILD_DEPTH = 32;
private static final long CHILD_SEED_SALT = 0x9E3779B97F4A7C15L;
@BeforeClass
public static void setupBukkit() {
if (Bukkit.getServer() != null) {
return;
}
Server server = mock(Server.class);
doReturn(Logger.getLogger("IrisTest")).when(server).getLogger();
doReturn("IrisTestServer").when(server).getName();
doReturn("1.0").when(server).getVersion();
doReturn("1.0").when(server).getBukkitVersion();
doAnswer((InvocationOnMock invocation) -> namedBlockData(invocation.getArgument(0, Material.class).name().toLowerCase(Locale.ROOT))).when(server).createBlockData(any(Material.class));
doAnswer((InvocationOnMock invocation) -> namedBlockData(invocation.getArgument(0, String.class))).when(server).createBlockData(anyString());
try {
Bukkit.setServer(server);
} catch (Throwable ignored) {
}
}
private static BlockData namedBlockData(String key) {
String canonical = key.indexOf(':') >= 0 ? key : "minecraft:" + key;
BlockData data = mock(BlockData.class);
doReturn(canonical).when(data).getAsString();
return data;
}
private static final long CHILD_GENERATOR_SALT = 2137L;
private static final int CHILD_GENERATOR_SIGNATURE = 2137;
private static final double MIN_CHILD_SCALE = 0.0001D;
@Test
public void resolverStatefulOverloadsMatchLegacyResolverAcrossSampleGrid() {
public void resolverMatchesLegacyResolverAcrossSampleGrid() {
Fixture fixture = createFixture();
CarvingResolver.State state = new CarvingResolver.State();
for (int worldY = -64; worldY <= 320; worldY += 11) {
ResolvedCarvingEntry legacyRoot = legacyResolveRootEntry(fixture.engine, worldY);
ResolvedCarvingEntry statefulRoot = CarvingResolver.resolveRootEntry(fixture.engine, worldY, state);
assertSame("root mismatch at worldY=" + worldY, legacyRoot, statefulRoot);
ResolvedCarvingEntry legacyRoot = fixture.legacyRootEntry(worldY);
ResolvedCarvingEntry root = fixture.resolver.rootEntryAtWorldY(worldY);
assertSame("root mismatch at worldY=" + worldY, legacyRoot, root);
for (int worldX = -384; worldX <= 384; worldX += 29) {
for (int worldZ = -384; worldZ <= 384; worldZ += 31) {
ResolvedCarvingEntry legacyResolved = legacyResolveFromRoot(fixture.engine, legacyRoot, worldX, worldZ);
ResolvedCarvingEntry statefulResolved = CarvingResolver.resolveFromRoot(fixture.engine, statefulRoot, worldX, worldZ, state);
assertSame("entry mismatch at worldY=" + worldY + " worldX=" + worldX + " worldZ=" + worldZ, legacyResolved, statefulResolved);
ResolvedCarvingEntry legacyResolved = fixture.legacyResolveFromRoot(legacyRoot, worldX, worldZ);
ResolvedCarvingEntry resolved = fixture.resolver.resolveFromRoot(root, worldX, worldZ);
assertSame("entry mismatch at worldY=" + worldY + " worldX=" + worldX + " worldZ=" + worldZ, legacyResolved, resolved);
}
}
}
}
@Test
public void resolverStatefulOverloadsMatchLegacyResolverAcrossMixedDepthGraph() {
public void resolverMatchesLegacyResolverAcrossMixedDepthGraph() {
Fixture fixture = createMixedDepthFixture();
CarvingResolver.State state = new CarvingResolver.State();
for (int worldY = -64; worldY <= 320; worldY += 17) {
ResolvedCarvingEntry legacyRoot = legacyResolveRootEntry(fixture.engine, worldY);
ResolvedCarvingEntry statefulRoot = CarvingResolver.resolveRootEntry(fixture.engine, worldY, state);
assertSame("mixed root mismatch at worldY=" + worldY, legacyRoot, statefulRoot);
ResolvedCarvingEntry legacyRoot = fixture.legacyRootEntry(worldY);
ResolvedCarvingEntry root = fixture.resolver.rootEntryAtWorldY(worldY);
assertSame("mixed root mismatch at worldY=" + worldY, legacyRoot, root);
for (int worldX = -640; worldX <= 640; worldX += 79) {
for (int worldZ = -640; worldZ <= 640; worldZ += 83) {
ResolvedCarvingEntry legacyResolved = legacyResolveFromRoot(fixture.engine, legacyRoot, worldX, worldZ);
ResolvedCarvingEntry statefulResolved = CarvingResolver.resolveFromRoot(fixture.engine, statefulRoot, worldX, worldZ, state);
assertSame("mixed entry mismatch at worldY=" + worldY + " worldX=" + worldX + " worldZ=" + worldZ, legacyResolved, statefulResolved);
ResolvedCarvingEntry legacyResolved = fixture.legacyResolveFromRoot(legacyRoot, worldX, worldZ);
ResolvedCarvingEntry resolved = fixture.resolver.resolveFromRoot(root, worldX, worldZ);
assertSame("mixed entry mismatch at worldY=" + worldY + " worldX=" + worldX + " worldZ=" + worldZ, legacyResolved, resolved);
}
}
}
@@ -123,324 +73,86 @@ public class CarvingResolverParityTest {
@Test
public void columnAnchoredChunkPlanResolutionIsStableAcrossRepeatedBuilds() {
Fixture fixture = createMixedDepthFixture();
CarvingResolver.State state = new CarvingResolver.State();
ResolvedCarvingEntry root = legacyResolveRootEntry(fixture.engine, 80);
ResolvedCarvingEntry root = fixture.legacyRootEntry(80);
for (int chunkX = -24; chunkX <= 24; chunkX += 6) {
for (int chunkZ = -24; chunkZ <= 24; chunkZ += 6) {
ResolvedCarvingEntry[] firstPlan = buildColumnPlan(fixture.engine, root, chunkX, chunkZ, state);
ResolvedCarvingEntry[] secondPlan = buildColumnPlan(fixture.engine, root, chunkX, chunkZ, state);
ResolvedCarvingEntry[] firstPlan = buildColumnPlan(fixture.resolver, root, chunkX, chunkZ);
ResolvedCarvingEntry[] secondPlan = buildColumnPlan(fixture.resolver, root, chunkX, chunkZ);
for (int columnIndex = 0; columnIndex < firstPlan.length; columnIndex++) {
assertSame(
"column plan mismatch at chunkX=" + chunkX + " chunkZ=" + chunkZ + " columnIndex=" + columnIndex,
firstPlan[columnIndex],
secondPlan[columnIndex]
);
assertSame("column plan mismatch at chunkX=" + chunkX + " chunkZ=" + chunkZ + " columnIndex=" + columnIndex,
firstPlan[columnIndex], secondPlan[columnIndex]);
}
}
}
}
@Test
public void sharedResolverStateNeverCarriesDimensionEntriesAcrossEngines() {
public void eachWorldKeepsItsOwnBands() {
Fixture first = createFixture();
Fixture second = createMixedDepthFixture();
CarvingResolver.State state = new CarvingResolver.State();
ResolvedCarvingEntry firstExpected = legacyResolveRootEntry(first.engine, 80);
ResolvedCarvingEntry secondExpected = legacyResolveRootEntry(second.engine, 80);
ResolvedCarvingEntry firstExpected = first.legacyRootEntry(80);
ResolvedCarvingEntry secondExpected = second.legacyRootEntry(80);
assertSame(firstExpected, CarvingResolver.resolveRootEntry(first.engine, 80, state));
assertSame(secondExpected, CarvingResolver.resolveRootEntry(second.engine, 80, state));
assertSame(firstExpected, CarvingResolver.resolveRootEntry(first.engine, 80, state));
assertSame(firstExpected, first.resolver.rootEntryAtWorldY(80));
assertSame(secondExpected, second.resolver.rootEntryAtWorldY(80));
assertSame(firstExpected, first.resolver.rootEntryAtWorldY(80));
assertNotSame(firstExpected, secondExpected);
}
@Test
public void threadLocalResolverNeverCarriesDimensionEntriesAcrossEngines() {
Fixture first = createFixture();
Fixture second = createMixedDepthFixture();
int worldY = 83;
public void aWorldReadsItsBandsFromTheDimensionsSettings() {
CarveTestWorld world = new CarveTestWorld().biome("root-low", 6)
.dimension(new CarvingSettings(List.of(buildEntry("root-low", "root-low", Range.of(-64, 120), 4, List.of()))));
ResolvedCarvingEntry firstExpected = legacyResolveRootEntry(first.engine, worldY);
ResolvedCarvingEntry secondExpected = legacyResolveRootEntry(second.engine, worldY);
CarvingResolver resolver = CarvingResolver.of(world);
assertSame(firstExpected, CarvingResolver.resolveRootEntry(first.engine, worldY));
assertSame(secondExpected, CarvingResolver.resolveRootEntry(second.engine, worldY));
}
@Test
public void threadLocalResolverInvalidatesWhenTheSameEnginePublishesReplacementData() {
Fixture first = createFixture();
Fixture replacement = createMixedDepthFixture();
AtomicReference<IrisDimension> dimension = new AtomicReference<>(first.engine.getDimension());
AtomicReference<IrisData> data = new AtomicReference<>(first.engine.getData());
AtomicReference<EngineGeneration> generation = new AtomicReference<>(first.engine.getGeneration());
Engine engine = mock(Engine.class, CALLS_REAL_METHODS);
doAnswer((InvocationOnMock invocation) -> dimension.get()).when(engine).getDimension();
doAnswer((InvocationOnMock invocation) -> data.get()).when(engine).getData();
doAnswer((InvocationOnMock invocation) -> generation.get()).when(engine).getGeneration();
int worldY = 83;
ResolvedCarvingEntry firstExpected = legacyResolveRootEntry(first.engine, worldY);
ResolvedCarvingEntry replacementExpected = legacyResolveRootEntry(replacement.engine, worldY);
assertSame(firstExpected, CarvingResolver.resolveRootEntry(engine, worldY));
dimension.set(replacement.engine.getDimension());
data.set(replacement.engine.getData());
generation.set(replacement.engine.getGeneration());
assertSame(replacementExpected, CarvingResolver.resolveRootEntry(engine, worldY));
}
@Test
public void resolverStateUsesWeakRuntimeIdentityBindings() throws NoSuchFieldException {
Field engineIdentity = CarvingResolver.State.class.getDeclaredField("engineIdentity");
Field dimensionIdentity = CarvingResolver.State.class.getDeclaredField("dimensionIdentity");
Field dataIdentity = CarvingResolver.State.class.getDeclaredField("dataIdentity");
assertSame(WeakReference.class, engineIdentity.getType());
assertSame(WeakReference.class, dimensionIdentity.getType());
assertSame(WeakReference.class, dataIdentity.getType());
}
@Test(timeout = 20_000L)
public void longLivedWorkerDoesNotRetainPopulatedThreadLocalStateOrEngine() throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
CountDownLatch blockerStarted = new CountDownLatch(1);
CountDownLatch releaseBlocker = new CountDownLatch(1);
try {
LifetimeReferences references = executor.submit(this::populateThreadLocalLifetimeReferences).get();
Future<?> blocker = executor.submit(() -> {
blockerStarted.countDown();
releaseBlocker.await();
return null;
});
assertTrue(blockerStarted.await(5L, TimeUnit.SECONDS));
awaitCollection(references);
releaseBlocker.countDown();
blocker.get(5L, TimeUnit.SECONDS);
} finally {
releaseBlocker.countDown();
executor.shutdownNow();
assertTrue(executor.awaitTermination(5L, TimeUnit.SECONDS));
}
}
private LifetimeReferences populateThreadLocalLifetimeReferences() throws Exception {
RetainedFixture fixture = createRetainedFixture();
assertNotNull(CarvingResolver.resolveRootEntry(fixture.engine(), 80));
Field threadStateField = CarvingResolver.class.getDeclaredField("THREAD_STATE");
threadStateField.setAccessible(true);
ThreadLocal<?> threadState = (ThreadLocal<?>) threadStateField.get(null);
Object value = threadState.get();
assertTrue(value instanceof WeakReference<?>);
@SuppressWarnings("unchecked")
WeakReference<CarvingResolver.State> state =
(WeakReference<CarvingResolver.State>) value;
CarvingResolver.State populatedState = state.get();
assertNotNull(populatedState);
Field biomeCacheField = CarvingResolver.State.class.getDeclaredField("biomeCache");
biomeCacheField.setAccessible(true);
assertFalse(((Map<?, ?>) biomeCacheField.get(populatedState)).isEmpty());
return new LifetimeReferences(
state,
new WeakReference<>(fixture.engine()));
}
private static void awaitCollection(LifetimeReferences references) throws InterruptedException {
for (int attempt = 0; attempt < 100; attempt++) {
System.gc();
if (references.state().get() == null
&& references.engine().get() == null) {
return;
}
byte[] pressure = new byte[1_048_576];
pressure[0] = (byte) attempt;
Thread.sleep(10L);
}
assertTrue("Thread-local State was retained", references.state().get() == null);
assertTrue("Engine was retained", references.engine().get() == null);
}
@Test
public void explicitStateRemainsStronglyCallerOwned() throws Exception {
RetainedFixture fixture = createRetainedFixture();
CarvingResolver.State state = new CarvingResolver.State();
assertSame(fixture.entry(), CarvingResolver.resolveRootEntry(
fixture.engine(), 80, state));
Field rootEntriesField = CarvingResolver.State.class
.getDeclaredField("rootEntriesByWorldY");
rootEntriesField.setAccessible(true);
System.gc();
assertSame(fixture.entry(), ((Map<?, ?>) rootEntriesField.get(state)).get(80));
}
private RetainedFixture createRetainedFixture() {
IrisData data = mock(IrisData.class);
IrisBiome biome = new IrisBiome();
biome.setLoader(data);
@SuppressWarnings("unchecked")
ResourceLoader<IrisBiome> biomeLoader = mock(ResourceLoader.class);
doReturn(biome).when(biomeLoader).load("retained");
doReturn(biomeLoader).when(data).getBiomeLoader();
CarvingBands bands = new CarvingBands(List.of(buildEntry("retained", "retained", Range.of(-64, 320), 0, List.of())));
IrisDimension dimension = new IrisDimension();
Engine[] engine = new Engine[1];
AtomicReference<EngineGeneration> generation = new AtomicReference<>();
engine[0] = (Engine) Proxy.newProxyInstance(
Engine.class.getClassLoader(),
new Class<?>[]{Engine.class},
(proxy, method, arguments) -> switch (method.getName()) {
case "getDimension" -> dimension;
case "getData" -> data;
case "getGeneration" -> generation.updateAndGet(existing -> existing != null ? existing : generationWith(engine[0], bands));
case "hashCode" -> System.identityHashCode(proxy);
case "equals" -> proxy == arguments[0];
case "toString" -> "carving-retention-test-engine";
default -> throw new UnsupportedOperationException(method.toString());
});
return new RetainedFixture(engine[0], bands.entries().getFirst());
assertSame(resolver, CarvingResolver.of(world));
assertSame(resolver.index().get("root-low"), resolver.rootEntryAt(80 - CarveTestWorld.MIN_HEIGHT));
assertNull(resolver.rootEntryAtWorldY(121));
}
private Fixture createFixture() {
IrisBiome rootLowBiome = mock(IrisBiome.class);
IrisBiome rootHighBiome = mock(IrisBiome.class);
IrisBiome childABiome = mock(IrisBiome.class);
IrisBiome childBBiome = mock(IrisBiome.class);
IrisBiome childCBiome = mock(IrisBiome.class);
IrisBiome fallbackBiome = mock(IrisBiome.class);
IrisBiome surfaceBiome = mock(IrisBiome.class);
doReturn(6).when(rootLowBiome).getRarity();
doReturn(4).when(rootHighBiome).getRarity();
doReturn(2).when(childABiome).getRarity();
doReturn(5).when(childBBiome).getRarity();
doReturn(1).when(childCBiome).getRarity();
@SuppressWarnings("unchecked")
ResourceLoader<IrisBiome> biomeLoader = mock(ResourceLoader.class);
doReturn(rootLowBiome).when(biomeLoader).load("root-low");
doReturn(rootHighBiome).when(biomeLoader).load("root-high");
doReturn(childABiome).when(biomeLoader).load("child-a");
doReturn(childBBiome).when(biomeLoader).load("child-b");
doReturn(childCBiome).when(biomeLoader).load("child-c");
IrisData data = mock(IrisData.class);
doReturn(biomeLoader).when(data).getBiomeLoader();
CarvingEntry rootLow = buildEntry("root-low", "root-low", Range.of(-64, 120), 4, List.of("child-a", "child-b"));
CarvingEntry rootHigh = buildEntry("root-high", "root-high", Range.of(121, 320), 3, List.of("child-b", "child-c"));
CarvingEntry childA = buildEntry("child-a", "child-a", Range.of(-2048, -1024), 3, List.of("child-b"));
CarvingEntry childB = buildEntry("child-b", "child-b", Range.of(-2048, -1024), 2, List.of("child-c", "child-a"));
CarvingEntry childC = buildEntry("child-c", "child-c", Range.of(-2048, -1024), 1, List.of());
CarvingBands bands = new CarvingBands(List.of(rootLow, rootHigh, childA, childB, childC));
IrisDimension dimension = mock(IrisDimension.class);
Engine engine = mock(Engine.class, CALLS_REAL_METHODS);
doReturn(dimension).when(engine).getDimension();
doReturn(data).when(engine).getData();
doReturn(new SeedManager(913_531_771L)).when(engine).getSeedManager();
doReturn(IrisWorld.builder().minHeight(-64).maxHeight(320).build()).when(engine).getWorld();
doReturn(surfaceBiome).when(engine).getSurfaceBiome(anyInt(), anyInt());
doReturn(fallbackBiome).when(engine).getCaveBiome(anyInt(), anyInt());
DecoratorTestEngines.withGeneration(engine).state(CarvingBands.class, ignored -> bands);
return new Fixture(engine);
CarveTestWorld world = new CarveTestWorld().carveSeed(913_531_771L)
.biome("root-low", 6).biome("root-high", 4).biome("child-a", 2).biome("child-b", 5).biome("child-c", 1);
return new Fixture(world, List.of(
buildEntry("root-low", "root-low", Range.of(-64, 120), 4, List.of("child-a", "child-b")),
buildEntry("root-high", "root-high", Range.of(121, 320), 3, List.of("child-b", "child-c")),
buildEntry("child-a", "child-a", Range.of(-2048, -1024), 3, List.of("child-b")),
buildEntry("child-b", "child-b", Range.of(-2048, -1024), 2, List.of("child-c", "child-a")),
buildEntry("child-c", "child-c", Range.of(-2048, -1024), 1, List.of())));
}
private Fixture createMixedDepthFixture() {
IrisBiome rootLowBiome = mock(IrisBiome.class);
IrisBiome rootHighBiome = mock(IrisBiome.class);
IrisBiome childABiome = mock(IrisBiome.class);
IrisBiome childBBiome = mock(IrisBiome.class);
IrisBiome childCBiome = mock(IrisBiome.class);
IrisBiome childDBiome = mock(IrisBiome.class);
IrisBiome childEBiome = mock(IrisBiome.class);
IrisBiome childFBiome = mock(IrisBiome.class);
IrisBiome childGBiome = mock(IrisBiome.class);
IrisBiome fallbackBiome = mock(IrisBiome.class);
IrisBiome surfaceBiome = mock(IrisBiome.class);
doReturn(7).when(rootLowBiome).getRarity();
doReturn(5).when(rootHighBiome).getRarity();
doReturn(2).when(childABiome).getRarity();
doReturn(3).when(childBBiome).getRarity();
doReturn(6).when(childCBiome).getRarity();
doReturn(1).when(childDBiome).getRarity();
doReturn(4).when(childEBiome).getRarity();
doReturn(8).when(childFBiome).getRarity();
doReturn(2).when(childGBiome).getRarity();
@SuppressWarnings("unchecked")
ResourceLoader<IrisBiome> biomeLoader = mock(ResourceLoader.class);
doReturn(rootLowBiome).when(biomeLoader).load("root-low");
doReturn(rootHighBiome).when(biomeLoader).load("root-high");
doReturn(childABiome).when(biomeLoader).load("child-a");
doReturn(childBBiome).when(biomeLoader).load("child-b");
doReturn(childCBiome).when(biomeLoader).load("child-c");
doReturn(childDBiome).when(biomeLoader).load("child-d");
doReturn(childEBiome).when(biomeLoader).load("child-e");
doReturn(childFBiome).when(biomeLoader).load("child-f");
doReturn(childGBiome).when(biomeLoader).load("child-g");
IrisData data = mock(IrisData.class);
doReturn(biomeLoader).when(data).getBiomeLoader();
CarvingEntry rootLow = buildEntry("root-low", "root-low", Range.of(-64, 120), 7, List.of("child-a", "child-d", "child-e"));
CarvingEntry rootHigh = buildEntry("root-high", "root-high", Range.of(121, 320), 6, List.of("child-b", "child-c", "child-f"));
CarvingEntry childA = buildEntry("child-a", "child-a", Range.of(-4096, 4096), 5, List.of("child-b", "child-g"));
CarvingEntry childB = buildEntry("child-b", "child-b", Range.of(-4096, 4096), 1, List.of("child-c"));
CarvingEntry childC = buildEntry("child-c", "child-c", Range.of(-4096, 4096), 0, List.of());
CarvingEntry childD = buildEntry("child-d", "child-d", Range.of(-4096, 4096), 6, List.of("child-e", "child-f"));
CarvingEntry childE = buildEntry("child-e", "child-e", Range.of(-4096, 4096), 2, List.of("child-a"));
CarvingEntry childF = buildEntry("child-f", "child-f", Range.of(-4096, 4096), 8, List.of("child-g", "child-c"));
CarvingEntry childG = buildEntry("child-g", "child-g", Range.of(-4096, 4096), 3, List.of("child-d"));
CarvingBands bands = new CarvingBands(List.of(rootLow, rootHigh, childA, childB, childC, childD, childE, childF, childG));
IrisDimension dimension = mock(IrisDimension.class);
Engine engine = mock(Engine.class, CALLS_REAL_METHODS);
doReturn(dimension).when(engine).getDimension();
doReturn(data).when(engine).getData();
doReturn(new SeedManager(4_627_991_643L)).when(engine).getSeedManager();
doReturn(IrisWorld.builder().minHeight(-64).maxHeight(320).build()).when(engine).getWorld();
doReturn(surfaceBiome).when(engine).getSurfaceBiome(anyInt(), anyInt());
doReturn(fallbackBiome).when(engine).getCaveBiome(anyInt(), anyInt());
DecoratorTestEngines.withGeneration(engine).state(CarvingBands.class, ignored -> bands);
return new Fixture(engine);
CarveTestWorld world = new CarveTestWorld().carveSeed(4_627_991_643L)
.biome("root-low", 7).biome("root-high", 5).biome("child-a", 2).biome("child-b", 3).biome("child-c", 6)
.biome("child-d", 1).biome("child-e", 4).biome("child-f", 8).biome("child-g", 2);
return new Fixture(world, List.of(
buildEntry("root-low", "root-low", Range.of(-64, 120), 7, List.of("child-a", "child-d", "child-e")),
buildEntry("root-high", "root-high", Range.of(121, 320), 6, List.of("child-b", "child-c", "child-f")),
buildEntry("child-a", "child-a", Range.of(-4096, 4096), 5, List.of("child-b", "child-g")),
buildEntry("child-b", "child-b", Range.of(-4096, 4096), 1, List.of("child-c")),
buildEntry("child-c", "child-c", Range.of(-4096, 4096), 0, List.of()),
buildEntry("child-d", "child-d", Range.of(-4096, 4096), 6, List.of("child-e", "child-f")),
buildEntry("child-e", "child-e", Range.of(-4096, 4096), 2, List.of("child-a")),
buildEntry("child-f", "child-f", Range.of(-4096, 4096), 8, List.of("child-g", "child-c")),
buildEntry("child-g", "child-g", Range.of(-4096, 4096), 3, List.of("child-d"))));
}
private ResolvedCarvingEntry[] buildColumnPlan(Engine engine, ResolvedCarvingEntry rootEntry, int chunkX, int chunkZ, CarvingResolver.State state) {
private ResolvedCarvingEntry[] buildColumnPlan(CarvingResolver resolver, ResolvedCarvingEntry rootEntry, int chunkX, int chunkZ) {
ResolvedCarvingEntry[] plan = new ResolvedCarvingEntry[256];
for (int localX = 0; localX < 16; localX++) {
int worldX = (chunkX << 4) + localX;
for (int localZ = 0; localZ < 16; localZ++) {
int worldZ = (chunkZ << 4) + localZ;
int columnIndex = (localX << 4) | localZ;
plan[columnIndex] = CarvingResolver.resolveFromRoot(engine, rootEntry, worldX, worldZ, state);
plan[(localX << 4) | localZ] = resolver.resolveFromRoot(rootEntry, worldX, worldZ);
}
}
return plan;
}
private static EngineGeneration generationWith(Engine engine, CarvingBands bands) {
EngineGeneration generation = new EngineGeneration(engine);
generation.state(CarvingBands.class, ignored -> bands);
return generation;
}
private CarvingEntry buildEntry(String id, String biome, Range worldRange, int depth, List<String> children) {
private static CarvingEntry buildEntry(String id, String biome, Range worldRange, int depth, List<String> children) {
JsonObject json = new JsonObject();
json.addProperty("id", id);
json.addProperty("biome", biome);
@@ -453,158 +165,123 @@ public class CarvingResolverParityTest {
return new Gson().fromJson(json, CarvingEntry.class);
}
private ResolvedCarvingEntry legacyResolveRootEntry(Engine engine, int worldY) {
List<ResolvedCarvingEntry> entries = CarvingBands.of(engine).entries();
if (entries.isEmpty()) {
return null;
}
ResolvedCarvingEntry resolved = null;
for (ResolvedCarvingEntry entry : entries) {
if (!legacyIsRootCandidate(engine, entry, worldY)) {
continue;
}
resolved = entry;
}
return resolved;
}
private ResolvedCarvingEntry legacyResolveFromRoot(Engine engine, ResolvedCarvingEntry rootEntry, int worldX, int worldZ) {
if (rootEntry == null) {
return null;
}
IrisBiome rootBiome = legacyResolveEntryBiome(engine, rootEntry);
if (rootBiome == null) {
return null;
}
int remainingDepth = clampDepth(rootEntry.childRecursionDepth());
if (remainingDepth <= 0) {
return rootEntry;
}
Map<String, ResolvedCarvingEntry> entryIndex = CarvingBands.of(engine).index();
ResolvedCarvingEntry current = rootEntry;
int depth = remainingDepth;
while (depth > 0) {
ResolvedCarvingEntry selected = legacySelectChild(engine, current, worldX, worldZ, entryIndex);
if (selected == null || selected == current) {
break;
}
depth--;
int childDepthLimit = clampDepth(selected.childRecursionDepth());
if (childDepthLimit < depth) {
depth = childDepthLimit;
}
current = selected;
}
return current;
}
private IrisBiome legacyResolveEntryBiome(Engine engine, ResolvedCarvingEntry entry) {
if (entry == null) {
return null;
}
return entry.realBiome(engine.getData());
}
private boolean legacyIsRootCandidate(Engine engine, ResolvedCarvingEntry entry, int worldY) {
if (entry == null || !entry.enabled()) {
return false;
}
Range worldYRange = entry.worldYRange();
if (worldYRange != null && !worldYRange.contains(worldY)) {
return false;
}
return legacyResolveEntryBiome(engine, entry) != null;
}
private ResolvedCarvingEntry legacySelectChild(
Engine engine,
ResolvedCarvingEntry parent,
int worldX,
int worldZ,
Map<String, ResolvedCarvingEntry> entryIndex
) {
List<String> children = parent.children();
if (children.isEmpty()) {
return parent;
}
IrisBiome parentBiome = legacyResolveEntryBiome(engine, parent);
if (parentBiome == null) {
return parent;
}
KList<LegacyCarvingChoice> options = new KList<>();
for (String childId : children) {
if (childId == null || childId.isBlank()) {
continue;
}
ResolvedCarvingEntry child = entryIndex.get(childId.trim());
if (child == null || !child.enabled()) {
continue;
}
IrisBiome childBiome = legacyResolveEntryBiome(engine, child);
if (childBiome == null) {
continue;
}
options.add(new LegacyCarvingChoice(child, rarity(childBiome)));
}
options.add(new LegacyCarvingChoice(parent, rarity(parentBiome)));
if (options.size() <= 1) {
return parent;
}
long seed = engine.getSeedManager().getCarve() ^ CHILD_SEED_SALT;
CNG childGenerator = parent.childrenGenerator(seed, engine.getData());
LegacyCarvingChoice selected = childGenerator.fitRarity(options, worldX, worldZ);
if (selected == null || selected.entry == null) {
return parent;
}
return selected.entry;
}
private int rarity(IrisBiome biome) {
if (biome == null) {
return 1;
}
int rarity = biome.getRarity();
return Math.max(rarity, 1);
}
private int clampDepth(int depth) {
private static int clampDepth(int depth) {
if (depth <= 0) {
return 0;
}
return Math.min(depth, MAX_CHILD_DEPTH);
}
private record Fixture(Engine engine) {
}
/** The module's resolver, and the band code as it was, over the same entries and world. */
private static final class Fixture {
private final CarveTestWorld world;
private final CarvingResolver resolver;
private final Map<String, CarvingEntry> settingsById = new HashMap<>();
private record RetainedFixture(Engine engine, ResolvedCarvingEntry entry) {
}
private Fixture(CarveTestWorld world, List<CarvingEntry> entries) {
this.world = world;
this.resolver = new CarvingResolver(world, entries);
entries.forEach(entry -> settingsById.put(entry.id(), entry));
}
private record LifetimeReferences(
WeakReference<CarvingResolver.State> state,
WeakReference<Engine> engine
) {
private ResolvedCarvingEntry legacyRootEntry(int worldY) {
ResolvedCarvingEntry resolved = null;
for (ResolvedCarvingEntry entry : resolver.entries()) {
if (!entry.enabled()) {
continue;
}
Range worldYRange = entry.worldYRange();
if (worldYRange != null && !worldYRange.contains(worldY)) {
continue;
}
if (resolver.entryBiome(entry) == null) {
continue;
}
resolved = entry;
}
return resolved;
}
private ResolvedCarvingEntry legacyResolveFromRoot(ResolvedCarvingEntry rootEntry, int worldX, int worldZ) {
if (rootEntry == null || resolver.entryBiome(rootEntry) == null) {
return null;
}
int remainingDepth = clampDepth(rootEntry.childRecursionDepth());
if (remainingDepth <= 0) {
return rootEntry;
}
ResolvedCarvingEntry current = rootEntry;
int depth = remainingDepth;
while (depth > 0) {
ResolvedCarvingEntry selected = legacySelectChild(current, worldX, worldZ);
if (selected == null || selected == current) {
break;
}
depth--;
int childDepthLimit = clampDepth(selected.childRecursionDepth());
if (childDepthLimit < depth) {
depth = childDepthLimit;
}
current = selected;
}
return current;
}
private ResolvedCarvingEntry legacySelectChild(ResolvedCarvingEntry parent, int worldX, int worldZ) {
List<String> children = parent.children();
if (children.isEmpty()) {
return parent;
}
if (resolver.entryBiome(parent) == null) {
return parent;
}
KList<LegacyCarvingChoice> options = new KList<>();
for (String childId : children) {
if (childId == null || childId.isBlank()) {
continue;
}
ResolvedCarvingEntry child = resolver.index().get(childId.trim());
if (child == null || !child.enabled() || resolver.entryBiome(child) == null) {
continue;
}
options.add(new LegacyCarvingChoice(child, rarity(child)));
}
options.add(new LegacyCarvingChoice(parent, rarity(parent)));
if (options.size() <= 1) {
return parent;
}
long seed = world.seed(art.arcane.iris.builtin.IrisSeed.CARVE) ^ CHILD_SEED_SALT;
LegacyCarvingChoice selected = legacyChildrenGenerator(parent, seed).fitRarity(options, worldX, worldZ);
if (selected == null || selected.entry == null) {
return parent;
}
return selected.entry;
}
private int rarity(ResolvedCarvingEntry entry) {
return Math.max(resolver.entryBiome(entry).rarity(), 1);
}
/** The generator of an entry's children as Iris built it: its style created from the entry's seed, then scaled by the shrink factor. */
private CNG legacyChildrenGenerator(ResolvedCarvingEntry parent, long seed) {
CarvingEntry settings = settingsById.get(parent.id());
long idHash = settings.id().trim().hashCode();
long generatorSeed = seed ^ (idHash << 32) ^ CHILD_GENERATOR_SALT;
double scale = Math.max(MIN_CHILD_SCALE, settings.childShrinkFactor());
RNG random = new RNG(generatorSeed);
return IrisValues.generatorStyle(settings.childStyle()).createNoCache(random.nextParallelRNG(CHILD_GENERATOR_SIGNATURE), world.data())
.bake().scale(scale).bake();
}
}
private static final class LegacyCarvingChoice implements IRare {
@@ -152,20 +152,20 @@ public class CaveProfileDecodingTest {
}
@Test
public void carversReadTheProfileAsIrisStylesAndRanges() {
ResolvedCaveProfile resolved = ResolvedCaveProfile.of(gson.fromJson(OVERWORLD_CAVE_PROFILE, CaveProfile.class));
public void carversReadTheProfileThroughItsApiValues() {
CaveProfile profile = gson.fromJson(OVERWORLD_CAVE_PROFILE, CaveProfile.class);
assertEquals(6, resolved.verticalRange().getMin(), 0);
assertEquals(700, resolved.verticalRange().getMax(), 0);
assertEquals("PERLIN_IRIS", resolved.baseDensityStyle().getStyle().name());
assertEquals(0.72, resolved.baseDensityStyle().getZoom(), 0);
assertEquals("FRACTAL_WATER", resolved.warpStyle().getStyle().name());
assertEquals(0.88, resolved.surfaceBreakStyle().getZoom(), 0);
assertEquals(-0.06, resolved.densityThreshold().getMax(), 0);
assertEquals("SIMPLEX", resolved.densityThreshold().getStyle().getStyle().name());
assertEquals(2, resolved.modules().size());
assertEquals(0.08, resolved.modules().get(0).weight(), 0);
assertEquals(24, resolved.modules().get(0).verticalRange().getMin(), 0);
assertTrue(resolved.modules().get(1).invert());
assertEquals(6, profile.verticalRange().min(), 0);
assertEquals(700, profile.verticalRange().max(), 0);
assertEquals("PERLIN_IRIS", profile.baseDensityStyle().style());
assertEquals(0.72, profile.baseDensityStyle().zoom(), 0);
assertEquals("FRACTAL_WATER", profile.warpStyle().style());
assertEquals(0.88, profile.surfaceBreakStyle().zoom(), 0);
assertEquals(-0.06, profile.densityThreshold().max(), 0);
assertEquals("SIMPLEX", profile.densityThreshold().style().style());
assertEquals(2, profile.modules().size());
assertEquals(0.08, profile.modules().get(0).weight(), 0);
assertEquals(24, profile.modules().get(0).verticalRange().min(), 0);
assertTrue(profile.modules().get(1).invert());
}
}