Replace the noise cave profile with listed caves

Packs now describe caves as files in caves/ and list them under "caves"
on the dimension, regions and biomes. The lists of a column add up.

A cave has tunnels, caverns or both. Tunnels are the lines where two of
three smooth fields meet, so they run long and join into one network.
Caverns are rooms where one slow field rises over a threshold; pillars
are columns where a second, 2D field peaks. Sizes are written in blocks.

Every shape reads its fields on a 4-block lattice and decides per block
from the interpolated values, so thin tunnels survive between lattice
points. The adaptive sampler and the 2,268-line carver are gone.

Removed with the profile: cave water pockets and their support check,
profile defaults for cave objects, and profile carving of floating
islands. Floating islands still carve with carveStyle.

Pack validation read module settings before the pack had resources; a
module that turns keys into ids then failed the pack. Linked biomes are
now skipped there and checked when the pack loads.
This commit is contained in:
piexel committed 2026-11-12 21:21:40 +01:00
1 parent 573e631bb8
commit 7d166df70f
60 files changed
+1996 -5915

No files matched your search

@@ -105,7 +105,9 @@ public final class ModuleSettings {
}
private Set<String> linkedBiomes(IrisPackResources resources, Function<LinkedBiomes, Set<ResourceId>> pick) {
if (values.isEmpty()) {
// Pack validation reads dimensions through pack data that has no resources of its own, and a module's
// settings cannot turn keys into ids without them. The biomes they link are checked when the pack loads.
if (values.isEmpty() || resources == null) {
return Set.of();
}
Set<String> biomes = new LinkedHashSet<>();
@@ -34,7 +34,7 @@ import java.util.Locale;
* Catches the shared IrisStyledRange class default (min 16, max 32) leaking into pack content.
* The POJO cannot distinguish an empty object from an explicit 16/32 after Gson runs, so the raw
* JSON is the only place this mistake is still visible: an objects[].densityStyle of {} places
* 16-32 objects per chunk, and a caveProfile.densityThreshold of {} hollows the whole cave range.
* 16-32 objects per chunk.
*/
final class PackStyledRangeDefaultValidator {
private static final String STYLE_RANGE_SNIPPET_FOLDER = "snippet/style-range/";
@@ -74,7 +74,6 @@ final class PackStyledRangeDefaultValidator {
}
validateObjectPlacements(packFolder, type, key, json, errors, warnings);
validateCaveProfileThreshold(packFolder, type, key, json.optJSONObject("caveProfile"), errors, warnings);
}
}
return new Validation(errors, warnings);
@@ -98,18 +97,6 @@ final class PackStyledRangeDefaultValidator {
}
}
private static void validateCaveProfileThreshold(File packFolder, String type, String key, JSONObject caveProfile,
List<String> errors, List<String> warnings) {
if (caveProfile == null || !caveProfile.has("densityThreshold") || caveProfile.isNull("densityThreshold")) {
return;
}
checkRange(packFolder, caveProfile.opt("densityThreshold"),
type + " '" + key + "' caveProfile.densityThreshold",
"a carve threshold of 16-32, hollowing the entire vertical range",
"remove densityThreshold to keep the cave profile default",
errors, warnings);
}
private static void checkRange(File packFolder, Object raw, String path, String consequence, String removal,
List<String> errors, List<String> warnings) {
JSONObject range = null;
@@ -18,7 +18,6 @@
package art.arcane.iris.core.modules;
import art.arcane.iris.builtin.anchor.ObjectPlaceMode;
import art.arcane.iris.modules.carve.CarvingBiomeSettings;
import art.arcane.iris.modules.carve.CarvingEnabledSettings;
import art.arcane.iris.modules.carve.CarvingChild;
@@ -26,7 +25,7 @@ import art.arcane.iris.modules.carve.CarvingEntry;
import art.arcane.iris.modules.carve.CarvingSettings;
import art.arcane.iris.modules.carve.CaveDepthSettings;
import art.arcane.iris.builtin.carve.CaveLavaHeightSettings;
import art.arcane.iris.modules.carve.CaveProfile;
import art.arcane.iris.modules.carve.CaveList;
import art.arcane.iris.modules.carve.UpperDimensionCarvingSettings;
import art.arcane.volmlib.util.json.JSONObject;
import com.google.gson.Gson;
@@ -51,7 +50,7 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* The cave settings packs have always written, read by the carve module under their old keys: {@code caveProfile} (an object at a
* The cave settings of packs, read by the carve module under their keys: {@code caves} (a list of cave keys at a
* dimension, region or biome), {@code carving} and {@code carvingEnabled} (a list and a boolean at a dimension), {@code carvingBiome} and
* {@code caveMinDepthBelowSurface} (a biome key and a number at a biome). The dimension, region and biome are files of the overworld pack
* as they were before the port.
@@ -81,25 +80,9 @@ public class CarveSettingsDecodingTest {
}
@Test
public void theOverworldReadsItsCaveProfileItsCarvingBandsAndCarvingEnabled() throws IOException {
public void theOverworldReadsItsCarvingBandsAndCarvingEnabled() throws IOException {
ModuleSettings settings = decoder.decode(Level.DIMENSION, file("dimensions/overworld.json"), "dimension overworld");
CaveProfile profile = settings.find(CaveProfile.class).orElseThrow();
assertTrue(profile.enabled());
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.14, profile.densityThreshold().min(), 0);
assertEquals(3, profile.sampleStep());
assertEquals(5, profile.surfaceClearance());
assertEquals(14, profile.objectMinDepthBelowSurface());
assertEquals(ObjectPlaceMode.ORGANIC_STILT, profile.defaultObjectPlaceMode().orElseThrow());
assertEquals(2, profile.modules().size());
assertTrue(profile.modules().get(1).invert());
assertEquals(240, profile.modules().get(1).verticalRange().max(), 0);
List<CarvingEntry> bands = settings.find(CarvingSettings.class).orElseThrow().entries();
assertEquals(1, bands.size());
assertEquals("global-deepdark-band", bands.getFirst().id());
@@ -115,44 +98,35 @@ public class CarveSettingsDecodingTest {
}
@Test
public void aRegionReadsItsCaveProfile() throws IOException {
JSONObject region = file("regions/forests.json");
public void cavesAreAListOfCaveKeysAtEveryLevel() {
JSONObject json = new JSONObject("{\"caves\": [\"tunnels\", \"deep/caverns\"]}");
CaveProfile profile = decoder.decode(Level.REGION, region, "region forests").find(CaveProfile.class).orElseThrow();
for (Level level : List.of(Level.DIMENSION, Level.REGION, Level.BIOME)) {
CaveList caves = decoder.decode(level, json, level + " test").find(CaveList.class).orElseThrow();
assertTrue(profile.enabled());
assertEquals(6, profile.verticalRange().min(), 0);
assertEquals(120, profile.verticalRange().max(), 0);
assertEquals(1, profile.baseWeight(), 0);
assertEquals(3, profile.sampleStep());
assertEquals(List.of("tunnels", "deep/caverns"), caves.caves());
}
}
@Test
public void aBiomeReadsItsCaveProfileAndItsMinimumDepth() throws IOException {
public void settingsLinkNoBiomesWhileThePackHasNoResourcesYet() {
ModuleSettings settings = decoder.decode(Level.DIMENSION, new JSONObject("{\"caves\": [\"tunnels\"]}"), "dimension test");
assertEquals(Set.of(), settings.usedBiomes(null, ModuleSettings.NONE, "overworld"));
assertEquals(Set.of(), settings.treeBiomes(null));
}
@Test
public void aBiomeReadsItsMinimumDepth() throws IOException {
JSONObject biome = file("biomes/carving/amethyst.json");
ModuleSettings settings = decoder.decode(Level.BIOME, biome, "biome carving/amethyst");
CaveProfile profile = settings.find(CaveProfile.class).orElseThrow();
assertTrue(profile.enabled());
assertEquals(620, profile.verticalRange().max(), 0);
assertEquals(0.91, profile.baseWeight(), 0);
assertEquals(2, profile.sampleStep());
assertEquals(biome.getInt("caveMinDepthBelowSurface"), settings.find(CaveDepthSettings.class).orElseThrow().depth());
assertEquals(10, settings.find(CaveDepthSettings.class).orElseThrow().depth());
assertTrue("the biome writes no carvingBiome", settings.find(CarvingBiomeSettings.class).isEmpty());
}
@Test
public void aCaveProfileMayBeWrittenAsASnippetReference() {
ModuleSettings settings = decoder.decode(Level.BIOME, new JSONObject("{\"caveProfile\": \"snippet/iris/carve/cave-profile/shallow\"}"), "biome test");
CaveProfile profile = settings.find(CaveProfile.class).orElseThrow();
assertTrue(profile.enabled());
assertEquals(100, profile.verticalRange().max(), 0);
assertEquals(2, profile.sampleStep());
}
@Test
public void carvingBandsReadChildrenAndTheirOptions() {
JSONObject json = new JSONObject("""
@@ -208,9 +182,9 @@ public class CarveSettingsDecodingTest {
@Test
public void everyKeyIsOnlyReadAtTheLevelsTheOldFieldExistedAt() {
assertTrue(decoder.keys(Level.DIMENSION).containsAll(List.of("caveProfile", "carving", "carvingEnabled", "caveLavaHeight", "upperDimensionCarving")));
assertTrue(decoder.keys(Level.REGION).contains("caveProfile"));
assertTrue(decoder.keys(Level.BIOME).containsAll(List.of("caveProfile", "carvingBiome", "caveMinDepthBelowSurface")));
assertTrue(decoder.keys(Level.DIMENSION).containsAll(List.of("caves", "carving", "carvingEnabled", "caveLavaHeight", "upperDimensionCarving")));
assertTrue(decoder.keys(Level.REGION).contains("caves"));
assertTrue(decoder.keys(Level.BIOME).containsAll(List.of("caves", "carvingBiome", "caveMinDepthBelowSurface")));
assertFalse(decoder.keys(Level.REGION).contains("carving"));
assertFalse(decoder.keys(Level.DIMENSION).contains("carvingBiome"));
assertFalse(decoder.keys(Level.DIMENSION).contains("caveMinDepthBelowSurface"));
@@ -22,6 +22,8 @@ import art.arcane.iris.builtin.IrisSeedPurposes;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.loader.ResourceLoader;
import art.arcane.iris.engine.object.material.IrisBlockData;
import art.arcane.iris.modules.carve.Cave;
import art.arcane.iris.modules.carve.CaveResources;
import com.volmit.config.Level;
import com.volmit.config.SettingsStack;
import com.volmit.IrisFeature;
@@ -78,6 +80,7 @@ public final class CarveTestWorld implements PackWorld {
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 Map<ResourceId, Cave> caves = new HashMap<>();
private final IrisData data = packData();
private final Resources resources = new Resources();
private long carveSeed = 1337L;
@@ -98,6 +101,12 @@ public final class CarveTestWorld implements PackWorld {
return this;
}
/** Puts {@code cave} in the pack's caves folder under {@code key}. */
public CarveTestWorld cave(String key, Cave cave) {
caves.put(resources.idOf(key), cave);
return this;
}
public CarveTestWorld carveSeed(long seed) {
this.carveSeed = seed;
return this;
@@ -228,6 +237,9 @@ public final class CarveTestWorld implements PackWorld {
@Override
public <T> Optional<T> find(ResourceKind<T> kind, ResourceId id) {
if (kind.equals(CaveResources.CAVES)) {
return Optional.ofNullable(kind.type().cast(caves.get(id)));
}
if (!kind.equals(BIOMES)) {
return Optional.empty();
}
@@ -67,18 +67,6 @@ public class PackStyledRangeDefaultValidatorTest {
assertTrue(validation.errors().get(0).contains("via snippet 'snippet/style-range/empty'"));
}
@Test
public void flagsEmptyCaveDensityThreshold() throws Exception {
File pack = temporaryFolder.newFolder("pack");
write(pack, "dimensions/main.json", "{\"caveProfile\":{\"densityThreshold\":{}}}");
PackStyledRangeDefaultValidator.Validation validation = PackStyledRangeDefaultValidator.validate(pack);
assertEquals(1, validation.errors().size());
assertTrue(validation.errors().get(0).startsWith(
"Dimension 'main' caveProfile.densityThreshold omits both min and max"));
}
@Test
public void emptyDensityStyleBlocksFullPackValidation() throws Exception {
File pack = temporaryFolder.newFolder("pack");
@@ -1,116 +1,129 @@
/*
* 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.modules.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.object.TestSettings;
import art.arcane.iris.modules.carve.Cave;
import art.arcane.iris.modules.carve.CaveList;
import art.arcane.volmlib.util.matter.MatterCavern;
import com.volmit.ModuleLog;
import com.volmit.config.Level;
import com.volmit.config.Range;
import com.volmit.noise.NoiseStyle;
import com.volmit.noise.StyledRange;
import com.volmit.resource.ResourceId;
import com.volmit.world.BiomeSample;
import org.junit.Before;
import org.junit.Test;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** 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 static final int ROCK_KEPT_UNDER_SURFACE = 8;
private static final ResourceId REGION = CarveTestWorld.id("region");
private static final ResourceId PLAINS = CarveTestWorld.id("plains");
private static final ResourceId LUSH = CarveTestWorld.id("cave/lush");
private InMemoryMantle mantle;
private CarveTestWorld world;
private ModuleLog log;
@Before
public void setUp() {
world = newWorld();
}
private static CarveTestWorld newWorld() {
return new CarveTestWorld().biome("cave/lush").biome("plains");
world = new CarveTestWorld().biome("cave/lush").biome("plains").cave("rooms", rooms(0, 127)).cave("low", rooms(-50, -30));
log = mock(ModuleLog.class);
}
@Test
public void theDimensionsProfileCarvesWhereNothingNarrowerDeclaresOne() {
world.dimension(profile(true));
assertTrue(carvedBlocks(BiomeSample::surfaceBiome) > 0);
public void nothingIsCarvedWhereNoLevelListsACave() {
assertEquals(0, carvedBlocks(sample -> PLAINS).size());
}
@Test
public void aDisabledProfileDeclaresNothingAndTheDimensionsStillCarves() {
world.dimension(profile(true));
int dimensionOnly = carvedBlocks(BiomeSample::surfaceBiome);
world = newWorld().dimension(profile(true)).declare(Level.REGION, "region", profile(false));
public void aCaveTheDimensionListsCarvesEveryColumn() {
world.dimension(new CaveList(List.of("rooms")));
assertTrue(dimensionOnly > 0);
assertEquals(dimensionOnly, carvedBlocks(BiomeSample::surfaceBiome));
assertTrue(carvedBlocks(sample -> PLAINS).size() > 0);
}
@Test
public void anEnabledProfileOfARegionReplacesTheDimensionsWithinItsOwnBounds() {
world.dimension(profile(true)).declare(Level.REGION, "region", TestSettings.with(profile(true), "verticalRange", Range.of(50D, 60D)));
public void theListsOfADimensionAndARegionAddUp() {
world.dimension(new CaveList(List.of("rooms")));
Set<Long> dimensionOnly = carvedBlocks(sample -> PLAINS);
world.declare(Level.REGION, "region", new CaveList(List.of("low")));
int carved = carvedBlocks(BiomeSample::surfaceBiome);
Set<Long> both = carvedBlocks(sample -> PLAINS);
assertTrue(carved > 0);
mantle.chunk(0, 0).iterate(MatterCavern.class, (x, y, z, cavern) -> assertTrue("y=" + y, y >= 50 && y <= 60));
assertTrue("the region's cave carves on top", both.size() > dimensionOnly.size());
assertTrue("the dimension's cave still carves all it did", both.containsAll(dimensionOnly));
}
@Test
public void theCaveBiomeOfAColumnCarvesWithItsOwnProfileWhereTheDimensionDeclaresNone() {
world.declare(Level.BIOME, "cave/lush", profile(true));
public void theCaveBiomeOfAColumnListsCavesToo() {
world.declare(Level.BIOME, "cave/lush", new CaveList(List.of("rooms")));
assertEquals("the surface biome declares none", 0, carvedBlocks(BiomeSample::surfaceBiome));
assertTrue(carvedBlocks(sample -> sample.caveBiome().orElseThrow()) > 0);
assertEquals("the surface biome lists none", 0, carvedBlocks(sample -> PLAINS).size());
assertTrue(carvedBlocks(sample -> LUSH).size() > 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) {
@Test
public void aCaveStaysInItsDepthRangeAndUnderTheRockItKeeps() {
world.dimension(new CaveList(List.of("low")));
Set<Long> carved = carvedBlocks(sample -> PLAINS);
assertFalse(carved.isEmpty());
for (long block : carved) {
int y = (int) (block & 0xFFF);
assertTrue("y=" + y, y >= 14 && y <= 34);
}
world = new CarveTestWorld().biome("plains").cave("rooms", rooms(0, 127)).dimension(new CaveList(List.of("rooms")));
for (long block : carvedBlocks(sample -> PLAINS)) {
int y = (int) (block & 0xFFF);
assertTrue("y=" + y, y <= SURFACE - ROCK_KEPT_UNDER_SURFACE);
}
}
@Test
public void aListedCaveThePackDoesNotHaveIsReportedAndCarvesNothing() {
world.dimension(new CaveList(List.of("missing")));
assertEquals(0, carvedBlocks(sample -> PLAINS).size());
verify(log).warnOnce(anyString(), anyString());
}
/** Carves chunk 0, 0 with the cave biome of every block {@code caveBiomeOf} says, and answers the blocks of the chunk that became cave. */
private Set<Long> carvedBlocks(Function<BiomeSample, 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")));
BiomeSample sample = new BiomeSample(REGION, PLAINS, Optional.of(LUSH));
return new BiomeSample(sample.region(), sample.surfaceBiome(), Optional.of(caveBiomeOf.apply(sample)));
});
CarveWorld carveWorld = new CarveWorld(world.resources().noise(), 1337L, HEIGHT, FLUID_HEIGHT, LAVA_HEIGHT, CarveTestWorld.MIN_HEIGHT);
new CaveCarving(world, carveWorld, false, (x, z) -> false).carve(mantle.carved(), terrain, 0, 0);
new CaveCarving(world, carveWorld, (x, z) -> false, log).carve(mantle.carved(), terrain, 0, 0);
int[] count = new int[1];
mantle.chunk(0, 0).iterate(MatterCavern.class, (x, y, z, cavern) -> count[0]++);
return count[0];
Set<Long> carved = new HashSet<>();
mantle.chunk(0, 0).iterate(MatterCavern.class, (x, y, z, cavern) -> carved.add(((long) x << 24) | ((long) z << 12) | y));
return carved;
}
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);
/** Caverns that take up most of the rock between two world heights, so a chunk is sure to hold some. */
private static Cave rooms(int minWorldY, int maxWorldY) {
return TestSettings.of(Cave.class, "{\"cavern\": {\"size\": 24, \"height\": 12, \"coverage\": 0.5},"
+ " \"depth\": {\"min\": " + minWorldY + ", \"max\": " + maxWorldY + "}, \"fade\": 0, \"surfaceClearance\": " + ROCK_KEPT_UNDER_SURFACE + "}");
}
}
@@ -1,163 +0,0 @@
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.modules.carve.CaveProfile;
import art.arcane.iris.engine.object.TestSettings;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class CaveCarvingTop2BlendTest {
private static Constructor<?> weightedProfileConstructor;
private static Method limitMethod;
private static Field profileField;
private static Field columnWeightsField;
@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, com.volmit.config.Range.class, int.class);
weightedProfileConstructor.setAccessible(true);
limitMethod = CaveCarving.class.getDeclaredMethod("limitAndMergeBlendedProfiles", List.class, int.class, int.class);
limitMethod.setAccessible(true);
profileField = weightedProfileClass.getDeclaredField("profile");
profileField.setAccessible(true);
columnWeightsField = weightedProfileClass.getDeclaredField("columnWeights");
columnWeightsField.setAccessible(true);
}
@Test
public void topTwoProfilesAreKeptAndDroppedWeightsAreMergedIntoDominantColumns() throws Exception {
WeightedInput input = createWeightedProfiles();
List<?> limited = invokeLimit(input.weightedProfiles(), 2);
assertEquals(2, limited.size());
Map<CaveProfile, double[]> byProfile = extractWeightsByProfile(limited);
CaveProfile first = input.profiles().first();
CaveProfile second = input.profiles().second();
assertEquals(1.0D, byProfile.get(first)[1], 0D);
assertEquals(1.0D, byProfile.get(second)[0], 0D);
}
@Test
public void topTwoMergeIsDeterministicAcrossRuns() throws Exception {
WeightedInput firstInput = createWeightedProfiles();
WeightedInput secondInput = createWeightedProfiles();
List<?> first = invokeLimit(firstInput.weightedProfiles(), 2);
List<?> second = invokeLimit(secondInput.weightedProfiles(), 2);
Map<CaveProfile, double[]> firstByProfile = extractWeightsByProfile(first);
Map<CaveProfile, double[]> secondByProfile = extractWeightsByProfile(second);
assertEquals(firstByProfile.get(firstInput.profiles().first())[0], secondByProfile.get(secondInput.profiles().first())[0], 0D);
assertEquals(firstByProfile.get(firstInput.profiles().first())[1], secondByProfile.get(secondInput.profiles().first())[1], 0D);
assertEquals(firstByProfile.get(firstInput.profiles().second())[0], secondByProfile.get(secondInput.profiles().second())[0], 0D);
assertEquals(firstByProfile.get(firstInput.profiles().second())[1], secondByProfile.get(secondInput.profiles().second())[1], 0D);
}
@Test
public void topTwoMergePreservesIndependentWeightsAtHighColumnIndexes() throws Exception {
WeightedInput input = createWeightedProfiles();
List<?> limited = invokeLimit(input.weightedProfiles(), 2);
Map<CaveProfile, double[]> byProfile = extractWeightsByProfile(limited);
CaveProfile first = input.profiles().first();
CaveProfile second = input.profiles().second();
assertEquals(1.0D, byProfile.get(first)[255], 0D);
assertEquals(1.0D, byProfile.get(second)[254], 0D);
}
@Test
public void topTwoTieBreaksBySequenceNotIdentity() throws Exception {
CaveProfile first = TestSettings.of(CaveProfile.class, "{\"enabled\":true,\"baseWeight\":1.0}");
CaveProfile second = TestSettings.of(CaveProfile.class, "{\"enabled\":true,\"baseWeight\":1.0}");
CaveProfile third = TestSettings.of(CaveProfile.class, "{\"enabled\":true,\"baseWeight\":1.0}");
double[] weightsA = new double[256];
double[] weightsB = new double[256];
double[] weightsC = new double[256];
weightsA[0] = 0.5D;
weightsB[0] = 0.5D;
weightsC[0] = 0.5D;
List<Object> weighted = new ArrayList<>();
weighted.add(weightedProfileConstructor.newInstance(first, weightsA, average(weightsA), null, 0));
weighted.add(weightedProfileConstructor.newInstance(second, weightsB, average(weightsB), null, 1));
weighted.add(weightedProfileConstructor.newInstance(third, weightsC, average(weightsC), null, 2));
List<?> limited = invokeLimit(weighted, 2);
assertEquals(2, limited.size());
Map<CaveProfile, double[]> byProfile = extractWeightsByProfile(limited);
assertEquals(true, byProfile.containsKey(first));
assertEquals(true, byProfile.containsKey(second));
assertEquals(false, byProfile.containsKey(third));
}
private WeightedInput createWeightedProfiles() throws Exception {
CaveProfile first = TestSettings.of(CaveProfile.class, "{\"enabled\":true,\"baseWeight\":1.31}");
CaveProfile second = TestSettings.of(CaveProfile.class, "{\"enabled\":true,\"baseWeight\":1.17}");
CaveProfile third = TestSettings.of(CaveProfile.class, "{\"enabled\":true,\"baseWeight\":0.93}");
Profiles profiles = new Profiles(first, second, third);
double[] firstWeights = new double[256];
firstWeights[0] = 0.2D;
firstWeights[1] = 0.8D;
firstWeights[255] = 0.6D;
double[] secondWeights = new double[256];
secondWeights[0] = 0.7D;
secondWeights[1] = 0.1D;
secondWeights[254] = 0.7D;
double[] thirdWeights = new double[256];
thirdWeights[0] = 0.3D;
thirdWeights[1] = 0.4D;
thirdWeights[254] = 0.3D;
thirdWeights[255] = 0.4D;
List<Object> weighted = new ArrayList<>();
weighted.add(weightedProfileConstructor.newInstance(first, firstWeights, average(firstWeights), null, 0));
weighted.add(weightedProfileConstructor.newInstance(second, secondWeights, average(secondWeights), null, 1));
weighted.add(weightedProfileConstructor.newInstance(third, thirdWeights, average(thirdWeights), null, 2));
return new WeightedInput(weighted, profiles);
}
private List<?> invokeLimit(List<Object> weightedProfiles, int limit) throws Exception {
return (List<?>) limitMethod.invoke(null, weightedProfiles, limit, 256);
}
private Map<CaveProfile, double[]> extractWeightsByProfile(List<?> weightedProfiles) throws Exception {
Map<CaveProfile, double[]> byProfile = new IdentityHashMap<>();
for (Object weightedProfile : weightedProfiles) {
CaveProfile profile = (CaveProfile) profileField.get(weightedProfile);
double[] weights = (double[]) columnWeightsField.get(weightedProfile);
byProfile.put(profile, weights);
}
return byProfile;
}
private double average(double[] weights) {
double total = 0D;
for (double weight : weights) {
total += weight;
}
return total / weights.length;
}
private record Profiles(CaveProfile first, CaveProfile second, CaveProfile third) {
}
private record WeightedInput(List<Object> weightedProfiles, Profiles profiles) {
}
}
@@ -1,7 +1,6 @@
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.anchor.ObjectPlaceMode;
import art.arcane.iris.modules.carve.CaveProfile;
import art.arcane.iris.builtin.objects.ObjectPlacement;
import art.arcane.iris.modules.objects.PlacementChanges;
import com.volmit.object.PlaceableObject;
@@ -54,18 +53,6 @@ public class EffectivePlacementsTest {
assertTrue(new EffectivePlacements(true, 0).forSurface(centered, object("castle")).isNone());
}
@Test
public void aCaveProfileGivesCenteredPlacementsItsPlaceMode() {
ObjectPlacement centered = TestSettings.of(ObjectPlacement.class, "{\"mode\":\"CENTER_HEIGHT\"}");
CaveProfile profile = TestSettings.of(CaveProfile.class, "{\"enabled\":true,\"defaultObjectPlaceMode\":\"STILT\"}");
PlacementChanges changes = new EffectivePlacements(true, 0).forCave(centered, object("crystal"), profile);
assertEquals(ObjectPlaceMode.STILT, changes.mode());
assertEquals(List.of("crystal"), changes.place());
assertNull(new EffectivePlacements(true, 0).forCave(centered, object("crystal"), null).mode());
}
private static PlaceableObject object(String key) {
PlaceableObject object = mock(PlaceableObject.class);
when(object.name()).thenReturn(key);
@@ -7,7 +7,9 @@ import art.arcane.iris.engine.mantle.components.CarveWorld;
import art.arcane.iris.engine.mantle.components.CaveCarving;
import art.arcane.iris.engine.mantle.components.CaveFloorMarking;
import art.arcane.iris.engine.object.TestSettings;
import art.arcane.iris.modules.carve.CaveProfile;
import art.arcane.iris.modules.carve.Cave;
import art.arcane.iris.modules.carve.CaveList;
import com.volmit.ModuleLog;
import art.arcane.volmlib.util.matter.MatterCavern;
import com.volmit.block.BlockState;
import com.volmit.config.Range;
@@ -46,8 +48,8 @@ public class CarvePipelineHarnessTest {
private static final long SEED = 424242L;
private static final int APPLIED_CHUNKS_PER_SIDE = 6;
private static final int CARVE_RING = 1;
private static final String VOIDS_DIGEST = "df7ae961c3025eb5";
private static final String BLOCKS_DIGEST = "bdb40db5625eb942";
private static final String VOIDS_DIGEST = "630fef28ea2529d4";
private static final String BLOCKS_DIGEST = "58fbce572cb007d4";
private static final BlockState STONE = new BlockState("minecraft:stone");
private static final BlockState AIR = new BlockState("minecraft:air");
@@ -99,7 +101,8 @@ public class CarvePipelineHarnessTest {
}
private Result run() {
CarveTestWorld world = new CarveTestWorld().biome("cave/lush").biome("plains").carveSeed(SEED).dimension(profile());
CarveTestWorld world = new CarveTestWorld().biome("cave/lush").biome("plains").carveSeed(SEED)
.cave("mixed", cave()).dimension(new CaveList(List.of("mixed")));
CarveWorld carveWorld = new CarveWorld(world.resources().noise(), SEED, HEIGHT, FLUID_HEIGHT, LAVA_HEIGHT, CarveTestWorld.MIN_HEIGHT);
RecordingCaveDressing dressing = new RecordingCaveDressing();
dressing.fluid = WATER;
@@ -108,7 +111,7 @@ public class CarvePipelineHarnessTest {
dressing.ceilings.put(CarveTestWorld.id("cave/lush"), List.of(CEILING));
InMemoryMantle mantle = new InMemoryMantle(HEIGHT / 16);
MantleLayer<CarvedVoid> voids = mantle.carved();
CaveCarving carving = new CaveCarving(world, carveWorld, false, (x, z) -> surface(x, z) < FLUID_HEIGHT);
CaveCarving carving = new CaveCarving(world, carveWorld, (x, z) -> surface(x, z) < FLUID_HEIGHT, mock(ModuleLog.class));
CaveFloorMarking floorMarking = new CaveFloorMarking(carveWorld, false);
CaveApplying applying = new CaveApplying(world, carveWorld, false);
List<String> floors = new ArrayList<>();
@@ -215,7 +218,11 @@ public class CarvePipelineHarnessTest {
return blocks;
}
private static CaveProfile profile() {
return TestSettings.with(new CaveProfile(), "enabled", true, "verticalRange", Range.of(4D, HEIGHT - 8D));
private static Cave cave() {
return TestSettings.of(Cave.class, """
{"tunnel": {"width": {"min": 3, "max": 5}, "stretch": 40},
"cavern": {"size": 32, "height": 14, "coverage": 0.12, "pillars": {"spacing": 12, "thickness": 3}},
"opensToSurface": true, "fade": 4}
""");
}
}
@@ -1,171 +0,0 @@
/*
* 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.object.terrain.carving;
import art.arcane.iris.builtin.anchor.ObjectPlaceMode;
import art.arcane.iris.builtin.carve.CaveAnchorMode;
import art.arcane.iris.modules.carve.CaveProfile;
import art.arcane.iris.builtin.carve.CarvingMode;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.builtin.objects.ObjectPlacement;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
/**
* The cave profile of the overworld pack's dimension, read into {@link CaveProfile} (IrisApi types only) with the values
* Iris's own cave profile class read from the same JSON, and what the carvers read it as ({@link ResolvedCaveProfile}).
*/
public class CaveProfileDecodingTest {
private static final String OVERWORLD_CAVE_PROFILE = """
{"enabled": true, "verticalRange": {"min": 6, "max": 700},
"baseDensityStyle": {"style": "PERLIN_IRIS", "zoom": 0.72}, "detailDensityStyle": {"style": "SIMPLEX", "zoom": 0.54},
"warpStyle": {"style": "FRACTAL_WATER", "zoom": 0.5}, "baseWeight": 0.9, "detailWeight": 0.11, "warpStrength": 0.24,
"densityThreshold": {"min": -0.14, "max": -0.06, "style": {"style": "SIMPLEX", "zoom": 0.74}},
"thresholdBias": 0.14, "sampleStep": 3, "surfaceClearance": 5, "allowSurfaceBreak": true,
"surfaceBreakStyle": {"style": "SIMPLEX", "zoom": 0.88}, "surfaceBreakNoiseThreshold": 0.6, "surfaceBreakDepth": 16,
"surfaceBreakThresholdBoost": 0.1, "objectMinDepthBelowSurface": 14, "defaultObjectAnchor": "FLOOR",
"defaultObjectPlaceMode": "ORGANIC_STILT", "anchorScanStep": 1, "anchorSearchAttempts": 12, "allowFluid": true,
"fluidMinDepthBelowSurface": 20, "fluidRequiresFloor": true, "allowLava": true,
"modules": [{"style": {"style": "SIMPLEX_VASCULAR", "zoom": 1.08}, "weight": 0.08, "threshold": 0.03,
"verticalRange": {"min": 24, "max": 660}, "invert": false},
{"style": {"style": "FRACTAL_FBM_SIMPLEX", "zoom": 0.24}, "weight": 0.04, "threshold": 0.08,
"verticalRange": {"min": 6, "max": 240}, "invert": true}],
"verticalEdgeFade": 24, "verticalEdgeFadeStrength": 0.18, "minCarveCells": 24, "recoveryThresholdBoost": 0.07}
""";
private static final String DARK_DEPTHS_OBJECT = """
{"place": ["rocks/a"], "chance": 0.235719, "density": 4, "carvingSupport": "CARVING_ONLY",
"caveAnchorMode": "PROFILE_DEFAULT", "translate": {"y": -1}, "bottom": true, "force": true}
""";
@Rule
public TemporaryFolder folder = new TemporaryFolder();
private Gson gson;
@Before
public void decodeLikeIrisDoes() throws IOException {
File snippets = folder.newFolder("snippet", "iris", "carve", "cave-profile");
Files.writeString(new File(snippets, "lush.json").toPath(), "{\"enabled\": true, \"sampleStep\": 2}");
IrisData data = mock(IrisData.class, CALLS_REAL_METHODS);
doReturn(folder.getRoot()).when(data).getDataFolder();
gson = new GsonBuilder().registerTypeAdapterFactory(data).create();
}
@Test
public void theOverworldProfileReadsEveryFieldIrisReadFromIt() {
CaveProfile profile = gson.fromJson(OVERWORLD_CAVE_PROFILE, CaveProfile.class);
assertTrue(profile.enabled());
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.9, profile.baseWeight(), 0);
assertEquals(0.24, profile.warpStrength(), 0);
assertEquals(-0.14, profile.densityThreshold().min(), 0);
assertEquals("SIMPLEX", profile.densityThreshold().style().style());
assertEquals(3, profile.sampleStep());
assertEquals(CaveAnchorMode.FLOOR, profile.defaultObjectAnchor());
assertEquals(ObjectPlaceMode.ORGANIC_STILT, profile.defaultObjectPlaceMode().orElseThrow());
assertEquals(12, profile.anchorSearchAttempts());
assertEquals(24, profile.verticalEdgeFade());
assertEquals(2, profile.modules().size());
assertEquals("SIMPLEX_VASCULAR", profile.modules().get(0).style().style());
assertFalse(profile.modules().get(0).invert());
assertTrue(profile.modules().get(1).invert());
assertEquals(240, profile.modules().get(1).verticalRange().max(), 0);
}
@Test
public void anEmptyProfileHasIrisDefaults() {
CaveProfile profile = gson.fromJson("{}", CaveProfile.class);
assertFalse(profile.enabled());
assertEquals(0, profile.verticalRange().min(), 0);
assertEquals(384, profile.verticalRange().max(), 0);
assertEquals("CELLULAR_IRIS_DOUBLE", profile.baseDensityStyle().style());
assertEquals("SIMPLEX", profile.detailDensityStyle().style());
assertEquals("FLAT", profile.warpStyle().style());
assertEquals(0.08, profile.surfaceBreakStyle().zoom(), 0);
assertEquals(-0.2, profile.densityThreshold().min(), 0);
assertEquals(0.2, profile.densityThreshold().max(), 0);
assertEquals(0.35, profile.detailWeight(), 0);
assertEquals(0.16, profile.thresholdBias(), 0);
assertEquals(20, profile.verticalEdgeFade());
assertEquals(CaveAnchorMode.FLOOR, profile.defaultObjectAnchor());
assertTrue(profile.defaultObjectPlaceMode().isEmpty());
assertTrue(profile.modules().isEmpty());
assertTrue(profile.allowFluid() && profile.fluidRequiresFloor() && profile.allowLava() && profile.adaptiveSampling());
assertEquals(12, profile.fluidMinDepthBelowSurface());
assertEquals(6, profile.anchorSearchAttempts());
}
@Test
public void profilesMayBeSnippets() {
CaveProfile profile = gson.fromJson("\"snippet/iris/carve/cave-profile/lush\"", CaveProfile.class);
assertTrue(profile.enabled());
assertEquals(2, profile.sampleStep());
}
@Test
public void placementsReadTheirCarvingSupportAndAnchorMode() {
ObjectPlacement placement = gson.fromJson(DARK_DEPTHS_OBJECT, ObjectPlacement.class);
assertEquals(CarvingMode.CARVING_ONLY, placement.carvingSupport());
assertTrue(placement.carvingSupport().supportsCarving());
assertFalse(placement.carvingSupport().supportsSurface());
assertEquals(CaveAnchorMode.PROFILE_DEFAULT, placement.caveAnchorMode());
assertEquals(CarvingMode.SURFACE_ONLY, gson.fromJson("{}", ObjectPlacement.class).carvingSupport());
}
@Test
public void carversReadTheProfileThroughItsApiValues() {
CaveProfile profile = gson.fromJson(OVERWORLD_CAVE_PROFILE, CaveProfile.class);
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());
}
}
@@ -547,8 +547,6 @@ public class FloatingIslandBoundarySamplerTest {
when(entry.topShapeNoise()).thenReturn(constant);
when(entry.bottomNoise()).thenReturn(constant);
when(entry.wallWarpNoise()).thenReturn(null);
when(entry.carvingProfileSampler()).thenReturn(null);
when(entry.hasCarvingReference()).thenReturn(false);
when(entry.carveNoise()).thenReturn(constant);
when(entry.settings()).thenReturn(TestSettings.with(new FloatingChildBiome(), "footprintThreshold", 0.5D, "minHeightAboveSurface", 160, "maxHeightAboveSurface", 160, "topShapeMode", TopShapeMode.NOISE, "topShapeAmp", 1.0D, "maxTopHeight", 18, "bottomExponent", 1.0D, "bottomDepthMin", 20, "bottomDepthMax", 20, "maxThickness", 64, "wallWarpAmplitude", 0.0D, "carveThreshold", 0.5D));
FloatingIslandBoundarySampler sampler = new FloatingIslandBoundarySampler((x, z) -> parent);
@@ -611,8 +609,6 @@ public class FloatingIslandBoundarySamplerTest {
when(entry.topShapeNoise()).thenReturn(constant);
when(entry.bottomNoise()).thenReturn(constant);
when(entry.wallWarpNoise()).thenReturn(null);
when(entry.carvingProfileSampler()).thenReturn(null);
when(entry.hasCarvingReference()).thenReturn(false);
when(entry.carveNoise()).thenReturn(null);
when(entry.settings()).thenReturn(TestSettings.with(new FloatingChildBiome(), "footprintThreshold", 0.5D, "topShapeMode", TopShapeMode.NOISE, "topShapeAmp", 1.0D, "maxTopHeight", 18, "bottomExponent", 1.0D, "bottomDepthMin", 20, "bottomDepthMax", 20, "maxThickness", 64, "wallWarpAmplitude", 0.0D, "carveThreshold", 1.0D,
"minHeightAboveSurface", entry == lower ? 160 : 180, "maxHeightAboveSurface", entry == lower ? 160 : 180));
@@ -319,11 +319,12 @@ public class FloatingIslandSampleBottomYTest {
}
@Test
public void directCarveEnabled_respectsCarvingReferenceOverride() {
ResolvedFloatingChild entry = new ResolvedFloatingChild(TestSettings.with(new FloatingChildBiome(), "carving", "carving/mushroom"), null);
public void directCarveEnabled_needsCarveNoiseAndAThresholdBelowOne() {
NoiseSampler carve = constantNoise(0.0);
assertFalse(FloatingIslandSample.directCarveEnabled(entry, null, carve, 0.5));
assertTrue(FloatingIslandSample.directCarveEnabled(carve, 0.5));
assertFalse(FloatingIslandSample.directCarveEnabled(carve, 1.0));
assertFalse(FloatingIslandSample.directCarveEnabled(null, 0.5));
}
@Test
@@ -0,0 +1,148 @@
package art.arcane.iris.modules.carve.field;
import art.arcane.iris.core.modules.CarveTestWorld;
import art.arcane.iris.engine.object.TestSettings;
import art.arcane.iris.modules.carve.Cave;
import com.volmit.noise.NoiseFactory;
import org.junit.Test;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.BitSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class CaveCarverTest {
private static final int CHUNKS = 8;
private static final int SIZE = CHUNKS * 16;
private static final int SURFACE_Y = 160;
private static final int LAYERS = SURFACE_Y + 1;
private static final int WORLD_BOTTOM_Y = 0;
private static final int WORLD_HEIGHT = 256;
private static final long SEED = 91_277L;
private static final String TUNNELS = "{\"tunnel\": {\"width\": {\"min\": 4, \"max\": 6}, \"stretch\": 48}, \"opensToSurface\": true}";
private final NoiseFactory noise = new CarveTestWorld().resources().noise();
@Test
public void theSameSeedCarvesTheSameCaveAndAnotherSeedADifferentOne() {
BitSet first = carve(TUNNELS, SEED, false);
assertFalse(first.isEmpty());
assertEquals(first, carve(TUNNELS, SEED, false));
assertNotEquals(first, carve(TUNNELS, SEED + 1, false));
}
@Test
public void tunnelsJoinIntoOneNetwork() {
BitSet carved = carve(TUNNELS, SEED, false);
double largestShare = largestConnectedShare(carved);
assertTrue("largest connected share " + largestShare, largestShare > 0.7D);
}
@Test
public void thinTunnelsSurviveBetweenTheLatticePoints() {
BitSet carved = carve("{\"tunnel\": {\"width\": {\"min\": 2, \"max\": 3}, \"stretch\": 48}, \"opensToSurface\": true}", SEED, false);
double largestShare = largestConnectedShare(carved);
assertTrue("largest connected share " + largestShare, largestShare > 0.5D);
}
@Test
public void pillarsLeaveRockStandingInACavern() {
String open = "{\"cavern\": {\"size\": 40, \"height\": 18, \"coverage\": 0.3}}";
String pillared = "{\"cavern\": {\"size\": 40, \"height\": 18, \"coverage\": 0.3, \"pillars\": {\"spacing\": 14, \"thickness\": 4}}}";
BitSet withoutPillars = carve(open, SEED, false);
BitSet withPillars = carve(pillared, SEED, false);
assertTrue(withPillars.cardinality() < withoutPillars.cardinality());
BitSet onlyWithPillars = (BitSet) withPillars.clone();
onlyWithPillars.andNot(withoutPillars);
assertTrue("pillars only ever keep rock", onlyWithPillars.isEmpty());
}
@Test
public void aCaveOpensTheSurfaceOnlyWhereItMayAndKeepsItsRockElsewhere() {
String cave = "{\"tunnel\": {\"width\": {\"min\": 5, \"max\": 7}, \"stretch\": 32}, \"opensToSurface\": true, \"surfaceClearance\": 10}";
BitSet open = carve(cave, SEED, false);
BitSet sealed = carve(cave, SEED, true);
assertTrue("an open cave reaches the surface somewhere", highestCarvedY(open) == SURFACE_Y);
assertTrue("a sealed cave keeps its clearance: " + highestCarvedY(sealed), highestCarvedY(sealed) <= SURFACE_Y - 10);
}
private BitSet carve(String caveJson, long seed, boolean sealEveryColumn) {
CaveCarver carver = new CaveCarver(TestSettings.of(Cave.class, caveJson), noise, seed, WORLD_BOTTOM_Y, WORLD_HEIGHT);
int[] surfaceY = new int[256];
Arrays.fill(surfaceY, SURFACE_Y);
double[] weight = new double[256];
Arrays.fill(weight, 1D);
boolean[] sealed = new boolean[256];
Arrays.fill(sealed, sealEveryColumn);
BitSet carved = new BitSet(SIZE * SIZE * LAYERS);
for (int chunkX = 0; chunkX < CHUNKS; chunkX++) {
for (int chunkZ = 0; chunkZ < CHUNKS; chunkZ++) {
int originX = chunkX * 16;
int originZ = chunkZ * 16;
carver.carve(originX, originZ, surfaceY, weight, sealed, (localX, y, localZ) -> carved.set(index(originX + localX, y, originZ + localZ)));
}
}
return carved;
}
private static int index(int x, int y, int z) {
return (y * SIZE * SIZE) + (z * SIZE) + x;
}
private static int highestCarvedY(BitSet carved) {
return (carved.length() - 1) / (SIZE * SIZE);
}
private static double largestConnectedShare(BitSet carved) {
BitSet seen = new BitSet(carved.size());
ArrayDeque<Integer> open = new ArrayDeque<>();
int largest = 0;
for (int root = carved.nextSetBit(0); root >= 0; root = carved.nextSetBit(root + 1)) {
if (seen.get(root)) {
continue;
}
int size = 0;
seen.set(root);
open.add(root);
while (!open.isEmpty()) {
int block = open.poll();
size++;
int x = block % SIZE;
int z = (block / SIZE) % SIZE;
int y = block / (SIZE * SIZE);
visit(carved, seen, open, x + 1, y, z);
visit(carved, seen, open, x - 1, y, z);
visit(carved, seen, open, x, y + 1, z);
visit(carved, seen, open, x, y - 1, z);
visit(carved, seen, open, x, y, z + 1);
visit(carved, seen, open, x, y, z - 1);
}
largest = Math.max(largest, size);
}
return largest / (double) carved.cardinality();
}
private static void visit(BitSet carved, BitSet seen, ArrayDeque<Integer> open, int x, int y, int z) {
if (x < 0 || z < 0 || y < 0 || x >= SIZE || z >= SIZE || y >= LAYERS) {
return;
}
int block = index(x, y, z);
if (carved.get(block) && !seen.get(block)) {
seen.set(block);
open.add(block);
}
}
}
@@ -850,88 +850,6 @@
"global-clutter"
]
},
"caveProfile": {
"enabled": true,
"verticalRange": {
"min": 6,
"max": 700
},
"baseDensityStyle": {
"style": "PERLIN_IRIS",
"zoom": 0.72
},
"detailDensityStyle": {
"style": "SIMPLEX",
"zoom": 0.54
},
"warpStyle": {
"style": "FRACTAL_WATER",
"zoom": 0.5
},
"baseWeight": 0.9,
"detailWeight": 0.11,
"warpStrength": 0.24,
"densityThreshold": {
"min": -0.14,
"max": -0.06,
"style": {
"style": "SIMPLEX",
"zoom": 0.74
}
},
"thresholdBias": 0.14,
"sampleStep": 3,
"surfaceClearance": 5,
"allowSurfaceBreak": true,
"surfaceBreakStyle": {
"style": "SIMPLEX",
"zoom": 0.88
},
"surfaceBreakNoiseThreshold": 0.6,
"surfaceBreakDepth": 16,
"surfaceBreakThresholdBoost": 0.1,
"objectMinDepthBelowSurface": 14,
"defaultObjectAnchor": "FLOOR",
"defaultObjectPlaceMode": "ORGANIC_STILT",
"anchorScanStep": 1,
"anchorSearchAttempts": 12,
"allowFluid": true,
"fluidMinDepthBelowSurface": 20,
"fluidRequiresFloor": true,
"allowLava": true,
"modules": [
{
"style": {
"style": "SIMPLEX_VASCULAR",
"zoom": 1.08
},
"weight": 0.08,
"threshold": 0.03,
"verticalRange": {
"min": 24,
"max": 660
},
"invert": false
},
{
"style": {
"style": "FRACTAL_FBM_SIMPLEX",
"zoom": 0.24
},
"weight": 0.04,
"threshold": 0.08,
"verticalRange": {
"min": 6,
"max": 240
},
"invert": true
}
],
"verticalEdgeFade": 24,
"verticalEdgeFadeStrength": 0.18,
"minCarveCells": 24,
"recoveryThresholdBoost": 0.07
},
"carving": [
{
"id": "global-deepdark-band",
@@ -76,57 +76,6 @@
"beach/clutter"
]
},
"caveProfile": {
"enabled": true,
"verticalRange": {
"min": 6,
"max": 90
},
"baseDensityStyle": {
"style": "IRIS_DOUBLE",
"zoom": 0.8
},
"detailDensityStyle": {
"style": "SIMPLEX",
"zoom": 0.5
},
"warpStyle": {
"style": "SIMPLEX",
"zoom": 0.5
},
"baseWeight": 1,
"detailWeight": 0,
"warpStrength": 0,
"densityThreshold": {
"min": -0.1,
"max": -0.04,
"style": {
"style": "SIMPLEX",
"zoom": 0.5
}
},
"thresholdBias": 0.14,
"sampleStep": 3,
"surfaceClearance": 12,
"allowSurfaceBreak": false,
"surfaceBreakStyle": {
"style": "SIMPLEX",
"zoom": 0.88
},
"surfaceBreakNoiseThreshold": 0.99,
"surfaceBreakDepth": 4,
"surfaceBreakThresholdBoost": 0.02,
"objectMinDepthBelowSurface": 14,
"defaultObjectAnchor": "FLOOR",
"defaultObjectPlaceMode": "ORGANIC_STILT",
"anchorScanStep": 1,
"anchorSearchAttempts": 12,
"allowFluid": true,
"fluidMinDepthBelowSurface": 20,
"fluidRequiresFloor": true,
"allowLava": true,
"modules": []
},
"caveBiomeZoom": 3.6,
"entitySpawners": [
"hot/cave",
@@ -135,57 +135,6 @@
"mushroom/food"
]
},
"caveProfile": {
"enabled": true,
"verticalRange": {
"min": 6,
"max": 100
},
"baseDensityStyle": {
"style": "CELLULAR",
"zoom": 0.9
},
"detailDensityStyle": {
"style": "SIMPLEX",
"zoom": 0.5
},
"warpStyle": {
"style": "SIMPLEX",
"zoom": 0.5
},
"baseWeight": 1.0,
"detailWeight": 0.0,
"warpStrength": 0.0,
"densityThreshold": {
"min": -0.12,
"max": -0.06,
"style": {
"style": "SIMPLEX",
"zoom": 0.5
}
},
"thresholdBias": 0.1,
"sampleStep": 3,
"surfaceClearance": 12,
"allowSurfaceBreak": false,
"surfaceBreakStyle": {
"style": "SIMPLEX",
"zoom": 0.88
},
"surfaceBreakNoiseThreshold": 0.99,
"surfaceBreakDepth": 4,
"surfaceBreakThresholdBoost": 0.02,
"objectMinDepthBelowSurface": 14,
"defaultObjectAnchor": "FLOOR",
"defaultObjectPlaceMode": "ORGANIC_STILT",
"anchorScanStep": 1,
"anchorSearchAttempts": 12,
"allowFluid": true,
"fluidMinDepthBelowSurface": 20,
"fluidRequiresFloor": true,
"allowLava": true,
"modules": []
},
"caveBiomeZoom": 3.2,
"entitySpawners": [
"mushroom/cave",
@@ -64,57 +64,6 @@
"swamp/food"
]
},
"caveProfile": {
"enabled": true,
"verticalRange": {
"min": 6,
"max": 80
},
"baseDensityStyle": {
"style": "FRACTAL_SMOKE",
"zoom": 0.45
},
"detailDensityStyle": {
"style": "SIMPLEX",
"zoom": 0.5
},
"warpStyle": {
"style": "SIMPLEX",
"zoom": 0.5
},
"baseWeight": 1,
"detailWeight": 0,
"warpStrength": 0,
"densityThreshold": {
"min": -0.14,
"max": -0.06,
"style": {
"style": "SIMPLEX",
"zoom": 0.5
}
},
"thresholdBias": 0.06,
"sampleStep": 3,
"surfaceClearance": 12,
"allowSurfaceBreak": false,
"surfaceBreakStyle": {
"style": "SIMPLEX",
"zoom": 0.88
},
"surfaceBreakNoiseThreshold": 0.99,
"surfaceBreakDepth": 4,
"surfaceBreakThresholdBoost": 0.02,
"objectMinDepthBelowSurface": 14,
"defaultObjectAnchor": "FLOOR",
"defaultObjectPlaceMode": "ORGANIC_STILT",
"anchorScanStep": 1,
"anchorSearchAttempts": 12,
"allowFluid": true,
"fluidMinDepthBelowSurface": 20,
"fluidRequiresFloor": true,
"allowLava": true,
"modules": []
},
"caveBiomeZoom": 3.2,
"entitySpawners": [
"swamp/cave",
@@ -34,57 +34,6 @@
{"biome": "carving/deepravine", "weight": 1},
{"biome": "carving/chalk-gardens", "weight": 1}
],
"caveProfile": {
"enabled": true,
"verticalRange": {
"min": 6,
"max": 60
},
"baseDensityStyle": {
"style": "SIMPLEX",
"zoom": 0.4
},
"detailDensityStyle": {
"style": "SIMPLEX",
"zoom": 0.5
},
"warpStyle": {
"style": "SIMPLEX",
"zoom": 0.5
},
"baseWeight": 1.0,
"detailWeight": 0.0,
"warpStrength": 0.0,
"densityThreshold": {
"min": -0.16,
"max": -0.08,
"style": {
"style": "SIMPLEX",
"zoom": 0.5
}
},
"thresholdBias": 0.12,
"sampleStep": 3,
"surfaceClearance": 12,
"allowSurfaceBreak": false,
"surfaceBreakStyle": {
"style": "SIMPLEX",
"zoom": 0.88
},
"surfaceBreakNoiseThreshold": 0.99,
"surfaceBreakDepth": 4,
"surfaceBreakThresholdBoost": 0.02,
"objectMinDepthBelowSurface": 14,
"defaultObjectAnchor": "FLOOR",
"defaultObjectPlaceMode": "ORGANIC_STILT",
"anchorScanStep": 1,
"anchorSearchAttempts": 12,
"allowFluid": true,
"fluidMinDepthBelowSurface": 20,
"fluidRequiresFloor": true,
"allowLava": true,
"modules": []
},
"caveBiomeZoom": 3.1,
"entitySpawners": [
"temperate/cave",
@@ -198,88 +198,6 @@
}
}
],
"caveProfile": {
"enabled": true,
"verticalRange": {
"min": 6,
"max": 620
},
"baseDensityStyle": {
"style": "PERLIN_IRIS",
"zoom": 0.8
},
"detailDensityStyle": {
"style": "FRACTAL_BILLOW_SIMPLEX",
"zoom": 0.52
},
"warpStyle": {
"style": "SIMPLEX",
"zoom": 0.46
},
"baseWeight": 0.91,
"detailWeight": 0.1,
"warpStrength": 0.18,
"densityThreshold": {
"min": -0.12,
"max": -0.04,
"style": {
"style": "SIMPLEX",
"zoom": 0.7
}
},
"thresholdBias": 0.12,
"sampleStep": 2,
"surfaceClearance": 6,
"allowSurfaceBreak": true,
"surfaceBreakStyle": {
"style": "SIMPLEX",
"zoom": 0.9
},
"surfaceBreakNoiseThreshold": 0.68,
"surfaceBreakDepth": 12,
"surfaceBreakThresholdBoost": 0.1,
"objectMinDepthBelowSurface": 16,
"defaultObjectAnchor": "FLOOR",
"defaultObjectPlaceMode": "ORGANIC_STILT",
"anchorScanStep": 1,
"anchorSearchAttempts": 18,
"allowFluid": true,
"fluidMinDepthBelowSurface": 20,
"fluidRequiresFloor": true,
"allowLava": true,
"modules": [
{
"style": {
"style": "SIMPLEX_VASCULAR",
"zoom": 0.98
},
"weight": 0.08,
"threshold": 0.03,
"verticalRange": {
"min": 24,
"max": 680
},
"invert": false
},
{
"style": {
"style": "FRACTAL_BILLOW_SIMPLEX",
"zoom": 0.34
},
"weight": 0.04,
"threshold": 0.07,
"verticalRange": {
"min": 8,
"max": 260
},
"invert": true
}
],
"verticalEdgeFade": 26,
"verticalEdgeFadeStrength": 0.18,
"minCarveCells": 24,
"recoveryThresholdBoost": 0.07
},
"caveMinDepthBelowSurface": 10,
"children": [
{"biome": "carving/amethyst", "weight": 1}
@@ -850,88 +850,6 @@
"global-clutter"
]
},
"caveProfile": {
"enabled": true,
"verticalRange": {
"min": 6,
"max": 700
},
"baseDensityStyle": {
"style": "PERLIN_IRIS",
"zoom": 0.72
},
"detailDensityStyle": {
"style": "SIMPLEX",
"zoom": 0.54
},
"warpStyle": {
"style": "FRACTAL_WATER",
"zoom": 0.5
},
"baseWeight": 0.9,
"detailWeight": 0.11,
"warpStrength": 0.24,
"densityThreshold": {
"min": -0.14,
"max": -0.06,
"style": {
"style": "SIMPLEX",
"zoom": 0.74
}
},
"thresholdBias": 0.14,
"sampleStep": 3,
"surfaceClearance": 5,
"allowSurfaceBreak": true,
"surfaceBreakStyle": {
"style": "SIMPLEX",
"zoom": 0.88
},
"surfaceBreakNoiseThreshold": 0.6,
"surfaceBreakDepth": 16,
"surfaceBreakThresholdBoost": 0.1,
"objectMinDepthBelowSurface": 14,
"defaultObjectAnchor": "FLOOR",
"defaultObjectPlaceMode": "ORGANIC_STILT",
"anchorScanStep": 1,
"anchorSearchAttempts": 12,
"allowFluid": true,
"fluidMinDepthBelowSurface": 20,
"fluidRequiresFloor": true,
"allowLava": true,
"modules": [
{
"style": {
"style": "SIMPLEX_VASCULAR",
"zoom": 1.08
},
"weight": 0.08,
"threshold": 0.03,
"verticalRange": {
"min": 24,
"max": 660
},
"invert": false
},
{
"style": {
"style": "FRACTAL_FBM_SIMPLEX",
"zoom": 0.24
},
"weight": 0.04,
"threshold": 0.08,
"verticalRange": {
"min": 6,
"max": 240
},
"invert": true
}
],
"verticalEdgeFade": 24,
"verticalEdgeFadeStrength": 0.18,
"minCarveCells": 24,
"recoveryThresholdBoost": 0.07
},
"carving": [
{
"id": "global-deepdark-band",
@@ -45,57 +45,6 @@
"temperate/food"
]
},
"caveProfile": {
"enabled": true,
"verticalRange": {
"min": 6,
"max": 120
},
"baseDensityStyle": {
"style": "PERLIN",
"zoom": 0.55
},
"detailDensityStyle": {
"style": "SIMPLEX",
"zoom": 0.5
},
"warpStyle": {
"style": "SIMPLEX",
"zoom": 0.5
},
"baseWeight": 1,
"detailWeight": 0,
"warpStrength": 0,
"densityThreshold": {
"min": -0.14,
"max": -0.06,
"style": {
"style": "SIMPLEX",
"zoom": 0.5
}
},
"thresholdBias": 0.06,
"sampleStep": 3,
"surfaceClearance": 12,
"allowSurfaceBreak": false,
"surfaceBreakStyle": {
"style": "SIMPLEX",
"zoom": 0.88
},
"surfaceBreakNoiseThreshold": 0.99,
"surfaceBreakDepth": 4,
"surfaceBreakThresholdBoost": 0.02,
"objectMinDepthBelowSurface": 14,
"defaultObjectAnchor": "FLOOR",
"defaultObjectPlaceMode": "ORGANIC_STILT",
"anchorScanStep": 1,
"anchorSearchAttempts": 12,
"allowFluid": true,
"fluidMinDepthBelowSurface": 20,
"fluidRequiresFloor": true,
"allowLava": true,
"modules": []
},
"caveBiomeZoom": 3.3,
"entitySpawners": [
"temperate/cave",
@@ -425,57 +425,6 @@
"cave/clutter"
]
},
"caveProfile": {
"enabled": true,
"verticalRange": {
"min": 6,
"max": 100
},
"baseDensityStyle": {
"style": "CELLULAR",
"zoom": 0.78
},
"detailDensityStyle": {
"style": "SIMPLEX",
"zoom": 0.32
},
"warpStyle": {
"style": "SIMPLEX",
"zoom": 0.26
},
"baseWeight": 1.0,
"detailWeight": 0.16,
"warpStrength": 0.32,
"densityThreshold": {
"min": -0.08,
"max": 0.02,
"style": {
"style": "SIMPLEX",
"zoom": 0.42
}
},
"thresholdBias": 0.06,
"sampleStep": 2,
"surfaceClearance": 12,
"allowSurfaceBreak": false,
"surfaceBreakStyle": {
"style": "SIMPLEX",
"zoom": 0.88
},
"surfaceBreakNoiseThreshold": 0.99,
"surfaceBreakDepth": 4,
"surfaceBreakThresholdBoost": 0.02,
"objectMinDepthBelowSurface": 14,
"defaultObjectAnchor": "FLOOR",
"defaultObjectPlaceMode": "ORGANIC_STILT",
"anchorScanStep": 1,
"anchorSearchAttempts": 12,
"allowFluid": true,
"fluidMinDepthBelowSurface": 20,
"fluidRequiresFloor": true,
"allowLava": true,
"modules": []
},
"caveBiomeZoom": 3.3,
"entitySpawners": [
"temperate/cave",
@@ -3,68 +3,6 @@
"derivative": "minecraft:lush_caves",
"vanillaDerivative": "minecraft:lush_caves",
"caveMinDepthBelowSurface": 9,
"caveProfile": {
"enabled": true,
"verticalRange": {
"min": 6,
"max": 700
},
"baseDensityStyle": {
"style": "SIMPLEX_VASCULAR",
"zoom": 0.88
},
"detailDensityStyle": {
"style": "FRACTAL_BILLOW_SIMPLEX",
"zoom": 0.42
},
"warpStyle": {
"style": "SIMPLEX",
"zoom": 0.28
},
"baseWeight": 0.9,
"detailWeight": 0.12,
"warpStrength": 0.38,
"densityThreshold": {
"min": -0.13,
"max": -0.035,
"style": {
"style": "SIMPLEX",
"zoom": 0.66
}
},
"thresholdBias": 0.08,
"sampleStep": 2,
"surfaceClearance": 9,
"allowSurfaceBreak": false,
"objectMinDepthBelowSurface": 13,
"defaultObjectAnchor": "FLOOR",
"defaultObjectPlaceMode": "ORGANIC_STILT",
"anchorScanStep": 1,
"anchorSearchAttempts": 16,
"allowFluid": true,
"fluidMinDepthBelowSurface": 18,
"fluidRequiresFloor": true,
"allowLava": true,
"modules": [
{
"style": {
"style": "FRACTAL_BILLOW_SIMPLEX",
"zoom": 0.34
},
"weight": 0.06,
"threshold": 0.06,
"verticalRange": {
"min": 12,
"max": 420
},
"invert": true
}
],
"verticalEdgeFade": 22,
"verticalEdgeFadeStrength": 0.15,
"minCarveCells": 20,
"recoveryThresholdBoost": 0.06
},
"wall": {
"style": {
"style": "SIMPLEX",
+3 -3
View File
@@ -16,7 +16,7 @@ mantle components outside the stage graph any more. Their stage constants, and t
types packs may read, live in `src/main/java/art/arcane/iris/builtin`, the package Iris exposes to pack
modules; their stage bodies live beside the features they replace. Settings and helper types that only the jar's modules read,
which Iris itself never touches, live in `art.arcane.iris.modules` instead, which Iris does not expose: the jar loads its own copy.
Every built-in snippet is named under its module's id, `iris/<module>/<name>` (folder `snippet/iris/carve/cave-profile/`), so a
Every built-in snippet is named under its module's id, `iris/<module>/<name>` (folder `snippet/iris/decorant/decorator/`), so a
snippet type may live in either package. A type stays in `art.arcane.iris.builtin` only when Iris reads it or an exposed type holds it.
Two of those modules are not in this project: `iris:biome` (writes the layout's platform biomes into the chunk) and
@@ -100,7 +100,7 @@ module-owned classes too (`art.arcane.iris.builtin.validate`, `.stilt`, `.vacuum
settings (the keys pack modules add at `Level.PLACEMENT`) from the JSON the placement was written as (`json()`); a
placement made in code uses `ObjectPlacement.builder()` or `toBuilder()`. Packs write the same JSON as before. Behaviour
that needs Iris (noise built from the styles, blocks resolved through the pack, baked object variants) lives in `Resolved*` classes beside the
worker (`ResolvedReplace`, `ResolvedCaveProfile`, `ResolvedFloatingChild`, `ResolvedProceduralPlacement`).
worker (`ResolvedReplace`, `ResolvedFloatingChild`, `ResolvedProceduralPlacement`).
`iris:decorant` is the second: `DecorantSettings` (biome level) holds `Decorator`s in `art.arcane.iris.builtin.decorant`,
written `"decorators": [...]` as always (`@Feature(key = "decorators", root = "decorators")`).
@@ -125,7 +125,7 @@ from the random of whoever asks first, as it always was. The slope limit of a la
object placement is the one `SlopeClip`.
Caves, floating islands and ores are settings of their modules too, written under the keys they always had. `iris:carve` owns
`caveProfile` (dimension, region, biome; an object, or a `snippet/iris/carve/cave-profile/...` reference), `carving` (dimension; a list of bands) and
`caves` (dimension, region, biome; a list of keys of the pack's `caves/` folder, the lists of a column adding up), `carving` (dimension; a list of bands) and
`carvingEnabled` (dimension; a boolean), `carvingBiome` (biome; a biome key) and `caveMinDepthBelowSurface` (biome; a number). `iris:floating`
owns `floatingChildBiomes` (biome; a list) and `mergeFloatingChildBiomes` (biome; a boolean). `iris:terrain` owns `ores` (dimension, region,
biome; a list of generators) and `hideOresForHiddenOre` (dimension; a boolean); `iris:deposit` owns `depositVariants` (dimension, region, biome; a list)
@@ -1,66 +0,0 @@
/*
* 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.builtin.carve;
import com.volmit.config.Desc;
import com.volmit.config.MaxNumber;
import com.volmit.config.MinNumber;
import com.volmit.config.Range;
import com.volmit.noise.NoiseStyle;
/** One more layer of noise a cave profile blends into its density, an entry of the profile's {@code modules}. */
@Desc("Represents a modular cave-density layer.")
public final class CaveFieldModule {
@Desc("Density style used by this module.")
private NoiseStyle style = NoiseStyle.of("CELLULAR_IRIS_DOUBLE");
@MinNumber(0)
@Desc("Layer contribution multiplier.")
private double weight = 1;
@MinNumber(-1)
@MaxNumber(1)
@Desc("Threshold offset applied to this layer before blending.")
private double threshold = 0;
@Desc("Vertical bounds where this module can contribute, in engine-local Y where 0 is the bottom of the dimension, not world Y.")
private Range verticalRange = Range.of(0, 384);
@Desc("Invert this module before weighting.")
private boolean invert = false;
public CaveFieldModule() {
}
public NoiseStyle style() {
return style;
}
public double weight() {
return weight;
}
public double threshold() {
return threshold;
}
public Range verticalRange() {
return verticalRange;
}
public boolean invert() {
return invert;
}
}
@@ -1,69 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 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 com.volmit.mantle.CarvedVoid;
final class CaveCarveScratch {
final int[] columnMaxY = new int[256];
final int[] fluidMaxY = new int[256];
final int[] surfaceBreakFloorY = new int[256];
final boolean[] surfaceBreakColumn = new boolean[256];
final boolean[] surfaceCeilingColumn = new boolean[256];
final double[] columnThreshold = new double[256];
final double[] passThreshold = new double[256];
final double[] fullWeights = new double[256];
final double[] clampedColumnWeights = new double[256];
final int[] activeColumnIndices = new int[256];
final int[] activeColumnTopY = new int[256];
final int[] planeColumnIndices = new int[256];
final double[] planeThresholdLimit = new double[256];
final boolean[] planeCarve = new boolean[256];
final double[] adaptivePlaneDensity = new double[81];
final double[] adaptivePlanePrediction = new double[256];
final double[] adaptivePlaneAmbiguity = new double[256];
final int[] adaptivePlaneSampleBounds = new int[4];
final int[] adaptiveCellX = new int[256];
final int[] adaptiveCellZ = new int[256];
final int[] adaptiveRow0 = new int[256];
final int[] adaptiveRow1 = new int[256];
final double[] adaptiveTx = new double[256];
final double[] adaptiveTz = new double[256];
final boolean[] warpCacheSet = new boolean[256];
final int[] warpCacheX = new int[256];
final int[] warpCacheY = new int[256];
final int[] warpCacheZ = new int[256];
final double[] warpCacheA = new double[256];
final double[] warpCacheB = new double[256];
final int[] tileIndices = new int[4];
final int[] tileLocalX = new int[4];
final int[] tileLocalZ = new int[4];
final int[] tileTopY = new int[4];
CaveFieldModuleState[] activeModules = new CaveFieldModuleState[0];
double[] activeModuleRemainingMin = new double[0];
double[] activeModuleRemainingMax = new double[0];
int activeModulesY = Integer.MIN_VALUE;
int activeModuleCount;
double[] verticalEdgeFade = new double[0];
double[] surfaceClosureThreshold = new double[0];
CarvedVoid[] voidByY = new CarvedVoid[0];
int adaptiveGeometryStep = -1;
int adaptiveGeometryAxisCells = -1;
boolean fullWeightsInitialized;
}
@@ -18,604 +18,290 @@
package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.modules.carve.CaveProfile;
import art.arcane.iris.engine.object.terrain.carving.CarvingResolver;
import art.arcane.iris.engine.object.terrain.carving.DeclaredCaveProfiles;
import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry;
import art.arcane.iris.engine.object.terrain.carving.DeclaredByLevel;
import art.arcane.iris.modules.carve.Cave;
import art.arcane.iris.modules.carve.CaveList;
import art.arcane.iris.modules.carve.CaveResources;
import art.arcane.iris.modules.carve.field.CaveCarver;
import art.arcane.iris.modules.carve.field.ChunkLattice;
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
import com.volmit.config.Range;
import com.volmit.ModuleLog;
import com.volmit.mantle.CarvedVoid;
import com.volmit.mantle.MantleLayer;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.world.BiomeSample;
import com.volmit.world.PackBiome;
import com.volmit.world.PackWorld;
import com.volmit.world.TerrainSampler;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.IdentityHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
/**
* Plans one chunk's caves into the mantle for {@link art.arcane.iris.engine.modifier.CarveModule}: the cave
* profiles of the dimension's carving entries and of the regions and biomes around the chunk, blended over
* their borders. One per engine runtime, keeping a carver per cave profile.
* Plans one chunk's caves into the mantle for {@link art.arcane.iris.engine.modifier.CarveModule}: every cave the
* dimension, the regions and the biomes around the chunk list under {@code caves}. The lists of a column add up, and a
* cave narrows to nothing over a few blocks where the columns that list it end. One per world, keeping a carver per cave.
*/
public class CaveCarving {
private static final int CHUNK_SIZE = 16;
private static final int CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE;
private static final int BLEND_RADIUS = 3;
private static final int WATER_FIELD_PADDING = 3;
private static final int WATER_FIELD_SIZE = CHUNK_SIZE + (WATER_FIELD_PADDING * 2);
/** A column's cave biome is the one the world places this far below its surface (at least at height 1). */
private static final int CAVE_SAMPLE_DEPTH_BELOW_SURFACE_BLOCKS = 56;
private static final int FIELD_SIZE = CHUNK_SIZE + (BLEND_RADIUS * 2);
private static final double MIN_WEIGHT = 0.08D;
private static final double THRESHOLD_PENALTY = 0.24D;
private static final int MAX_BLENDED_PROFILE_PASSES = 2;
private static final int KERNEL_WIDTH = (BLEND_RADIUS * 2) + 1;
private static final int KERNEL_SIZE = KERNEL_WIDTH * KERNEL_WIDTH;
private static final int[] KERNEL_DX = new int[KERNEL_SIZE];
private static final int[] KERNEL_DZ = new int[KERNEL_SIZE];
private static final double[] KERNEL_WEIGHT = new double[KERNEL_SIZE];
private static final ThreadLocal<BlendScratch> BLEND_SCRATCH = ThreadLocal.withInitial(BlendScratch::new);
/** Which caves a column lists is read every fourth block, one ring beyond the chunk, and smoothed between the readings. */
private static final int LISTING_STEP_BLOCKS = ChunkLattice.CELL_BLOCKS;
private static final int LISTINGS_PER_AXIS = ChunkLattice.CELLS_PER_CHUNK_AXIS + 3;
private static final int LISTINGS = LISTINGS_PER_AXIS * LISTINGS_PER_AXIS;
private static final int WEIGHTS_PER_AXIS = ChunkLattice.CELLS_PER_CHUNK_AXIS + 1;
private static final int LISTINGS_PER_WEIGHT = 9;
/** Loose rock is swept this far below the surface where a cave opens to it. */
private static final int LOOSE_ROCK_SWEEP_DEPTH_BLOCKS = 16;
private static final double[] LISTED_EVERYWHERE = filled(1D);
private static final ThreadLocal<Scratch> SCRATCH = ThreadLocal.withInitial(Scratch::new);
private final CarveWorld world;
private final DeclaredCaveProfiles declaredProfiles;
private final CarvingResolver resolver;
private final PackResources resources;
private final DeclaredByLevel<CaveList> lists;
private final FluidColumns fluidColumns;
private final boolean upperDimensionCarving;
private final Object profileCarverLock = new Object();
private volatile Map<CaveProfile, IrisCaveCarver3D> profileCarvers = new IdentityHashMap<>();
private final ModuleLog log;
private final Map<ResourceId, Optional<ListedCave>> caves = new ConcurrentHashMap<>();
private final Map<ListingKey, List<ResourceId>> listings = new ConcurrentHashMap<>();
/** What every column lists when only the dimension lists caves, which spares reading the biomes around each chunk. */
private final Map<ResourceId, double[]> dimensionCaves;
static {
int kernelIndex = 0;
for (int offsetX = -BLEND_RADIUS; offsetX <= BLEND_RADIUS; offsetX++) {
for (int offsetZ = -BLEND_RADIUS; offsetZ <= BLEND_RADIUS; offsetZ++) {
KERNEL_DX[kernelIndex] = offsetX;
KERNEL_DZ[kernelIndex] = offsetZ;
int edgeDistance = Math.max(Math.abs(offsetX), Math.abs(offsetZ));
KERNEL_WEIGHT[kernelIndex] = (BLEND_RADIUS + 1D) - edgeDistance;
kernelIndex++;
}
}
}
/** Whether the dimension's fluid palette gives a column a fluid, which caves near it blend towards. */
/** Whether the dimension's fluid palette gives a column a fluid, which caves do not cut into. */
@FunctionalInterface
public interface FluidColumns {
boolean hasFluid(int worldX, int worldZ);
}
public CaveCarving(PackWorld packWorld, CarveWorld world, boolean upperDimensionCarving, FluidColumns fluidColumns) {
public CaveCarving(PackWorld packWorld, CarveWorld world, FluidColumns fluidColumns, ModuleLog log) {
this.world = world;
this.declaredProfiles = DeclaredCaveProfiles.of(packWorld);
this.resolver = CarvingResolver.of(packWorld);
this.resources = packWorld.resources();
this.lists = DeclaredByLevel.of(packWorld, CaveList.class);
this.fluidColumns = fluidColumns;
this.upperDimensionCarving = upperDimensionCarving;
this.log = log;
this.dimensionCaves = new TreeMap<>();
Set<ResourceId> listedByDimension = new LinkedHashSet<>();
addListed(listedByDimension, lists.ofDimension());
for (ResourceId cave : listedByDimension) {
dimensionCaves.put(cave, LISTED_EVERYWHERE);
}
}
/** Carves the caves of the chunk at chunk coordinates {@code x}, {@code z} into {@code voids}, reading the terrain around it from {@code terrain}. */
public void carve(MantleLayer<CarvedVoid> voids, TerrainSampler terrain, int x, int z) {
BlendScratch blendScratch = BLEND_SCRATCH.get();
int[] chunkSurfaceHeights = prepareChunkSurfaceHeights(x, z, terrain, blendScratch.chunkSurfaceHeights);
List<WeightedProfile> weightedProfiles = resolveWeightedProfiles(x, z, terrain);
int fluidHeight = world.fluidHeight();
int[] surfaceFluidBoundaryStartY = blendScratch.surfaceFluidBoundaryStartY;
SurfaceFluidBoundaryPlan.fill(
chunkSurfaceHeights,
blendScratch.fieldSurfaceHeights,
blendScratch.fieldHasFluid,
FIELD_SIZE,
BLEND_RADIUS,
fluidHeight,
surfaceFluidBoundaryStartY
);
CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan();
for (WeightedProfile weightedProfile : weightedProfiles) {
carveProfile(weightedProfile, voids, x, z, chunkSurfaceHeights, surfaceFluidBoundaryStartY, fluidSupportPlan);
}
if (upperDimensionCarving && hasUpperDimension(terrain, x, z)) {
carveUpperTerrain(terrain, weightedProfiles, voids, x, z, fluidSupportPlan);
}
fluidSupportPlan.resolve(voids, PowerOfTwoCoordinates.chunkToBlock(x), PowerOfTwoCoordinates.chunkToBlock(z), world.height());
if (!weightedProfiles.isEmpty()) {
CarveOrphanSweep.sweepChunk(
voids,
PowerOfTwoCoordinates.chunkToBlock(x),
PowerOfTwoCoordinates.chunkToBlock(z),
chunkSurfaceHeights,
maxSurfaceBreakDepth(weightedProfiles),
world.height() - 1,
surfaceFluidBoundaryStartY,
fluidHeight
);
}
}
private static boolean hasUpperDimension(TerrainSampler terrain, int chunkX, int chunkZ) {
return terrain.upperDimensionY(PowerOfTwoCoordinates.chunkToBlock(chunkX), PowerOfTwoCoordinates.chunkToBlock(chunkZ)).isPresent();
}
private static int maxSurfaceBreakDepth(List<WeightedProfile> weightedProfiles) {
int maxDepth = 0;
for (WeightedProfile weightedProfile : weightedProfiles) {
maxDepth = Math.max(maxDepth, Math.max(0, weightedProfile.profile.surfaceBreakDepth()));
}
return maxDepth;
}
private void carveProfile(WeightedProfile weightedProfile, MantleLayer<CarvedVoid> voids, int cx, int cz,
int[] chunkSurfaceHeights, int[] surfaceFluidBoundaryStartY,
CaveFluidSupportPlan fluidSupportPlan) {
IrisCaveCarver3D carver = getCarver(weightedProfile.profile);
carver.carve(voids, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY,
weightedProfile.worldYRange, chunkSurfaceHeights, surfaceFluidBoundaryStartY, null, fluidSupportPlan);
}
private void carveUpperTerrain(TerrainSampler terrain, List<WeightedProfile> normalProfiles,
MantleLayer<CarvedVoid> voids, int cx, int cz,
CaveFluidSupportPlan fluidSupportPlan) {
int chunkHeight = world.height();
int worldMinHeight = world.minHeight();
int baseX = PowerOfTwoCoordinates.chunkToBlock(cx);
int baseZ = PowerOfTwoCoordinates.chunkToBlock(cz);
int minUpperSurfaceY = chunkHeight;
for (int localX = 0; localX < CHUNK_SIZE; localX++) {
int worldX = baseX + localX;
for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) {
int worldZ = baseZ + localZ;
int upperY = terrain.upperDimensionY(worldX, worldZ).getAsInt();
if (upperY < minUpperSurfaceY) {
minUpperSurfaceY = upperY;
}
}
}
if (minUpperSurfaceY >= chunkHeight - 2) {
Scratch scratch = SCRATCH.get();
int originX = PowerOfTwoCoordinates.chunkToBlock(x);
int originZ = PowerOfTwoCoordinates.chunkToBlock(z);
Map<ResourceId, double[]> listed = listedCaves(terrain, originX, originZ, scratch);
if (listed.isEmpty()) {
return;
}
Range upperYRange = Range.of(
minUpperSurfaceY + worldMinHeight,
chunkHeight - 1 + worldMinHeight
);
Range fullVerticalRange = Range.of(0, chunkHeight);
int[] ceilingSurfaceHeights = new int[CHUNK_AREA];
Arrays.fill(ceilingSurfaceHeights, chunkHeight - 1);
for (WeightedProfile weightedProfile : normalProfiles) {
Range constrainedRange;
if (weightedProfile.worldYRange != null) {
double min = Math.max(weightedProfile.worldYRange.min(), upperYRange.min());
double max = Math.min(weightedProfile.worldYRange.max(), upperYRange.max());
if (min >= max) {
continue;
}
constrainedRange = Range.of(min, max);
} else {
constrainedRange = upperYRange;
readSurface(terrain, originX, originZ, scratch);
boolean opensToSurface = false;
boolean carved = false;
for (Map.Entry<ResourceId, double[]> entry : listed.entrySet()) {
ListedCave cave = caveOf(entry.getKey());
if (cave == null) {
continue;
}
IrisCaveCarver3D carver = getCarver(weightedProfile.profile);
carver.carve(voids, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY,
constrainedRange, ceilingSurfaceHeights, null, fullVerticalRange, fluidSupportPlan);
opensToSurface |= cave.carver.opensToSurface();
carved |= carveCave(cave, entry.getValue(), voids, originX, originZ, scratch);
}
if (carved) {
CarveOrphanSweep.sweepChunk(voids, originX, originZ, scratch.surfaceY,
opensToSurface ? LOOSE_ROCK_SWEEP_DEPTH_BLOCKS : 0, world.height() - 1, scratch.waterStartY, world.fluidHeight());
}
}
private List<WeightedProfile> resolveWeightedProfiles(int chunkX, int chunkZ, TerrainSampler terrain) {
BlendScratch blendScratch = BLEND_SCRATCH.get();
CaveProfile[] profileField = blendScratch.profileField;
Map<CaveProfile, double[]> columnProfileWeights = blendScratch.columnProfileWeights;
IdentityHashMap<CaveProfile, Boolean> activeProfiles = blendScratch.activeProfiles;
List<CaveProfile> profileOrder = blendScratch.profileOrder;
CaveProfile[] kernelProfiles = blendScratch.kernelProfiles;
double[] kernelProfileWeights = blendScratch.kernelProfileWeights;
activeProfiles.clear();
profileOrder.clear();
fillProfileField(profileField, chunkX, chunkZ, terrain, blendScratch);
private boolean carveCave(ListedCave cave, double[] columnWeight, MantleLayer<CarvedVoid> voids, int originX, int originZ, Scratch scratch) {
int[] waterStartY = scratch.waterStartY;
int fluidHeight = world.fluidHeight();
boolean[] carved = scratch.carvedAnything;
carved[0] = false;
cave.carver.carve(originX, originZ, scratch.surfaceY, columnWeight, scratch.underWater, (localX, y, localZ) -> {
if (SurfaceFluidBoundaryPlan.protects(waterStartY, PowerOfTwoCoordinates.packLocal16(localX, localZ), y, fluidHeight)) {
return;
}
voids.set(originX + localX, y, originZ + localZ, cave.carvedVoid);
carved[0] = true;
});
return carved[0];
}
/** The surface of the chunk's columns, and which of them lie under or next to water, where no cave may open the surface. */
private void readSurface(TerrainSampler terrain, int originX, int originZ, Scratch scratch) {
for (int localX = 0; localX < CHUNK_SIZE; localX++) {
for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) {
int profileCount = 0;
int centerX = localX + BLEND_RADIUS;
int centerZ = localZ + BLEND_RADIUS;
double totalKernelWeight = 0D;
for (int kernelIndex = 0; kernelIndex < KERNEL_SIZE; kernelIndex++) {
int sampleX = centerX + KERNEL_DX[kernelIndex];
int sampleZ = centerZ + KERNEL_DZ[kernelIndex];
CaveProfile profile = profileField[(sampleX * FIELD_SIZE) + sampleZ];
if (!isProfileEnabled(profile)) {
continue;
}
double kernelWeight = KERNEL_WEIGHT[kernelIndex];
int existingIndex = findProfileIndex(kernelProfiles, profileCount, profile);
if (existingIndex >= 0) {
kernelProfileWeights[existingIndex] += kernelWeight;
} else {
kernelProfiles[profileCount] = profile;
kernelProfileWeights[profileCount] = kernelWeight;
profileCount++;
}
totalKernelWeight += kernelWeight;
}
if (totalKernelWeight <= 0D || profileCount == 0) {
continue;
}
int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ);
for (int profileIndex = 0; profileIndex < profileCount; profileIndex++) {
CaveProfile profile = kernelProfiles[profileIndex];
double kernelWeight = kernelProfileWeights[profileIndex];
kernelProfiles[profileIndex] = null;
kernelProfileWeights[profileIndex] = 0D;
double columnWeight = clampWeight(kernelWeight / totalKernelWeight);
if (columnWeight < MIN_WEIGHT) {
continue;
}
double[] weights = columnProfileWeights.get(profile);
if (weights == null) {
weights = new double[CHUNK_AREA];
columnProfileWeights.put(profile, weights);
} else if (!activeProfiles.containsKey(profile)) {
Arrays.fill(weights, 0D);
}
if (activeProfiles.put(profile, Boolean.TRUE) == null) {
profileOrder.add(profile);
}
weights[columnIndex] = columnWeight;
}
scratch.surfaceY[PowerOfTwoCoordinates.packLocal16(localX, localZ)] = terrain.surfaceHeight(originX + localX, originZ + localZ);
}
}
List<WeightedProfile> columnWeightedProfiles = new ArrayList<>();
for (CaveProfile profile : profileOrder) {
double[] weights = columnProfileWeights.get(profile);
if (weights == null) {
continue;
}
// averageWeight ranks and orders carve passes, so it must be bit-identical across
// installations: kernels.sum reassociates FP addition under the vector kernel,
// making profile order depend on a JVM flag. max() is order-independent and safe.
double maxWeight = maxOf(weights);
if (maxWeight < MIN_WEIGHT) {
continue;
}
double averageWeight = computeAverageWeight(weights);
columnWeightedProfiles.add(new WeightedProfile(profile, weights, averageWeight, null, columnWeightedProfiles.size()));
}
List<WeightedProfile> blendedProfiles = limitAndMergeBlendedProfiles(columnWeightedProfiles, MAX_BLENDED_PROFILE_PASSES, CHUNK_AREA);
List<WeightedProfile> resolvedProfiles = resolveDimensionCarvingProfiles(chunkX, chunkZ, blendScratch);
resolvedProfiles.addAll(blendedProfiles);
return resolvedProfiles;
}
private List<WeightedProfile> resolveDimensionCarvingProfiles(int chunkX, int chunkZ, BlendScratch blendScratch) {
List<WeightedProfile> weightedProfiles = new ArrayList<>();
List<ResolvedCarvingEntry> entries = resolver.entries();
if (entries.isEmpty()) {
return weightedProfiles;
}
Map<ResolvedCarvingEntry, ResolvedCarvingEntry[]> dimensionColumnPlans = blendScratch.dimensionColumnPlans;
dimensionColumnPlans.clear();
for (ResolvedCarvingEntry entry : entries) {
if (!entry.enabled()) {
continue;
}
PackBiome rootBiome = resolver.entryBiome(entry);
if (rootBiome == null) {
continue;
}
ResolvedCarvingEntry[] columnPlan = dimensionColumnPlans.computeIfAbsent(entry, key -> new ResolvedCarvingEntry[CHUNK_AREA]);
buildDimensionColumnPlan(columnPlan, chunkX, chunkZ, entry);
Map<CaveProfile, double[]> rootProfileColumnWeights = new IdentityHashMap<>();
List<CaveProfile> rootProfileOrder = new ArrayList<>();
Range worldYRange = entry.worldYRange();
for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) {
ResolvedCarvingEntry resolvedEntry = columnPlan[columnIndex];
PackBiome resolvedBiome = resolver.entryBiome(resolvedEntry);
if (resolvedBiome == null) {
continue;
}
CaveProfile profile = declaredProfiles.ofBiome(resolvedBiome.id());
if (!isProfileEnabled(profile)) {
continue;
}
double[] columnWeights = rootProfileColumnWeights.get(profile);
if (columnWeights == null) {
columnWeights = new double[CHUNK_AREA];
rootProfileColumnWeights.put(profile, columnWeights);
rootProfileOrder.add(profile);
}
columnWeights[columnIndex] = 1D;
}
for (CaveProfile profile : rootProfileOrder) {
weightedProfiles.add(new WeightedProfile(profile, rootProfileColumnWeights.get(profile), -1D, worldYRange, weightedProfiles.size()));
for (int fieldX = 0; fieldX < WATER_FIELD_SIZE; fieldX++) {
int worldX = originX - WATER_FIELD_PADDING + fieldX;
for (int fieldZ = 0; fieldZ < WATER_FIELD_SIZE; fieldZ++) {
int worldZ = originZ - WATER_FIELD_PADDING + fieldZ;
int fieldIndex = (fieldX * WATER_FIELD_SIZE) + fieldZ;
scratch.fieldSurfaceY[fieldIndex] = terrain.surfaceY(worldX, worldZ);
scratch.fieldHasFluid[fieldIndex] = fluidColumns.hasFluid(worldX, worldZ);
}
}
return weightedProfiles;
}
private void buildDimensionColumnPlan(ResolvedCarvingEntry[] columnPlan, int chunkX, int chunkZ, ResolvedCarvingEntry entry) {
int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX);
int baseZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ);
for (int localX = 0; localX < CHUNK_SIZE; localX++) {
int worldX = baseX + localX;
for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) {
int worldZ = baseZ + localZ;
int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ);
columnPlan[columnIndex] = resolver.resolveFromRoot(entry, worldX, worldZ);
}
SurfaceFluidBoundaryPlan.fill(scratch.surfaceY, scratch.fieldSurfaceY, scratch.fieldHasFluid, WATER_FIELD_SIZE,
WATER_FIELD_PADDING, world.fluidHeight(), scratch.waterStartY);
for (int column = 0; column < CHUNK_AREA; column++) {
scratch.underWater[column] = scratch.waterStartY[column] != SurfaceFluidBoundaryPlan.NO_BOUNDARY;
}
}
private void fillProfileField(CaveProfile[] profileField, int chunkX, int chunkZ, TerrainSampler terrain, BlendScratch blendScratch) {
int startX = PowerOfTwoCoordinates.chunkToBlock(chunkX) - BLEND_RADIUS;
int startZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ) - BLEND_RADIUS;
prefillFieldHeightsAndFluid(terrain, startX, startZ, blendScratch);
for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) {
int worldX = startX + fieldX;
for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) {
int worldZ = startZ + fieldZ;
int fieldIndex = (fieldX * FIELD_SIZE) + fieldZ;
profileField[fieldIndex] = resolveColumnProfile(terrain, worldX, worldZ, blendScratch.fieldSurfaceHeights[fieldIndex]);
}
}
}
private int findProfileIndex(CaveProfile[] profiles, int size, CaveProfile profile) {
for (int index = 0; index < size; index++) {
if (profiles[index] == profile) {
return index;
}
}
return -1;
}
/**
* The profile that carves a column: the dimension's, replaced by the region's, the surface biome's and the cave biome's
* wherever they declare an enabled one. The cave biome is the one the world places at the depth below the surface this
* column's caves start at ({@link #CAVE_SAMPLE_DEPTH_BELOW_SURFACE_BLOCKS}), after the dimension's carving bands.
* The caves any column of the chunk lists, in the order of their ids, each with how much every column lists it:
* 1 well inside the columns that do, 0 well outside, in between across their border.
*/
private CaveProfile resolveColumnProfile(TerrainSampler terrain, int worldX, int worldZ, double surfaceHeight) {
CaveProfile resolved = null;
CaveProfile dimensionProfile = declaredProfiles.ofDimension();
if (isProfileEnabled(dimensionProfile)) {
resolved = dimensionProfile;
private Map<ResourceId, double[]> listedCaves(TerrainSampler terrain, int originX, int originZ, Scratch scratch) {
if (lists.onlyDimensionDeclares()) {
return dimensionCaves;
}
int roundedSurfaceY = (int) Math.round(surfaceHeight);
int sampleY = Math.max(1, roundedSurfaceY - CAVE_SAMPLE_DEPTH_BELOW_SURFACE_BLOCKS);
BiomeSample sample = terrain.biome(worldX, sampleY, worldZ);
CaveProfile regionProfile = declaredProfiles.ofRegion(sample.region());
if (isProfileEnabled(regionProfile)) {
resolved = regionProfile;
}
CaveProfile surfaceProfile = declaredProfiles.ofBiome(sample.surfaceBiome());
if (isProfileEnabled(surfaceProfile)) {
resolved = surfaceProfile;
}
if (sample.caveBiome().isPresent()) {
CaveProfile caveProfile = declaredProfiles.ofBiome(sample.caveBiome().get());
if (isProfileEnabled(caveProfile)) {
resolved = caveProfile;
Map<ResourceId, boolean[]> listedAt = new TreeMap<>();
for (int listingX = 0; listingX < LISTINGS_PER_AXIS; listingX++) {
int worldX = originX + ((listingX - 1) * LISTING_STEP_BLOCKS);
for (int listingZ = 0; listingZ < LISTINGS_PER_AXIS; listingZ++) {
int worldZ = originZ + ((listingZ - 1) * LISTING_STEP_BLOCKS);
int listing = (listingX * LISTINGS_PER_AXIS) + listingZ;
for (ResourceId cave : listingAt(terrain, worldX, worldZ)) {
listedAt.computeIfAbsent(cave, absent -> new boolean[LISTINGS])[listing] = true;
}
}
}
return resolved;
Map<ResourceId, double[]> weights = new TreeMap<>();
for (Map.Entry<ResourceId, boolean[]> entry : listedAt.entrySet()) {
weights.put(entry.getKey(), columnWeights(entry.getValue(), scratch));
}
return weights;
}
private void prefillFieldHeightsAndFluid(TerrainSampler terrain, int startX, int startZ, BlendScratch blendScratch) {
for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) {
int worldX = startX + fieldX;
for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) {
int worldZ = startZ + fieldZ;
int fieldIndex = (fieldX * FIELD_SIZE) + fieldZ;
blendScratch.fieldSurfaceHeights[fieldIndex] = terrain.surfaceY(worldX, worldZ);
blendScratch.fieldHasFluid[fieldIndex] = fluidColumns.hasFluid(worldX, worldZ);
private List<ResourceId> listingAt(TerrainSampler terrain, int worldX, int worldZ) {
int surfaceY = (int) Math.round(terrain.surfaceY(worldX, worldZ));
BiomeSample sample = terrain.biome(worldX, Math.max(1, surfaceY - CAVE_SAMPLE_DEPTH_BELOW_SURFACE_BLOCKS), worldZ);
ListingKey key = new ListingKey(sample.region(), sample.surfaceBiome(), sample.caveBiome().orElse(null));
return listings.computeIfAbsent(key, this::listingOf);
}
/** Every cave the dimension, the region, the surface biome and the cave biome of a column list between them. */
private List<ResourceId> listingOf(ListingKey key) {
Set<ResourceId> listed = new LinkedHashSet<>();
addListed(listed, lists.ofDimension());
addListed(listed, lists.ofRegion(key.region));
addListed(listed, lists.ofBiome(key.surfaceBiome));
if (key.caveBiome != null) {
addListed(listed, lists.ofBiome(key.caveBiome));
}
return List.copyOf(listed);
}
private void addListed(Set<ResourceId> listed, CaveList list) {
if (list == null) {
return;
}
for (String key : list.caves()) {
if (key != null && !key.isBlank()) {
listed.add(resources.idOf(key));
}
}
}
private IrisCaveCarver3D getCarver(CaveProfile profile) {
IrisCaveCarver3D carver = profileCarvers.get(profile);
if (carver != null) {
return carver;
private static double[] columnWeights(boolean[] listedAt, Scratch scratch) {
if (isAllTrue(listedAt)) {
return LISTED_EVERYWHERE;
}
IrisCaveCarver3D createdCarver = new IrisCaveCarver3D(world, profile);
synchronized (profileCarverLock) {
IrisCaveCarver3D published = profileCarvers.get(profile);
if (published != null) {
return published;
double[] latticeWeight = scratch.latticeWeight;
for (int weightX = 0; weightX < WEIGHTS_PER_AXIS; weightX++) {
for (int weightZ = 0; weightZ < WEIGHTS_PER_AXIS; weightZ++) {
latticeWeight[(weightX * WEIGHTS_PER_AXIS) + weightZ] = listingsAround(listedAt, weightX, weightZ) / (double) LISTINGS_PER_WEIGHT;
}
Map<CaveProfile, IrisCaveCarver3D> updated = new IdentityHashMap<>(profileCarvers);
updated.put(profile, createdCarver);
profileCarvers = updated;
return createdCarver;
}
}
private boolean isProfileEnabled(CaveProfile profile) {
return profile != null && profile.enabled();
}
private int[] prepareChunkSurfaceHeights(int chunkX, int chunkZ, TerrainSampler terrain, int[] scratch) {
int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX);
int baseZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ);
double[] columnWeight = new double[CHUNK_AREA];
for (int localX = 0; localX < CHUNK_SIZE; localX++) {
int worldX = baseX + localX;
int weightX = localX / LISTING_STEP_BLOCKS;
double shareX = (localX % LISTING_STEP_BLOCKS) / (double) LISTING_STEP_BLOCKS;
for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) {
int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ);
scratch[columnIndex] = terrain.surfaceHeight(worldX, baseZ + localZ);
int weightZ = localZ / LISTING_STEP_BLOCKS;
double shareZ = (localZ % LISTING_STEP_BLOCKS) / (double) LISTING_STEP_BLOCKS;
double west = between(latticeWeight[(weightX * WEIGHTS_PER_AXIS) + weightZ], latticeWeight[(weightX * WEIGHTS_PER_AXIS) + weightZ + 1], shareZ);
double east = between(latticeWeight[((weightX + 1) * WEIGHTS_PER_AXIS) + weightZ], latticeWeight[((weightX + 1) * WEIGHTS_PER_AXIS) + weightZ + 1], shareZ);
columnWeight[PowerOfTwoCoordinates.packLocal16(localX, localZ)] = between(west, east, shareX);
}
}
return scratch;
return columnWeight;
}
private static double maxOf(double[] values) {
double max = Double.NEGATIVE_INFINITY;
for (double value : values) {
max = Math.max(max, value);
}
return max;
}
private static List<WeightedProfile> limitAndMergeBlendedProfiles(List<WeightedProfile> blendedProfiles, int maxProfiles) {
return limitAndMergeBlendedProfiles(blendedProfiles, maxProfiles, CHUNK_AREA);
}
private static List<WeightedProfile> limitAndMergeBlendedProfiles(List<WeightedProfile> blendedProfiles, int maxProfiles, int areaSize) {
if (blendedProfiles == null || blendedProfiles.isEmpty()) {
return new ArrayList<>();
}
int clampedLimit = Math.max(1, maxProfiles);
List<WeightedProfile> rankedProfiles = new ArrayList<>(blendedProfiles);
rankedProfiles.sort(CaveCarving::compareBySelectionRank);
List<WeightedProfile> keptProfiles = new ArrayList<>();
int keptCount = Math.min(clampedLimit, rankedProfiles.size());
for (int index = 0; index < keptCount; index++) {
keptProfiles.add(rankedProfiles.get(index));
}
if (rankedProfiles.size() > keptCount) {
for (int columnIndex = 0; columnIndex < areaSize; columnIndex++) {
int dominantIndex = 0;
double dominantWeight = Double.NEGATIVE_INFINITY;
for (int keptIndex = 0; keptIndex < keptProfiles.size(); keptIndex++) {
double keptWeight = keptProfiles.get(keptIndex).columnWeights[columnIndex];
if (keptWeight > dominantWeight) {
dominantWeight = keptWeight;
dominantIndex = keptIndex;
}
/** How many of the nine readings on and around a lattice point list the cave. The point's own reading is one ring in. */
private static int listingsAround(boolean[] listedAt, int weightX, int weightZ) {
int count = 0;
for (int listingX = weightX; listingX <= weightX + 2; listingX++) {
for (int listingZ = weightZ; listingZ <= weightZ + 2; listingZ++) {
if (listedAt[(listingX * LISTINGS_PER_AXIS) + listingZ]) {
count++;
}
double droppedWeight = 0D;
for (int droppedIndex = keptCount; droppedIndex < rankedProfiles.size(); droppedIndex++) {
droppedWeight += rankedProfiles.get(droppedIndex).columnWeights[columnIndex];
}
if (droppedWeight <= 0D) {
continue;
}
WeightedProfile dominantProfile = keptProfiles.get(dominantIndex);
double mergedWeight = dominantProfile.columnWeights[columnIndex] + droppedWeight;
dominantProfile.columnWeights[columnIndex] = clampWeight(mergedWeight);
}
}
List<WeightedProfile> mergedProfiles = new ArrayList<>();
for (WeightedProfile keptProfile : keptProfiles) {
double averageWeight = computeAverageWeight(keptProfile.columnWeights, areaSize);
mergedProfiles.add(new WeightedProfile(keptProfile.profile, keptProfile.columnWeights, averageWeight, keptProfile.worldYRange, keptProfile.sequence));
}
mergedProfiles.sort(CaveCarving::compareByCarveOrder);
return mergedProfiles;
return count;
}
private static int compareBySelectionRank(WeightedProfile a, WeightedProfile b) {
int weightOrder = Double.compare(b.averageWeight, a.averageWeight);
if (weightOrder != 0) {
return weightOrder;
}
return Integer.compare(a.sequence, b.sequence);
private static double between(double from, double to, double share) {
return from + ((to - from) * share);
}
private static int compareByCarveOrder(WeightedProfile a, WeightedProfile b) {
int weightOrder = Double.compare(a.averageWeight, b.averageWeight);
if (weightOrder != 0) {
return weightOrder;
private static boolean isAllTrue(boolean[] values) {
for (boolean value : values) {
if (!value) {
return false;
}
}
return Integer.compare(a.sequence, b.sequence);
return true;
}
private static double computeAverageWeight(double[] weights) {
return computeAverageWeight(weights, CHUNK_AREA);
private static double[] filled(double value) {
double[] values = new double[CHUNK_AREA];
Arrays.fill(values, value);
return values;
}
private static double computeAverageWeight(double[] weights, int areaSize) {
if (weights == null || weights.length == 0) {
return 0D;
}
double sum = 0D;
for (double weight : weights) {
sum += weight;
}
return sum / Math.max(1, areaSize);
/** The cave with this id, ready to carve; null when the pack has no such cave, which is reported once. */
private ListedCave caveOf(ResourceId id) {
return caves.computeIfAbsent(id, this::loadCave).orElse(null);
}
private static double clampWeight(double value) {
if (Double.isNaN(value) || Double.isInfinite(value)) {
return 0D;
private Optional<ListedCave> loadCave(ResourceId id) {
Cave cave = CaveResources.cave(resources, id);
if (cave == null) {
log.warnOnce("missing-cave:" + id, "Cave '" + id.path() + "' is listed under caves but the pack has no readable caves/" + id.path() + ".json");
return Optional.empty();
}
if (value <= 0D) {
return 0D;
}
if (value >= 1D) {
return 1D;
}
return value;
CarvedVoid carvedVoid = cave.biome().isBlank() ? CarvedVoid.OPEN : CarvedVoid.OPEN.withBiome(resources.idOf(cave.biome()));
long seed = world.carveSeed() + (31L * id.toString().hashCode());
return Optional.of(new ListedCave(new CaveCarver(cave, world.noise(), seed, world.minHeight(), world.height()), carvedVoid));
}
private static final class WeightedProfile {
private final CaveProfile profile;
private final double[] columnWeights;
private final double averageWeight;
private final Range worldYRange;
private final int sequence;
private WeightedProfile(CaveProfile profile, double[] columnWeights, double averageWeight, Range worldYRange, int sequence) {
this.profile = profile;
this.columnWeights = columnWeights;
this.averageWeight = averageWeight;
this.worldYRange = worldYRange;
this.sequence = sequence;
}
private double averageWeight() {
return averageWeight;
}
private record ListedCave(CaveCarver carver, CarvedVoid carvedVoid) {
}
private static final class BlendScratch {
private final CaveProfile[] profileField = new CaveProfile[FIELD_SIZE * FIELD_SIZE];
private final CaveProfile[] kernelProfiles = new CaveProfile[KERNEL_SIZE];
private final double[] kernelProfileWeights = new double[KERNEL_SIZE];
private final IdentityHashMap<CaveProfile, double[]> columnProfileWeights = new IdentityHashMap<>();
private final IdentityHashMap<ResolvedCarvingEntry, ResolvedCarvingEntry[]> dimensionColumnPlans = new IdentityHashMap<>();
private final IdentityHashMap<CaveProfile, Boolean> activeProfiles = new IdentityHashMap<>();
private final List<CaveProfile> profileOrder = new ArrayList<>();
private final double[] fieldSurfaceHeights = new double[FIELD_SIZE * FIELD_SIZE];
private final boolean[] fieldHasFluid = new boolean[FIELD_SIZE * FIELD_SIZE];
private final int[] chunkSurfaceHeights = new int[CHUNK_AREA];
private final int[] surfaceFluidBoundaryStartY = new int[CHUNK_AREA];
private record ListingKey(ResourceId region, ResourceId surfaceBiome, ResourceId caveBiome) {
}
private static final class Scratch {
private final int[] surfaceY = new int[CHUNK_AREA];
private final int[] waterStartY = new int[CHUNK_AREA];
private final boolean[] underWater = new boolean[CHUNK_AREA];
private final double[] fieldSurfaceY = new double[WATER_FIELD_SIZE * WATER_FIELD_SIZE];
private final boolean[] fieldHasFluid = new boolean[WATER_FIELD_SIZE * WATER_FIELD_SIZE];
private final double[] latticeWeight = new double[WEIGHTS_PER_AXIS * WEIGHTS_PER_AXIS];
private final boolean[] carvedAnything = new boolean[1];
}
}
@@ -1,58 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 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.carve.CaveFieldModule;
import com.volmit.config.Range;
import com.volmit.noise.NoiseSampler;
final class CaveFieldModuleState {
final NoiseSampler density;
final int minY;
final int maxY;
final double weight;
final double threshold;
final boolean invert;
final double minContribution;
final double maxContribution;
CaveFieldModuleState(CaveFieldModule module, NoiseSampler density) {
Range range = module.verticalRange();
this.density = density;
this.minY = (int) Math.floor(range.min());
this.maxY = (int) Math.ceil(range.max());
this.weight = module.weight();
this.threshold = module.threshold();
this.invert = module.invert();
double rawMin = invert ? threshold - 1D : -1D - threshold;
double rawMax = invert ? threshold + 1D : 1D - threshold;
this.minContribution = rawMin * weight;
this.maxContribution = rawMax * weight;
}
double sample(double x, int y, double z) {
double sampled = density.signed(x, y, z);
return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight;
}
double sample(double x, double y, double z) {
double sampled = density.signed(x, y, z);
return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight;
}
}
@@ -1,90 +0,0 @@
/*
* 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.volmlib.util.math.PowerOfTwoCoordinates;
import com.volmit.mantle.CarvedVoid;
import com.volmit.mantle.MantleLayer;
import java.util.BitSet;
/** The fluid voids a carver planned in one chunk, to be drained back to open voids where no solid cup holds them. */
final class CaveFluidSupportPlan {
private static final int MIN_SUPPORTED_NEIGHBOURS = 4;
private static final int CHUNK_WIDTH = 16;
private static final int COLUMN_BITS = 8;
private static final int COLUMN_MASK = (1 << COLUMN_BITS) - 1;
private final BitSet fluidPositions = new BitSet();
void add(int localX, int y, int localZ) {
int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ);
fluidPositions.set((y << COLUMN_BITS) | columnIndex);
}
/** Turns every planned fluid void of the chunk at block origin {@code originX}, {@code originZ} that is no longer fluid or has no cup under it into an open void. */
void resolve(MantleLayer<CarvedVoid> voids, int originX, int originZ, int worldHeight) {
for (int position = fluidPositions.nextSetBit(0); position >= 0; position = fluidPositions.nextSetBit(position + 1)) {
int y = position >>> COLUMN_BITS;
int columnIndex = position & COLUMN_MASK;
int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex);
int localZ = columnIndex & (CHUNK_WIDTH - 1);
int x = originX + localX;
int z = originZ + localZ;
if (voids.get(x, y, z) != CarvedVoid.FLUID || hasCupSupport(voids, originX, originZ, localX, y, localZ, worldHeight)) {
continue;
}
voids.set(x, y, z, CarvedVoid.OPEN);
}
fluidPositions.clear();
}
private static boolean hasCupSupport(MantleLayer<CarvedVoid> voids, int originX, int originZ, int localX, int y, int localZ, int worldHeight) {
if (localX <= 0 || localX >= CHUNK_WIDTH - 1 || localZ <= 0 || localZ >= CHUNK_WIDTH - 1
|| y <= 1 || !isSolid(voids, originX, originZ, localX, y - 1, localZ, worldHeight)
|| !isSolid(voids, originX, originZ, localX, y - 2, localZ, worldHeight)) {
return false;
}
int support = 0;
if (isSolid(voids, originX, originZ, localX + 1, y, localZ, worldHeight)) {
support++;
}
if (isSolid(voids, originX, originZ, localX - 1, y, localZ, worldHeight)) {
support++;
}
if (isSolid(voids, originX, originZ, localX, y, localZ + 1, worldHeight)) {
support++;
}
if (isSolid(voids, originX, originZ, localX, y, localZ - 1, worldHeight)) {
support++;
}
if (isSolid(voids, originX, originZ, localX, y + 1, localZ, worldHeight)) {
support++;
}
return support >= MIN_SUPPORTED_NEIGHBOURS;
}
private static boolean isSolid(MantleLayer<CarvedVoid> voids, int originX, int originZ, int localX, int y, int localZ, int worldHeight) {
if (localX < 0 || localX >= CHUNK_WIDTH || localZ < 0 || localZ >= CHUNK_WIDTH) {
return false;
}
return y >= worldHeight || voids.get(originX + localX, y, originZ + localZ) == null;
}
}
@@ -20,69 +20,31 @@ package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.anchor.PlaceTrait;
import art.arcane.iris.builtin.carve.CaveAnchorMode;
import art.arcane.iris.modules.carve.CaveProfile;
import art.arcane.iris.builtin.objects.ObjectPlacement;
/** What a cave object placement takes from the cave profile that applies to it. */
/** How a cave object placement looks for its anchor. A placement sets its own anchor mode; nothing sets one for all caves. */
final class CaveSettings {
private static final CaveProfile DEFAULT_PROFILE = new CaveProfile();
private static final int DEFAULT_SCAN_STEP = 1;
private static final int DEFAULT_MIN_DEPTH_BELOW_SURFACE = 6;
private static final int DEFAULT_SEARCH_ATTEMPTS = 6;
private static final int SCAN_STEP_BLOCKS = 1;
private static final int MIN_DEPTH_BELOW_SURFACE_BLOCKS = 6;
private static final int SEARCH_ATTEMPTS = 6;
private final CaveProfile dimensionProfile;
CaveSettings(CaveProfile dimensionProfile) {
this.dimensionProfile = dimensionProfile;
private CaveSettings() {
}
/** The profile of the first of {@code preferred} and {@code secondary} that is enabled, else the dimension's, else the default one. */
CaveProfile resolve(CaveProfile preferred, CaveProfile secondary) {
if (preferred != null && preferred.enabled()) {
return preferred;
}
if (secondary != null && secondary.enabled()) {
return secondary;
}
if (dimensionProfile != null) {
return dimensionProfile;
}
return DEFAULT_PROFILE;
}
/** How the placement looks for its anchor in caves: its own mode, else the profile's, else the floor; turned upside down, the ceiling. */
CaveAnchors.Search searchFor(ObjectPlacement placement, CaveProfile profile) {
CaveAnchorMode mode = anchorMode(placement, profile);
/** The placement's own anchor mode, else the floor; turned upside down, the ceiling. */
static CaveAnchors.Search searchFor(ObjectPlacement placement) {
CaveAnchorMode mode = anchorMode(placement);
if (placement.mode().placeMode().has(PlaceTrait.UPSIDE_DOWN)) {
mode = CaveAnchorMode.CEILING;
}
return new CaveAnchors.Search(mode, scanStep(profile), minDepthBelowSurface(profile), searchAttempts(profile));
return new CaveAnchors.Search(mode, SCAN_STEP_BLOCKS, MIN_DEPTH_BELOW_SURFACE_BLOCKS, SEARCH_ATTEMPTS);
}
private static CaveAnchorMode anchorMode(ObjectPlacement placement, CaveProfile profile) {
private static CaveAnchorMode anchorMode(ObjectPlacement placement) {
CaveAnchorMode placementMode = placement.caveAnchorMode();
if (placementMode != null && !placementMode.equals(CaveAnchorMode.PROFILE_DEFAULT)) {
return placementMode;
}
if (profile == null) {
if (placementMode == null || placementMode.equals(CaveAnchorMode.PROFILE_DEFAULT)) {
return CaveAnchorMode.FLOOR;
}
CaveAnchorMode profileMode = profile.defaultObjectAnchor();
if (profileMode == null || profileMode.equals(CaveAnchorMode.PROFILE_DEFAULT)) {
return CaveAnchorMode.FLOOR;
}
return profileMode;
}
private static int scanStep(CaveProfile profile) {
return profile == null ? DEFAULT_SCAN_STEP : Math.max(1, profile.anchorScanStep());
}
private static int minDepthBelowSurface(CaveProfile profile) {
return profile == null ? DEFAULT_MIN_DEPTH_BELOW_SURFACE : Math.max(0, profile.objectMinDepthBelowSurface());
}
private static int searchAttempts(CaveProfile profile) {
return profile == null ? DEFAULT_SEARCH_ATTEMPTS : Math.max(1, profile.anchorSearchAttempts());
return placementMode;
}
}
@@ -21,7 +21,6 @@ package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.anchor.ObjectPlaceMode;
import art.arcane.iris.builtin.carve.CarvingMode;
import art.arcane.iris.builtin.carve.CaveLavaHeightSettings;
import art.arcane.iris.modules.carve.CaveProfile;
import art.arcane.iris.builtin.objects.ObjectPlacement;
import art.arcane.iris.builtin.objects.ObjectSettings;
import art.arcane.iris.builtin.objects.RequireSurfaceSupportSettings;
@@ -86,7 +85,6 @@ final class ChunkObjectPlacing {
private final boolean traceRegen;
private final boolean golden;
private final EffectivePlacements effective;
private final CaveSettings caves;
private final int worldHeight;
private final int caveLavaHeight;
@@ -107,7 +105,6 @@ final class ChunkObjectPlacing {
this.worldHeight = context.mantle().bounds().maxY();
this.caveLavaHeight = Optional.ofNullable(dimensionLevel(CaveLavaHeightSettings.class)).orElseGet(CaveLavaHeightSettings::new).height();
this.effective = new EffectivePlacements(dimensionRequiresSurfaceSupport(), dimensionSurfaceSupportBuffer());
this.caves = new CaveSettings(dimensionLevel(CaveProfile.class));
}
/** Places what originates in this chunk. */
@@ -134,7 +131,7 @@ final class ChunkObjectPlacing {
ResourceId surface = terrain.surfaceBiome(centerX, centerZ);
int surfaceY = terrain.surfaceHeight(centerX, centerZ);
ResourceId cave = resolveCaveObjectBiome(surfaceY, surface);
return new Column(region, surface, cave, surfaceY, objectsOf(cave, region, surface), profilesOf(cave, region, surface));
return new Column(region, surface, cave, surfaceY, objectsOf(cave, region, surface));
}
private ResourceId resolveCaveObjectBiome(int surfaceY, ResourceId surfaceBiome) {
@@ -166,12 +163,6 @@ final class ChunkObjectPlacing {
levelValue(declared, Level.REGION));
}
private ColumnProfiles profilesOf(ResourceId cave, ResourceId region, ResourceId surface) {
SettingsStack<CaveProfile> declared = context.settings().at(CaveProfile.class, centerX, centerZ);
return new ColumnProfiles(levelValue(declared, Level.BIOME), caveSettings(cave, surface, declared, CaveProfile.class),
levelValue(declared, Level.REGION));
}
private <F extends IrisFeature> F caveSettings(ResourceId cave, ResourceId surface, SettingsStack<F> declared, Class<F> type) {
if (cave.equals(surface)) {
return levelValue(declared, Level.BIOME);
@@ -222,16 +213,14 @@ final class ChunkObjectPlacing {
private Tally placeObjects(Column column) {
Tally tally = new Tally();
CaveProfile biomeCaveProfile = caves.resolve(column.profiles().cave(), column.profiles().region());
CaveProfile regionCaveProfile = caves.resolve(column.profiles().region(), column.profiles().cave());
CaveAnchors anchors = newAnchors();
PlacementOwner surfaceBiome = PlacementOwner.biome(column.surface());
PlacementOwner region = PlacementOwner.region(column.region());
placeSurfaceScope(tally, "biome-surface", surfaceObjects(column.objects().surface()), surfaceBiome);
placeCaveScope(tally, "biome-cave", carvingObjects(column.objects().cave()), biomeCaveProfile, column.cave(),
placeCaveScope(tally, "biome-cave", carvingObjects(column.objects().cave()), column.cave(),
PlacementOwner.biome(column.cave()), anchors);
placeSurfaceScope(tally, "region-surface", surfaceObjects(column.objects().region()), region);
placeCaveScope(tally, "region-cave", carvingObjects(column.objects().region()), regionCaveProfile, null, region, anchors);
placeCaveScope(tally, "region-cave", carvingObjects(column.objects().region()), null, region, anchors);
return tally;
}
@@ -276,7 +265,7 @@ final class ChunkObjectPlacing {
placeOnSurfaceAt(tally, placement, scope, owner, picked.get(), candidate.x(), candidate.z(), candidate.rng(), 0, 1);
}
private void placeCaveScope(Tally tally, String scope, List<ObjectPlacement> placements, CaveProfile profile,
private void placeCaveScope(Tally tally, String scope, List<ObjectPlacement> placements,
ResourceId expectedCaveBiome, PlacementOwner owner, CaveAnchors anchors) {
for (ObjectPlacement placement : placements) {
tally.checked(scope);
@@ -287,7 +276,7 @@ final class ChunkObjectPlacing {
}
tally.triggered(scope);
try {
placeCaveObject(tally, placement, profile, scope, owner, expectedCaveBiome, anchors);
placeCaveObject(tally, placement, scope, owner, expectedCaveBiome, anchors);
} catch (Throwable failure) {
skipObjectPlacement("cave object", "in " + describe(owner), placement, failure);
tally.errors++;
@@ -347,12 +336,12 @@ final class ChunkObjectPlacing {
}
}
private void placeCaveObject(Tally tally, ObjectPlacement placement, CaveProfile profile, String scope, PlacementOwner owner,
private void placeCaveObject(Tally tally, ObjectPlacement placement, String scope, PlacementOwner owner,
ResourceId expectedCaveBiome, CaveAnchors anchors) {
int minX = context.originX();
int minZ = context.originZ();
int density = objects.density(placement, minX, minZ);
CaveAnchors.Search search = caves.searchFor(placement, profile);
CaveAnchors.Search search = CaveSettings.searchFor(placement);
for (int i = 0; i < density; i++) {
tally.attempts++;
Optional<PlaceableObject> picked = objects.pickScaled(placement, rng);
@@ -370,7 +359,7 @@ final class ChunkObjectPlacing {
continue;
}
int id = rng.i(0, Integer.MAX_VALUE);
PlacementChanges changes = effective.forCave(placement, object, profile);
PlacementChanges changes = effective.forSurface(placement, object);
try {
PlacementTags tags = tags(object, id, "cave", isTreePlacement(object, placement), placement, owner);
CavePlacement contained = chunk.placeInCave(object, anchor.x(), anchor.y(), anchor.z(), placement, changes,
@@ -557,16 +546,12 @@ final class ChunkObjectPlacing {
+ " objectNull=" + tally.nullObjects + " objectErrors=" + tally.errors);
}
private record Column(ResourceId region, ResourceId surface, ResourceId cave, int surfaceY, ColumnObjects objects,
ColumnProfiles profiles) {
private record Column(ResourceId region, ResourceId surface, ResourceId cave, int surfaceY, ColumnObjects objects) {
}
private record ColumnObjects(ObjectSettings surface, ObjectSettings cave, ObjectSettings region) {
}
private record ColumnProfiles(CaveProfile surface, CaveProfile cave, CaveProfile region) {
}
/** What placing the objects of a chunk came to. */
private static final class Tally {
private final java.util.Map<String, int[]> scopes = new java.util.LinkedHashMap<>();
@@ -20,7 +20,6 @@ package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.anchor.ObjectPlaceMode;
import art.arcane.iris.builtin.anchor.PlaceTrait;
import art.arcane.iris.modules.carve.CaveProfile;
import art.arcane.iris.builtin.objects.ObjectPlacement;
import art.arcane.iris.modules.objects.PlacementChanges;
import com.volmit.object.PlaceableObject;
@@ -45,22 +44,6 @@ final class EffectivePlacements {
return withDimensionSurfaceSupport(placement, withImportedMode(placement, object, PlacementChanges.NONE));
}
/** The changes to make to {@code placement} to place {@code object} in a cave with the cave profile {@code caveProfile}. */
PlacementChanges forCave(ObjectPlacement placement, PlaceableObject object, CaveProfile caveProfile) {
PlacementChanges changes = forSurface(placement, object);
ObjectPlaceMode mode = changes.mode() != null ? changes.mode() : placement.mode();
if (mode != ObjectPlaceMode.CENTER_HEIGHT || caveProfile == null) {
return changes;
}
ObjectPlaceMode profileMode = caveProfile.defaultObjectPlaceMode().orElse(null);
if (profileMode == null) {
return changes;
}
String key = object.name();
List<String> place = key == null || key.isBlank() ? List.of() : List.of(key);
return changes.withPlace(place).withMode(profileMode);
}
/** Imported objects are placed with the fast minimal stilt unless their mode finds its own height. */
private static PlacementChanges withImportedMode(ObjectPlacement placement, PlaceableObject object, PlacementChanges changes) {
String key = object.name();
@@ -25,7 +25,8 @@ import art.arcane.iris.modules.carve.CarvingEnabledSettings;
import art.arcane.iris.modules.carve.CarvingSettings;
import art.arcane.iris.modules.carve.CaveDepthSettings;
import art.arcane.iris.builtin.carve.CaveLavaHeightSettings;
import art.arcane.iris.modules.carve.CaveProfile;
import art.arcane.iris.modules.carve.CaveList;
import art.arcane.iris.modules.carve.CaveResources;
import art.arcane.iris.modules.carve.UpperDimensionCarvingSettings;
import art.arcane.iris.modules.terrain.TerrainPalettes;
import art.arcane.iris.engine.mantle.components.CarveWorld;
@@ -34,6 +35,7 @@ import art.arcane.iris.engine.mantle.components.CaveFloorMarking;
import com.volmit.IrisFeature;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.ModuleLog;
import com.volmit.ModuleSetup;
import com.volmit.generation.ChunkContext;
import com.volmit.hunk.Hunk;
@@ -53,16 +55,17 @@ import java.util.Optional;
import java.util.function.Function;
/**
* Module {@code iris:carve}: caves. A mantle stage plans them into the mantle, reaching one block into each
* neighboring chunk where blended cave walls cross the border; a chunk stage later cuts them out of the chunk's
* terrain. The mantle stage is a port of what was Iris's carving mantle component, its work done by
* {@link CaveCarving}, one per world. The chunk stage's work is done by {@link CaveApplying}.
* Module {@code iris:carve}: caves. A mantle stage plans the caves a pack lists under {@code caves} into the mantle;
* a chunk stage later cuts them out of the chunk's terrain. The mantle stage's work is done by {@link CaveCarving},
* one per world, and the chunk stage's by {@link CaveApplying}.
*/
public final class CarveModule implements IrisModule {
private static final String VERSION = "1.0.0";
/** Blended cave walls reach one block past the chunk. */
/** The chunk stage reads the caves one block past the chunk to wall the ones that cross its border. */
private static final int CAVE_REACH_BLOCKS = 1;
private ModuleLog log;
@Override
public ModuleInfo info() {
return ModuleInfo.of("iris:carve", "Caves", VERSION);
@@ -70,18 +73,20 @@ public final class CarveModule implements IrisModule {
@Override
public void setup(ModuleSetup setup) {
log = setup.log();
var registry = setup.registry();
List.of(CaveProfile.class, CarvingSettings.class, CarvingEnabledSettings.class, CarvingBiomeSettings.class,
registry.registerResourceKind(CaveResources.CAVES);
List.of(CaveList.class, CarvingSettings.class, CarvingEnabledSettings.class, CarvingBiomeSettings.class,
CaveDepthSettings.class, CaveLavaHeightSettings.class, UpperDimensionCarvingSettings.class)
.forEach(registry::registerSettings);
registry.registerService(CaveBiomes.class, new CaveBiomeBands());
var graph = setup.stages();
graph.define(IrisStages.Carve.CAVES).reach(CAVE_REACH_BLOCKS).run(CarveModule::planCaves);
graph.define(IrisStages.Carve.CAVES).reach(CAVE_REACH_BLOCKS).run(this::planCaves);
graph.define(IrisStages.Carve.APPLY).requires(IrisStages.Terrain.SHAPE).run(CarveModule::applyCaves);
}
private static void planCaves(MantleStageContext context) {
private void planCaves(MantleStageContext context) {
if (!carves(context)) {
return;
}
@@ -100,9 +105,9 @@ public final class CarveModule implements IrisModule {
upperDimensionCarving(context)));
}
private static CaveCarving caveCarving(ChunkContext context) {
private CaveCarving caveCarving(ChunkContext context) {
return context.world().state(CaveCarving.class, generating -> new CaveCarving(generating, carveWorld(generating, context.terrain()),
upperDimensionCarving(context), fluidColumns(generating)));
fluidColumns(generating), log));
}
private static CaveApplying caveApplying(ChunkContext context) {
@@ -1,178 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 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.object.terrain.carving;
import art.arcane.iris.builtin.carve.CaveFieldModule;
import art.arcane.iris.modules.carve.CaveProfile;
import art.arcane.volmlib.util.math.M;
import com.volmit.config.Range;
import com.volmit.noise.NoiseFactory;
import com.volmit.noise.NoiseSampler;
import com.volmit.noise.NoiseStyle;
import com.volmit.noise.StyledRange;
import java.util.ArrayList;
import java.util.List;
public final class CaveProfileSampler {
private static final double FLOATING_THRESHOLD_BIAS_SCALE = 0.2D;
private final CaveProfile profile;
private final NoiseSampler baseDensity;
private final NoiseSampler detailDensity;
private final NoiseSampler warpDensity;
private final NoiseSampler thresholdNoise;
private final ModuleState[] modules;
private final double inverseNormalization;
private final double baseWeight;
private final double detailWeight;
private final double warpStrength;
private final boolean enabled;
private final boolean hasWarp;
private final boolean hasModules;
public CaveProfileSampler(NoiseFactory noise, long carveSeed, CaveProfile profile) {
this.profile = profile;
List<ModuleState> moduleStates = new ArrayList<>();
this.baseDensity = noise.sampler(profile.baseDensityStyle(), carveSeed + 934_447);
this.detailDensity = noise.sampler(profile.detailDensityStyle(), carveSeed + 612_991);
this.warpDensity = noise.sampler(profile.warpStyle(), carveSeed + 770_713);
this.thresholdNoise = noise.sampler(profile.densityThreshold().style(), carveSeed + 489_112);
this.baseWeight = profile.baseWeight();
this.detailWeight = profile.detailWeight();
this.warpStrength = profile.warpStrength();
this.hasWarp = warpStrength > 0D;
double weight = Math.abs(baseWeight) + Math.abs(detailWeight);
int index = 0;
for (CaveFieldModule module : profile.modules()) {
NoiseSampler moduleDensity = noise.sampler(module.style(), carveSeed + 1_000_003L + (index * 65_537L));
ModuleState state = new ModuleState(module, moduleDensity);
moduleStates.add(state);
weight += Math.abs(state.weight);
index++;
}
this.modules = moduleStates.toArray(new ModuleState[0]);
double normalization = weight <= 0 ? 1D : weight;
this.inverseNormalization = 1D / normalization;
this.hasModules = modules.length > 0;
this.enabled = profile.enabled();
}
public boolean shouldCarve(int x, int y, int z, double floatingCarveThreshold) {
if (!enabled) {
return false;
}
double threshold = thresholdAt(x, z) - profile.thresholdBias();
threshold += floatingThresholdBias(floatingCarveThreshold);
return sampleDensity(x, y, z) <= threshold;
}
/** The profile's density threshold at the column, as a styled range picks its value. */
private double thresholdAt(int x, int z) {
StyledRange range = profile.densityThreshold();
if (range.min() == range.max()) {
return range.min();
}
if (NoiseStyle.FLAT.equals(range.style().style())) {
return M.lerp(range.min(), range.max(), 0.5);
}
return range.min() + (thresholdNoise.sample(x, z) * (range.max() - range.min()));
}
double sampleDensity(int x, int y, int z) {
if (hasWarp) {
return sampleDensityWarped(x, y, z);
}
return sampleDensityUnwarped(x, y, z);
}
private double sampleDensityUnwarped(int x, int y, int z) {
double density = baseDensity.signed(x, y, z) * baseWeight;
density += detailDensity.signed(x, y, z) * detailWeight;
if (hasModules) {
for (ModuleState module : modules) {
if (!module.isActive(y)) {
continue;
}
density += module.sample(x, y, z);
}
}
return density * inverseNormalization;
}
private double sampleDensityWarped(int x, int y, int z) {
double warpA = warpDensity.signed(x, y, z);
double warpB = warpDensity.signed(x + 31.37D, y - 17.21D, z + 23.91D);
double warpedX = x + (warpA * warpStrength);
double warpedY = y + (warpB * warpStrength);
double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength);
double density = baseDensity.signed(warpedX, warpedY, warpedZ) * baseWeight;
density += detailDensity.signed(warpedX, warpedY, warpedZ) * detailWeight;
if (hasModules) {
for (ModuleState module : modules) {
if (!module.isActive(y)) {
continue;
}
density += module.sample(warpedX, warpedY, warpedZ);
}
}
return density * inverseNormalization;
}
private double floatingThresholdBias(double floatingCarveThreshold) {
double clamped = Math.max(0D, Math.min(1D, floatingCarveThreshold));
return (1D - clamped) * FLOATING_THRESHOLD_BIAS_SCALE;
}
private static final class ModuleState {
private final NoiseSampler density;
private final int minY;
private final int maxY;
private final double weight;
private final double threshold;
private final boolean invert;
private ModuleState(CaveFieldModule module, NoiseSampler density) {
Range range = module.verticalRange();
this.density = density;
this.minY = (int) Math.floor(range.min());
this.maxY = (int) Math.ceil(range.max());
this.weight = module.weight();
this.threshold = module.threshold();
this.invert = module.invert();
}
private boolean isActive(int y) {
return density != null && y >= minY && y <= maxY;
}
private double sample(double x, double y, double z) {
double sampled = density.signed(x, y, z);
return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight;
}
}
}
@@ -65,6 +65,11 @@ public final class DeclaredByLevel<F extends IrisFeature> {
return dimension;
}
/** Whether no region and no biome declares anything, so the dimension's declaration holds for every column. */
public boolean onlyDimensionDeclares() {
return regions.isEmpty() && biomes.isEmpty();
}
/** The declaration of the region with this id; null when it declares none. */
public F ofRegion(ResourceId region) {
return regions.get(region);
@@ -1,52 +0,0 @@
/*
* 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.object.terrain.carving;
import art.arcane.iris.modules.carve.CaveProfile;
import com.volmit.resource.ResourceId;
import com.volmit.world.PackWorld;
/**
* What the carve module keeps for one world: the cave profiles its dimension, regions and biomes declare ({@code caveProfile}).
* A profile that is not declared is as good as one that is not enabled, so the lookups answer null for it.
*/
public final class DeclaredCaveProfiles {
private final DeclaredByLevel<CaveProfile> declared;
private DeclaredCaveProfiles(PackWorld world) {
this.declared = DeclaredByLevel.of(world, CaveProfile.class);
}
/** The profiles of the world {@code world}. */
public static DeclaredCaveProfiles of(PackWorld world) {
return world.state(DeclaredCaveProfiles.class, DeclaredCaveProfiles::new);
}
public CaveProfile ofDimension() {
return declared.ofDimension();
}
public CaveProfile ofRegion(ResourceId region) {
return declared.ofRegion(region);
}
public CaveProfile ofBiome(ResourceId biome) {
return declared.ofBiome(biome);
}
}
@@ -19,7 +19,6 @@
package art.arcane.iris.engine.object.terrain.floating;
import art.arcane.iris.modules.floating.FloatingChildBiome;
import art.arcane.iris.engine.object.terrain.carving.CaveProfileSampler;
import art.arcane.volmlib.util.collection.KList;
import com.volmit.ModuleLog;
import com.volmit.noise.NoiseSampler;
@@ -411,13 +410,11 @@ public final class FloatingIslandSample {
NoiseSampler wallWarp = entry.wallWarpNoise();
double warpAmp = Math.max(0, entry.settings().wallWarpAmplitude());
double effectiveWarpAmp = effectiveWallWarpAmplitude(warpAmp, edgeFade);
CaveProfileSampler carvingProfileSampler = entry.carvingProfileSampler();
NoiseSampler carve = carvingProfileSampler == null && !entry.hasCarvingReference() ? entry.carveNoise() : null;
NoiseSampler carve = entry.carveNoise();
double carveThreshold = entry.settings().carveThreshold();
boolean useWarp = wallWarp != null && effectiveWarpAmp > 0;
boolean useProfileCarve = carvingProfileSampler != null;
boolean useCarve = directCarveEnabled(entry, carvingProfileSampler, carve, carveThreshold);
boolean[] lateralCarveMask = useProfileCarve || useCarve ? new boolean[thickness] : null;
boolean useCarve = directCarveEnabled(carve, carveThreshold);
boolean[] lateralCarveMask = useCarve ? new boolean[thickness] : null;
boolean baseCarveInterior = lateralCarveMask != null && canCarveLaterally(edgeFade, footprintSupport);
if (useWarp) {
@@ -444,9 +441,7 @@ public final class FloatingIslandSample {
}
int solidCount = solidifyUncarvedInterior(solidMask);
if (useProfileCarve) {
solidCount = carveSolidInterior(solidMask, lateralCarveMask, botY, wx, wz, carvingProfileSampler, carveThreshold);
} else if (useCarve) {
if (useCarve) {
solidCount = carveSolidInterior(solidMask, lateralCarveMask, botY, wx, wz, carve, carveThreshold);
}
int highestSolidIdx = highestSolidIndex(solidMask);
@@ -480,8 +475,8 @@ public final class FloatingIslandSample {
return amplitude * fade;
}
static boolean directCarveEnabled(ResolvedFloatingChild entry, CaveProfileSampler carvingProfileSampler, NoiseSampler carve, double carveThreshold) {
return carvingProfileSampler == null && (entry == null || !entry.hasCarvingReference()) && carve != null && carveThreshold < 1.0;
static boolean directCarveEnabled(NoiseSampler carve, double carveThreshold) {
return carve != null && carveThreshold < 1.0;
}
static boolean canCarveLaterally(double edgeFade, NeighborSupport support) {
@@ -496,10 +491,6 @@ public final class FloatingIslandSample {
});
}
static int carveSolidInterior(boolean[] solidMask, boolean[] lateralCarveMask, int botY, int wx, int wz, CaveProfileSampler carve, double carveThreshold) {
return carveSolidInterior(solidMask, lateralCarveMask, botY, wx, wz, (x, y, z) -> carve.shouldCarve(x, y, z, carveThreshold));
}
private static int carveSolidInterior(boolean[] solidMask, boolean[] lateralCarveMask, int botY, int wx, int wz, CarveSampler carve) {
int firstSolid = -1;
int lastSolid = -1;
@@ -21,7 +21,6 @@ package art.arcane.iris.engine.object.terrain.floating;
import art.arcane.iris.builtin.IrisSeedPurposes;
import art.arcane.iris.modules.carve.CarvingEntry;
import art.arcane.iris.modules.carve.CarvingSettings;
import art.arcane.iris.modules.carve.CaveProfile;
import art.arcane.iris.modules.floating.FloatingChildBiome;
import art.arcane.iris.modules.floating.FloatingChildSettings;
import art.arcane.iris.modules.floating.MergeFloatingChildrenSettings;
@@ -155,8 +154,4 @@ public final class FloatingWorld {
return Optional.ofNullable(found);
}
/** The cave profile {@code biome} declares; null when it declares none. */
CaveProfile caveProfile(ResourceId biome) {
return running.settings().declaredBy(biome, CaveProfile.class).orElse(null);
}
}
@@ -19,10 +19,8 @@
package art.arcane.iris.engine.object.terrain.floating;
import art.arcane.iris.modules.carve.CarvingEntry;
import art.arcane.iris.modules.carve.CaveProfile;
import art.arcane.iris.modules.floating.FloatingChildBiome;
import art.arcane.iris.builtin.objects.ObjectPlacement;
import art.arcane.iris.engine.object.terrain.carving.CaveProfileSampler;
import art.arcane.volmlib.util.cache.AtomicCache;
import art.arcane.volmlib.util.collection.KList;
import com.volmit.noise.NoiseSampler;
@@ -34,7 +32,7 @@ import java.util.Optional;
/**
* A {@link FloatingChildBiome} made ready for one world: the noise its styles build (each from the world's floating seed),
* the edge taper profile, the biome it targets, the carving profile sampler and the objects it hosts. One per decoded entry
* the edge taper profile, the biome it targets and the objects it hosts. One per decoded entry
* ({@link FloatingWorld#resolve}).
*/
public final class ResolvedFloatingChild {
@@ -59,7 +57,6 @@ public final class ResolvedFloatingChild {
private final AtomicCache<NoiseSampler> bottomCache = new AtomicCache<>();
private final AtomicCache<NoiseSampler> wallWarpCache = new AtomicCache<>();
private final AtomicCache<NoiseSampler> carveCache = new AtomicCache<>();
private final AtomicCache<CaveProfileSampler> carvingProfileSamplerCache = new AtomicCache<>(true);
ResolvedFloatingChild(FloatingChildBiome settings, FloatingWorld world) {
this.settings = settings;
@@ -117,26 +114,7 @@ public final class ResolvedFloatingChild {
return world.noise().sampler(style, world.baseSeed() ^ salt);
}
public CaveProfileSampler carvingProfileSampler() {
if (!hasCarvingReference()) {
return null;
}
return carvingProfileSamplerCache.aquire(() -> {
CaveProfile profile = carvingBiome().map(world::caveProfile).orElse(null);
if (profile == null || !profile.enabled()) {
return null;
}
return new CaveProfileSampler(world.noise(), world.carveSeed(), profile);
});
}
public boolean hasCarvingReference() {
return !settings.carving().isBlank();
}
/** The biome whose cave profile carves the island: the biome of the dimension's carving entry the id names, or the biome the id names. */
/** The carving biome the island names: the biome of the dimension's carving entry the id names, or the biome the id names. */
Optional<ResourceId> carvingBiome() {
String carving = settings.carving();
Optional<CarvingEntry> entry = world.dimensionCarving(carving);
@@ -0,0 +1,92 @@
/*
* 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.modules.carve;
import com.volmit.config.Desc;
import com.volmit.config.MaxNumber;
import com.volmit.config.MinNumber;
import com.volmit.config.Range;
import com.volmit.config.ResourceRef;
import com.volmit.world.PackBiome;
import java.util.Optional;
/**
* One kind of cave, a file of a pack's {@code caves/} folder that dimensions, regions and biomes list under {@code caves}.
* It carves tunnels, caverns or both, within a depth range and under the surface rules it sets.
*/
@Desc("One kind of cave: tunnels, caverns or both, with where they may occur.")
public final class Cave {
@Desc("Winding tunnels. Leave out for a cave without tunnels.")
private CaveTunnel tunnel;
@Desc("Large open rooms. Leave out for a cave without caverns.")
private CaveCavern cavern;
@Desc("World Y range this cave occurs in. Leave out to allow every height.")
private Range depth;
@MinNumber(0)
@MaxNumber(128)
@Desc("Blocks over which the cave narrows to nothing at both ends of its depth range.")
private int fade = 12;
@MinNumber(0)
@MaxNumber(128)
@Desc("Blocks of rock kept between the cave and the surface. Ignored when opensToSurface is set.")
private int surfaceClearance = 8;
@Desc("Let the cave cut through the surface, which makes entrances wherever it reaches the top.")
private boolean opensToSurface = false;
@ResourceRef(PackBiome.class)
@Desc("Cave biome that paints this cave's walls. Leave out to use the cave biome of the place.")
private String biome = "";
public Cave() {
}
public Optional<CaveTunnel> tunnel() {
return Optional.ofNullable(tunnel);
}
public Optional<CaveCavern> cavern() {
return Optional.ofNullable(cavern);
}
public Optional<Range> depth() {
return Optional.ofNullable(depth);
}
public int fade() {
return fade;
}
public int surfaceClearance() {
return surfaceClearance;
}
public boolean opensToSurface() {
return opensToSurface;
}
public String biome() {
return biome == null ? "" : biome;
}
}
@@ -0,0 +1,66 @@
/*
* 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.modules.carve;
import com.volmit.config.Desc;
import com.volmit.config.MaxNumber;
import com.volmit.config.MinNumber;
import java.util.Optional;
/** The caverns of a {@link Cave}: large open rooms, with pillars left standing in them where the cave asks for some. */
@Desc("Large open rooms.")
public final class CaveCavern {
@MinNumber(16)
@MaxNumber(512)
@Desc("Rough span of a room in blocks.")
private int size = 56;
@MinNumber(8)
@MaxNumber(256)
@Desc("Rough height of a room in blocks.")
private int height = 22;
@MinNumber(0)
@MaxNumber(0.6)
@Desc("Share of the underground that is cavern. 0.1 gives scattered rooms, 0.3 joins them into halls.")
private double coverage = 0.1;
@Desc("Rock columns left standing inside the rooms. Leave out for open rooms.")
private CavePillars pillars;
public CaveCavern() {
}
public int size() {
return size;
}
public int height() {
return height;
}
public double coverage() {
return coverage;
}
public Optional<CavePillars> pillars() {
return Optional.ofNullable(pillars);
}
}
@@ -0,0 +1,69 @@
/*
* 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.modules.carve;
import com.volmit.IrisFeature;
import com.volmit.config.Desc;
import com.volmit.config.Feature;
import com.volmit.config.Level;
import com.volmit.config.PackSettings;
import com.volmit.config.ResourceRef;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.world.LinkedBiomes;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* The caves a dimension, region or biome lists under {@code caves}, by their keys in the pack's {@code caves/} folder.
* The lists of a column's dimension, region and biomes add up: every cave any of them lists carves there.
*/
@Desc("Caves that carve here, by their file in the pack's caves folder. Dimension, region and biome lists add up.")
@Feature(id = "iris:carve/cave-list", name = "Caves", key = "caves", root = "caves", targets = {Level.DIMENSION, Level.REGION, Level.BIOME})
public final class CaveList implements IrisFeature, LinkedBiomes {
@ResourceRef(Cave.class)
@Desc("Caves that carve here, by their file in the pack's caves folder. Dimension, region and biome lists add up.")
private List<String> caves = List.of();
public CaveList() {
}
public CaveList(List<String> caves) {
this.caves = List.copyOf(caves);
}
public List<String> caves() {
return caves == null ? List.of() : Collections.unmodifiableList(caves);
}
@Override
public Set<ResourceId> usedBiomes(PackResources pack, PackSettings dimension) {
Set<ResourceId> biomes = new LinkedHashSet<>();
for (String key : caves()) {
Cave cave = CaveResources.cave(pack, key);
if (cave != null && !cave.biome().isBlank()) {
biomes.add(pack.idOf(cave.biome()));
}
}
return biomes;
}
}
@@ -0,0 +1,48 @@
/*
* 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.modules.carve;
import com.volmit.config.Desc;
import com.volmit.config.MaxNumber;
import com.volmit.config.MinNumber;
/** The pillars of a {@link CaveCavern}: columns of rock left standing from floor to ceiling. */
@Desc("Rock columns left standing inside caverns.")
public final class CavePillars {
@MinNumber(6)
@MaxNumber(256)
@Desc("Rough distance between pillars in blocks.")
private int spacing = 22;
@MinNumber(1)
@MaxNumber(64)
@Desc("Rough thickness of a pillar at its middle, in blocks. Pillars widen towards floor and ceiling.")
private int thickness = 4;
public CavePillars() {
}
public int spacing() {
return spacing;
}
public int thickness() {
return thickness;
}
}
@@ -1,308 +0,0 @@
/*
* 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.modules.carve;
import art.arcane.iris.builtin.anchor.ObjectPlaceMode;
import art.arcane.iris.builtin.carve.CaveAnchorMode;
import art.arcane.iris.builtin.carve.CaveFieldModule;
import com.volmit.config.Level;
import com.volmit.IrisFeature;
import com.volmit.config.Desc;
import com.volmit.config.Feature;
import com.volmit.config.MaxNumber;
import com.volmit.config.MinNumber;
import com.volmit.config.Range;
import com.volmit.config.Snippet;
import com.volmit.noise.NoiseStyle;
import com.volmit.noise.StyledRange;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
/**
* A 3D cave profile as packs write it for a dimension, region or biome ({@code caveProfile}) or under
* {@code snippet/iris/carve/cave-profile/}: the noise fields that decide where caves are, how they meet the surface, where
* cave fluid may sit and how objects find anchors in them. A level that writes none has no profile, which is the
* same as one that is not {@code enabled}. IrisApi types only; the carving module builds the noise.
*/
@Snippet("iris/carve/cave-profile")
@Desc("Represents a configurable 3D cave profile.")
@Feature(id = "iris:carve/profile", name = "Cave profile", key = "caveProfile", targets = {Level.DIMENSION, Level.REGION, Level.BIOME})
public final class CaveProfile implements IrisFeature {
@Desc("Enable profile-driven cave carving.")
private boolean enabled = false;
@Desc("Global vertical bounds for profile cave carving, in engine-local Y where 0 is the bottom of the dimension, not world Y.")
private Range verticalRange = Range.of(0, 384);
@MinNumber(0)
@MaxNumber(128)
@Desc("Vertical fade range applied near cave profile min/max bounds to avoid abrupt hard-stop ceilings/floors.")
private int verticalEdgeFade = 20;
@MinNumber(0)
@MaxNumber(1)
@Desc("Strength of the vertical edge fade at cave profile min/max bounds.")
private double verticalEdgeFadeStrength = 0.18;
@Desc("Base density style for cave field generation.")
private NoiseStyle baseDensityStyle = NoiseStyle.of("CELLULAR_IRIS_DOUBLE");
@Desc("Detail density style blended into base caves.")
private NoiseStyle detailDensityStyle = NoiseStyle.of("SIMPLEX");
@Desc("Warp style used to distort cave coordinates.")
private NoiseStyle warpStyle = NoiseStyle.of("FLAT");
@MinNumber(0)
@Desc("Base cave field multiplier.")
private double baseWeight = 1;
@MinNumber(0)
@Desc("Detail cave field multiplier.")
private double detailWeight = 0.35;
@MinNumber(0)
@Desc("Coordinate warp strength for cave fields.")
private double warpStrength = 0;
@Desc("Threshold range used for carve cutoff decisions.")
private StyledRange densityThreshold = StyledRange.of(-0.2, 0.2, NoiseStyle.of("CELLULAR_IRIS_DOUBLE"));
@MinNumber(0)
@MaxNumber(1)
@Desc("Extra threshold bias subtracted from sampled threshold before carve tests.")
private double thresholdBias = 0.16;
@MinNumber(1)
@MaxNumber(8)
@Desc("Vertical sample step used while evaluating cave density.")
private int sampleStep = 1;
@Desc("Use adaptive cave density prediction so only threshold-adjacent cells fall back to full-resolution evaluation.")
private boolean adaptiveSampling = true;
@MinNumber(2)
@MaxNumber(4)
@Desc("Horizontal adaptive predictor tuning. The carver always samples the predictor grid at a fixed step of 8; values below 8 only widen the ambiguity margin slightly and do not tighten the grid.")
private int adaptiveSampleStep = 2;
@MinNumber(0)
@MaxNumber(1)
@Desc("Additional adaptive ambiguity margin used before the cave predictor falls back to exact sampling.")
private double adaptiveThresholdMargin = 0.04;
@MinNumber(0)
@MaxNumber(64)
@Desc("Minimum solid clearance below terrain surface where carving may occur.")
private int surfaceClearance = 4;
@Desc("Allow profile-driven cave carving to break through terrain surface in selected columns.")
private boolean allowSurfaceBreak = true;
@Desc("Noise style used to decide where surface-breaking cave columns are allowed.")
private NoiseStyle surfaceBreakStyle = NoiseStyle.of("SIMPLEX").withZoom(0.08);
@MinNumber(-1)
@MaxNumber(1)
@Desc("Minimum signed surface-break noise value required before near-surface carving is allowed.")
private double surfaceBreakNoiseThreshold = 0.62;
@MinNumber(0)
@MaxNumber(64)
@Desc("Near-surface depth window used for surface-break carve logic.")
private int surfaceBreakDepth = 18;
@MinNumber(0)
@MaxNumber(1)
@Desc("Additional threshold boost applied while carving in the surface-break depth window.")
private double surfaceBreakThresholdBoost = 0.2;
@MinNumber(0)
@MaxNumber(64)
@Desc("Minimum depth below terrain surface required for cave-only object anchor placement.")
private int objectMinDepthBelowSurface = 6;
@Desc("Additional layered cave-density modules.")
private List<CaveFieldModule> modules = List.of();
@Desc("Default cave anchor mode for cave-only object placement.")
private CaveAnchorMode defaultObjectAnchor = CaveAnchorMode.FLOOR;
@Desc("Default placement mode for cave objects. Only applies to placements that are still on the default CENTER_HEIGHT mode; an explicit mode on the placement always wins. Stilt modes tile the object base block down to the cave floor surface. FAST_MIN_STILT is recommended for cave objects to prevent floating.")
private ObjectPlaceMode defaultObjectPlaceMode;
@MinNumber(1)
@MaxNumber(8)
@Desc("Vertical scan step used while searching cave anchors.")
private int anchorScanStep = 1;
@MinNumber(1)
@MaxNumber(64)
@Desc("Maximum random column retries while searching a valid cave object anchor in the chunk.")
private int anchorSearchAttempts = 6;
@Desc("Allow cave fluid placement from the dimension fluid palette below fluid level.")
private boolean allowFluid = true;
@MinNumber(0)
@MaxNumber(64)
@Desc("Minimum depth below terrain surface required before cave fluid may be placed.")
private int fluidMinDepthBelowSurface = 12;
@Desc("Require solid floor support below cave fluid to reduce unsupported fluid flows.")
private boolean fluidRequiresFloor = true;
@Desc("Allow cave lava placement based on lava height.")
private boolean allowLava = true;
public CaveProfile() {
}
public boolean enabled() {
return enabled;
}
public Range verticalRange() {
return verticalRange;
}
public int verticalEdgeFade() {
return verticalEdgeFade;
}
public double verticalEdgeFadeStrength() {
return verticalEdgeFadeStrength;
}
public NoiseStyle baseDensityStyle() {
return baseDensityStyle;
}
public NoiseStyle detailDensityStyle() {
return detailDensityStyle;
}
public NoiseStyle warpStyle() {
return warpStyle;
}
public double baseWeight() {
return baseWeight;
}
public double detailWeight() {
return detailWeight;
}
public double warpStrength() {
return warpStrength;
}
public StyledRange densityThreshold() {
return densityThreshold;
}
public double thresholdBias() {
return thresholdBias;
}
public int sampleStep() {
return sampleStep;
}
public boolean adaptiveSampling() {
return adaptiveSampling;
}
public int adaptiveSampleStep() {
return adaptiveSampleStep;
}
public double adaptiveThresholdMargin() {
return adaptiveThresholdMargin;
}
public int surfaceClearance() {
return surfaceClearance;
}
public boolean allowSurfaceBreak() {
return allowSurfaceBreak;
}
public NoiseStyle surfaceBreakStyle() {
return surfaceBreakStyle;
}
public double surfaceBreakNoiseThreshold() {
return surfaceBreakNoiseThreshold;
}
public int surfaceBreakDepth() {
return surfaceBreakDepth;
}
public double surfaceBreakThresholdBoost() {
return surfaceBreakThresholdBoost;
}
public int objectMinDepthBelowSurface() {
return objectMinDepthBelowSurface;
}
public List<CaveFieldModule> modules() {
return modules == null ? List.of() : Collections.unmodifiableList(modules);
}
public CaveAnchorMode defaultObjectAnchor() {
return defaultObjectAnchor == null ? CaveAnchorMode.FLOOR : defaultObjectAnchor;
}
/** The mode cave objects take where their placement has none of its own; empty when the profile sets none. */
public Optional<ObjectPlaceMode> defaultObjectPlaceMode() {
return Optional.ofNullable(defaultObjectPlaceMode);
}
public int anchorScanStep() {
return anchorScanStep;
}
public int anchorSearchAttempts() {
return anchorSearchAttempts;
}
public boolean allowFluid() {
return allowFluid;
}
public int fluidMinDepthBelowSurface() {
return fluidMinDepthBelowSurface;
}
public boolean fluidRequiresFloor() {
return fluidRequiresFloor;
}
public boolean allowLava() {
return allowLava;
}
}
@@ -0,0 +1,49 @@
/*
* 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.modules.carve;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKind;
/** The resource kind of module {@code iris:carve}: the caves of a pack's {@code caves/} folder. */
public final class CaveResources {
/** Caves, in {@code caves/}. */
public static final ResourceKind<Cave> CAVES = ResourceKind.of("iris:carve/cave", "caves", Cave.class);
private CaveResources() {
}
/** The cave with this pack key; null for a blank key, a key the pack has no file for and a file that fails to load. */
public static Cave cave(PackResources resources, String key) {
if (key == null || key.isBlank()) {
return null;
}
return cave(resources, resources.idOf(key));
}
/** The cave with this id; null when the pack has no file for it or the file fails to load. */
public static Cave cave(PackResources resources, ResourceId id) {
try {
return resources.find(CAVES, id).orElse(null);
} catch (IllegalStateException failedToLoad) {
return null;
}
}
}
@@ -0,0 +1,65 @@
/*
* 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.modules.carve;
import com.volmit.config.Desc;
import com.volmit.config.MaxNumber;
import com.volmit.config.MinNumber;
import com.volmit.config.Range;
/** The tunnels of a {@link Cave}: long winding passages. Thin ones link other caves together. */
@Desc("Long winding passages.")
public final class CaveTunnel {
@Desc("Tunnel width in blocks. A tunnel varies between the two along its length.")
private Range width = Range.of(4, 7);
@MinNumber(16)
@MaxNumber(512)
@Desc("Roughly how many blocks a tunnel runs between turns and junctions. Larger gives longer, straighter and sparser tunnels.")
private int stretch = 96;
@MinNumber(1)
@MaxNumber(4)
@Desc("How level tunnels run. 1 lets them go in any direction, higher keeps them closer to horizontal.")
private double flatness = 1.4;
@MinNumber(0)
@MaxNumber(1)
@Desc("Share of the underground that has tunnels at all. 1 puts them everywhere, lower leaves areas without any.")
private double coverage = 1;
public CaveTunnel() {
}
public Range width() {
return width == null ? Range.of(4, 7) : width;
}
public int stretch() {
return stretch;
}
public double flatness() {
return flatness;
}
public double coverage() {
return coverage;
}
}
@@ -0,0 +1,25 @@
/*
* 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.modules.carve.field;
/** Takes the blocks a cave shape carves in a chunk, by their place in the chunk and their height above the dimension's bottom. */
@FunctionalInterface
public interface CarveSink {
void carve(int localX, int y, int localZ);
}
@@ -0,0 +1,94 @@
/*
* 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.modules.carve.field;
import art.arcane.iris.modules.carve.Cave;
import com.volmit.config.Range;
import com.volmit.noise.NoiseFactory;
import java.util.ArrayList;
import java.util.List;
/**
* One cave of a pack, ready to carve chunks of one world: its shapes with their noise built for the world's seed, and
* the heights it may carve at. Heights count from the dimension's bottom. Safe to use from several threads at once.
*/
public final class CaveCarver {
private static final int CHUNK_COLUMNS = 256;
/** Caves stay this far above the dimension's bottom, clear of the bedrock floor. */
private static final int ROCK_KEPT_ABOVE_BOTTOM_BLOCKS = 5;
private final List<LatticeShape> shapes = new ArrayList<>();
private final int depthMinY;
private final int depthMaxY;
private final int fadeBlocks;
private final int surfaceClearance;
private final boolean opensToSurface;
/**
* @param seed the seed of this cave in this world; two caves with the same settings and seed carve the same
* @param worldBottomY world Y of the dimension's lowest block
* @param worldHeight the dimension's height in blocks
*/
public CaveCarver(Cave cave, NoiseFactory noise, long seed, int worldBottomY, int worldHeight) {
CaveNoise caveNoise = new CaveNoise(noise, seed);
cave.tunnel().ifPresent(tunnel -> shapes.add(new TunnelShape(caveNoise, tunnel)));
cave.cavern().ifPresent(cavern -> shapes.add(new CavernShape(caveNoise, cavern)));
Range depth = cave.depth().orElse(null);
int lowest = depth == null ? 0 : (int) Math.floor(Math.min(depth.min(), depth.max())) - worldBottomY;
int highest = depth == null ? worldHeight - 1 : (int) Math.ceil(Math.max(depth.min(), depth.max())) - worldBottomY;
this.depthMinY = Math.max(ROCK_KEPT_ABOVE_BOTTOM_BLOCKS, lowest);
this.depthMaxY = Math.min(worldHeight - 1, highest);
this.fadeBlocks = Math.max(0, cave.fade());
this.surfaceClearance = Math.max(0, cave.surfaceClearance());
this.opensToSurface = cave.opensToSurface();
}
public boolean opensToSurface() {
return opensToSurface;
}
/**
* Carves the chunk whose first block is {@code originX}, {@code originZ}. Columns are indexed as
* {@code (localX << 4) | localZ}.
*
* @param surfaceY the height of the surface in each column
* @param columnWeight how much each column lists this cave, from 0 to 1
* @param sealed columns whose surface the cave must not cut through, even if it opens to the surface
*/
public void carve(int originX, int originZ, int[] surfaceY, double[] columnWeight, boolean[] sealed, CarveSink sink) {
if (shapes.isEmpty() || depthMaxY < depthMinY) {
return;
}
int[] columnTopY = new int[CHUNK_COLUMNS];
boolean[] columnOpens = new boolean[CHUNK_COLUMNS];
for (int column = 0; column < CHUNK_COLUMNS; column++) {
columnOpens[column] = opensToSurface && !sealed[column];
columnTopY[column] = columnOpens[column] ? surfaceY[column] : surfaceY[column] - surfaceClearance;
}
CaveLimits limits = new CaveLimits(depthMinY, depthMaxY, fadeBlocks, columnTopY, columnOpens, columnWeight);
if (limits.carvesNothing()) {
return;
}
ChunkLattice lattice = ChunkLattice.covering(originX, originZ, limits.lowestY(), limits.highestY());
for (LatticeShape shape : shapes) {
shape.carve(lattice, limits, sink);
}
}
}
@@ -0,0 +1,120 @@
/*
* 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.modules.carve.field;
/**
* Where one cave may carve in one chunk, and how freely: fully inside its depth range and well under the surface,
* narrowing to nothing towards the ends of the range, towards the rock it keeps under the surface and towards columns
* that do not list it. Columns are indexed as {@code (localX << 4) | localZ}; heights count from the dimension's bottom.
*/
public final class CaveLimits {
private static final int CHUNK_COLUMNS = 256;
private static final int CELL_COLUMNS = ChunkLattice.CELLS_PER_CHUNK_AXIS * ChunkLattice.CELLS_PER_CHUNK_AXIS;
/** A cave that keeps rock above it closes over this many blocks instead of ending in a flat ceiling. */
private static final int CEILING_FADE_BLOCKS = 8;
private final int lowestY;
private final int highestY;
private final int depthMinY;
private final int depthMaxY;
private final int fadeBlocks;
private final int[] columnTopY;
private final boolean[] columnOpensToSurface;
private final double[] columnWeight;
private final int[] cellTopY = new int[CELL_COLUMNS];
private final boolean[] cellHasWeight = new boolean[CELL_COLUMNS];
/**
* @param depthMinY lowest height of the cave's depth range
* @param depthMaxY highest height of the cave's depth range
* @param fadeBlocks blocks over which the cave narrows at both ends of the range
* @param columnTopY highest height the cave may carve in each column
* @param columnOpensToSurface whether the cave reaches its top at full width in each column, instead of closing under it
* @param columnWeight how much each column lists the cave, from 0 to 1
*/
public CaveLimits(int depthMinY, int depthMaxY, int fadeBlocks, int[] columnTopY, boolean[] columnOpensToSurface, double[] columnWeight) {
this.depthMinY = depthMinY;
this.depthMaxY = depthMaxY;
this.fadeBlocks = fadeBlocks;
this.columnTopY = columnTopY;
this.columnOpensToSurface = columnOpensToSurface;
this.columnWeight = columnWeight;
java.util.Arrays.fill(cellTopY, Integer.MIN_VALUE);
int highestTopY = Integer.MIN_VALUE;
for (int column = 0; column < CHUNK_COLUMNS; column++) {
if (columnWeight[column] <= 0D) {
continue;
}
int cell = cellOf(column >> 4, column & 15);
cellHasWeight[cell] = true;
cellTopY[cell] = Math.max(cellTopY[cell], columnTopY[column]);
highestTopY = Math.max(highestTopY, columnTopY[column]);
}
this.lowestY = depthMinY;
this.highestY = Math.min(depthMaxY, highestTopY);
}
private static int cellOf(int localX, int localZ) {
return ((localX / ChunkLattice.CELL_BLOCKS) * ChunkLattice.CELLS_PER_CHUNK_AXIS) + (localZ / ChunkLattice.CELL_BLOCKS);
}
public int lowestY() {
return lowestY;
}
public int highestY() {
return highestY;
}
/** Whether the cave carves nothing in this chunk. */
public boolean carvesNothing() {
return highestY < lowestY;
}
/** Whether no column of the cell lets the cave carve at or above {@code bottomY}. */
boolean cellIsClosed(int cellX, int cellZ, int bottomY) {
int cell = (cellX * ChunkLattice.CELLS_PER_CHUNK_AXIS) + cellZ;
return !cellHasWeight[cell] || cellTopY[cell] < bottomY;
}
/** How freely the cave carves the block, from 0 (not at all) to 1 (at its full size). */
double openness(int column, int y) {
double weight = columnWeight[column];
if (weight <= 0D || y < depthMinY || y > depthMaxY) {
return 0D;
}
int belowTop = columnTopY[column] - y;
if (belowTop < 0) {
return 0D;
}
double openness = weight * easeIn(Math.min(y - depthMinY, depthMaxY - y), fadeBlocks);
if (!columnOpensToSurface[column]) {
openness *= easeIn(belowTop, CEILING_FADE_BLOCKS);
}
return openness;
}
private static double easeIn(int distance, int fadeBlocks) {
if (fadeBlocks <= 0 || distance >= fadeBlocks) {
return 1D;
}
double share = distance / (double) fadeBlocks;
return share * share * (3D - (2D * share));
}
}
@@ -0,0 +1,83 @@
/*
* 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.modules.carve.field;
import com.volmit.noise.NoiseFactory;
import com.volmit.noise.NoiseSampler;
import com.volmit.noise.NoiseStyle;
/** Builds the noise fields of cave shapes, sized in blocks instead of in a noise style's zoom. */
final class CaveNoise {
private static final String STYLE = "SIMPLEX";
/** Measured on the host's SIMPLEX style at zoom 1: the mean distance in blocks between two sign changes along a line. */
private static final double SIMPLEX_ZERO_SPACING_BLOCKS = 80.6D;
/** Measured on the same style: how much its value typically changes per block, times the spacing above. */
private static final double SIMPLEX_SLOPE_TIMES_SPACING = 2.43D;
/** The features of a field's finer second layer are this much smaller than its own. */
private static final double DETAIL_SHRINK = 2.7D;
/** Below this size a detail layer is finer than the sampling lattice can carry. */
private static final double MIN_DETAIL_SPACING_BLOCKS = 12D;
private final NoiseFactory noise;
private final long seed;
private int fieldsBuilt;
CaveNoise(NoiseFactory noise, long seed) {
this.noise = noise;
this.seed = seed;
}
/** How much a field with this spacing typically changes over one block. */
static double typicalSlope(double spacing) {
return SIMPLEX_SLOPE_TIMES_SPACING / spacing;
}
/** A field whose sign changes about every {@code spacing} blocks horizontally and {@code verticalSpacing} vertically. */
Field3 smooth(double spacing, double verticalSpacing) {
NoiseSampler sampler = nextSampler();
double horizontal = SIMPLEX_ZERO_SPACING_BLOCKS / spacing;
double vertical = SIMPLEX_ZERO_SPACING_BLOCKS / verticalSpacing;
return (x, y, z) -> sampler.signed(x * horizontal, y * vertical, z * horizontal);
}
/** {@link #smooth} with a finer layer of {@code detailWeight} times its strength on top, where the lattice can carry one. */
Field3 detailed(double spacing, double verticalSpacing, double detailWeight) {
Field3 base = smooth(spacing, verticalSpacing);
double detailSpacing = spacing / DETAIL_SHRINK;
double detailVerticalSpacing = verticalSpacing / DETAIL_SHRINK;
if (Math.min(detailSpacing, detailVerticalSpacing) < MIN_DETAIL_SPACING_BLOCKS) {
return base;
}
Field3 detail = smooth(detailSpacing, detailVerticalSpacing);
double normalization = 1D / (1D + detailWeight);
return (x, y, z) -> (base.at(x, y, z) + (detail.at(x, y, z) * detailWeight)) * normalization;
}
/** A field that only varies over X and Z, changing sign about every {@code spacing} blocks. */
Field3 columns(double spacing) {
NoiseSampler sampler = nextSampler();
double scale = SIMPLEX_ZERO_SPACING_BLOCKS / spacing;
return (x, y, z) -> sampler.signed(x * scale, z * scale);
}
private NoiseSampler nextSampler() {
fieldsBuilt++;
return noise.sampler(NoiseStyle.of(STYLE), seed + (fieldsBuilt * 1_000_003L));
}
}
@@ -0,0 +1,117 @@
/*
* 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.modules.carve.field;
import art.arcane.iris.modules.carve.CaveCavern;
import art.arcane.iris.modules.carve.CavePillars;
/**
* Caverns: the rooms where one slow field rises above a threshold. Pillars are columns where a second field, which
* only varies across X and Z, peaks: there the room has to be more open to be carved, so a pillar stands from floor
* to ceiling and widens towards both, where the room is least open.
*/
final class CavernShape extends LatticeShape {
private static final int ROOMS = 0;
/** A room is the part of a feature above the threshold, which is narrower than the feature itself. */
private static final double FEATURE_BLOCKS_PER_ROOM_BLOCK = 1.6D;
/** A finer layer keeps room walls from looking like smooth bubbles. */
private static final double WALL_DETAIL = 0.3D;
/** Closing a cavern takes a little more than its most open spot, so nothing is left at the very edge of its limits. */
private static final double CLOSING_MARGIN = 1.1D;
/** Pillars are two features apart: one peak, one trough. */
private static final double PILLAR_FEATURES_PER_SPACING = 0.5D;
/** How much more ground a pillar covers at floor and ceiling than at its middle. */
private static final double PILLAR_FOOT_AREA = 4D;
private static final double LARGEST_PILLAR_AREA_SHARE = 0.3D;
private final Field3 rooms;
private final double threshold;
private final double mostOpen;
private final Field3 pillars;
private final double pillarMiddle;
private final double pillarFoot;
CavernShape(CaveNoise noise, CaveCavern cavern) {
double span = cavern.size() * FEATURE_BLOCKS_PER_ROOM_BLOCK;
double height = cavern.height() * FEATURE_BLOCKS_PER_ROOM_BLOCK;
this.rooms = noise.detailed(span, height, WALL_DETAIL);
FieldStats stats = FieldStats.measure(rooms, span);
this.threshold = stats.valueAboveShare(cavern.coverage());
this.mostOpen = Math.max(0D, stats.highest() - threshold);
if (cavern.pillars().isEmpty()) {
this.pillars = null;
this.pillarMiddle = Double.POSITIVE_INFINITY;
this.pillarFoot = Double.POSITIVE_INFINITY;
return;
}
CavePillars settings = cavern.pillars().get();
double featureBlocks = settings.spacing() * PILLAR_FEATURES_PER_SPACING;
this.pillars = noise.columns(featureBlocks);
FieldStats pillarStats = FieldStats.measure(pillars, featureBlocks);
double middleAreaShare = Math.min(LARGEST_PILLAR_AREA_SHARE, pillarAreaShare(settings));
this.pillarMiddle = pillarStats.valueAboveShare(middleAreaShare);
this.pillarFoot = pillarStats.valueAboveShare(Math.min(1D, middleAreaShare * PILLAR_FOOT_AREA));
}
private static double pillarAreaShare(CavePillars pillars) {
double radius = pillars.thickness() / 2D;
return (Math.PI * radius * radius) / ((double) pillars.spacing() * pillars.spacing());
}
@Override
protected int fieldCount() {
return 1;
}
@Override
protected void readFields(int x, int y, int z, double[] values) {
values[ROOMS] = rooms.at(x, y, z);
}
@Override
protected boolean mayCarveIn(Pass pass) {
return pass.cell(ROOMS).highest() > threshold;
}
@Override
protected boolean carvesAt(Pass pass, double shareX, double shareY, double shareZ, double openness, int column) {
double open = pass.cell(ROOMS).at(shareX, shareY, shareZ) - threshold - ((1D - openness) * mostOpen * CLOSING_MARGIN);
if (open <= 0D) {
return false;
}
if (pillars == null) {
return true;
}
return open > pillarStrength(pass, column) * mostOpen;
}
/** How strongly the column is a pillar: 0 outside one, 1 in its middle, in between on the foot it widens into. */
private double pillarStrength(Pass pass, int column) {
double[] strengths = pass.columnValues();
double known = strengths[column];
if (!Double.isNaN(known)) {
return known;
}
double value = pillars.at(pass.lattice().originX() + (column >> 4), 0D, pass.lattice().originZ() + (column & 15));
double intoPillar = Math.max(0D, Math.min(1D, (value - pillarFoot) / (pillarMiddle - pillarFoot)));
double strength = intoPillar * intoPillar;
strengths[column] = strength;
return strength;
}
}
@@ -0,0 +1,94 @@
/*
* 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.modules.carve.field;
/**
* The points one chunk samples its cave fields at: every fourth block along each axis, over the heights a cave may
* carve. A shape reads its fields at these points only and interpolates between them, which is where the carver's
* speed comes from. Points sit at multiples of four in world coordinates, so neighboring chunks sample the very same
* points along their shared border and their caves meet without a seam.
*/
public final class ChunkLattice {
public static final int CELL_BLOCKS = 4;
public static final int CELLS_PER_CHUNK_AXIS = 16 / CELL_BLOCKS;
private static final int POINTS_PER_AXIS = CELLS_PER_CHUNK_AXIS + 1;
private static final int POINTS_PER_LAYER = POINTS_PER_AXIS * POINTS_PER_AXIS;
private final int originX;
private final int originZ;
private final int baseY;
private final int cellsY;
private ChunkLattice(int originX, int originZ, int baseY, int cellsY) {
this.originX = originX;
this.originZ = originZ;
this.baseY = baseY;
this.cellsY = cellsY;
}
/** The lattice of the chunk whose first block is {@code originX}, {@code originZ}, covering heights {@code minY} to {@code maxY}. */
public static ChunkLattice covering(int originX, int originZ, int minY, int maxY) {
int baseY = Math.floorDiv(minY, CELL_BLOCKS) * CELL_BLOCKS;
int cellsY = Math.max(1, Math.floorDiv(maxY - baseY, CELL_BLOCKS) + 1);
return new ChunkLattice(originX, originZ, baseY, cellsY);
}
public int originX() {
return originX;
}
public int originZ() {
return originZ;
}
public int baseY() {
return baseY;
}
public int cellsY() {
return cellsY;
}
public int pointCount() {
return POINTS_PER_LAYER * (cellsY + 1);
}
/** Takes the lattice's points one by one, each with its place in a list of {@link #pointCount()} values. */
@FunctionalInterface
interface PointReader {
void read(int index, int x, int y, int z);
}
void forEachPoint(PointReader reader) {
int index = 0;
for (int layer = 0; layer <= cellsY; layer++) {
int y = baseY + (layer * CELL_BLOCKS);
for (int pointX = 0; pointX < POINTS_PER_AXIS; pointX++) {
int x = originX + (pointX * CELL_BLOCKS);
for (int pointZ = 0; pointZ < POINTS_PER_AXIS; pointZ++) {
reader.read(index++, x, y, originZ + (pointZ * CELL_BLOCKS));
}
}
}
}
int pointIndex(int pointX, int layer, int pointZ) {
return (layer * POINTS_PER_LAYER) + (pointX * POINTS_PER_AXIS) + pointZ;
}
}
@@ -0,0 +1,25 @@
/*
* 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.modules.carve.field;
/** A smooth value over the world's blocks, from -1 to 1, that a cave shape reads to decide where it carves. */
@FunctionalInterface
public interface Field3 {
double at(double x, double y, double z);
}
@@ -0,0 +1,67 @@
/*
* 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.modules.carve.field;
import java.util.Arrays;
/**
* What a field's values look like, measured once on fixed sample points so every server measures the same: which value
* a given share of the world lies above. Shapes turn a share of the underground into a field threshold with it.
*/
final class FieldStats {
private static final int SAMPLES = 4096;
/** Samples spread over this many features, far enough apart to be independent. */
private static final double SPAN_IN_FEATURES = 200D;
private static final double STEP_X = 0.7548776662466927D;
private static final double STEP_Y = 0.5698402909980532D;
private static final double STEP_Z = 0.8191725133961645D;
private final double[] sortedValues;
private FieldStats(double[] sortedValues) {
this.sortedValues = sortedValues;
}
/** Measures {@code field}, whose features are about {@code featureBlocks} blocks apart. */
static FieldStats measure(Field3 field, double featureBlocks) {
double span = featureBlocks * SPAN_IN_FEATURES;
double[] values = new double[SAMPLES];
for (int sample = 0; sample < SAMPLES; sample++) {
values[sample] = field.at(coordinate(sample, STEP_X, span), coordinate(sample, STEP_Y, span), coordinate(sample, STEP_Z, span));
}
Arrays.sort(values);
return new FieldStats(values);
}
private static double coordinate(int sample, double step, double span) {
double fraction = (sample * step) % 1D;
return (fraction - 0.5D) * span;
}
/** The value that {@code share} of the world lies above, from 0 to 1. */
double valueAboveShare(double share) {
double clamped = Math.max(0D, Math.min(1D, share));
int index = (int) Math.round((1D - clamped) * (sortedValues.length - 1));
return sortedValues[index];
}
double highest() {
return sortedValues[sortedValues.length - 1];
}
}
@@ -0,0 +1,100 @@
/*
* 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.modules.carve.field;
/**
* One field's values at the eight corners of a lattice cell, and the value interpolated between them at any block of
* the cell. An interpolated value never leaves the range of the corners, so a shape can rule a whole cell out from
* {@link #lowest()} and {@link #highest()} without looking at its blocks.
*/
final class LatticeCell {
/** A face holds four corners, and opposite faces are one cell apart. */
private static final double SLOPE_PER_FACE_SUM = 1D / (4D * ChunkLattice.CELL_BLOCKS);
private double lowWestNorth;
private double lowWestSouth;
private double lowEastNorth;
private double lowEastSouth;
private double highWestNorth;
private double highWestSouth;
private double highEastNorth;
private double highEastSouth;
void load(double[] values, ChunkLattice lattice, int cellX, int cellY, int cellZ) {
lowWestNorth = values[lattice.pointIndex(cellX, cellY, cellZ)];
lowWestSouth = values[lattice.pointIndex(cellX, cellY, cellZ + 1)];
lowEastNorth = values[lattice.pointIndex(cellX + 1, cellY, cellZ)];
lowEastSouth = values[lattice.pointIndex(cellX + 1, cellY, cellZ + 1)];
highWestNorth = values[lattice.pointIndex(cellX, cellY + 1, cellZ)];
highWestSouth = values[lattice.pointIndex(cellX, cellY + 1, cellZ + 1)];
highEastNorth = values[lattice.pointIndex(cellX + 1, cellY + 1, cellZ)];
highEastSouth = values[lattice.pointIndex(cellX + 1, cellY + 1, cellZ + 1)];
}
double lowest() {
return Math.min(Math.min(Math.min(lowWestNorth, lowWestSouth), Math.min(lowEastNorth, lowEastSouth)),
Math.min(Math.min(highWestNorth, highWestSouth), Math.min(highEastNorth, highEastSouth)));
}
double highest() {
return Math.max(Math.max(Math.max(lowWestNorth, lowWestSouth), Math.max(lowEastNorth, lowEastSouth)),
Math.max(Math.max(highWestNorth, highWestSouth), Math.max(highEastNorth, highEastSouth)));
}
/** How far every value of the cell stays from zero; 0 when the cell may cross it. */
double distanceFromZero() {
double lowest = lowest();
if (lowest > 0D) {
return lowest;
}
double highest = highest();
return highest < 0D ? -highest : 0D;
}
/** How much the value changes per block towards higher X, averaged over the cell. */
double slopeX() {
return ((lowEastNorth + lowEastSouth + highEastNorth + highEastSouth)
- (lowWestNorth + lowWestSouth + highWestNorth + highWestSouth)) * SLOPE_PER_FACE_SUM;
}
/** How much the value changes per block upwards, averaged over the cell. */
double slopeY() {
return ((highWestNorth + highWestSouth + highEastNorth + highEastSouth)
- (lowWestNorth + lowWestSouth + lowEastNorth + lowEastSouth)) * SLOPE_PER_FACE_SUM;
}
/** How much the value changes per block towards higher Z, averaged over the cell. */
double slopeZ() {
return ((lowWestSouth + lowEastSouth + highWestSouth + highEastSouth)
- (lowWestNorth + lowEastNorth + highWestNorth + highEastNorth)) * SLOPE_PER_FACE_SUM;
}
/** The value at a block of the cell, each coordinate as its share of the way across the cell, from 0 to 1. */
double at(double shareX, double shareY, double shareZ) {
double low = across(lowWestNorth, lowWestSouth, lowEastNorth, lowEastSouth, shareX, shareZ);
double high = across(highWestNorth, highWestSouth, highEastNorth, highEastSouth, shareX, shareZ);
return low + ((high - low) * shareY);
}
private static double across(double westNorth, double westSouth, double eastNorth, double eastSouth, double shareX, double shareZ) {
double west = westNorth + ((westSouth - westNorth) * shareZ);
double east = eastNorth + ((eastSouth - eastNorth) * shareZ);
return west + ((east - west) * shareX);
}
}
@@ -0,0 +1,149 @@
/*
* 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.modules.carve.field;
import java.util.Arrays;
/**
* A cave shape that reads smooth fields on a chunk's lattice and decides block by block from their interpolated
* values. The fields are interpolated, never the decision, so a passage thinner than a lattice cell survives: its
* fields still cross zero between the points.
*/
abstract class LatticeShape {
private static final ThreadLocal<Pass> PASS = ThreadLocal.withInitial(Pass::new);
private static final double CELL_SHARE = 1D / ChunkLattice.CELL_BLOCKS;
/** How many fields the shape reads. {@link Pass#cell} numbers them from 0. */
protected abstract int fieldCount();
/** Reads every field of the shape at one block into {@code values}, one value per field. */
protected abstract void readFields(int x, int y, int z, double[] values);
/** Whether the shape can carve anywhere in the cell the pass has loaded, whatever the limits allow. */
protected abstract boolean mayCarveIn(Pass pass);
/** Whether the shape carves the block at these shares of the way across the loaded cell. */
protected abstract boolean carvesAt(Pass pass, double shareX, double shareY, double shareZ, double openness, int column);
final void carve(ChunkLattice lattice, CaveLimits limits, CarveSink sink) {
Pass pass = PASS.get();
pass.begin(lattice, this);
for (int cellY = 0; cellY < lattice.cellsY(); cellY++) {
int bottomY = lattice.baseY() + (cellY * ChunkLattice.CELL_BLOCKS);
if (bottomY > limits.highestY() || bottomY + ChunkLattice.CELL_BLOCKS <= limits.lowestY()) {
continue;
}
for (int cellX = 0; cellX < ChunkLattice.CELLS_PER_CHUNK_AXIS; cellX++) {
for (int cellZ = 0; cellZ < ChunkLattice.CELLS_PER_CHUNK_AXIS; cellZ++) {
if (limits.cellIsClosed(cellX, cellZ, bottomY)) {
continue;
}
pass.load(cellX, cellY, cellZ);
if (mayCarveIn(pass)) {
carveCell(pass, limits, sink, cellX, bottomY, cellZ);
}
}
}
}
}
private void carveCell(Pass pass, CaveLimits limits, CarveSink sink, int cellX, int bottomY, int cellZ) {
for (int stepY = 0; stepY < ChunkLattice.CELL_BLOCKS; stepY++) {
int y = bottomY + stepY;
if (y < limits.lowestY() || y > limits.highestY()) {
continue;
}
for (int stepX = 0; stepX < ChunkLattice.CELL_BLOCKS; stepX++) {
int localX = (cellX * ChunkLattice.CELL_BLOCKS) + stepX;
for (int stepZ = 0; stepZ < ChunkLattice.CELL_BLOCKS; stepZ++) {
int localZ = (cellZ * ChunkLattice.CELL_BLOCKS) + stepZ;
int column = (localX << 4) | localZ;
double openness = limits.openness(column, y);
if (openness > 0D && carvesAt(pass, stepX * CELL_SHARE, stepY * CELL_SHARE, stepZ * CELL_SHARE, openness, column)) {
sink.carve(localX, y, localZ);
}
}
}
}
}
/** One chunk's carving by one shape on one thread: the sampled fields, the cell being decided and a value per column. */
static final class Pass {
private static final int CHUNK_COLUMNS = 256;
private static final int CELL_VALUES = 12;
private ChunkLattice lattice;
private double[] pointValues = new double[0];
private double[][] values = new double[0][];
private LatticeCell[] cells = new LatticeCell[0];
private int fieldCount;
private final double[] columnValues = new double[CHUNK_COLUMNS];
private final double[] cellValues = new double[CELL_VALUES];
private void begin(ChunkLattice lattice, LatticeShape shape) {
this.lattice = lattice;
this.fieldCount = shape.fieldCount();
if (values.length < fieldCount) {
values = Arrays.copyOf(values, fieldCount);
cells = Arrays.copyOf(cells, fieldCount);
pointValues = new double[fieldCount];
}
int points = lattice.pointCount();
for (int field = 0; field < fieldCount; field++) {
if (values[field] == null || values[field].length < points) {
values[field] = new double[points];
}
if (cells[field] == null) {
cells[field] = new LatticeCell();
}
}
lattice.forEachPoint((index, x, y, z) -> {
shape.readFields(x, y, z, pointValues);
for (int field = 0; field < fieldCount; field++) {
values[field][index] = pointValues[field];
}
});
Arrays.fill(columnValues, Double.NaN);
}
private void load(int cellX, int cellY, int cellZ) {
for (int field = 0; field < fieldCount; field++) {
cells[field].load(values[field], lattice, cellX, cellY, cellZ);
}
}
LatticeCell cell(int field) {
return cells[field];
}
ChunkLattice lattice() {
return lattice;
}
/** A value the shape keeps per column of the chunk for the length of the pass; NaN until the shape sets it. */
double[] columnValues() {
return columnValues;
}
/** Values the shape works out in {@link LatticeShape#mayCarveIn} for the blocks of the loaded cell. */
double[] cellValues() {
return cellValues;
}
}
}
@@ -0,0 +1,207 @@
/*
* 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.modules.carve.field;
import art.arcane.iris.modules.carve.CaveTunnel;
/**
* Tunnels: the lines along which two of three fields are both zero. Each field is zero on winding sheets through the
* rock and two sheets meet in a line, which never ends on its own, so tunnels are long. Every line runs inside two
* sheets and sooner or later crosses the third, and there all three lines meet: that is a junction, and it is what
* joins the tunnels into one network.
*
* <p>A tunnel is every block within its radius of a line. The distance is worked out in blocks from how steeply the
* fields change in the cell, so a tunnel keeps the width the pack asks for wherever the noise is steep or shallow.
* The fields are read at gently shifted places, which makes a tunnel's path wiggle without ever breaking it.
*/
final class TunnelShape extends LatticeShape {
private static final int SHEETS = 3;
private static final int WIDTH = SHEETS;
private static final int PRESENCE = SHEETS + 1;
private static final int[] PAIR_FIRST = {0, 0, 1};
private static final int[] PAIR_SECOND = {1, 2, 2};
private static final int PAIRS = PAIR_FIRST.length;
private static final int VALUES_PER_PAIR = 4;
private static final int FIRST_SQUARED = 0;
private static final int FIRST_TIMES_SECOND = 1;
private static final int SECOND_SQUARED = 2;
private static final int PAIR_IS_NEAR = 3;
private static final double NEAR = 1D;
private static final double FAR = 0D;
/** A path shifts by this share of the tunnel's stretch, and changes direction this many times per stretch. */
private static final double WIGGLE_SHARE_OF_STRETCH = 0.06D;
private static final double WIGGLES_PER_STRETCH = 3D;
private static final double SMALLEST_WIGGLE_SPACING_BLOCKS = 16D;
private static final double VERTICAL_WIGGLE_SHARE = 0.5D;
private static final double WIDTH_CHANGE_STRETCHES = 1.5D;
private static final double WIDTH_SPREAD = 1D;
private static final double PRESENCE_STRETCHES = 3D;
/** Field value over which tunnels widen from nothing to full size at the edge of an area that has them. */
private static final double PRESENCE_EDGE = 0.15D;
/** A tunnel narrower than this is not a passage any more, so it ends instead. */
private static final double NARROWEST_RADIUS_BLOCKS = 1D;
/** A cell's slope is an average, so a cell is only ruled out when the line is clearly further than the widest tunnel. */
private static final double CELL_REACH_SLACK = 1.5D;
/**
* Where a field is nearly flat, a small value says little about how far its sheet is, and the tunnel would swell
* into a blob. A field counts as changing at least this share of its typical slope.
*/
private static final double LEAST_SLOPE_SHARE = 0.45D;
/** Where two sheets run nearly side by side the line between them is ill-defined; they count as crossing at least this squarely. */
private static final double LEAST_CROSSING = 0.03D;
private final Field3[] sheets = new Field3[SHEETS];
private final Field3 width;
private final Field3 presence;
private final Field3 wiggleX;
private final Field3 wiggleY;
private final Field3 wiggleZ;
private final double wiggleBlocks;
private final double narrowRadius;
private final double wideRadius;
private final double leastSteepness;
private final double presenceThreshold;
TunnelShape(CaveNoise noise, CaveTunnel tunnel) {
double stretch = tunnel.stretch();
double verticalStretch = stretch / Math.max(1D, tunnel.flatness());
for (int sheet = 0; sheet < SHEETS; sheet++) {
sheets[sheet] = noise.smooth(stretch, verticalStretch);
}
double wiggleSpacing = Math.max(SMALLEST_WIGGLE_SPACING_BLOCKS, stretch / WIGGLES_PER_STRETCH);
this.wiggleX = noise.smooth(wiggleSpacing, wiggleSpacing);
this.wiggleY = noise.smooth(wiggleSpacing, wiggleSpacing);
this.wiggleZ = noise.smooth(wiggleSpacing, wiggleSpacing);
this.wiggleBlocks = stretch * WIGGLE_SHARE_OF_STRETCH;
this.width = noise.smooth(stretch * WIDTH_CHANGE_STRETCHES, stretch * WIDTH_CHANGE_STRETCHES);
this.narrowRadius = Math.min(tunnel.width().min(), tunnel.width().max()) / 2D;
this.wideRadius = Math.max(tunnel.width().min(), tunnel.width().max()) / 2D;
double leastSlope = CaveNoise.typicalSlope(stretch) * LEAST_SLOPE_SHARE;
this.leastSteepness = leastSlope * leastSlope;
if (tunnel.coverage() >= 1D) {
this.presence = null;
this.presenceThreshold = Double.NEGATIVE_INFINITY;
return;
}
double presenceStretch = stretch * PRESENCE_STRETCHES;
this.presence = noise.smooth(presenceStretch, presenceStretch);
this.presenceThreshold = FieldStats.measure(presence, presenceStretch).valueAboveShare(tunnel.coverage());
}
@Override
protected int fieldCount() {
return presence == null ? SHEETS + 1 : SHEETS + 2;
}
@Override
protected void readFields(int x, int y, int z, double[] values) {
double shiftedX = x + (wiggleX.at(x, y, z) * wiggleBlocks);
double shiftedY = y + (wiggleY.at(x, y, z) * wiggleBlocks * VERTICAL_WIGGLE_SHARE);
double shiftedZ = z + (wiggleZ.at(x, y, z) * wiggleBlocks);
for (int sheet = 0; sheet < SHEETS; sheet++) {
values[sheet] = sheets[sheet].at(shiftedX, shiftedY, shiftedZ);
}
values[WIDTH] = width.at(x, y, z);
if (presence != null) {
values[PRESENCE] = presence.at(x, y, z);
}
}
@Override
protected boolean mayCarveIn(Pass pass) {
if (presence != null && pass.cell(PRESENCE).highest() <= presenceThreshold) {
return false;
}
double reach = wideRadius * CELL_REACH_SLACK;
double[] pairValues = pass.cellValues();
boolean anyPairNear = false;
for (int pair = 0; pair < PAIRS; pair++) {
boolean near = preparePair(pass.cell(PAIR_FIRST[pair]), pass.cell(PAIR_SECOND[pair]), reach, pairValues, pair * VALUES_PER_PAIR);
pairValues[(pair * VALUES_PER_PAIR) + PAIR_IS_NEAR] = near ? NEAR : FAR;
anyPairNear |= near;
}
return anyPairNear;
}
/**
* Works out, for the line where two sheets meet, the terms that turn the two field values at a block of the cell
* into its squared distance from that line in blocks. Answers false when the line is out of reach of the whole cell.
*/
private boolean preparePair(LatticeCell first, LatticeCell second, double reach, double[] pairValues, int offset) {
double firstSteepness = Math.max(squaredSlope(first), leastSteepness);
double secondSteepness = Math.max(squaredSlope(second), leastSteepness);
if (isFurtherThan(first.distanceFromZero(), firstSteepness, reach) || isFurtherThan(second.distanceFromZero(), secondSteepness, reach)) {
return false;
}
double together = (first.slopeX() * second.slopeX()) + (first.slopeY() * second.slopeY()) + (first.slopeZ() * second.slopeZ());
double crossing = Math.max((firstSteepness * secondSteepness) - (together * together), firstSteepness * secondSteepness * LEAST_CROSSING);
pairValues[offset + FIRST_SQUARED] = secondSteepness / crossing;
pairValues[offset + FIRST_TIMES_SECOND] = (-2D * together) / crossing;
pairValues[offset + SECOND_SQUARED] = firstSteepness / crossing;
return true;
}
private static double squaredSlope(LatticeCell cell) {
return (cell.slopeX() * cell.slopeX()) + (cell.slopeY() * cell.slopeY()) + (cell.slopeZ() * cell.slopeZ());
}
/** Whether a sheet whose field stays {@code fieldDistance} from zero in the cell is more than {@code blocks} away. */
private static boolean isFurtherThan(double fieldDistance, double squaredSlope, double blocks) {
return fieldDistance * fieldDistance > blocks * blocks * squaredSlope;
}
@Override
protected boolean carvesAt(Pass pass, double shareX, double shareY, double shareZ, double openness, int column) {
double radius = radiusAt(pass, shareX, shareY, shareZ) * openness;
if (radius < NARROWEST_RADIUS_BLOCKS) {
return false;
}
double squaredRadius = radius * radius;
double[] pairValues = pass.cellValues();
for (int pair = 0; pair < PAIRS; pair++) {
int offset = pair * VALUES_PER_PAIR;
if (pairValues[offset + PAIR_IS_NEAR] == FAR) {
continue;
}
double first = pass.cell(PAIR_FIRST[pair]).at(shareX, shareY, shareZ);
double second = pass.cell(PAIR_SECOND[pair]).at(shareX, shareY, shareZ);
double squaredBlocksFromLine = (pairValues[offset + FIRST_SQUARED] * first * first)
+ (pairValues[offset + FIRST_TIMES_SECOND] * first * second)
+ (pairValues[offset + SECOND_SQUARED] * second * second);
if (squaredBlocksFromLine < squaredRadius) {
return true;
}
}
return false;
}
private double radiusAt(Pass pass, double shareX, double shareY, double shareZ) {
double widthShare = clampToShare(0.5D + (pass.cell(WIDTH).at(shareX, shareY, shareZ) * WIDTH_SPREAD));
double radius = narrowRadius + ((wideRadius - narrowRadius) * widthShare);
if (presence == null) {
return radius;
}
double intoArea = (pass.cell(PRESENCE).at(shareX, shareY, shareZ) - presenceThreshold) / PRESENCE_EDGE;
return radius * clampToShare(intoArea);
}
private static double clampToShare(double value) {
return Math.max(0D, Math.min(1D, value));
}
}
@@ -165,12 +165,12 @@ public final class FloatingChildBiome {
@Desc("Optional 3D noise that swiss-cheeses the island interior by marking individual blocks as air when the noise exceeds carveThreshold. Leave null to keep the island solid. Good defaults: {\"style\":\"CELLULAR\",\"zoom\":0.3} for bubble pockets, {\"style\":\"VASCULAR\",\"zoom\":0.25} for wormy tunnels.")
private NoiseStyle carveStyle;
@Desc("Optional carving biome key or dimension carving entry id whose caveProfile drives floating-island internal air pockets. Dimension carving ids resolve first; biome keys such as carving/mushroom resolve second. When set, this overrides carveStyle while carveThreshold remains a final tuning bias.")
@Desc("Optional carving biome key or dimension carving entry id that joins the pack's biomes with this island. Dimension carving ids resolve first; biome keys such as carving/mushroom resolve second. It does not carve; carveStyle does.")
private String carving = "";
@MinNumber(0)
@MaxNumber(1)
@Desc("Threshold (0..1) above which carveStyle noise carves air pockets. 1.0 = no direct-noise carving. 0.75 = sparse pockets. 0.55 = heavy swiss-cheese. 0.4 = shredded lattice. When carving is set, lower values add a final positive threshold bias to the referenced caveProfile.")
@Desc("Threshold (0..1) above which carveStyle noise carves air pockets. 1.0 = no direct-noise carving. 0.75 = sparse pockets. 0.55 = heavy swiss-cheese. 0.4 = shredded lattice.")
private double carveThreshold = 1.0;
@Desc("Optional water surface height above the island base, in blocks. null = no internal water. Positive = water fills any dip in the top profile up to baseY + localFluidHeight (forms lakes/ponds in concavities of the biome-top heightmap).")