From 7d166df70fb5b312b8b1849af67549288785536a Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 12 Nov 2026 21:21:40 +0100 Subject: [PATCH] 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. --- .../iris/core/modules/ModuleSettings.java | 4 +- .../pack/PackStyledRangeDefaultValidator.java | 15 +- .../modules/CarveSettingsDecodingTest.java | 68 +- .../iris/core/modules/CarveTestWorld.java | 12 + .../PackStyledRangeDefaultValidatorTest.java | 12 - .../mantle/components/CaveCarvingTest.java | 131 +- .../components/CaveCarvingTop2BlendTest.java | 163 -- .../components/EffectivePlacementsTest.java | 13 - .../IrisCaveCarver3DNearParityTest.java | 1057 -------- .../modifier/CarvePipelineHarnessTest.java | 21 +- .../carving/CaveProfileDecodingTest.java | 171 -- .../FloatingIslandBoundarySamplerTest.java | 4 - .../FloatingIslandSampleBottomYTest.java | 7 +- .../modules/carve/field/CaveCarverTest.java | 148 ++ .../dimensions/overworld.json | 82 - .../regions/hot.json | 51 - .../regions/mushroom.json | 51 - .../regions/swamp.json | 51 - .../regions/terralost.json | 51 - .../biomes/carving/amethyst.json | 82 - .../dimensions/overworld.json | 82 - .../pack-before-the-port/regions/forests.json | 51 - .../regions/magnetics.json | 51 - .../biomes/carving/polarity-grotto.json | 62 - module/README.md | 6 +- .../iris/builtin/carve/CaveFieldModule.java | 66 - .../mantle/components/CaveCarveScratch.java | 69 - .../engine/mantle/components/CaveCarving.java | 706 ++--- .../components/CaveFieldModuleState.java | 58 - .../components/CaveFluidSupportPlan.java | 90 - .../mantle/components/CaveSettings.java | 62 +- .../mantle/components/ChunkObjectPlacing.java | 33 +- .../components/EffectivePlacements.java | 17 - .../mantle/components/IrisCaveCarver3D.java | 2268 ----------------- .../iris/engine/modifier/CarveModule.java | 27 +- .../terrain/carving/CaveProfileSampler.java | 178 -- .../terrain/carving/DeclaredByLevel.java | 5 + .../terrain/carving/DeclaredCaveProfiles.java | 52 - .../floating/FloatingIslandSample.java | 21 +- .../terrain/floating/FloatingWorld.java | 5 - .../floating/ResolvedFloatingChild.java | 26 +- .../art/arcane/iris/modules/carve/Cave.java | 92 + .../arcane/iris/modules/carve/CaveCavern.java | 66 + .../arcane/iris/modules/carve/CaveList.java | 69 + .../iris/modules/carve/CavePillars.java | 48 + .../iris/modules/carve/CaveProfile.java | 308 --- .../iris/modules/carve/CaveResources.java | 49 + .../arcane/iris/modules/carve/CaveTunnel.java | 65 + .../iris/modules/carve/field/CarveSink.java | 25 + .../iris/modules/carve/field/CaveCarver.java | 94 + .../iris/modules/carve/field/CaveLimits.java | 120 + .../iris/modules/carve/field/CaveNoise.java | 83 + .../iris/modules/carve/field/CavernShape.java | 117 + .../modules/carve/field/ChunkLattice.java | 94 + .../iris/modules/carve/field/Field3.java | 25 + .../iris/modules/carve/field/FieldStats.java | 67 + .../iris/modules/carve/field/LatticeCell.java | 100 + .../modules/carve/field/LatticeShape.java | 149 ++ .../iris/modules/carve/field/TunnelShape.java | 207 ++ .../modules/floating/FloatingChildBiome.java | 4 +- 60 files changed, 1996 insertions(+), 5915 deletions(-) delete mode 100644 core/src/test/java/art/arcane/iris/engine/mantle/components/CaveCarvingTop2BlendTest.java delete mode 100644 core/src/test/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3DNearParityTest.java delete mode 100644 core/src/test/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileDecodingTest.java create mode 100644 core/src/test/java/art/arcane/iris/modules/carve/field/CaveCarverTest.java delete mode 100644 module/src/main/java/art/arcane/iris/builtin/carve/CaveFieldModule.java delete mode 100644 module/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarveScratch.java delete mode 100644 module/src/main/java/art/arcane/iris/engine/mantle/components/CaveFieldModuleState.java delete mode 100644 module/src/main/java/art/arcane/iris/engine/mantle/components/CaveFluidSupportPlan.java delete mode 100644 module/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java delete mode 100644 module/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileSampler.java delete mode 100644 module/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredCaveProfiles.java create mode 100644 module/src/main/java/art/arcane/iris/modules/carve/Cave.java create mode 100644 module/src/main/java/art/arcane/iris/modules/carve/CaveCavern.java create mode 100644 module/src/main/java/art/arcane/iris/modules/carve/CaveList.java create mode 100644 module/src/main/java/art/arcane/iris/modules/carve/CavePillars.java delete mode 100644 module/src/main/java/art/arcane/iris/modules/carve/CaveProfile.java create mode 100644 module/src/main/java/art/arcane/iris/modules/carve/CaveResources.java create mode 100644 module/src/main/java/art/arcane/iris/modules/carve/CaveTunnel.java create mode 100644 module/src/main/java/art/arcane/iris/modules/carve/field/CarveSink.java create mode 100644 module/src/main/java/art/arcane/iris/modules/carve/field/CaveCarver.java create mode 100644 module/src/main/java/art/arcane/iris/modules/carve/field/CaveLimits.java create mode 100644 module/src/main/java/art/arcane/iris/modules/carve/field/CaveNoise.java create mode 100644 module/src/main/java/art/arcane/iris/modules/carve/field/CavernShape.java create mode 100644 module/src/main/java/art/arcane/iris/modules/carve/field/ChunkLattice.java create mode 100644 module/src/main/java/art/arcane/iris/modules/carve/field/Field3.java create mode 100644 module/src/main/java/art/arcane/iris/modules/carve/field/FieldStats.java create mode 100644 module/src/main/java/art/arcane/iris/modules/carve/field/LatticeCell.java create mode 100644 module/src/main/java/art/arcane/iris/modules/carve/field/LatticeShape.java create mode 100644 module/src/main/java/art/arcane/iris/modules/carve/field/TunnelShape.java diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleSettings.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleSettings.java index 70d948333..07d88f241 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleSettings.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleSettings.java @@ -105,7 +105,9 @@ public final class ModuleSettings { } private Set linkedBiomes(IrisPackResources resources, Function> 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 biomes = new LinkedHashSet<>(); diff --git a/core/src/main/java/art/arcane/iris/core/pack/PackStyledRangeDefaultValidator.java b/core/src/main/java/art/arcane/iris/core/pack/PackStyledRangeDefaultValidator.java index 7054e8ed1..71427a000 100644 --- a/core/src/main/java/art/arcane/iris/core/pack/PackStyledRangeDefaultValidator.java +++ b/core/src/main/java/art/arcane/iris/core/pack/PackStyledRangeDefaultValidator.java @@ -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 errors, List 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 errors, List warnings) { JSONObject range = null; diff --git a/core/src/test/java/art/arcane/iris/core/modules/CarveSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/CarveSettingsDecodingTest.java index 0e14c4aef..9152ba54b 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/CarveSettingsDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/CarveSettingsDecodingTest.java @@ -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 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")); diff --git a/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java b/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java index e59318277..cba6a7358 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java +++ b/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java @@ -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, Object> states = new HashMap<>(); private final List> declared = new ArrayList<>(); private final Map biomes = new HashMap<>(); + private final Map 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 Optional find(ResourceKind kind, ResourceId id) { + if (kind.equals(CaveResources.CAVES)) { + return Optional.ofNullable(kind.type().cast(caves.get(id))); + } if (!kind.equals(BIOMES)) { return Optional.empty(); } diff --git a/core/src/test/java/art/arcane/iris/core/pack/PackStyledRangeDefaultValidatorTest.java b/core/src/test/java/art/arcane/iris/core/pack/PackStyledRangeDefaultValidatorTest.java index 9b8a57257..901f206fd 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/PackStyledRangeDefaultValidatorTest.java +++ b/core/src/test/java/art/arcane/iris/core/pack/PackStyledRangeDefaultValidatorTest.java @@ -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"); diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/CaveCarvingTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/CaveCarvingTest.java index 2b248d7d9..9580c0e59 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/CaveCarvingTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/CaveCarvingTest.java @@ -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 . - */ - 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 dimensionOnly = carvedBlocks(sample -> PLAINS); + world.declare(Level.REGION, "region", new CaveList(List.of("low"))); - int carved = carvedBlocks(BiomeSample::surfaceBiome); + Set 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 caveBiomeOf) { + @Test + public void aCaveStaysInItsDepthRangeAndUnderTheRockItKeeps() { + world.dimension(new CaveList(List.of("low"))); + + Set 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 carvedBlocks(Function 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 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 + "}"); } } diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/CaveCarvingTop2BlendTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/CaveCarvingTop2BlendTest.java deleted file mode 100644 index 675ddf92a..000000000 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/CaveCarvingTop2BlendTest.java +++ /dev/null @@ -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 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 firstByProfile = extractWeightsByProfile(first); - Map 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 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 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 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 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 weightedProfiles, int limit) throws Exception { - return (List) limitMethod.invoke(null, weightedProfiles, limit, 256); - } - - private Map extractWeightsByProfile(List weightedProfiles) throws Exception { - Map 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 weightedProfiles, Profiles profiles) { - } -} diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/EffectivePlacementsTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/EffectivePlacementsTest.java index cc4897236..47f156393 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/EffectivePlacementsTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/EffectivePlacementsTest.java @@ -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); diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3DNearParityTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3DNearParityTest.java deleted file mode 100644 index 9b71723f1..000000000 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3DNearParityTest.java +++ /dev/null @@ -1,1057 +0,0 @@ -package art.arcane.iris.engine.mantle.components; - -import art.arcane.iris.builtin.carve.CaveFieldModule; -import art.arcane.iris.modules.carve.CaveProfile; -import art.arcane.iris.core.modules.CarveTestWorld; -import art.arcane.iris.modules.terrain.FluidPaletteSettings; -import art.arcane.iris.engine.framework.SeedManager; -import art.arcane.iris.engine.object.TestSettings; -import com.volmit.config.Range; -import com.volmit.geometry.BlockBox; -import com.volmit.mantle.CarvedVoid; -import com.volmit.mantle.MantleLayer; -import com.volmit.mantle.MantleVisitor; -import com.volmit.noise.NoiseSampler; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.atomic.AtomicReference; - -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 IrisCaveCarver3DNearParityTest { - private static final int SURFACE_CEILING_FADE_DEPTH = 12; - private static final double SURFACE_CEILING_SOLID_EPSILON = 0.000001D; - - private static Method sampleDensityMethod; - private static Method aquiferCandidateMethod; - private static final int MIN_HEIGHT = 0; - private static final int FLUID_HEIGHT = 64; - private static final int LAVA_HEIGHT = 18; - private static final long CARVE_SEED = new SeedManager(942_337_445L).getCarve(); - - private static Field profileField; - private static Field surfaceBreakDensityField; - private static Field thresholdNoiseField; - - @BeforeClass - public static void setupReflection() throws Exception { - sampleDensityMethod = IrisCaveCarver3D.class.getDeclaredMethod("sampleDensityOptimized", int.class, int.class, int.class); - sampleDensityMethod.setAccessible(true); - aquiferCandidateMethod = IrisCaveCarver3D.class.getDeclaredMethod("isAquiferCandidate", int.class, int.class, int.class, double.class); - aquiferCandidateMethod.setAccessible(true); - profileField = IrisCaveCarver3D.class.getDeclaredField("profile"); - profileField.setAccessible(true); - surfaceBreakDensityField = IrisCaveCarver3D.class.getDeclaredField("surfaceBreakDensity"); - surfaceBreakDensityField.setAccessible(true); - thresholdNoiseField = IrisCaveCarver3D.class.getDeclaredField("thresholdNoise"); - thresholdNoiseField.setAccessible(true); - } - - @Test - public void genericFluidContractKeepsOverworldDefaults() { - CaveProfile profile = new CaveProfile(); - assertTrue(profile.allowFluid()); - assertEquals(12, profile.fluidMinDepthBelowSurface()); - assertTrue(profile.fluidRequiresFloor()); - assertEquals("water", new FluidPaletteSettings().palette().palette().get(0).block()); - } - - @Test - public void carvedCellDistributionStableAcrossEquivalentCarvers() { - CarveWorld engine = createEngine(128, 92); - - IrisCaveCarver3D firstCarver = new IrisCaveCarver3D(engine, createProfile(true, true)); - WriterCapture firstCapture = createWriterCapture(128); - int firstCarved = firstCarver.carve(firstCapture.writer, 7, -3, fullWeights(), 0D, 0D, null, filledHeights(92)); - - IrisCaveCarver3D secondCarver = new IrisCaveCarver3D(engine, createProfile(true, true)); - WriterCapture secondCapture = createWriterCapture(128); - int secondCarved = secondCarver.carve(secondCapture.writer, 7, -3, fullWeights(), 0D, 0D, null, filledHeights(92)); - - assertTrue(firstCarved > 0); - assertEquals(firstCarved, secondCarved); - assertEquals(firstCapture.carvedCells, secondCapture.carvedCells); - assertEquals(firstCapture.carvedLiquids, secondCapture.carvedLiquids); - } - - @Test - public void warpCacheDoesNotCrossContaminateCarverInstancesOnSameThread() throws Exception { - CarveWorld engine = createEngine(128, 92); - CaveProfile firstProfile = createProfile(true, false); - TestSettings.with(firstProfile, "warpStyle", com.volmit.noise.NoiseStyle.of("SIMPLEX").withZoom(0.12D)); - CaveProfile secondProfile = createProfile(true, false); - TestSettings.with(secondProfile, "warpStyle", com.volmit.noise.NoiseStyle.of("CELLULAR").withZoom(0.12D)); - CaveProfile controlProfile = createProfile(true, false); - TestSettings.with(controlProfile, "warpStyle", com.volmit.noise.NoiseStyle.of("CELLULAR").withZoom(0.12D)); - IrisCaveCarver3D firstCarver = new IrisCaveCarver3D(engine, firstProfile); - IrisCaveCarver3D secondCarver = new IrisCaveCarver3D(engine, secondProfile); - IrisCaveCarver3D controlCarver = new IrisCaveCarver3D(engine, controlProfile); - int x = 48; - int y = 64; - int z = -352; - - double firstDensity = sampleDensity(firstCarver, x, y, z); - double secondDensity = sampleDensity(secondCarver, x, y, z); - AtomicReference controlDensity = new AtomicReference<>(); - AtomicReference controlFailure = new AtomicReference<>(); - Thread controlThread = new Thread(() -> { - try { - controlDensity.set(sampleDensity(controlCarver, x, y, z)); - } catch (Throwable throwable) { - controlFailure.set(throwable); - } - }, "Iris cave warp cache control"); - controlThread.start(); - controlThread.join(); - - if (controlFailure.get() != null) { - throw new AssertionError(controlFailure.get()); - } - assertNotEquals(firstDensity, controlDensity.get(), 0D); - assertEquals(controlDensity.get(), secondDensity, 0D); - } - - @Test - public void exactPathCarvesChunkEdgesAndRespectsWorldHeightClipping() { - CarveWorld engine = createEngine(48, 46); - IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, createProfile(true, true)); - WriterCapture capture = createWriterCapture(48); - double[] columnWeights = fullWeights(); - int[] precomputedSurfaceHeights = filledHeights(46); - - int carved = carver.carve(capture.writer, 0, 0, columnWeights, 0D, 0D, Range.of(0D, 80D), precomputedSurfaceHeights); - - assertTrue(carved > 0); - assertTrue(hasX(capture.carvedCells, 14)); - assertTrue(hasX(capture.carvedCells, 15)); - assertTrue(hasZ(capture.carvedCells, 14)); - assertTrue(hasZ(capture.carvedCells, 15)); - assertTrue(maxY(capture.carvedCells) <= 47); - assertTrue(minY(capture.carvedCells) >= 0); - } - - @Test - public void flatSurfaceDoesNotHardClipLargeCaveCeiling() { - assertFlatSurfaceCeiling(TestSettings.with(createFluidProfile(), "verticalRange", com.volmit.config.Range.of(20D, 72D), "allowSurfaceBreak", false, "surfaceClearance", 5, "allowFluid", false, "allowLava", false, "adaptiveSampling", false, "sampleStep", 1)); - assertFlatSurfaceCeiling(TestSettings.with(createFluidProfile(), "verticalRange", com.volmit.config.Range.of(20D, 72D), "allowSurfaceBreak", false, "surfaceClearance", 5, "allowFluid", false, "allowLava", false, "adaptiveSampling", true, "sampleStep", 1)); - } - - @Test - public void exactPathMatchesNaiveReferenceWithoutWarpOrModules() throws Exception { - assertExactParity(false, false, false); - } - - @Test - public void exactPathMatchesNaiveReferenceWithWarpAndModules() throws Exception { - assertExactParity(true, true, false); - } - - @Test - public void legacySampleStepTwoMatchesExactReference() throws Exception { - CarveWorld engine = createEngine(96, 90); - double[] columnWeights = fullWeights(); - int[] precomputedSurfaceHeights = filledHeights(90); - Range worldYRange = Range.of(0D, 88D); - - CaveProfile exactProfile = TestSettings.with(createProfile(true, true), "sampleStep", 1, "adaptiveSampling", false); - IrisCaveCarver3D exactCarver = new IrisCaveCarver3D(engine, exactProfile); - WriterCapture exactCapture = createWriterCapture(96); - int exactCarved = exactCarver.carve(exactCapture.writer, 5, -1, columnWeights, 0D, 0D, worldYRange, precomputedSurfaceHeights); - - CaveProfile legacyProfile = TestSettings.with(createProfile(true, true), "sampleStep", 2, "adaptiveSampling", false); - IrisCaveCarver3D legacyCarver = new IrisCaveCarver3D(engine, legacyProfile); - WriterCapture legacyCapture = createWriterCapture(96); - int legacyCarved = legacyCarver.carve(legacyCapture.writer, 5, -1, columnWeights, 0D, 0D, worldYRange, precomputedSurfaceHeights); - - assertEquals(exactCarved, legacyCarved); - assertEquals(exactCapture.carvedCells, legacyCapture.carvedCells); - assertEquals(exactCapture.carvedLiquids, legacyCapture.carvedLiquids); - } - - @Test - public void exactPathUsesExpectedLavaAndForcedAirBands() { - CarveWorld engine = createEngine(48, 46); - double[] columnWeights = fullWeights(); - int[] precomputedSurfaceHeights = filledHeights(46); - - CaveProfile lavaProfile = TestSettings.with(createProfile(false, false), "allowLava", true, "allowFluid", false); - IrisCaveCarver3D lavaCarver = new IrisCaveCarver3D(engine, lavaProfile); - WriterCapture lavaCapture = createWriterCapture(48); - lavaCarver.carve(lavaCapture.writer, 0, 0, columnWeights, 0D, 0D, Range.of(0D, 80D), precomputedSurfaceHeights); - - CaveProfile forcedAirProfile = TestSettings.with(createProfile(false, false), "allowLava", false, "allowFluid", false); - IrisCaveCarver3D forcedAirCarver = new IrisCaveCarver3D(engine, forcedAirProfile); - WriterCapture forcedAirCapture = createWriterCapture(48); - forcedAirCarver.carve(forcedAirCapture.writer, 0, 0, columnWeights, 0D, 0D, Range.of(0D, 80D), precomputedSurfaceHeights); - - assertTrue(containsLiquidInRange(lavaCapture.carvedLiquids, 0, 18, (byte) 2)); - assertTrue(containsLiquidInRange(forcedAirCapture.carvedLiquids, 0, 18, (byte) 3)); - assertTrue(containsLiquidInRange(lavaCapture.carvedLiquids, 19, 47, (byte) 0)); - assertTrue(containsLiquidInRange(forcedAirCapture.carvedLiquids, 19, 47, (byte) 0)); - } - - @Test - public void fluidPrecedesForcedAirWhenLavaIsDisabled() { - CarveWorld engine = createEngine(48, 46); - int[] surfaceHeights = filledHeights(46); - CaveProfile wetProfile = TestSettings.with(createFluidProfile(), "verticalRange", com.volmit.config.Range.of(2D, 18D), "allowLava", false, "fluidRequiresFloor", false); - WriterCapture wetCapture = createWriterCapture(48); - new IrisCaveCarver3D(engine, wetProfile).carve( - wetCapture.writer, 0, 0, fullWeights(), 0D, 0D, null, surfaceHeights); - - CaveProfile dryProfile = TestSettings.with(createFluidProfile(), "verticalRange", com.volmit.config.Range.of(2D, 18D), "allowFluid", false, "allowLava", false, "fluidRequiresFloor", false); - WriterCapture dryCapture = createWriterCapture(48); - new IrisCaveCarver3D(engine, dryProfile).carve( - dryCapture.writer, 0, 0, fullWeights(), 0D, 0D, null, surfaceHeights); - - assertEquals(wetCapture.carvedCells, dryCapture.carvedCells); - assertTrue(containsLiquidInRange(wetCapture.carvedLiquids, 2, 18, (byte) 1)); - assertTrue(containsLiquidInRange(wetCapture.carvedLiquids, 2, 18, (byte) 3)); - assertEquals(0, countLiquid(dryCapture, (byte) 1)); - assertTrue(containsLiquidInRange(dryCapture.carvedLiquids, 2, 18, (byte) 3)); - } - - @Test - public void fluidToggleAndMinimumDepthUseEachColumnsTerrainSurface() { - CarveWorld engine = createEngine(80, 70); - int[] surfaceHeights = splitSurfaceHeights(40, 70); - - CaveProfile enabledProfile = TestSettings.with(createFluidProfile(), "allowFluid", true, "fluidMinDepthBelowSurface", 10); - WriterCapture enabledCapture = createWriterCapture(80); - new IrisCaveCarver3D(engine, enabledProfile).carve( - enabledCapture.writer, 0, 0, fullWeights(), 0D, 0D, null, surfaceHeights); - - CaveProfile disabledProfile = TestSettings.with(createFluidProfile(), "allowFluid", false, "fluidMinDepthBelowSurface", 10); - WriterCapture disabledCapture = createWriterCapture(80); - new IrisCaveCarver3D(engine, disabledProfile).carve( - disabledCapture.writer, 0, 0, fullWeights(), 0D, 0D, null, surfaceHeights); - - assertEquals(enabledCapture.carvedCells, disabledCapture.carvedCells); - assertTrue(countLiquid(enabledCapture, (byte) 1) > 0); - assertEquals(0, countLiquid(disabledCapture, (byte) 1)); - assertFluidRespectsSplitCutoff(enabledCapture, 30, 60); - assertTrue(enabledCapture.carvedCells.contains(cellKey(0, 40, 0))); - assertTrue(enabledCapture.carvedCells.contains(cellKey(15, 70, 0))); - } - - @Test - public void dimensionFluidHeightCapsFluidIntent() { - CarveWorld engine = createEngine(80, 70); - CaveProfile profile = TestSettings.with(createFluidProfile(), "fluidMinDepthBelowSurface", 0); - WriterCapture capture = createWriterCapture(80); - - new IrisCaveCarver3D(engine, profile).carve( - capture.writer, 0, 0, fullWeights(), 0D, 0D, null, filledHeights(70)); - - assertTrue(countLiquid(capture, (byte) 1) > 0); - assertLiquidAtOrBelow(capture, (byte) 1, 64); - assertTrue(containsLiquidInRange(capture.carvedLiquids, 65, 70, (byte) 0)); - } - - @Test - public void surfaceFluidBoundaryProtectsReservoirWithoutFloodingDeeperCaves() { - assertSurfaceFluidBoundaryForProfile(TestSettings.with(createFluidProfile(), "adaptiveSampling", false, "sampleStep", 1)); - assertSurfaceFluidBoundaryForProfile(TestSettings.with(createFluidProfile(), "adaptiveSampling", true, "sampleStep", 1)); - assertSurfaceFluidBoundaryForProfile(TestSettings.with(createFluidProfile(), "adaptiveSampling", false, "sampleStep", 4)); - } - - @Test - public void floorRequiredFluidResolvesAfterTheCompleteCarveMask() { - CarveWorld engine = createEngine(80, 70); - int[] surfaceHeights = filledHeights(70); - int chunkX = -8; - int chunkZ = -1; - - com.volmit.noise.StyledRange cupThreshold = com.volmit.noise.StyledRange.of(0.15D, 0.15D, com.volmit.noise.NoiseStyle.of("FLAT")); - CaveProfile supportedProfile = TestSettings.with(createFluidProfile(), "densityThreshold", cupThreshold, "fluidMinDepthBelowSurface", 0, "fluidRequiresFloor", true); - WriterCapture firstCapture = createWriterCapture(80); - CaveFluidSupportPlan supportPlan = new CaveFluidSupportPlan(); - new IrisCaveCarver3D(engine, supportedProfile).carve( - firstCapture.writer, chunkX, chunkZ, fullWeights(), 0D, 0D, null, surfaceHeights, null, null, supportPlan); - int candidateCount = countLiquid(firstCapture, (byte) 1); - supportPlan.resolve(firstCapture.writer, chunkX << 4, chunkZ << 4, firstCapture.worldHeight); - - CaveProfile repeatedProfile = TestSettings.with(createFluidProfile(), "densityThreshold", cupThreshold, "fluidMinDepthBelowSurface", 0, "fluidRequiresFloor", true); - WriterCapture secondCapture = createWriterCapture(80); - new IrisCaveCarver3D(engine, repeatedProfile).carve( - secondCapture.writer, chunkX, chunkZ, fullWeights(), 0D, 0D, null, surfaceHeights); - - CaveProfile unrestrictedProfile = TestSettings.with(createFluidProfile(), "densityThreshold", cupThreshold, "fluidMinDepthBelowSurface", 0, "fluidRequiresFloor", false); - WriterCapture unrestrictedCapture = createWriterCapture(80); - new IrisCaveCarver3D(engine, unrestrictedProfile).carve( - unrestrictedCapture.writer, chunkX, chunkZ, fullWeights(), 0D, 0D, null, surfaceHeights); - - assertTrue(candidateCount > 0); - assertEquals(firstCapture.carvedLiquids, secondCapture.carvedLiquids); - assertTrue(countLiquid(firstCapture, (byte) 1) > 0); - assertTrue(countLiquid(firstCapture, (byte) 1) < countLiquid(unrestrictedCapture, (byte) 1)); - assertFluidCellsHaveSolidSupport(firstCapture); - } - - @Test - public void finalFluidSupportRejectsUnknownNeighborChunkEdges() { - WriterCapture capture = createWriterCapture(80); - int y = 56; - int z = 8; - capture.writer.set(0, y, z, CarvedVoid.FLUID); - capture.writer.set(8, y, z, CarvedVoid.FLUID); - CaveFluidSupportPlan supportPlan = new CaveFluidSupportPlan(); - supportPlan.add(0, y, z); - supportPlan.add(8, y, z); - - supportPlan.resolve(capture.writer, 0, 0, capture.worldHeight); - - assertEquals(Byte.valueOf((byte) 0), capture.carvedLiquids.get(cellKey(0, y, z))); - assertEquals(Byte.valueOf((byte) 1), capture.carvedLiquids.get(cellKey(8, y, z))); - } - - @Test - public void floorRequiredFluidSeesLaterProfileCarvePasses() { - CarveWorld engine = createEngine(80, 70); - int[] surfaceHeights = filledHeights(70); - int chunkX = -8; - int chunkZ = -1; - WriterCapture capture = createWriterCapture(80); - CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan(); - CaveProfile fluidProfile = TestSettings.with(createFluidProfile(), "densityThreshold", com.volmit.noise.StyledRange.of(0.15D, 0.15D, com.volmit.noise.NoiseStyle.of("FLAT")), "fluidMinDepthBelowSurface", 0, "fluidRequiresFloor", true); - CaveProfile airProfile = TestSettings.with(createFluidProfile(), "allowFluid", false); - - new IrisCaveCarver3D(engine, fluidProfile).carve( - capture.writer, chunkX, chunkZ, fullWeights(), 0D, 0D, null, surfaceHeights, - null, Range.of(20D, 64D), fluidSupportPlan); - String fluidCell = firstCellWithLiquid(capture, (byte) 1); - assertTrue(fluidCell != null); - int fluidY = coordinate(fluidCell, 1); - new IrisCaveCarver3D(engine, airProfile).carve( - capture.writer, chunkX, chunkZ, fullWeights(), 0D, 0D, null, surfaceHeights, - null, Range.of(fluidY - 1D, fluidY - 1D), fluidSupportPlan); - - assertEquals(Byte.valueOf((byte) 1), capture.carvedLiquids.get(fluidCell)); - fluidSupportPlan.resolve(capture.writer, chunkX << 4, chunkZ << 4, capture.worldHeight); - assertEquals(Byte.valueOf((byte) 0), capture.carvedLiquids.get(fluidCell)); - } - - @Test - public void optimizedExactPathOutperformsNaiveReference() throws Exception { - CarveWorld engine = createEngine(128, 92); - IrisCaveCarver3D optimizedCarver = new IrisCaveCarver3D(engine, TestSettings.with(createProfile(true, true), "adaptiveSampling", false)); - IrisCaveCarver3D naiveCarver = new IrisCaveCarver3D(engine, TestSettings.with(createProfile(true, true), "adaptiveSampling", false)); - double[] columnWeights = fullWeights(); - int[] precomputedSurfaceHeights = filledHeights(92); - Range worldYRange = Range.of(0D, 96D); - - for (int warmup = 0; warmup < 4; warmup++) { - runOptimizedOnce(optimizedCarver, 3, -2, columnWeights, worldYRange, precomputedSurfaceHeights, 128); - runNaiveOnce(naiveCarver, 3, -2, columnWeights, worldYRange, precomputedSurfaceHeights, 128); - } - - long optimizedTime = Long.MAX_VALUE; - long naiveTime = Long.MAX_VALUE; - for (int iteration = 0; iteration < 10; iteration++) { - if ((iteration & 1) == 0) { - optimizedTime = Math.min(optimizedTime, runOptimizedOnce(optimizedCarver, 3, -2, columnWeights, worldYRange, precomputedSurfaceHeights, 128)); - naiveTime = Math.min(naiveTime, runNaiveOnce(naiveCarver, 3, -2, columnWeights, worldYRange, precomputedSurfaceHeights, 128)); - continue; - } - - naiveTime = Math.min(naiveTime, runNaiveOnce(naiveCarver, 3, -2, columnWeights, worldYRange, precomputedSurfaceHeights, 128)); - optimizedTime = Math.min(optimizedTime, runOptimizedOnce(optimizedCarver, 3, -2, columnWeights, worldYRange, precomputedSurfaceHeights, 128)); - } - - // Fastest of ten alternating runs, not the sum: one scheduling hiccup decides a summed comparison. - // The bar is deliberately well under the measured ratio; a loaded machine reaches 1.6x while a - // regression that drops the skip logic lands at 1.0x, which is what this guard has to catch. - double speedup = naiveTime / (double) optimizedTime; - assertTrue("expected at least 1.4x speedup but was " + speedup, speedup >= 1.4D); - } - - @Test - public void adaptivePathStaysNearExactReferenceWithWarpAndModules() throws Exception { - CarveWorld engine = createEngine(96, 90); - double[] columnWeights = fullWeights(); - int[] precomputedSurfaceHeights = filledHeights(90); - Range worldYRange = Range.of(0D, 88D); - - IrisCaveCarver3D adaptiveCarver = new IrisCaveCarver3D(engine, TestSettings.with(createProfile(true, true), "adaptiveSampling", true)); - WriterCapture adaptiveCapture = createWriterCapture(96); - int adaptiveCarved = adaptiveCarver.carve(adaptiveCapture.writer, 5, -1, columnWeights, 0D, 0D, worldYRange, precomputedSurfaceHeights); - - IrisCaveCarver3D exactCarver = new IrisCaveCarver3D(engine, TestSettings.with(createProfile(true, true), "adaptiveSampling", false)); - WriterCapture exactCapture = createWriterCapture(96); - int exactCarved = exactCarver.carve(exactCapture.writer, 5, -1, columnWeights, 0D, 0D, worldYRange, precomputedSurfaceHeights); - - Set differingCells = new HashSet<>(adaptiveCapture.carvedCells); - differingCells.addAll(exactCapture.carvedCells); - Set sharedCells = new HashSet<>(adaptiveCapture.carvedCells); - sharedCells.retainAll(exactCapture.carvedCells); - differingCells.removeAll(sharedCells); - - int baselineCells = Math.max(1, exactCapture.carvedCells.size()); - double carveDeltaRatio = Math.abs(adaptiveCarved - exactCarved) / (double) baselineCells; - double differingRatio = differingCells.size() / (double) baselineCells; - assertTrue("expected carve count delta below 2.5% but was " + carveDeltaRatio, carveDeltaRatio <= 0.025D); - assertTrue("expected carved cell delta below 3.5% but was " + differingRatio, differingRatio <= 0.035D); - } - - private void assertFlatSurfaceCeiling(CaveProfile profile) { - CarveWorld engine = createEngine(96, 72); - WriterCapture capture = createWriterCapture(96); - - new IrisCaveCarver3D(engine, profile).carve( - capture.writer, 0, 0, fullWeights(), 0D, 0D, null, filledHeights(72)); - - int[] ceilingYByColumn = new int[256]; - Arrays.fill(ceilingYByColumn, Integer.MIN_VALUE); - for (String cell : capture.carvedCells) { - int localX = coordinate(cell, 0); - int y = coordinate(cell, 1); - int localZ = coordinate(cell, 2); - int columnIndex = (localX << 4) | localZ; - ceilingYByColumn[columnIndex] = Math.max(ceilingYByColumn[columnIndex], y); - } - - Map ceilingPlaneCounts = new HashMap<>(); - int largestPlane = 0; - for (int ceilingY : ceilingYByColumn) { - assertTrue(ceilingY != Integer.MIN_VALUE); - assertTrue(ceilingY <= 67); - int planeCount = ceilingPlaneCounts.merge(ceilingY, 1, Integer::sum); - largestPlane = Math.max(largestPlane, planeCount); - } - - assertTrue("expected at least three ceiling levels but found " + ceilingPlaneCounts, - ceilingPlaneCounts.size() >= 3); - assertTrue("expected no dominant ceiling plane but found " + ceilingPlaneCounts, - largestPlane < 192); - } - - private void assertExactParity(boolean warp, boolean modules, boolean adaptiveSampling) throws Exception { - CarveWorld engine = createEngine(96, 90); - double[] columnWeights = fullWeights(); - int[] precomputedSurfaceHeights = filledHeights(90); - Range worldYRange = Range.of(0D, 88D); - - IrisCaveCarver3D optimizedCarver = new IrisCaveCarver3D(engine, TestSettings.with(createProfile(warp, modules), "adaptiveSampling", adaptiveSampling)); - WriterCapture optimizedCapture = createWriterCapture(96); - int optimizedCarved = optimizedCarver.carve(optimizedCapture.writer, 5, -1, columnWeights, 0D, 0D, worldYRange, precomputedSurfaceHeights); - - IrisCaveCarver3D naiveCarver = new IrisCaveCarver3D(engine, TestSettings.with(createProfile(warp, modules), "adaptiveSampling", false)); - WriterCapture naiveCapture = createWriterCapture(96); - int naiveCarved = carveNaiveExact(naiveCarver, naiveCapture.writer, 96, 5, -1, columnWeights, worldYRange, precomputedSurfaceHeights); - - assertEquals(optimizedCarved, naiveCarved); - assertEquals(optimizedCapture.carvedCells, naiveCapture.carvedCells); - assertEquals(optimizedCapture.carvedLiquids, naiveCapture.carvedLiquids); - } - - private long runOptimizedOnce(IrisCaveCarver3D carver, int chunkX, int chunkZ, double[] columnWeights, Range worldYRange, int[] precomputedSurfaceHeights, int worldHeight) { - WriterCapture capture = createWriterCapture(worldHeight); - long start = System.nanoTime(); - carver.carve(capture.writer, chunkX, chunkZ, columnWeights, 0D, 0D, worldYRange, precomputedSurfaceHeights); - long elapsed = System.nanoTime() - start; - assertTrue(!capture.carvedCells.isEmpty()); - return elapsed; - } - - private double sampleDensity(IrisCaveCarver3D carver, int x, int y, int z) throws Exception { - return (double) sampleDensityMethod.invoke(carver, x, y, z); - } - - private long runNaiveOnce(IrisCaveCarver3D carver, int chunkX, int chunkZ, double[] columnWeights, Range worldYRange, int[] precomputedSurfaceHeights, int worldHeight) throws Exception { - WriterCapture capture = createWriterCapture(worldHeight); - long start = System.nanoTime(); - int carved = carveNaiveExact(carver, capture.writer, worldHeight, chunkX, chunkZ, columnWeights, worldYRange, precomputedSurfaceHeights); - long elapsed = System.nanoTime() - start; - assertTrue(carved > 0); - return elapsed; - } - - private int carveNaiveExact(IrisCaveCarver3D carver, MantleLayer writer, int worldHeight, int chunkX, int chunkZ, double[] columnWeights, Range worldYRange, int[] precomputedSurfaceHeights) throws Exception { - CaveProfile profile = (CaveProfile) profileField.get(carver); - NoiseSampler surfaceBreakDensity = (NoiseSampler) surfaceBreakDensityField.get(carver); - NoiseSampler thresholdNoise = (NoiseSampler) thresholdNoiseField.get(carver); - - double[] resolvedWeights = columnWeights; - if (resolvedWeights == null || resolvedWeights.length < 256) { - resolvedWeights = fullWeights(); - } - - int minY = Math.max(0, (int) Math.floor(profile.verticalRange().min())); - int maxY = Math.min(worldHeight - 1, (int) Math.ceil(profile.verticalRange().max())); - if (worldYRange != null) { - int rangeMinY = (int) Math.floor(worldYRange.min() - MIN_HEIGHT); - int rangeMaxY = (int) Math.ceil(worldYRange.max() - MIN_HEIGHT); - minY = Math.max(minY, rangeMinY); - maxY = Math.min(maxY, rangeMaxY); - } - if (maxY < minY) { - return 0; - } - - boolean allowSurfaceBreak = profile.allowSurfaceBreak(); - int surfaceClearance = Math.max(0, profile.surfaceClearance()); - int surfaceBreakDepth = Math.max(0, profile.surfaceBreakDepth()); - double surfaceBreakNoiseThreshold = profile.surfaceBreakNoiseThreshold(); - double surfaceBreakThresholdBoost = Math.max(0D, profile.surfaceBreakThresholdBoost()); - int[] columnTopY = new int[256]; - int[] surfaceBreakFloorY = new int[256]; - boolean[] surfaceBreakColumn = new boolean[256]; - boolean[] surfaceCeilingColumn = new boolean[256]; - int[] fluidMaxY = new int[256]; - double[] passThreshold = new double[256]; - double[] verticalEdgeFade = computeVerticalEdgeFade(profile, minY, maxY); - double[] surfaceClosureThreshold = computeSurfaceClosureThresholds(profile, minY, maxY); - CarvedVoid[] voidByY = computeVoidByY(profile, minY, maxY); - - int x0 = chunkX << 4; - int z0 = chunkZ << 4; - for (int localX = 0; localX < 16; localX++) { - int x = x0 + localX; - for (int localZ = 0; localZ < 16; localZ++) { - int z = z0 + localZ; - int columnIndex = (localX << 4) | localZ; - int columnSurfaceY = precomputedSurfaceHeights[columnIndex]; - - int unclampedClearanceTopY = columnSurfaceY - surfaceClearance; - int clearanceTopY = Math.min(maxY, Math.max(minY, unclampedClearanceTopY)); - boolean breakColumn = allowSurfaceBreak && surfaceBreakDensity.signed(x, z) >= surfaceBreakNoiseThreshold; - int resolvedTopY = breakColumn ? Math.min(maxY, Math.max(minY, columnSurfaceY)) : clearanceTopY; - columnTopY[columnIndex] = resolvedTopY; - fluidMaxY[columnIndex] = profile.allowFluid() - ? Math.min(FLUID_HEIGHT, columnSurfaceY - Math.max(0, profile.fluidMinDepthBelowSurface())) - : Integer.MIN_VALUE; - surfaceBreakFloorY[columnIndex] = Math.max(minY, columnSurfaceY - surfaceBreakDepth); - surfaceBreakColumn[columnIndex] = breakColumn; - surfaceCeilingColumn[columnIndex] = !breakColumn && unclampedClearanceTopY <= maxY; - double columnWeight = clampColumnWeight(resolvedWeights[columnIndex]); - if (columnWeight <= 0D || resolvedTopY < minY) { - passThreshold[columnIndex] = Double.NaN; - continue; - } - - passThreshold[columnIndex] = thresholdAt(profile, thresholdNoise, x, z) - profile.thresholdBias(); - } - } - - int carved = 0; - for (int localX = 0; localX < 16; localX++) { - int x = x0 + localX; - for (int localZ = 0; localZ < 16; localZ++) { - int z = z0 + localZ; - int columnIndex = (localX << 4) | localZ; - if (Double.isNaN(passThreshold[columnIndex])) { - continue; - } - - int topY = columnTopY[columnIndex]; - for (int y = minY; y <= topY; y++) { - double localThreshold = passThreshold[columnIndex]; - if (surfaceBreakColumn[columnIndex] && y >= surfaceBreakFloorY[columnIndex]) { - localThreshold += surfaceBreakThresholdBoost; - } - localThreshold -= verticalEdgeFade[y - minY]; - localThreshold = applySurfaceCeilingFade( - localThreshold, - surfaceCeilingColumn[columnIndex], - topY, - y, - minY, - surfaceClosureThreshold - ); - - double density = (double) sampleDensityMethod.invoke(carver, x, y, z); - if (density > localThreshold) { - continue; - } - - CarvedVoid verticalVoid = voidByY[y - minY]; - boolean aquifer = verticalVoid == CarvedVoid.OPEN - && y <= fluidMaxY[columnIndex] - && (boolean) aquiferCandidateMethod.invoke(carver, x, y, z, localThreshold); - writer.set(x, y, z, aquifer ? CarvedVoid.FLUID : verticalVoid); - carved++; - } - } - } - - return carved; - } - - /** The density threshold at the column the way a styled range picks it. */ - private double thresholdAt(CaveProfile profile, NoiseSampler thresholdNoise, int x, int z) { - com.volmit.noise.StyledRange range = profile.densityThreshold(); - if (range.min() == range.max()) { - return range.min(); - } - if (com.volmit.noise.NoiseStyle.FLAT.equals(range.style().style())) { - return art.arcane.volmlib.util.math.M.lerp(range.min(), range.max(), 0.5); - } - return range.min() + (thresholdNoise.sample(x, z) * (range.max() - range.min())); - } - - private double applySurfaceCeilingFade( - double threshold, - boolean surfaceCeilingColumn, - int columnTopY, - int y, - int minY, - double[] surfaceClosureThreshold - ) { - if (!surfaceCeilingColumn) { - return threshold; - } - - int ceilingDistance = columnTopY - y; - if (ceilingDistance < 0 || ceilingDistance >= SURFACE_CEILING_FADE_DEPTH) { - return threshold; - } - - double closureThreshold = surfaceClosureThreshold[y - minY]; - if (threshold <= closureThreshold) { - return threshold; - } - - double progress = ceilingDistance / (double) SURFACE_CEILING_FADE_DEPTH; - double smooth = progress * progress * (3D - (2D * progress)); - return closureThreshold + ((threshold - closureThreshold) * smooth); - } - - private double[] computeSurfaceClosureThresholds(CaveProfile profile, int minY, int maxY) { - double normalization = Math.abs(profile.baseWeight()) + Math.abs(profile.detailWeight()); - for (CaveFieldModule module : profile.modules()) { - normalization += Math.abs(module.weight()); - } - if (normalization <= 0D) { - normalization = 1D; - } - - double[] thresholds = new double[Math.max(0, maxY - minY + 1)]; - double baseMinimum = -Math.abs(profile.baseWeight()) - Math.abs(profile.detailWeight()); - for (int y = minY; y <= maxY; y++) { - double minimumDensity = baseMinimum; - for (CaveFieldModule module : profile.modules()) { - Range range = module.verticalRange(); - if (y < Math.floor(range.min()) || y > Math.ceil(range.max())) { - continue; - } - double rawMinimum = module.invert() - ? module.threshold() - 1D - : -1D - module.threshold(); - double rawMaximum = module.invert() - ? module.threshold() + 1D - : 1D - module.threshold(); - minimumDensity += Math.min(rawMinimum * module.weight(), rawMaximum * module.weight()); - } - thresholds[y - minY] = (minimumDensity / normalization) - SURFACE_CEILING_SOLID_EPSILON; - } - return thresholds; - } - - private double[] computeVerticalEdgeFade(CaveProfile profile, int minY, int maxY) { - int size = Math.max(0, maxY - minY + 1); - double[] verticalEdgeFade = new double[size]; - int fadeRange = Math.max(0, profile.verticalEdgeFade()); - double fadeStrength = Math.max(0D, profile.verticalEdgeFadeStrength()); - if (size == 0 || fadeRange <= 0 || maxY <= minY || fadeStrength <= 0D) { - return verticalEdgeFade; - } - - for (int y = minY; y <= maxY; y++) { - int floorDistance = y - minY; - int ceilingDistance = maxY - y; - int edgeDistance = Math.min(floorDistance, ceilingDistance); - int offsetIndex = y - minY; - if (edgeDistance >= fadeRange) { - continue; - } - - double t = Math.max(0D, Math.min(1D, edgeDistance / (double) fadeRange)); - double smooth = t * t * (3D - (2D * t)); - verticalEdgeFade[offsetIndex] = (1D - smooth) * fadeStrength; - } - - return verticalEdgeFade; - } - - private CarvedVoid[] computeVoidByY(CaveProfile profile, int minY, int maxY) { - CarvedVoid[] voidByY = new CarvedVoid[Math.max(0, maxY - minY + 1)]; - boolean allowLava = profile.allowLava(); - int lavaHeight = LAVA_HEIGHT; - - for (int y = minY; y <= maxY; y++) { - int offset = y - minY; - if (allowLava && y <= lavaHeight) { - voidByY[offset] = CarvedVoid.LAVA; - continue; - } - if (!allowLava && y <= lavaHeight) { - voidByY[offset] = CarvedVoid.AIR; - continue; - } - - voidByY[offset] = CarvedVoid.OPEN; - } - - return voidByY; - } - - private CarveWorld createEngine(int worldHeight, int sampledHeight) { - CarveTestWorld world = new CarveTestWorld(); - return new CarveWorld(world.resources().noise(), CARVE_SEED, worldHeight, FLUID_HEIGHT, LAVA_HEIGHT, MIN_HEIGHT); - } - - private CaveProfile createProfile(boolean warp, boolean modules) { - CaveProfile profile = new CaveProfile(); - TestSettings.with(profile, "enabled", true); - TestSettings.with(profile, "verticalRange", com.volmit.config.Range.of(0D, 120D)); - TestSettings.with(profile, "verticalEdgeFade", 14); - TestSettings.with(profile, "verticalEdgeFadeStrength", 0.21D); - TestSettings.with(profile, "baseDensityStyle", com.volmit.noise.NoiseStyle.of("SIMPLEX").withZoom(0.07D)); - TestSettings.with(profile, "detailDensityStyle", com.volmit.noise.NoiseStyle.of("SIMPLEX").withZoom(0.17D)); - TestSettings.with(profile, "warpStyle", com.volmit.noise.NoiseStyle.of("SIMPLEX").withZoom(0.12D)); - TestSettings.with(profile, "surfaceBreakStyle", com.volmit.noise.NoiseStyle.of("SIMPLEX").withZoom(0.09D)); - TestSettings.with(profile, "baseWeight", 1D); - TestSettings.with(profile, "detailWeight", 0.48D); - TestSettings.with(profile, "warpStrength", warp ? 0.37D : 0D); - TestSettings.with(profile, "densityThreshold", com.volmit.noise.StyledRange.of(1D, 1D, com.volmit.noise.NoiseStyle.of("FLAT"))); - TestSettings.with(profile, "thresholdBias", 0D); - TestSettings.with(profile, "sampleStep", 1); - TestSettings.with(profile, "surfaceClearance", 5); - TestSettings.with(profile, "allowSurfaceBreak", true); - TestSettings.with(profile, "surfaceBreakNoiseThreshold", 0.16D); - TestSettings.with(profile, "surfaceBreakDepth", 12); - TestSettings.with(profile, "surfaceBreakThresholdBoost", 0.17D); - TestSettings.with(profile, "allowFluid", true); - TestSettings.with(profile, "fluidMinDepthBelowSurface", 8); - TestSettings.with(profile, "fluidRequiresFloor", false); - TestSettings.with(profile, "allowLava", true); - if (modules) { - TestSettings.with(profile, "modules", List.of( - TestSettings.of(CaveFieldModule.class, "{\"style\": {\"style\": \"SIMPLEX\", \"zoom\": 0.11}, \"weight\": 0.23," - + " \"threshold\": 0.04, \"verticalRange\": {\"min\": 0, \"max\": 72}, \"invert\": false}"), - TestSettings.of(CaveFieldModule.class, "{\"style\": {\"style\": \"SIMPLEX\", \"zoom\": 0.19}, \"weight\": 0.17," - + " \"threshold\": -0.06, \"verticalRange\": {\"min\": 24, \"max\": 120}, \"invert\": true}"))); - } else { - TestSettings.with(profile, "modules", List.of()); - } - return profile; - } - - private CaveProfile createFluidProfile() { - return TestSettings.with(createProfile(false, false), "verticalRange", com.volmit.config.Range.of(20D, 70D), "verticalEdgeFade", 0, "verticalEdgeFadeStrength", 0D, "densityThreshold", com.volmit.noise.StyledRange.of(2D, 2D, com.volmit.noise.NoiseStyle.of("FLAT")), "adaptiveSampling", false, "surfaceClearance", 5, "allowSurfaceBreak", true, "surfaceBreakNoiseThreshold", -1D, "surfaceBreakThresholdBoost", 0D, "allowFluid", true, "fluidRequiresFloor", false, "allowLava", true); - } - - private void assertSurfaceFluidBoundaryForProfile(CaveProfile profile) { - CarveWorld engine = createEngine(80, 70); - int[] surfaceHeights = filledHeights(70); - surfaceHeights[0] = 60; - int[] boundaryStartY = new int[256]; - Arrays.fill(boundaryStartY, SurfaceFluidBoundaryPlan.NO_BOUNDARY); - boundaryStartY[0] = 60; - boundaryStartY[16] = 61; - WriterCapture capture = createWriterCapture(80); - CaveFluidSupportPlan supportPlan = new CaveFluidSupportPlan(); - - new IrisCaveCarver3D(engine, TestSettings.with(profile, "fluidMinDepthBelowSurface", 0, "fluidRequiresFloor", false)).carve( - capture.writer, - 0, - 0, - fullWeights(), - 0D, - 0D, - null, - surfaceHeights, - boundaryStartY, - null, - supportPlan - ); - - assertTrue(capture.carvedCells.contains(cellKey(0, 56, 0))); - assertFalse(capture.carvedCells.contains(cellKey(0, 60, 0))); - assertTrue(capture.carvedCells.contains(cellKey(1, 60, 0))); - for (int y = 61; y <= 64; y++) { - assertFalse(capture.carvedCells.contains(cellKey(1, y, 0))); - } - assertTrue(capture.carvedCells.contains(cellKey(1, 65, 0))); - assertTrue(capture.carvedCells.contains(cellKey(2, 64, 0))); - assertTrue(countLiquid(capture, (byte) 1) > 0); - assertTrue(countLiquid(capture, (byte) 0) > 0); - } - - private WriterCapture createWriterCapture(int worldHeight) { - Set carvedCells = new HashSet<>(); - Map carvedLiquids = new HashMap<>(); - return new WriterCapture(new CapturingVoids(carvedCells, carvedLiquids), worldHeight, carvedCells, carvedLiquids); - } - - /** The carved voids of one chunk, recorded by the chunk's local X and Z and the height, with the carver's liquid code of each fill. */ - private static final class CapturingVoids implements MantleLayer { - private final Map voids = new HashMap<>(); - private final Set carvedCells; - private final Map carvedLiquids; - - private CapturingVoids(Set carvedCells, Map carvedLiquids) { - this.carvedCells = carvedCells; - this.carvedLiquids = carvedLiquids; - } - - @Override - public CarvedVoid get(int x, int y, int z) { - return voids.get(position(x, y, z)); - } - - @Override - public void set(int x, int y, int z, CarvedVoid value) { - voids.put(position(x, y, z), value); - String cell = x - ((x >> 4) << 4) + ":" + y + ":" + (z - ((z >> 4) << 4)); - carvedCells.add(cell); - carvedLiquids.put(cell, liquidCode(value)); - } - - @Override - public void remove(int x, int y, int z) { - throw new UnsupportedOperationException(); - } - - @Override - public void visit(BlockBox area, MantleVisitor visitor) { - throw new UnsupportedOperationException(); - } - - @Override - public void clear(BlockBox area) { - throw new UnsupportedOperationException(); - } - - private static long position(int x, int y, int z) { - return ((long) x << 40) ^ ((long) y << 20) ^ (z & 0xfffffL); - } - - private static byte liquidCode(CarvedVoid value) { - return switch (value.fill()) { - case OPEN -> 0; - case FLUID -> 1; - case LAVA -> 2; - case AIR -> 3; - }; - } - } - - private double[] fullWeights() { - double[] columnWeights = new double[256]; - Arrays.fill(columnWeights, 1D); - return columnWeights; - } - - private int[] filledHeights(int height) { - int[] heights = new int[256]; - Arrays.fill(heights, height); - return heights; - } - - private int[] splitSurfaceHeights(int lowHeight, int highHeight) { - int[] heights = new int[256]; - for (int localX = 0; localX < 16; localX++) { - for (int localZ = 0; localZ < 16; localZ++) { - heights[(localX << 4) | localZ] = localX < 8 ? lowHeight : highHeight; - } - } - return heights; - } - - private void assertFluidCellsHaveSolidSupport(WriterCapture capture) { - for (Map.Entry entry : capture.carvedLiquids.entrySet()) { - if (entry.getValue() != 1) { - continue; - } - - String[] split = entry.getKey().split(":"); - int x = Integer.parseInt(split[0]); - int y = Integer.parseInt(split[1]); - int z = Integer.parseInt(split[2]); - assertFalse(capture.carvedCells.contains(cellKey(x, y - 1, z))); - assertFalse(capture.carvedCells.contains(cellKey(x, y - 2, z))); - int support = 0; - if (!capture.carvedCells.contains(cellKey(x + 1, y, z))) { - support++; - } - if (!capture.carvedCells.contains(cellKey(x - 1, y, z))) { - support++; - } - if (!capture.carvedCells.contains(cellKey(x, y, z + 1))) { - support++; - } - if (!capture.carvedCells.contains(cellKey(x, y, z - 1))) { - support++; - } - if (!capture.carvedCells.contains(cellKey(x, y + 1, z))) { - support++; - } - assertTrue(support >= 4); - } - } - - private void assertFluidRespectsSplitCutoff(WriterCapture capture, int lowCutoff, int highCutoff) { - boolean lowFluid = false; - boolean highFluid = false; - for (Map.Entry entry : capture.carvedLiquids.entrySet()) { - if (entry.getValue() != 1) { - continue; - } - int x = coordinate(entry.getKey(), 0); - int y = coordinate(entry.getKey(), 1); - if (x < 8) { - assertTrue(y <= lowCutoff); - lowFluid = true; - } else { - assertTrue(y <= highCutoff); - highFluid = true; - } - } - assertTrue(lowFluid); - assertTrue(highFluid); - } - - private void assertLiquidAtOrBelow(WriterCapture capture, byte liquid, int maxY) { - for (Map.Entry entry : capture.carvedLiquids.entrySet()) { - if (entry.getValue() == liquid) { - assertTrue(coordinate(entry.getKey(), 1) <= maxY); - } - } - } - - private int countLiquid(WriterCapture capture, byte liquid) { - int count = 0; - for (byte value : capture.carvedLiquids.values()) { - if (value == liquid) { - count++; - } - } - return count; - } - - private String firstCellWithLiquid(WriterCapture capture, byte liquid) { - for (Map.Entry entry : capture.carvedLiquids.entrySet()) { - if (entry.getValue() == liquid) { - return entry.getKey(); - } - } - return null; - } - - private int coordinate(String cell, int index) { - return Integer.parseInt(cell.split(":")[index]); - } - - private double clampColumnWeight(double weight) { - if (Double.isNaN(weight) || Double.isInfinite(weight)) { - return 0D; - } - if (weight <= 0D) { - return 0D; - } - if (weight >= 1D) { - return 1D; - } - return weight; - } - - private double signed(double value) { - return (value * 2D) - 1D; - } - - private int packLocal(int x, int y, int z) { - return (x << 8) | (y << 4) | z; - } - - private String cellKey(int x, int y, int z) { - return x + ":" + y + ":" + z; - } - - private boolean containsLiquidInRange(Map carvedLiquids, int minY, int maxY, byte liquid) { - for (Map.Entry entry : carvedLiquids.entrySet()) { - if (entry.getValue() != liquid) { - continue; - } - - String[] split = entry.getKey().split(":"); - int y = Integer.parseInt(split[1]); - if (y >= minY && y <= maxY) { - return true; - } - } - return false; - } - - private boolean hasX(Set carvedCells, int x) { - for (String cell : carvedCells) { - String[] split = cell.split(":"); - if (Integer.parseInt(split[0]) == x) { - return true; - } - } - - return false; - } - - private boolean hasZ(Set carvedCells, int z) { - for (String cell : carvedCells) { - String[] split = cell.split(":"); - if (Integer.parseInt(split[2]) == z) { - return true; - } - } - - return false; - } - - private int maxY(Set carvedCells) { - int max = Integer.MIN_VALUE; - for (String cell : carvedCells) { - String[] split = cell.split(":"); - int y = Integer.parseInt(split[1]); - if (y > max) { - max = y; - } - } - return max; - } - - private int minY(Set carvedCells) { - int min = Integer.MAX_VALUE; - for (String cell : carvedCells) { - String[] split = cell.split(":"); - int y = Integer.parseInt(split[1]); - if (y < min) { - min = y; - } - } - return min; - } - - private static final class WriterCapture { - private final MantleLayer writer; - private final int worldHeight; - private final Set carvedCells; - private final Map carvedLiquids; - - private WriterCapture(MantleLayer writer, int worldHeight, Set carvedCells, Map carvedLiquids) { - this.writer = writer; - this.worldHeight = worldHeight; - this.carvedCells = carvedCells; - this.carvedLiquids = carvedLiquids; - } - } -} diff --git a/core/src/test/java/art/arcane/iris/engine/modifier/CarvePipelineHarnessTest.java b/core/src/test/java/art/arcane/iris/engine/modifier/CarvePipelineHarnessTest.java index f83e0955b..d461a74d3 100644 --- a/core/src/test/java/art/arcane/iris/engine/modifier/CarvePipelineHarnessTest.java +++ b/core/src/test/java/art/arcane/iris/engine/modifier/CarvePipelineHarnessTest.java @@ -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 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 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} + """); } } diff --git a/core/src/test/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileDecodingTest.java b/core/src/test/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileDecodingTest.java deleted file mode 100644 index 5d2731bcc..000000000 --- a/core/src/test/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileDecodingTest.java +++ /dev/null @@ -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 . - */ - -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()); - } -} diff --git a/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySamplerTest.java b/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySamplerTest.java index 03db96dc8..1c6f586d8 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySamplerTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySamplerTest.java @@ -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)); diff --git a/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSampleBottomYTest.java b/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSampleBottomYTest.java index 8e8bf4832..0a56622be 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSampleBottomYTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSampleBottomYTest.java @@ -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 diff --git a/core/src/test/java/art/arcane/iris/modules/carve/field/CaveCarverTest.java b/core/src/test/java/art/arcane/iris/modules/carve/field/CaveCarverTest.java new file mode 100644 index 000000000..0b4e08fdc --- /dev/null +++ b/core/src/test/java/art/arcane/iris/modules/carve/field/CaveCarverTest.java @@ -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 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 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); + } + } +} diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/dimensions/overworld.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/dimensions/overworld.json index 2148a0e0e..65c116cdf 100644 --- a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/dimensions/overworld.json +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/dimensions/overworld.json @@ -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", diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/hot.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/hot.json index 9e0edb04d..2f058a4b4 100644 --- a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/hot.json +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/hot.json @@ -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", diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/mushroom.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/mushroom.json index 31699834b..f75c0a32e 100644 --- a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/mushroom.json +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/mushroom.json @@ -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", diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/swamp.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/swamp.json index a8e8a1893..652a3ee4f 100644 --- a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/swamp.json +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/swamp.json @@ -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", diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/terralost.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/terralost.json index a800c9030..fc7e7cdb6 100644 --- a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/terralost.json +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/terralost.json @@ -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", diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/biomes/carving/amethyst.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/biomes/carving/amethyst.json index b149cff46..e65d694f6 100644 --- a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/biomes/carving/amethyst.json +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/biomes/carving/amethyst.json @@ -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} diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/dimensions/overworld.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/dimensions/overworld.json index 4c4bc79ea..231945f4a 100644 --- a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/dimensions/overworld.json +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/dimensions/overworld.json @@ -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", diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/regions/forests.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/regions/forests.json index e24bc2fc9..380d00e5c 100644 --- a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/regions/forests.json +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/regions/forests.json @@ -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", diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/regions/magnetics.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/regions/magnetics.json index 84c8b16b5..ec8af9fb7 100644 --- a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/regions/magnetics.json +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/regions/magnetics.json @@ -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", diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/biomes/carving/polarity-grotto.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/biomes/carving/polarity-grotto.json index dd238072e..d2fcb0c34 100644 --- a/core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/biomes/carving/polarity-grotto.json +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/biomes/carving/polarity-grotto.json @@ -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", diff --git a/module/README.md b/module/README.md index 4d7fd8696..b1ef35b4a 100644 --- a/module/README.md +++ b/module/README.md @@ -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//` (folder `snippet/iris/carve/cave-profile/`), so a +Every built-in snippet is named under its module's id, `iris//` (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) diff --git a/module/src/main/java/art/arcane/iris/builtin/carve/CaveFieldModule.java b/module/src/main/java/art/arcane/iris/builtin/carve/CaveFieldModule.java deleted file mode 100644 index e2267807d..000000000 --- a/module/src/main/java/art/arcane/iris/builtin/carve/CaveFieldModule.java +++ /dev/null @@ -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 . - */ - -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; - } -} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarveScratch.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarveScratch.java deleted file mode 100644 index 80042c2a7..000000000 --- a/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarveScratch.java +++ /dev/null @@ -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 . - */ - -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; -} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java index 9054e62e2..57241329a 100644 --- a/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java @@ -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 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 = ThreadLocal.withInitial(Scratch::new); private final CarveWorld world; - private final DeclaredCaveProfiles declaredProfiles; - private final CarvingResolver resolver; + private final PackResources resources; + private final DeclaredByLevel lists; private final FluidColumns fluidColumns; - private final boolean upperDimensionCarving; - private final Object profileCarverLock = new Object(); - private volatile Map profileCarvers = new IdentityHashMap<>(); + private final ModuleLog log; + private final Map> caves = new ConcurrentHashMap<>(); + private final Map> listings = new ConcurrentHashMap<>(); + /** What every column lists when only the dimension lists caves, which spares reading the biomes around each chunk. */ + private final Map 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 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 voids, TerrainSampler terrain, int x, int z) { - BlendScratch blendScratch = BLEND_SCRATCH.get(); - int[] chunkSurfaceHeights = prepareChunkSurfaceHeights(x, z, terrain, blendScratch.chunkSurfaceHeights); - List 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 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 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 normalProfiles, - MantleLayer 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 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 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 resolveWeightedProfiles(int chunkX, int chunkZ, TerrainSampler terrain) { - BlendScratch blendScratch = BLEND_SCRATCH.get(); - CaveProfile[] profileField = blendScratch.profileField; - Map columnProfileWeights = blendScratch.columnProfileWeights; - IdentityHashMap activeProfiles = blendScratch.activeProfiles; - List 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 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 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 blendedProfiles = limitAndMergeBlendedProfiles(columnWeightedProfiles, MAX_BLENDED_PROFILE_PASSES, CHUNK_AREA); - List resolvedProfiles = resolveDimensionCarvingProfiles(chunkX, chunkZ, blendScratch); - resolvedProfiles.addAll(blendedProfiles); - return resolvedProfiles; - } - - private List resolveDimensionCarvingProfiles(int chunkX, int chunkZ, BlendScratch blendScratch) { - List weightedProfiles = new ArrayList<>(); - List entries = resolver.entries(); - if (entries.isEmpty()) { - return weightedProfiles; - } - - Map 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 rootProfileColumnWeights = new IdentityHashMap<>(); - List 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 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 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 weights = new TreeMap<>(); + for (Map.Entry 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 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 listingOf(ListingKey key) { + Set 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 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 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 limitAndMergeBlendedProfiles(List blendedProfiles, int maxProfiles) { - return limitAndMergeBlendedProfiles(blendedProfiles, maxProfiles, CHUNK_AREA); - } - - private static List limitAndMergeBlendedProfiles(List blendedProfiles, int maxProfiles, int areaSize) { - if (blendedProfiles == null || blendedProfiles.isEmpty()) { - return new ArrayList<>(); - } - - int clampedLimit = Math.max(1, maxProfiles); - List rankedProfiles = new ArrayList<>(blendedProfiles); - rankedProfiles.sort(CaveCarving::compareBySelectionRank); - List 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 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 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 columnProfileWeights = new IdentityHashMap<>(); - private final IdentityHashMap dimensionColumnPlans = new IdentityHashMap<>(); - private final IdentityHashMap activeProfiles = new IdentityHashMap<>(); - private final List 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]; } } diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveFieldModuleState.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveFieldModuleState.java deleted file mode 100644 index 392ac27ce..000000000 --- a/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveFieldModuleState.java +++ /dev/null @@ -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 . - */ - -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; - } -} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveFluidSupportPlan.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveFluidSupportPlan.java deleted file mode 100644 index da3cebfad..000000000 --- a/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveFluidSupportPlan.java +++ /dev/null @@ -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 . - */ - -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 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 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 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; - } -} diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveSettings.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveSettings.java index a62b89d82..b17e3ae1c 100644 --- a/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveSettings.java +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/CaveSettings.java @@ -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; } } diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java index 9314d32a6..77002896b 100644 --- a/module/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java @@ -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 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 caveSettings(ResourceId cave, ResourceId surface, SettingsStack declared, Class 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 placements, CaveProfile profile, + private void placeCaveScope(Tally tally, String scope, List 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 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 scopes = new java.util.LinkedHashMap<>(); diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java index a192f25cd..7efcab4cd 100644 --- a/module/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java @@ -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 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(); diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java deleted file mode 100644 index f59d5e366..000000000 --- a/module/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java +++ /dev/null @@ -1,2268 +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 . - */ - -package art.arcane.iris.engine.mantle.components; - -import art.arcane.iris.builtin.carve.CaveFieldModule; -import art.arcane.iris.modules.carve.CaveProfile; -import art.arcane.volmlib.util.math.M; -import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; -import com.volmit.config.Range; -import com.volmit.mantle.CarvedVoid; -import com.volmit.mantle.MantleLayer; -import com.volmit.noise.NoiseSampler; -import com.volmit.noise.NoiseStyle; -import com.volmit.noise.StyledRange; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class IrisCaveCarver3D { - private static final int LOCAL_MASK = 15; - private static final int ADAPTIVE_MIN_PLANE_COLUMNS = 16; - private static final int ADAPTIVE_DEEP_SAMPLE_STEP = 8; - private static final double ADAPTIVE_LOCAL_RANGE_SCALE = 0.125D; - private static final double ADAPTIVE_DEEP_MARGIN_BOOST = 0.015D; - private static final int SURFACE_CEILING_FADE_DEPTH = 12; - private static final double SURFACE_CEILING_SOLID_EPSILON = 0.000001D; - - private final CaveProfile profile; - private final NoiseSampler baseDensity; - private final NoiseSampler detailDensity; - private final NoiseSampler warpDensity; - private final NoiseSampler surfaceBreakDensity; - private final NoiseSampler thresholdNoise; - private final int lavaHeight; - private final CaveFieldModuleState[] modules; - private final double inverseNormalization; - private final double normalizationFactor; - private final double baseWeight; - private final double detailWeight; - private final double detailMinContribution; - private final double detailMaxContribution; - private final double warpStrength; - private final boolean hasWarp; - private final boolean hasModules; - private final int warpResolution; - private final boolean allowFluid; - private final boolean fluidRequiresFloor; - private final int fluidMinDepthBelowSurface; - private final int fluidHeight; - private final int aquiferCeilingY; - private final int minHeight; - private final int worldHeight; - private final ThreadLocal scratchCache = ThreadLocal.withInitial(CaveCarveScratch::new); - - public IrisCaveCarver3D(CarveWorld world, CaveProfile profile) { - this.profile = profile; - List moduleStates = new ArrayList<>(); - - long carveSeed = world.carveSeed(); - this.baseDensity = world.noise().sampler(profile.baseDensityStyle(), carveSeed + 934_447); - this.detailDensity = world.noise().sampler(profile.detailDensityStyle(), carveSeed + 612_991); - this.warpDensity = world.noise().sampler(profile.warpStyle(), carveSeed + 770_713); - this.surfaceBreakDensity = world.noise().sampler(profile.surfaceBreakStyle(), carveSeed + 341_219); - this.thresholdNoise = world.noise().sampler(profile.densityThreshold().style(), carveSeed + 489_112); - this.baseWeight = profile.baseWeight(); - this.detailWeight = profile.detailWeight(); - this.warpStrength = profile.warpStrength(); - this.hasWarp = this.warpStrength > 0D; - this.warpResolution = 2; - this.allowFluid = profile.allowFluid(); - this.fluidRequiresFloor = profile.fluidRequiresFloor(); - this.fluidMinDepthBelowSurface = Math.max(0, profile.fluidMinDepthBelowSurface()); - this.fluidHeight = world.fluidHeight(); - this.worldHeight = world.height(); - this.aquiferCeilingY = world.height() - 1; - this.lavaHeight = world.lavaHeight(); - this.minHeight = world.minHeight(); - - double weight = Math.abs(baseWeight) + Math.abs(detailWeight); - int index = 0; - for (CaveFieldModule module : profile.modules()) { - NoiseSampler moduleDensity = world.noise().sampler(module.style(), carveSeed + 1_000_003L + (index * 65_537L)); - CaveFieldModuleState state = new CaveFieldModuleState(module, moduleDensity); - moduleStates.add(state); - weight += Math.abs(state.weight); - index++; - } - - this.modules = moduleStates.toArray(new CaveFieldModuleState[0]); - double normalization = weight <= 0 ? 1 : weight; - normalizationFactor = normalization; - inverseNormalization = 1D / normalization; - hasModules = modules.length > 0; - detailMinContribution = -detailWeight; - detailMaxContribution = detailWeight; - } - - public int carve( - MantleLayer voids, - int chunkX, - int chunkZ, - double[] columnWeights, - double minWeight, - double thresholdPenalty, - Range worldYRange, - int[] surfaceHeights - ) { - return carve(voids, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, worldYRange, surfaceHeights, null); - } - - public int carve( - MantleLayer voids, - int chunkX, - int chunkZ, - double[] columnWeights, - double minWeight, - double thresholdPenalty, - Range worldYRange, - int[] surfaceHeights, - Range overrideVerticalRange - ) { - CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan(); - int carved = carve(voids, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, - worldYRange, surfaceHeights, null, overrideVerticalRange, fluidSupportPlan); - fluidSupportPlan.resolve(voids, PowerOfTwoCoordinates.chunkToBlock(chunkX), PowerOfTwoCoordinates.chunkToBlock(chunkZ), worldHeight); - return carved; - } - - /** {@code surfaceHeights} are the rounded heights of the chunk's columns, packed as {@link PowerOfTwoCoordinates#packLocal16}. */ - int carve( - MantleLayer voids, - int chunkX, - int chunkZ, - double[] columnWeights, - double minWeight, - double thresholdPenalty, - Range worldYRange, - int[] surfaceHeights, - int[] surfaceFluidBoundaryStartY, - Range overrideVerticalRange, - CaveFluidSupportPlan fluidSupportPlan - ) { - CaveCarveScratch scratch = scratchCache.get(); - if (columnWeights == null || columnWeights.length < 256) { - if (!scratch.fullWeightsInitialized) { - Arrays.fill(scratch.fullWeights, 1D); - scratch.fullWeightsInitialized = true; - } - columnWeights = scratch.fullWeights; - } - - double resolvedMinWeight = Math.max(0D, Math.min(1D, minWeight)); - double resolvedThresholdPenalty = Math.max(0D, thresholdPenalty); - Range effectiveVerticalRange = overrideVerticalRange != null ? overrideVerticalRange : profile.verticalRange(); - int minY = Math.max(0, (int) Math.floor(effectiveVerticalRange.min())); - int maxY = Math.min(worldHeight - 1, (int) Math.ceil(effectiveVerticalRange.max())); - if (worldYRange != null) { - int rangeMinY = (int) Math.floor(worldYRange.min() - minHeight); - int rangeMaxY = (int) Math.ceil(worldYRange.max() - minHeight); - minY = Math.max(minY, rangeMinY); - maxY = Math.min(maxY, rangeMaxY); - } - int sampleStep = Math.max(1, profile.sampleStep()); - boolean exactSampling = sampleStep <= 2; - boolean adaptiveSampling = exactSampling && profile.adaptiveSampling(); - int adaptiveSampleStep = Math.max(2, profile.adaptiveSampleStep()); - double adaptiveThresholdMargin = Math.max(0D, profile.adaptiveThresholdMargin()); - int surfaceClearance = Math.max(0, profile.surfaceClearance()); - int surfaceBreakDepth = Math.max(0, profile.surfaceBreakDepth()); - double surfaceBreakNoiseThreshold = profile.surfaceBreakNoiseThreshold(); - double surfaceBreakThresholdBoost = Math.max(0, profile.surfaceBreakThresholdBoost()); - boolean allowSurfaceBreak = profile.allowSurfaceBreak(); - if (maxY < minY) { - return 0; - } - - int x0 = PowerOfTwoCoordinates.chunkToBlock(chunkX); - int z0 = PowerOfTwoCoordinates.chunkToBlock(chunkZ); - int[] columnMaxY = scratch.columnMaxY; - int[] fluidMaxY = scratch.fluidMaxY; - int[] surfaceBreakFloorY = scratch.surfaceBreakFloorY; - boolean[] surfaceBreakColumn = scratch.surfaceBreakColumn; - boolean[] surfaceCeilingColumn = scratch.surfaceCeilingColumn; - double[] columnThreshold = scratch.columnThreshold; - double[] clampedWeights = scratch.clampedColumnWeights; - double[] verticalEdgeFade = prepareVerticalEdgeFadeTable(scratch, minY, maxY); - prepareSurfaceClosureThresholdTable(scratch, minY, maxY); - CarvedVoid[] voidByY = prepareVoidByYTable(scratch, minY, maxY); - - // The threshold noise is constant for the carver, so it is built once (in the constructor) and the - // min==max / flat-style short circuits are decided here, as Iris's styled range has always decided them. - StyledRange densityThreshold = profile.densityThreshold(); - double thresholdMin = densityThreshold.min(); - double thresholdMax = densityThreshold.max(); - double thresholdBias = profile.thresholdBias(); - NoiseSampler thresholdDensity = null; - double constantThreshold = 0D; - if (thresholdMin == thresholdMax) { - constantThreshold = thresholdMin; - } else if (NoiseStyle.FLAT.equals(densityThreshold.style().style())) { - constantThreshold = M.lerp(thresholdMin, thresholdMax, 0.5); - } else { - thresholdDensity = thresholdNoise; - } - - for (int lx = 0; lx < 16; lx++) { - int x = x0 + lx; - for (int lz = 0; lz < 16; lz++) { - int z = z0 + lz; - int index = PowerOfTwoCoordinates.packLocal16(lx, lz); - int columnSurfaceY; - columnSurfaceY = surfaceHeights[index]; - int unclampedClearanceTopY = columnSurfaceY - surfaceClearance; - int clearanceTopY = Math.min(maxY, Math.max(minY, unclampedClearanceTopY)); - boolean breakColumn = allowSurfaceBreak - && surfaceBreakDensity.signed(x, z) >= surfaceBreakNoiseThreshold; - int columnTopY = breakColumn - ? Math.min(maxY, Math.max(minY, columnSurfaceY)) - : clearanceTopY; - - columnMaxY[index] = columnTopY; - fluidMaxY[index] = allowFluid - ? Math.min(fluidHeight, columnSurfaceY - fluidMinDepthBelowSurface) - : Integer.MIN_VALUE; - surfaceBreakFloorY[index] = Math.max(minY, columnSurfaceY - surfaceBreakDepth); - surfaceBreakColumn[index] = breakColumn; - surfaceCeilingColumn[index] = !breakColumn && unclampedClearanceTopY <= maxY; - columnThreshold[index] = (thresholdDensity == null - ? constantThreshold - : thresholdMin + (thresholdDensity.sample(x, z) * (thresholdMax - thresholdMin))) - thresholdBias; - clampedWeights[index] = clampColumnWeight(columnWeights[index]); - } - } - - int carved; - if (exactSampling) { - if (adaptiveSampling) { - carved = carvePassAdaptive( - voids, - x0, - z0, - minY, - maxY, - adaptiveSampleStep, - adaptiveThresholdMargin, - surfaceBreakThresholdBoost, - columnMaxY, - fluidMaxY, - surfaceFluidBoundaryStartY, - surfaceBreakFloorY, - surfaceBreakColumn, - columnThreshold, - clampedWeights, - verticalEdgeFade, - voidByY, - fluidRequiresFloor ? fluidSupportPlan : null, - resolvedMinWeight, - resolvedThresholdPenalty, - 0D, - false - ); - } else { - carved = carvePassExact( - voids, - x0, - z0, - minY, - maxY, - surfaceBreakThresholdBoost, - columnMaxY, - fluidMaxY, - surfaceFluidBoundaryStartY, - surfaceBreakFloorY, - surfaceBreakColumn, - columnThreshold, - clampedWeights, - verticalEdgeFade, - voidByY, - fluidRequiresFloor ? fluidSupportPlan : null, - resolvedMinWeight, - resolvedThresholdPenalty, - 0D, - false - ); - } - } else { - int latticeStep = sampleStep; - carved = carvePassLattice( - voids, - x0, - z0, - minY, - maxY, - latticeStep, - surfaceBreakThresholdBoost, - columnMaxY, - fluidMaxY, - surfaceFluidBoundaryStartY, - surfaceBreakFloorY, - surfaceBreakColumn, - columnThreshold, - clampedWeights, - verticalEdgeFade, - voidByY, - fluidRequiresFloor ? fluidSupportPlan : null, - resolvedMinWeight, - resolvedThresholdPenalty, - 0D, - false - ); - if (carved == 0 && hasFallbackCandidates(columnMaxY, clampedWeights, minY, resolvedMinWeight)) { - carved += carvePassFallback( - voids, - x0, - z0, - minY, - maxY, - sampleStep, - surfaceBreakThresholdBoost, - columnMaxY, - fluidMaxY, - surfaceFluidBoundaryStartY, - surfaceBreakFloorY, - surfaceBreakColumn, - columnThreshold, - clampedWeights, - verticalEdgeFade, - voidByY, - fluidRequiresFloor ? fluidSupportPlan : null, - resolvedMinWeight, - resolvedThresholdPenalty, - 0D, - false - ); - } - } - - return carved; - } - - private int carvePassExact( - MantleLayer voids, - int x0, - int z0, - int minY, - int maxY, - double surfaceBreakThresholdBoost, - int[] columnMaxY, - int[] fluidMaxY, - int[] surfaceFluidBoundaryStartY, - int[] surfaceBreakFloorY, - boolean[] surfaceBreakColumn, - double[] columnThreshold, - double[] clampedWeights, - double[] verticalEdgeFade, - CarvedVoid[] voidByY, - CaveFluidSupportPlan fluidSupportPlan, - double minWeight, - double thresholdPenalty, - double thresholdBoost, - boolean skipExistingCarved - ) { - int carved = 0; - CaveCarveScratch scratch = scratchCache.get(); - double[] passThreshold = scratch.passThreshold; - int[] activeColumnIndices = scratch.activeColumnIndices; - int[] activeColumnTopY = scratch.activeColumnTopY; - int activeColumnCount = 0; - - for (int index = 0; index < 256; index++) { - double columnWeight = clampedWeights[index]; - if (columnWeight <= minWeight || columnMaxY[index] < minY) { - passThreshold[index] = Double.NaN; - continue; - } - - passThreshold[index] = columnThreshold[index] + thresholdBoost - ((1D - columnWeight) * thresholdPenalty); - activeColumnIndices[activeColumnCount] = index; - activeColumnTopY[activeColumnCount] = columnMaxY[index]; - activeColumnCount++; - } - - if (activeColumnCount == 0) { - return 0; - } - - int[] planeColumnIndices = scratch.planeColumnIndices; - double[] planeThresholdLimit = scratch.planeThresholdLimit; - boolean[] planeCarve = scratch.planeCarve; - int minSection = PowerOfTwoCoordinates.floorDivPow2(minY, 4); - int maxSection = PowerOfTwoCoordinates.floorDivPow2(maxY, 4); - - for (int sectionIndex = minSection; sectionIndex <= maxSection; sectionIndex++) { - int sectionMinY = Math.max(minY, PowerOfTwoCoordinates.chunkToBlock(sectionIndex)); - int sectionMaxY = Math.min(maxY, PowerOfTwoCoordinates.chunkToBlock(sectionIndex) + 15); - - for (int y = sectionMinY; y <= sectionMaxY; y++) { - int planeCount = 0; - for (int activeIndex = 0; activeIndex < activeColumnCount; activeIndex++) { - if (activeColumnTopY[activeIndex] < y) { - continue; - } - - int columnIndex = activeColumnIndices[activeIndex]; - if (SurfaceFluidBoundaryPlan.protects(surfaceFluidBoundaryStartY, columnIndex, y, fluidHeight)) { - continue; - } - planeColumnIndices[planeCount] = columnIndex; - double localThreshold = passThreshold[columnIndex]; - if (surfaceBreakColumn[columnIndex] && y >= surfaceBreakFloorY[columnIndex]) { - localThreshold += surfaceBreakThresholdBoost; - } - localThreshold -= verticalEdgeFade[y - minY]; - localThreshold = applySurfaceCeilingFade(scratch, localThreshold, columnIndex, y, minY); - planeThresholdLimit[planeCount] = localThreshold * normalizationFactor; - planeCount++; - } - - if (planeCount == 0) { - continue; - } - - classifyDensityPlane(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); - int fadeIndex = y - minY; - CarvedVoid verticalVoid = voidByY[fadeIndex]; - - if (skipExistingCarved) { - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - if (!planeCarve[planeIndex]) { - continue; - } - - int columnIndex = planeColumnIndices[planeIndex]; - int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int localZ = columnIndex & 15; - if (voids.get(x0 + localX, y, z0 + localZ) != null) { - continue; - } - - double localThreshold = planeThresholdLimit[planeIndex] * inverseNormalization; - CarvedVoid carvedVoid = resolveVoid(scratch, verticalVoid, x0 + localX, y, z0 + localZ, - columnIndex, fluidMaxY, localThreshold); - writeVoid(voids, x0 + localX, y, z0 + localZ, carvedVoid, fluidSupportPlan); - carved++; - } - continue; - } - - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - if (!planeCarve[planeIndex]) { - continue; - } - - int columnIndex = planeColumnIndices[planeIndex]; - int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int localZ = columnIndex & 15; - double localThreshold = planeThresholdLimit[planeIndex] * inverseNormalization; - CarvedVoid carvedVoid = resolveVoid(scratch, verticalVoid, x0 + localX, y, z0 + localZ, - columnIndex, fluidMaxY, localThreshold); - writeVoid(voids, x0 + localX, y, z0 + localZ, carvedVoid, fluidSupportPlan); - carved++; - } - } - } - - return carved; - } - - private int carvePassAdaptive( - MantleLayer voids, - int x0, - int z0, - int minY, - int maxY, - int adaptiveSampleStep, - double adaptiveThresholdMargin, - double surfaceBreakThresholdBoost, - int[] columnMaxY, - int[] fluidMaxY, - int[] surfaceFluidBoundaryStartY, - int[] surfaceBreakFloorY, - boolean[] surfaceBreakColumn, - double[] columnThreshold, - double[] clampedWeights, - double[] verticalEdgeFade, - CarvedVoid[] voidByY, - CaveFluidSupportPlan fluidSupportPlan, - double minWeight, - double thresholdPenalty, - double thresholdBoost, - boolean skipExistingCarved - ) { - int carved = 0; - CaveCarveScratch scratch = scratchCache.get(); - double[] passThreshold = scratch.passThreshold; - int[] activeColumnIndices = scratch.activeColumnIndices; - int[] activeColumnTopY = scratch.activeColumnTopY; - int activeColumnCount = 0; - - for (int index = 0; index < 256; index++) { - double columnWeight = clampedWeights[index]; - if (columnWeight <= minWeight || columnMaxY[index] < minY) { - passThreshold[index] = Double.NaN; - continue; - } - - passThreshold[index] = columnThreshold[index] + thresholdBoost - ((1D - columnWeight) * thresholdPenalty); - activeColumnIndices[activeColumnCount] = index; - activeColumnTopY[activeColumnCount] = columnMaxY[index]; - activeColumnCount++; - } - - if (activeColumnCount == 0) { - return 0; - } - - int[] planeColumnIndices = scratch.planeColumnIndices; - double[] planeThresholdLimit = scratch.planeThresholdLimit; - boolean[] planeCarve = scratch.planeCarve; - int minSection = PowerOfTwoCoordinates.floorDivPow2(minY, 4); - int maxSection = PowerOfTwoCoordinates.floorDivPow2(maxY, 4); - int effectiveAdaptiveSampleStep = Math.max(adaptiveSampleStep, ADAPTIVE_DEEP_SAMPLE_STEP); - double effectiveAdaptiveThresholdMargin = resolveAdaptivePlaneThresholdMargin( - adaptiveThresholdMargin, - adaptiveSampleStep, - effectiveAdaptiveSampleStep - ); - - for (int sectionIndex = minSection; sectionIndex <= maxSection; sectionIndex++) { - int sectionMinY = Math.max(minY, PowerOfTwoCoordinates.chunkToBlock(sectionIndex)); - int sectionMaxY = Math.min(maxY, PowerOfTwoCoordinates.chunkToBlock(sectionIndex) + 15); - - for (int y = sectionMinY; y <= sectionMaxY; y++) { - int planeCount = 0; - for (int activeIndex = 0; activeIndex < activeColumnCount; activeIndex++) { - if (activeColumnTopY[activeIndex] < y) { - continue; - } - - int columnIndex = activeColumnIndices[activeIndex]; - if (SurfaceFluidBoundaryPlan.protects(surfaceFluidBoundaryStartY, columnIndex, y, fluidHeight)) { - continue; - } - planeColumnIndices[planeCount] = columnIndex; - double localThreshold = passThreshold[columnIndex]; - if (surfaceBreakColumn[columnIndex] && y >= surfaceBreakFloorY[columnIndex]) { - localThreshold += surfaceBreakThresholdBoost; - } - localThreshold -= verticalEdgeFade[y - minY]; - localThreshold = applySurfaceCeilingFade(scratch, localThreshold, columnIndex, y, minY); - planeThresholdLimit[planeCount] = localThreshold * normalizationFactor; - planeCount++; - } - - if (planeCount == 0) { - continue; - } - - classifyDensityPlaneAdaptive( - scratch, - x0, - z0, - y, - planeColumnIndices, - planeThresholdLimit, - planeCount, - planeCarve, - effectiveAdaptiveSampleStep, - effectiveAdaptiveThresholdMargin - ); - int fadeIndex = y - minY; - CarvedVoid verticalVoid = voidByY[fadeIndex]; - - if (skipExistingCarved) { - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - if (!planeCarve[planeIndex]) { - continue; - } - - int columnIndex = planeColumnIndices[planeIndex]; - int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int localZ = columnIndex & 15; - if (voids.get(x0 + localX, y, z0 + localZ) != null) { - continue; - } - - double localThreshold = planeThresholdLimit[planeIndex] * inverseNormalization; - CarvedVoid carvedVoid = resolveVoid(scratch, verticalVoid, x0 + localX, y, z0 + localZ, - columnIndex, fluidMaxY, localThreshold); - writeVoid(voids, x0 + localX, y, z0 + localZ, carvedVoid, fluidSupportPlan); - carved++; - } - continue; - } - - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - if (!planeCarve[planeIndex]) { - continue; - } - - int columnIndex = planeColumnIndices[planeIndex]; - int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int localZ = columnIndex & 15; - double localThreshold = planeThresholdLimit[planeIndex] * inverseNormalization; - CarvedVoid carvedVoid = resolveVoid(scratch, verticalVoid, x0 + localX, y, z0 + localZ, - columnIndex, fluidMaxY, localThreshold); - writeVoid(voids, x0 + localX, y, z0 + localZ, carvedVoid, fluidSupportPlan); - carved++; - } - } - } - - return carved; - } - - private double resolveAdaptivePlaneThresholdMargin( - double adaptiveThresholdMargin, - int adaptiveSampleStep, - int effectiveAdaptiveSampleStep - ) { - if (effectiveAdaptiveSampleStep <= adaptiveSampleStep) { - return adaptiveThresholdMargin; - } - - return adaptiveThresholdMargin + ((effectiveAdaptiveSampleStep - adaptiveSampleStep) * ADAPTIVE_DEEP_MARGIN_BOOST); - } - - private int carvePassLattice( - MantleLayer voids, - int x0, - int z0, - int minY, - int maxY, - int latticeStep, - double surfaceBreakThresholdBoost, - int[] columnMaxY, - int[] fluidMaxY, - int[] surfaceFluidBoundaryStartY, - int[] surfaceBreakFloorY, - boolean[] surfaceBreakColumn, - double[] columnThreshold, - double[] clampedWeights, - double[] verticalEdgeFade, - CarvedVoid[] voidByY, - CaveFluidSupportPlan fluidSupportPlan, - double minWeight, - double thresholdPenalty, - double thresholdBoost, - boolean skipExistingCarved - ) { - int carved = 0; - CaveCarveScratch scratch = scratchCache.get(); - double[] passThreshold = scratch.passThreshold; - int[] tileIndices = scratch.tileIndices; - int[] tileLocalX = scratch.tileLocalX; - int[] tileLocalZ = scratch.tileLocalZ; - int[] tileTopY = scratch.tileTopY; - - for (int index = 0; index < 256; index++) { - double columnWeight = clampedWeights[index]; - if (columnWeight <= minWeight || columnMaxY[index] < minY) { - passThreshold[index] = Double.NaN; - continue; - } - passThreshold[index] = columnThreshold[index] + thresholdBoost - ((1D - columnWeight) * thresholdPenalty); - } - - for (int lx = 0; lx < 16; lx += 2) { - int x = x0 + lx; - int lx1 = lx + 1; - for (int lz = 0; lz < 16; lz += 2) { - int z = z0 + lz; - int lz1 = lz + 1; - int activeColumns = 0; - - int index00 = PowerOfTwoCoordinates.packLocal16(lx, lz); - if (!Double.isNaN(passThreshold[index00])) { - tileIndices[activeColumns] = index00; - tileLocalX[activeColumns] = lx; - tileLocalZ[activeColumns] = lz; - tileTopY[activeColumns] = columnMaxY[index00]; - activeColumns++; - } - - int index01 = PowerOfTwoCoordinates.packLocal16(lx, lz1); - if (!Double.isNaN(passThreshold[index01])) { - tileIndices[activeColumns] = index01; - tileLocalX[activeColumns] = lx; - tileLocalZ[activeColumns] = lz1; - tileTopY[activeColumns] = columnMaxY[index01]; - activeColumns++; - } - - int index10 = PowerOfTwoCoordinates.packLocal16(lx1, lz); - if (!Double.isNaN(passThreshold[index10])) { - tileIndices[activeColumns] = index10; - tileLocalX[activeColumns] = lx1; - tileLocalZ[activeColumns] = lz; - tileTopY[activeColumns] = columnMaxY[index10]; - activeColumns++; - } - - int index11 = PowerOfTwoCoordinates.packLocal16(lx1, lz1); - if (!Double.isNaN(passThreshold[index11])) { - tileIndices[activeColumns] = index11; - tileLocalX[activeColumns] = lx1; - tileLocalZ[activeColumns] = lz1; - tileTopY[activeColumns] = columnMaxY[index11]; - activeColumns++; - } - - if (activeColumns == 0) { - continue; - } - - int tileMaxY = minY; - for (int columnIndex = 0; columnIndex < activeColumns; columnIndex++) { - if (tileTopY[columnIndex] > tileMaxY) { - tileMaxY = tileTopY[columnIndex]; - } - } - if (tileMaxY < minY) { - continue; - } - - for (int y = minY; y <= tileMaxY; y += latticeStep) { - double density = sampleDensityOptimized(scratch, x, y, z); - int stampMaxY = Math.min(maxY, y + 1); - for (int yy = y; yy <= stampMaxY; yy++) { - CarvedVoid verticalVoid = voidByY[yy - minY]; - int fadeIndex = yy - minY; - for (int columnIndex = 0; columnIndex < activeColumns; columnIndex++) { - if (yy > tileTopY[columnIndex]) { - continue; - } - - int index = tileIndices[columnIndex]; - if (SurfaceFluidBoundaryPlan.protects(surfaceFluidBoundaryStartY, index, yy, fluidHeight)) { - continue; - } - double localThreshold = passThreshold[index]; - if (surfaceBreakColumn[index] && yy >= surfaceBreakFloorY[index]) { - localThreshold += surfaceBreakThresholdBoost; - } - localThreshold -= verticalEdgeFade[fadeIndex]; - localThreshold = applySurfaceCeilingFade(scratch, localThreshold, index, yy, minY); - if (density > localThreshold) { - continue; - } - - int localX = tileLocalX[columnIndex]; - int localZ = tileLocalZ[columnIndex]; - int worldX = x0 + localX; - int worldZ = z0 + localZ; - CarvedVoid carvedVoid = resolveVoid(scratch, verticalVoid, worldX, yy, worldZ, - index, fluidMaxY, localThreshold); - if (skipExistingCarved) { - if (voids.get(worldX, yy, worldZ) == null) { - writeVoid(voids, worldX, yy, worldZ, carvedVoid, fluidSupportPlan); - carved++; - } - continue; - } - - writeVoid(voids, worldX, yy, worldZ, carvedVoid, fluidSupportPlan); - carved++; - } - } - } - } - } - - return carved; - } - - private int carvePassFallback( - MantleLayer voids, - int x0, - int z0, - int minY, - int maxY, - int sampleStep, - double surfaceBreakThresholdBoost, - int[] columnMaxY, - int[] fluidMaxY, - int[] surfaceFluidBoundaryStartY, - int[] surfaceBreakFloorY, - boolean[] surfaceBreakColumn, - double[] columnThreshold, - double[] clampedWeights, - double[] verticalEdgeFade, - CarvedVoid[] voidByY, - CaveFluidSupportPlan fluidSupportPlan, - double minWeight, - double thresholdPenalty, - double thresholdBoost, - boolean skipExistingCarved - ) { - int carved = 0; - CaveCarveScratch scratch = scratchCache.get(); - - for (int lx = 0; lx < 16; lx++) { - int x = x0 + lx; - for (int lz = 0; lz < 16; lz++) { - int z = z0 + lz; - int index = PowerOfTwoCoordinates.packLocal16(lx, lz); - double columnWeight = clampedWeights[index]; - if (columnWeight <= minWeight) { - continue; - } - - int columnTopY = columnMaxY[index]; - if (columnTopY < minY) { - continue; - } - - boolean breakColumn = surfaceBreakColumn[index]; - int breakFloorY = surfaceBreakFloorY[index]; - double threshold = columnThreshold[index] + thresholdBoost - ((1D - columnWeight) * thresholdPenalty); - - for (int y = minY; y <= columnTopY; y += sampleStep) { - double density = sampleDensityOptimized(scratch, x, y, z); - int carveMaxY = Math.min(columnTopY, y + sampleStep - 1); - for (int yy = y; yy <= carveMaxY; yy++) { - if (SurfaceFluidBoundaryPlan.protects(surfaceFluidBoundaryStartY, index, yy, fluidHeight)) { - continue; - } - double localThreshold = threshold; - if (breakColumn && yy >= breakFloorY) { - localThreshold += surfaceBreakThresholdBoost; - } - localThreshold -= verticalEdgeFade[yy - minY]; - localThreshold = applySurfaceCeilingFade(scratch, localThreshold, index, yy, minY); - if (density > localThreshold) { - continue; - } - CarvedVoid verticalVoid = voidByY[yy - minY]; - CarvedVoid carvedVoid = resolveVoid(scratch, verticalVoid, x, yy, z, - index, fluidMaxY, localThreshold); - if (skipExistingCarved) { - if (voids.get(x, yy, z) == null) { - writeVoid(voids, x, yy, z, carvedVoid, fluidSupportPlan); - carved++; - } - continue; - } - - writeVoid(voids, x, yy, z, carvedVoid, fluidSupportPlan); - carved++; - } - } - } - } - - return carved; - } - - private boolean hasFallbackCandidates(int[] columnMaxY, double[] clampedWeights, int minY, double minWeight) { - for (int index = 0; index < 256; index++) { - if (clampedWeights[index] <= minWeight) { - continue; - } - - if (columnMaxY[index] >= minY) { - return true; - } - } - - return false; - } - - private double sampleDensityOptimized(int x, int y, int z) { - if (!hasWarp && !hasModules) { - return sampleDensityNoWarpNoModules(x, y, z); - } - - return sampleDensityOptimized(scratchCache.get(), x, y, z); - } - - private double sampleDensityOptimized(CaveCarveScratch scratch, int x, int y, int z) { - if (!hasWarp) { - if (!hasModules) { - return sampleDensityNoWarpNoModules(x, y, z); - } - - return sampleDensityNoWarpModules(scratch, x, y, z); - } - - if (!hasModules) { - return sampleDensityWarpOnly(scratch, x, y, z); - } - - return sampleDensityWarpModules(scratch, x, y, z); - } - - private void classifyDensityPlane(CaveCarveScratch scratch, int x0, int z0, int y, int[] planeColumnIndices, double[] planeThresholdLimit, int planeCount, boolean[] planeCarve) { - if (!hasWarp) { - if (!hasModules) { - classifyDensityPlaneNoWarpNoModules(x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); - return; - } - - classifyDensityPlaneNoWarpModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); - return; - } - - if (!hasModules) { - classifyDensityPlaneWarpOnly(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); - return; - } - - classifyDensityPlaneWarpModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); - } - - private void classifyDensityPlaneAdaptive( - CaveCarveScratch scratch, - int x0, - int z0, - int y, - int[] planeColumnIndices, - double[] planeThresholdLimit, - int planeCount, - boolean[] planeCarve, - int adaptiveSampleStep, - double adaptiveThresholdMargin - ) { - if (adaptiveSampleStep <= 1 || planeCount < ADAPTIVE_MIN_PLANE_COLUMNS) { - classifyDensityPlane(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); - return; - } - - if (!hasWarp) { - if (!hasModules) { - classifyDensityPlaneAdaptiveNoWarpNoModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); - return; - } - - classifyDensityPlaneAdaptiveNoWarpModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); - return; - } - - if (!hasModules) { - classifyDensityPlaneAdaptiveWarpOnly(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); - return; - } - - classifyDensityPlaneAdaptiveWarpModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); - } - - private void classifyDensityPlaneNoWarpNoModules(int x0, int z0, int y, int[] planeColumnIndices, double[] planeThresholdLimit, int planeCount, boolean[] planeCarve) { - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - int columnIndex = planeColumnIndices[planeIndex]; - int x = x0 + PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int z = z0 + (columnIndex & 15); - planeCarve[planeIndex] = classifyDensityPointNoWarpNoModules(x, y, z, planeThresholdLimit[planeIndex]); - } - } - - private void classifyDensityPlaneNoWarpModules(CaveCarveScratch scratch, int x0, int z0, int y, int[] planeColumnIndices, double[] planeThresholdLimit, int planeCount, boolean[] planeCarve) { - int activeModuleCount = prepareActiveModules(scratch, y); - if (activeModuleCount == 0) { - classifyDensityPlaneNoWarpNoModules(x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); - return; - } - - CaveFieldModuleState[] localModules = scratch.activeModules; - double[] remainingMin = scratch.activeModuleRemainingMin; - double[] remainingMax = scratch.activeModuleRemainingMax; - - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - int columnIndex = planeColumnIndices[planeIndex]; - int x = x0 + PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int z = z0 + (columnIndex & 15); - planeCarve[planeIndex] = classifyDensityPointNoWarpModules( - x, - y, - z, - planeThresholdLimit[planeIndex], - localModules, - activeModuleCount, - remainingMin, - remainingMax - ); - } - } - - private void classifyDensityPlaneWarpOnly(CaveCarveScratch scratch, int x0, int z0, int y, int[] planeColumnIndices, double[] planeThresholdLimit, int planeCount, boolean[] planeCarve) { - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - int columnIndex = planeColumnIndices[planeIndex]; - int x = x0 + PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int z = z0 + (columnIndex & 15); - planeCarve[planeIndex] = classifyDensityPointWarpOnly(scratch, x, y, z, planeThresholdLimit[planeIndex]); - } - } - - private void classifyDensityPlaneWarpModules(CaveCarveScratch scratch, int x0, int z0, int y, int[] planeColumnIndices, double[] planeThresholdLimit, int planeCount, boolean[] planeCarve) { - int activeModuleCount = prepareActiveModules(scratch, y); - if (activeModuleCount == 0) { - classifyDensityPlaneWarpOnly(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); - return; - } - - CaveFieldModuleState[] localModules = scratch.activeModules; - double[] remainingMin = scratch.activeModuleRemainingMin; - double[] remainingMax = scratch.activeModuleRemainingMax; - - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - int columnIndex = planeColumnIndices[planeIndex]; - int x = x0 + PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int z = z0 + (columnIndex & 15); - planeCarve[planeIndex] = classifyDensityPointWarpModules( - scratch, - x, - y, - z, - planeThresholdLimit[planeIndex], - localModules, - activeModuleCount, - remainingMin, - remainingMax - ); - } - } - - private void classifyDensityPlaneAdaptiveNoWarpNoModules( - CaveCarveScratch scratch, - int x0, - int z0, - int y, - int[] planeColumnIndices, - double[] planeThresholdLimit, - int planeCount, - boolean[] planeCarve, - int adaptiveSampleStep, - double adaptiveThresholdMargin - ) { - double[] adaptivePlaneDensity = scratch.adaptivePlaneDensity; - int axisCells = (16 + adaptiveSampleStep - 1) / adaptiveSampleStep; - int axisSamples = axisCells + 1; - int[] adaptivePlaneSampleBounds = scratch.adaptivePlaneSampleBounds; - prepareAdaptivePlaneSampleBounds(scratch, planeColumnIndices, planeCount, adaptiveSampleStep, adaptivePlaneSampleBounds, axisCells); - for (int sampleXIndex = adaptivePlaneSampleBounds[0]; sampleXIndex <= adaptivePlaneSampleBounds[1]; sampleXIndex++) { - int sampleLocalX = Math.min(sampleXIndex * adaptiveSampleStep, 16); - int x = x0 + sampleLocalX; - int rowOffset = sampleXIndex * axisSamples; - for (int sampleZIndex = adaptivePlaneSampleBounds[2]; sampleZIndex <= adaptivePlaneSampleBounds[3]; sampleZIndex++) { - int sampleLocalZ = Math.min(sampleZIndex * adaptiveSampleStep, 16); - adaptivePlaneDensity[rowOffset + sampleZIndex] = sampleDensityNoWarpNoModules(x, y, z0 + sampleLocalZ); - } - } - - classifyAdaptivePlaneColumnsNoWarpNoModules( - scratch, - x0, - z0, - y, - planeColumnIndices, - planeThresholdLimit, - planeCount, - planeCarve, - adaptiveSampleStep, - adaptiveThresholdMargin, - adaptivePlaneDensity, - axisCells, - axisSamples - ); - } - - private void classifyDensityPlaneAdaptiveNoWarpModules( - CaveCarveScratch scratch, - int x0, - int z0, - int y, - int[] planeColumnIndices, - double[] planeThresholdLimit, - int planeCount, - boolean[] planeCarve, - int adaptiveSampleStep, - double adaptiveThresholdMargin - ) { - int activeModuleCount = prepareActiveModules(scratch, y); - if (activeModuleCount == 0) { - classifyDensityPlaneAdaptiveNoWarpNoModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); - return; - } - - CaveFieldModuleState[] localModules = scratch.activeModules; - double[] remainingMin = scratch.activeModuleRemainingMin; - double[] remainingMax = scratch.activeModuleRemainingMax; - double[] adaptivePlaneDensity = scratch.adaptivePlaneDensity; - int axisCells = (16 + adaptiveSampleStep - 1) / adaptiveSampleStep; - int axisSamples = axisCells + 1; - int[] adaptivePlaneSampleBounds = scratch.adaptivePlaneSampleBounds; - prepareAdaptivePlaneSampleBounds(scratch, planeColumnIndices, planeCount, adaptiveSampleStep, adaptivePlaneSampleBounds, axisCells); - for (int sampleXIndex = adaptivePlaneSampleBounds[0]; sampleXIndex <= adaptivePlaneSampleBounds[1]; sampleXIndex++) { - int sampleLocalX = Math.min(sampleXIndex * adaptiveSampleStep, 16); - int x = x0 + sampleLocalX; - int rowOffset = sampleXIndex * axisSamples; - for (int sampleZIndex = adaptivePlaneSampleBounds[2]; sampleZIndex <= adaptivePlaneSampleBounds[3]; sampleZIndex++) { - int sampleLocalZ = Math.min(sampleZIndex * adaptiveSampleStep, 16); - adaptivePlaneDensity[rowOffset + sampleZIndex] = sampleDensityNoWarpNoModules(x, y, z0 + sampleLocalZ); - } - } - - classifyAdaptivePlaneColumnsNoWarpModules( - scratch, - x0, - z0, - y, - planeColumnIndices, - planeThresholdLimit, - planeCount, - planeCarve, - adaptiveSampleStep, - adaptiveThresholdMargin, - adaptivePlaneDensity, - axisCells, - axisSamples, - localModules, - activeModuleCount, - remainingMin, - remainingMax - ); - } - - private void classifyDensityPlaneAdaptiveWarpOnly( - CaveCarveScratch scratch, - int x0, - int z0, - int y, - int[] planeColumnIndices, - double[] planeThresholdLimit, - int planeCount, - boolean[] planeCarve, - int adaptiveSampleStep, - double adaptiveThresholdMargin - ) { - double[] adaptivePlaneDensity = scratch.adaptivePlaneDensity; - int axisCells = (16 + adaptiveSampleStep - 1) / adaptiveSampleStep; - int axisSamples = axisCells + 1; - int[] adaptivePlaneSampleBounds = scratch.adaptivePlaneSampleBounds; - prepareAdaptivePlaneSampleBounds(scratch, planeColumnIndices, planeCount, adaptiveSampleStep, adaptivePlaneSampleBounds, axisCells); - for (int sampleXIndex = adaptivePlaneSampleBounds[0]; sampleXIndex <= adaptivePlaneSampleBounds[1]; sampleXIndex++) { - int sampleLocalX = Math.min(sampleXIndex * adaptiveSampleStep, 16); - int x = x0 + sampleLocalX; - int rowOffset = sampleXIndex * axisSamples; - for (int sampleZIndex = adaptivePlaneSampleBounds[2]; sampleZIndex <= adaptivePlaneSampleBounds[3]; sampleZIndex++) { - int sampleLocalZ = Math.min(sampleZIndex * adaptiveSampleStep, 16); - adaptivePlaneDensity[rowOffset + sampleZIndex] = sampleDensityWarpOnly(scratch, x, y, z0 + sampleLocalZ); - } - } - - classifyAdaptivePlaneColumnsWarpOnly( - scratch, - x0, - z0, - y, - planeColumnIndices, - planeThresholdLimit, - planeCount, - planeCarve, - adaptiveSampleStep, - adaptiveThresholdMargin, - adaptivePlaneDensity, - axisCells, - axisSamples - ); - } - - private void classifyDensityPlaneAdaptiveWarpModules( - CaveCarveScratch scratch, - int x0, - int z0, - int y, - int[] planeColumnIndices, - double[] planeThresholdLimit, - int planeCount, - boolean[] planeCarve, - int adaptiveSampleStep, - double adaptiveThresholdMargin - ) { - int activeModuleCount = prepareActiveModules(scratch, y); - if (activeModuleCount == 0) { - classifyDensityPlaneAdaptiveWarpOnly(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); - return; - } - - CaveFieldModuleState[] localModules = scratch.activeModules; - double[] remainingMin = scratch.activeModuleRemainingMin; - double[] remainingMax = scratch.activeModuleRemainingMax; - double[] adaptivePlaneDensity = scratch.adaptivePlaneDensity; - int axisCells = (16 + adaptiveSampleStep - 1) / adaptiveSampleStep; - int axisSamples = axisCells + 1; - int[] adaptivePlaneSampleBounds = scratch.adaptivePlaneSampleBounds; - prepareAdaptivePlaneSampleBounds(scratch, planeColumnIndices, planeCount, adaptiveSampleStep, adaptivePlaneSampleBounds, axisCells); - for (int sampleXIndex = adaptivePlaneSampleBounds[0]; sampleXIndex <= adaptivePlaneSampleBounds[1]; sampleXIndex++) { - int sampleLocalX = Math.min(sampleXIndex * adaptiveSampleStep, 16); - int x = x0 + sampleLocalX; - int rowOffset = sampleXIndex * axisSamples; - for (int sampleZIndex = adaptivePlaneSampleBounds[2]; sampleZIndex <= adaptivePlaneSampleBounds[3]; sampleZIndex++) { - int sampleLocalZ = Math.min(sampleZIndex * adaptiveSampleStep, 16); - adaptivePlaneDensity[rowOffset + sampleZIndex] = sampleDensityWarpModules( - scratch, - x, - y, - z0 + sampleLocalZ, - localModules, - activeModuleCount - ); - } - } - - classifyAdaptivePlaneColumnsWarpModulesSampled( - scratch, - x0, - z0, - y, - planeColumnIndices, - planeThresholdLimit, - planeCount, - planeCarve, - adaptiveSampleStep, - adaptiveThresholdMargin, - adaptivePlaneDensity, - axisCells, - axisSamples, - localModules, - activeModuleCount, - remainingMin, - remainingMax - ); - } - - private void classifyAdaptivePlaneColumnsNoWarpNoModules( - CaveCarveScratch scratch, - int x0, - int z0, - int y, - int[] planeColumnIndices, - double[] planeThresholdLimit, - int planeCount, - boolean[] planeCarve, - int adaptiveSampleStep, - double adaptiveThresholdMargin, - double[] adaptivePlaneDensity, - int axisCells, - int axisSamples - ) { - double[] adaptivePlanePrediction = scratch.adaptivePlanePrediction; - double[] adaptivePlaneAmbiguity = scratch.adaptivePlaneAmbiguity; - prepareAdaptivePlaneColumns( - scratch, - planeColumnIndices, - planeCount, - adaptiveSampleStep, - adaptiveThresholdMargin, - adaptivePlaneDensity, - axisCells, - axisSamples, - adaptivePlanePrediction, - adaptivePlaneAmbiguity - ); - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - int columnIndex = planeColumnIndices[planeIndex]; - int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int localZ = columnIndex & 15; - double threshold = planeThresholdLimit[planeIndex] * inverseNormalization; - double predictedDensity = adaptivePlanePrediction[planeIndex]; - double ambiguityMargin = adaptivePlaneAmbiguity[planeIndex]; - if (isAdaptivePlaneSampleAligned(localX, localZ, adaptiveSampleStep)) { - planeCarve[planeIndex] = predictedDensity <= threshold; - continue; - } - if (predictedDensity <= threshold - ambiguityMargin) { - planeCarve[planeIndex] = true; - continue; - } - if (predictedDensity > threshold + ambiguityMargin) { - planeCarve[planeIndex] = false; - continue; - } - if (adaptiveSampleStep >= ADAPTIVE_DEEP_SAMPLE_STEP) { - planeCarve[planeIndex] = predictedDensity <= threshold; - continue; - } - - planeCarve[planeIndex] = classifyDensityPointNoWarpNoModules(x0 + localX, y, z0 + localZ, planeThresholdLimit[planeIndex]); - } - } - - private void classifyAdaptivePlaneColumnsNoWarpModules( - CaveCarveScratch scratch, - int x0, - int z0, - int y, - int[] planeColumnIndices, - double[] planeThresholdLimit, - int planeCount, - boolean[] planeCarve, - int adaptiveSampleStep, - double adaptiveThresholdMargin, - double[] adaptivePlaneDensity, - int axisCells, - int axisSamples, - CaveFieldModuleState[] localModules, - int activeModuleCount, - double[] remainingMin, - double[] remainingMax - ) { - double[] adaptivePlanePrediction = scratch.adaptivePlanePrediction; - double[] adaptivePlaneAmbiguity = scratch.adaptivePlaneAmbiguity; - prepareAdaptivePlaneColumns( - scratch, - planeColumnIndices, - planeCount, - adaptiveSampleStep, - adaptiveThresholdMargin, - adaptivePlaneDensity, - axisCells, - axisSamples, - adaptivePlanePrediction, - adaptivePlaneAmbiguity - ); - double minRemaining = remainingMin[0] * inverseNormalization; - double maxRemaining = remainingMax[0] * inverseNormalization; - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - int columnIndex = planeColumnIndices[planeIndex]; - int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int localZ = columnIndex & 15; - double threshold = planeThresholdLimit[planeIndex] * inverseNormalization; - double predictedDensity = adaptivePlanePrediction[planeIndex]; - double ambiguityMargin = adaptivePlaneAmbiguity[planeIndex]; - if (isAdaptivePlaneSampleAligned(localX, localZ, adaptiveSampleStep)) { - planeCarve[planeIndex] = classifyDensityPointNoWarpModulesFromExactDensity( - x0 + localX, - y, - z0 + localZ, - threshold, - predictedDensity, - localModules, - activeModuleCount, - remainingMin, - remainingMax - ); - continue; - } - if ((predictedDensity + maxRemaining) <= threshold - ambiguityMargin) { - planeCarve[planeIndex] = true; - continue; - } - if ((predictedDensity + minRemaining) > threshold + ambiguityMargin) { - planeCarve[planeIndex] = false; - continue; - } - if (adaptiveSampleStep >= ADAPTIVE_DEEP_SAMPLE_STEP) { - planeCarve[planeIndex] = predictedDensity <= threshold; - continue; - } - - planeCarve[planeIndex] = classifyDensityPointNoWarpModules( - x0 + localX, - y, - z0 + localZ, - planeThresholdLimit[planeIndex], - localModules, - activeModuleCount, - remainingMin, - remainingMax - ); - } - } - - private void classifyAdaptivePlaneColumnsWarpOnly( - CaveCarveScratch scratch, - int x0, - int z0, - int y, - int[] planeColumnIndices, - double[] planeThresholdLimit, - int planeCount, - boolean[] planeCarve, - int adaptiveSampleStep, - double adaptiveThresholdMargin, - double[] adaptivePlaneDensity, - int axisCells, - int axisSamples - ) { - double[] adaptivePlanePrediction = scratch.adaptivePlanePrediction; - double[] adaptivePlaneAmbiguity = scratch.adaptivePlaneAmbiguity; - prepareAdaptivePlaneColumns( - scratch, - planeColumnIndices, - planeCount, - adaptiveSampleStep, - adaptiveThresholdMargin, - adaptivePlaneDensity, - axisCells, - axisSamples, - adaptivePlanePrediction, - adaptivePlaneAmbiguity - ); - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - int columnIndex = planeColumnIndices[planeIndex]; - int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int localZ = columnIndex & 15; - double threshold = planeThresholdLimit[planeIndex] * inverseNormalization; - double predictedDensity = adaptivePlanePrediction[planeIndex]; - double ambiguityMargin = adaptivePlaneAmbiguity[planeIndex]; - if (isAdaptivePlaneSampleAligned(localX, localZ, adaptiveSampleStep)) { - planeCarve[planeIndex] = predictedDensity <= threshold; - continue; - } - if (predictedDensity <= threshold - ambiguityMargin) { - planeCarve[planeIndex] = true; - continue; - } - if (predictedDensity > threshold + ambiguityMargin) { - planeCarve[planeIndex] = false; - continue; - } - if (adaptiveSampleStep >= ADAPTIVE_DEEP_SAMPLE_STEP) { - planeCarve[planeIndex] = predictedDensity <= threshold; - continue; - } - - planeCarve[planeIndex] = classifyDensityPointWarpOnly(scratch, x0 + localX, y, z0 + localZ, planeThresholdLimit[planeIndex]); - } - } - - private void classifyAdaptivePlaneColumnsWarpModules( - CaveCarveScratch scratch, - int x0, - int z0, - int y, - int[] planeColumnIndices, - double[] planeThresholdLimit, - int planeCount, - boolean[] planeCarve, - int adaptiveSampleStep, - double adaptiveThresholdMargin, - double[] adaptivePlaneDensity, - int axisCells, - int axisSamples, - CaveFieldModuleState[] localModules, - int activeModuleCount, - double[] remainingMin, - double[] remainingMax - ) { - double[] adaptivePlanePrediction = scratch.adaptivePlanePrediction; - double[] adaptivePlaneAmbiguity = scratch.adaptivePlaneAmbiguity; - prepareAdaptivePlaneColumns( - scratch, - planeColumnIndices, - planeCount, - adaptiveSampleStep, - adaptiveThresholdMargin, - adaptivePlaneDensity, - axisCells, - axisSamples, - adaptivePlanePrediction, - adaptivePlaneAmbiguity - ); - double minRemaining = remainingMin[0] * inverseNormalization; - double maxRemaining = remainingMax[0] * inverseNormalization; - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - int columnIndex = planeColumnIndices[planeIndex]; - int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int localZ = columnIndex & 15; - double threshold = planeThresholdLimit[planeIndex] * inverseNormalization; - double predictedDensity = adaptivePlanePrediction[planeIndex]; - double ambiguityMargin = adaptivePlaneAmbiguity[planeIndex]; - if (isAdaptivePlaneSampleAligned(localX, localZ, adaptiveSampleStep)) { - planeCarve[planeIndex] = classifyDensityPointWarpModulesFromExactDensity( - scratch, - x0 + localX, - y, - z0 + localZ, - threshold, - predictedDensity, - localModules, - activeModuleCount, - remainingMin, - remainingMax - ); - continue; - } - if ((predictedDensity + maxRemaining) <= threshold - ambiguityMargin) { - planeCarve[planeIndex] = true; - continue; - } - if ((predictedDensity + minRemaining) > threshold + ambiguityMargin) { - planeCarve[planeIndex] = false; - continue; - } - - planeCarve[planeIndex] = classifyDensityPointWarpModules( - scratch, - x0 + localX, - y, - z0 + localZ, - planeThresholdLimit[planeIndex], - localModules, - activeModuleCount, - remainingMin, - remainingMax - ); - } - } - - private void classifyAdaptivePlaneColumnsWarpModulesSampled( - CaveCarveScratch scratch, - int x0, - int z0, - int y, - int[] planeColumnIndices, - double[] planeThresholdLimit, - int planeCount, - boolean[] planeCarve, - int adaptiveSampleStep, - double adaptiveThresholdMargin, - double[] adaptivePlaneDensity, - int axisCells, - int axisSamples, - CaveFieldModuleState[] localModules, - int activeModuleCount, - double[] remainingMin, - double[] remainingMax - ) { - double[] adaptivePlanePrediction = scratch.adaptivePlanePrediction; - double[] adaptivePlaneAmbiguity = scratch.adaptivePlaneAmbiguity; - prepareAdaptivePlaneColumns( - scratch, - planeColumnIndices, - planeCount, - adaptiveSampleStep, - adaptiveThresholdMargin, - adaptivePlaneDensity, - axisCells, - axisSamples, - adaptivePlanePrediction, - adaptivePlaneAmbiguity - ); - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - int columnIndex = planeColumnIndices[planeIndex]; - int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int localZ = columnIndex & 15; - double threshold = planeThresholdLimit[planeIndex] * inverseNormalization; - double predictedDensity = adaptivePlanePrediction[planeIndex]; - double ambiguityMargin = adaptivePlaneAmbiguity[planeIndex]; - if (isAdaptivePlaneSampleAligned(localX, localZ, adaptiveSampleStep)) { - planeCarve[planeIndex] = predictedDensity <= threshold; - continue; - } - if (predictedDensity <= threshold - ambiguityMargin) { - planeCarve[planeIndex] = true; - continue; - } - if (predictedDensity > threshold + ambiguityMargin) { - planeCarve[planeIndex] = false; - continue; - } - if (adaptiveSampleStep >= ADAPTIVE_DEEP_SAMPLE_STEP) { - planeCarve[planeIndex] = predictedDensity <= threshold; - continue; - } - - planeCarve[planeIndex] = classifyDensityPointWarpModules( - scratch, - x0 + localX, - y, - z0 + localZ, - planeThresholdLimit[planeIndex], - localModules, - activeModuleCount, - remainingMin, - remainingMax - ); - } - } - - private boolean classifyDensityPointNoWarpNoModules(int x, int y, int z, double thresholdLimit) { - double density = baseDensity.signed(x, y, z) * baseWeight; - if ((density + detailMinContribution) > thresholdLimit) { - return false; - } - if ((density + detailMaxContribution) <= thresholdLimit) { - return true; - } - - density += detailDensity.signed(x, y, z) * detailWeight; - return density <= thresholdLimit; - } - - private boolean classifyDensityPointNoWarpModules( - int x, - int y, - int z, - double thresholdLimit, - CaveFieldModuleState[] localModules, - int activeModuleCount, - double[] remainingMin, - double[] remainingMax - ) { - if (activeModuleCount == 0) { - return classifyDensityPointNoWarpNoModules(x, y, z, thresholdLimit); - } - - double density = baseDensity.signed(x, y, z) * baseWeight; - if ((density + detailMinContribution + remainingMin[0]) > thresholdLimit) { - return false; - } - if ((density + detailMaxContribution + remainingMax[0]) <= thresholdLimit) { - return true; - } - - density += detailDensity.signed(x, y, z) * detailWeight; - if ((density + remainingMin[0]) > thresholdLimit) { - return false; - } - if ((density + remainingMax[0]) <= thresholdLimit) { - return true; - } - - for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { - density += localModules[moduleIndex].sample(x, y, z); - if ((density + remainingMin[moduleIndex + 1]) > thresholdLimit) { - return false; - } - if ((density + remainingMax[moduleIndex + 1]) <= thresholdLimit) { - return true; - } - } - - return density <= thresholdLimit; - } - - private int snapWarp(int c) { - int g = warpResolution; - if (g <= 1) { - return c; - } - if ((g & (g - 1)) == 0) { - return c & -g; - } - return Math.floorDiv(c, g) * g; - } - - private boolean classifyDensityPointWarpOnly(CaveCarveScratch scratch, int x, int y, int z, double thresholdLimit) { - int sx = snapWarp(x); - int sy = snapWarp(y); - int sz = snapWarp(z); - int warpSlot = prepareWarpSample(scratch, sx, sy, sz); - double warpA = scratch.warpCacheA[warpSlot]; - double warpB = scratch.warpCacheB[warpSlot]; - 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; - if ((density + detailMinContribution) > thresholdLimit) { - return false; - } - if ((density + detailMaxContribution) <= thresholdLimit) { - return true; - } - - density += detailDensity.signed(warpedX, warpedY, warpedZ) * detailWeight; - return density <= thresholdLimit; - } - - private boolean classifyDensityPointWarpModules( - CaveCarveScratch scratch, - int x, - int y, - int z, - double thresholdLimit, - CaveFieldModuleState[] localModules, - int activeModuleCount, - double[] remainingMin, - double[] remainingMax - ) { - if (activeModuleCount == 0) { - return classifyDensityPointWarpOnly(scratch, x, y, z, thresholdLimit); - } - - int sx = snapWarp(x); - int sy = snapWarp(y); - int sz = snapWarp(z); - int warpSlot = prepareWarpSample(scratch, sx, sy, sz); - double warpA = scratch.warpCacheA[warpSlot]; - double warpB = scratch.warpCacheB[warpSlot]; - 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; - if ((density + detailMinContribution + remainingMin[0]) > thresholdLimit) { - return false; - } - if ((density + detailMaxContribution + remainingMax[0]) <= thresholdLimit) { - return true; - } - - density += detailDensity.signed(warpedX, warpedY, warpedZ) * detailWeight; - if ((density + remainingMin[0]) > thresholdLimit) { - return false; - } - if ((density + remainingMax[0]) <= thresholdLimit) { - return true; - } - - for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { - density += localModules[moduleIndex].sample(warpedX, warpedY, warpedZ); - if ((density + remainingMin[moduleIndex + 1]) > thresholdLimit) { - return false; - } - if ((density + remainingMax[moduleIndex + 1]) <= thresholdLimit) { - return true; - } - } - - return density <= thresholdLimit; - } - - private boolean classifyDensityPointNoWarpModulesFromExactDensity( - int x, - int y, - int z, - double threshold, - double density, - CaveFieldModuleState[] localModules, - int activeModuleCount, - double[] remainingMin, - double[] remainingMax - ) { - if (activeModuleCount == 0) { - return density <= threshold; - } - - double minRemaining = remainingMin[0] * inverseNormalization; - double maxRemaining = remainingMax[0] * inverseNormalization; - if ((density + minRemaining) > threshold) { - return false; - } - if ((density + maxRemaining) <= threshold) { - return true; - } - - for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { - density += localModules[moduleIndex].sample(x, y, z) * inverseNormalization; - if ((density + (remainingMin[moduleIndex + 1] * inverseNormalization)) > threshold) { - return false; - } - if ((density + (remainingMax[moduleIndex + 1] * inverseNormalization)) <= threshold) { - return true; - } - } - - return density <= threshold; - } - - private boolean classifyDensityPointWarpModulesFromExactDensity( - CaveCarveScratch scratch, - int x, - int y, - int z, - double threshold, - double density, - CaveFieldModuleState[] localModules, - int activeModuleCount, - double[] remainingMin, - double[] remainingMax - ) { - if (activeModuleCount == 0) { - return density <= threshold; - } - - double minRemaining = remainingMin[0] * inverseNormalization; - double maxRemaining = remainingMax[0] * inverseNormalization; - if ((density + minRemaining) > threshold) { - return false; - } - if ((density + maxRemaining) <= threshold) { - return true; - } - - int sx = snapWarp(x); - int sy = snapWarp(y); - int sz = snapWarp(z); - int warpSlot = prepareWarpSample(scratch, sx, sy, sz); - double warpA = scratch.warpCacheA[warpSlot]; - double warpB = scratch.warpCacheB[warpSlot]; - double warpedX = x + (warpA * warpStrength); - double warpedY = y + (warpB * warpStrength); - double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); - for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { - density += localModules[moduleIndex].sample(warpedX, warpedY, warpedZ) * inverseNormalization; - if ((density + (remainingMin[moduleIndex + 1] * inverseNormalization)) > threshold) { - return false; - } - if ((density + (remainingMax[moduleIndex + 1] * inverseNormalization)) <= threshold) { - return true; - } - } - - return density <= threshold; - } - - private boolean isAdaptivePlaneSampleAligned(int localX, int localZ, int adaptiveSampleStep) { - if ((adaptiveSampleStep & (adaptiveSampleStep - 1)) == 0) { - int mask = adaptiveSampleStep - 1; - return (localX & mask) == 0 && (localZ & mask) == 0; - } - return localX % adaptiveSampleStep == 0 && localZ % adaptiveSampleStep == 0; - } - - private void prepareAdaptivePlaneSampleBounds( - CaveCarveScratch scratch, - int[] planeColumnIndices, - int planeCount, - int adaptiveSampleStep, - int[] adaptivePlaneSampleBounds, - int axisCells - ) { - prepareAdaptiveGeometry(scratch, adaptiveSampleStep, axisCells, axisCells + 1); - int[] adaptiveCellX = scratch.adaptiveCellX; - int[] adaptiveCellZ = scratch.adaptiveCellZ; - int minSampleX = axisCells; - int maxSampleX = 0; - int minSampleZ = axisCells; - int maxSampleZ = 0; - - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - int columnIndex = planeColumnIndices[planeIndex]; - int sampleX = adaptiveCellX[columnIndex]; - int sampleZ = adaptiveCellZ[columnIndex]; - if (sampleX < minSampleX) { - minSampleX = sampleX; - } - if (sampleX + 1 > maxSampleX) { - maxSampleX = sampleX + 1; - } - if (sampleZ < minSampleZ) { - minSampleZ = sampleZ; - } - if (sampleZ + 1 > maxSampleZ) { - maxSampleZ = sampleZ + 1; - } - } - - adaptivePlaneSampleBounds[0] = minSampleX; - adaptivePlaneSampleBounds[1] = maxSampleX; - adaptivePlaneSampleBounds[2] = minSampleZ; - adaptivePlaneSampleBounds[3] = maxSampleZ; - } - - private void prepareAdaptivePlaneColumns( - CaveCarveScratch scratch, - int[] planeColumnIndices, - int planeCount, - int adaptiveSampleStep, - double adaptiveThresholdMargin, - double[] adaptivePlaneDensity, - int axisCells, - int axisSamples, - double[] adaptivePlanePrediction, - double[] adaptivePlaneAmbiguity - ) { - prepareAdaptiveGeometry(scratch, adaptiveSampleStep, axisCells, axisSamples); - int[] adaptiveCellZ = scratch.adaptiveCellZ; - int[] adaptiveRow0 = scratch.adaptiveRow0; - int[] adaptiveRow1 = scratch.adaptiveRow1; - double[] adaptiveTx = scratch.adaptiveTx; - double[] adaptiveTz = scratch.adaptiveTz; - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - int columnIndex = planeColumnIndices[planeIndex]; - int cellZ = adaptiveCellZ[columnIndex]; - int row0 = adaptiveRow0[columnIndex]; - int row1 = adaptiveRow1[columnIndex]; - double tx = adaptiveTx[columnIndex]; - double tz = adaptiveTz[columnIndex]; - double d00 = adaptivePlaneDensity[row0 + cellZ]; - double d01 = adaptivePlaneDensity[row0 + cellZ + 1]; - double d10 = adaptivePlaneDensity[row1 + cellZ]; - double d11 = adaptivePlaneDensity[row1 + cellZ + 1]; - double dx0 = d00 + ((d10 - d00) * tx); - double dx1 = d01 + ((d11 - d01) * tx); - adaptivePlanePrediction[planeIndex] = dx0 + ((dx1 - dx0) * tz); - double minDensity = Math.min(Math.min(d00, d01), Math.min(d10, d11)); - double maxDensity = Math.max(Math.max(d00, d01), Math.max(d10, d11)); - adaptivePlaneAmbiguity[planeIndex] = adaptiveThresholdMargin + ((maxDensity - minDensity) * ADAPTIVE_LOCAL_RANGE_SCALE); - } - } - - private void prepareAdaptiveGeometry(CaveCarveScratch scratch, int adaptiveSampleStep, int axisCells, int axisSamples) { - if (scratch.adaptiveGeometryStep == adaptiveSampleStep && scratch.adaptiveGeometryAxisCells == axisCells) { - return; - } - - for (int columnIndex = 0; columnIndex < 256; columnIndex++) { - int localX = columnIndex >> 4; - int localZ = columnIndex & 15; - int cellX = Math.min(localX / adaptiveSampleStep, axisCells - 1); - int cellZ = Math.min(localZ / adaptiveSampleStep, axisCells - 1); - int x0 = cellX * adaptiveSampleStep; - int z0 = cellZ * adaptiveSampleStep; - int x1 = Math.min(x0 + adaptiveSampleStep, 16); - int z1 = Math.min(z0 + adaptiveSampleStep, 16); - scratch.adaptiveCellX[columnIndex] = cellX; - scratch.adaptiveCellZ[columnIndex] = cellZ; - scratch.adaptiveRow0[columnIndex] = cellX * axisSamples; - scratch.adaptiveRow1[columnIndex] = (cellX + 1) * axisSamples; - scratch.adaptiveTx[columnIndex] = x1 == x0 ? 0D : (localX - x0) / (double) (x1 - x0); - scratch.adaptiveTz[columnIndex] = z1 == z0 ? 0D : (localZ - z0) / (double) (z1 - z0); - } - - scratch.adaptiveGeometryStep = adaptiveSampleStep; - scratch.adaptiveGeometryAxisCells = axisCells; - } - - private double sampleDensityNoWarpNoModules(int x, int y, int z) { - double density = baseDensity.signed(x, y, z) * baseWeight; - density += detailDensity.signed(x, y, z) * detailWeight; - return density * inverseNormalization; - } - - private double sampleDensityNoWarpModules(CaveCarveScratch scratch, int x, int y, int z) { - int activeModuleCount = prepareActiveModules(scratch, y); - if (activeModuleCount == 0) { - return sampleDensityNoWarpNoModules(x, y, z); - } - - CaveFieldModuleState[] localModules = scratch.activeModules; - double density = baseDensity.signed(x, y, z) * baseWeight; - density += detailDensity.signed(x, y, z) * detailWeight; - for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { - CaveFieldModuleState module = localModules[moduleIndex]; - double moduleDensity = module.density.signed(x, y, z) - module.threshold; - if (module.invert) { - moduleDensity = -moduleDensity; - } - - density += moduleDensity * module.weight; - } - - return density * inverseNormalization; - } - - private double sampleDensityWarpOnly(CaveCarveScratch scratch, int x, int y, int z) { - int sx = snapWarp(x); - int sy = snapWarp(y); - int sz = snapWarp(z); - int warpSlot = prepareWarpSample(scratch, sx, sy, sz); - double warpA = scratch.warpCacheA[warpSlot]; - double warpB = scratch.warpCacheB[warpSlot]; - 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; - return density * inverseNormalization; - } - - private double sampleDensityWarpModules(CaveCarveScratch scratch, int x, int y, int z) { - int activeModuleCount = prepareActiveModules(scratch, y); - if (activeModuleCount == 0) { - return sampleDensityWarpOnly(scratch, x, y, z); - } - - CaveFieldModuleState[] localModules = scratch.activeModules; - return sampleDensityWarpModules(scratch, x, y, z, localModules, activeModuleCount); - } - - private double sampleDensityWarpModules(CaveCarveScratch scratch, int x, int y, int z, CaveFieldModuleState[] localModules, int activeModuleCount) { - int sx = snapWarp(x); - int sy = snapWarp(y); - int sz = snapWarp(z); - int warpSlot = prepareWarpSample(scratch, sx, sy, sz); - double warpA = scratch.warpCacheA[warpSlot]; - double warpB = scratch.warpCacheB[warpSlot]; - 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; - for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { - CaveFieldModuleState module = localModules[moduleIndex]; - double moduleDensity = module.density.signed(warpedX, warpedY, warpedZ) - module.threshold; - if (module.invert) { - moduleDensity = -moduleDensity; - } - - density += moduleDensity * module.weight; - } - - return density * inverseNormalization; - } - - private int prepareWarpSample(CaveCarveScratch scratch, int sx, int sy, int sz) { - int slot = mixWarpKey(sx, sy, sz) & (scratch.warpCacheX.length - 1); - if (scratch.warpCacheSet[slot] - && scratch.warpCacheX[slot] == sx - && scratch.warpCacheY[slot] == sy - && scratch.warpCacheZ[slot] == sz) { - return slot; - } - - scratch.warpCacheSet[slot] = true; - scratch.warpCacheX[slot] = sx; - scratch.warpCacheY[slot] = sy; - scratch.warpCacheZ[slot] = sz; - scratch.warpCacheA[slot] = warpDensity.signed(sx, sy, sz); - scratch.warpCacheB[slot] = warpDensity.signed(sx + 31.37D, sy - 17.21D, sz + 23.91D); - return slot; - } - - private static int mixWarpKey(int sx, int sy, int sz) { - int hash = sx * 73428767; - hash ^= sy * 91227153; - hash ^= sz * 43828939; - hash ^= hash >>> 16; - return hash; - } - - private int prepareActiveModules(CaveCarveScratch scratch, int y) { - CaveFieldModuleState[] configuredModules = modules; - int configuredCount = configuredModules.length; - if (configuredCount == 0) { - return 0; - } - - // Pure function of (y, modules). modules is final and the scratch is per carver per thread, - // so the band selection and the remaining-contribution prefix sums only change when y does. - if (scratch.activeModulesY == y) { - return scratch.activeModuleCount; - } - - if (scratch.activeModules.length < configuredCount) { - scratch.activeModules = new CaveFieldModuleState[configuredCount]; - } - - int activeCount = 0; - for (int moduleIndex = 0; moduleIndex < configuredCount; moduleIndex++) { - CaveFieldModuleState module = configuredModules[moduleIndex]; - if (y < module.minY || y > module.maxY) { - continue; - } - - scratch.activeModules[activeCount] = module; - activeCount++; - } - - if (scratch.activeModuleRemainingMin.length < activeCount + 1) { - scratch.activeModuleRemainingMin = new double[activeCount + 1]; - scratch.activeModuleRemainingMax = new double[activeCount + 1]; - } - - scratch.activeModuleRemainingMin[activeCount] = 0D; - scratch.activeModuleRemainingMax[activeCount] = 0D; - for (int moduleIndex = activeCount - 1; moduleIndex >= 0; moduleIndex--) { - CaveFieldModuleState module = scratch.activeModules[moduleIndex]; - scratch.activeModuleRemainingMin[moduleIndex] = scratch.activeModuleRemainingMin[moduleIndex + 1] + module.minContribution; - scratch.activeModuleRemainingMax[moduleIndex] = scratch.activeModuleRemainingMax[moduleIndex + 1] + module.maxContribution; - } - - scratch.activeModulesY = y; - scratch.activeModuleCount = activeCount; - return activeCount; - } - - private CarvedVoid[] prepareVoidByYTable(CaveCarveScratch scratch, int minY, int maxY) { - int size = Math.max(0, maxY - minY + 1); - if (scratch.voidByY.length < size) { - scratch.voidByY = new CarvedVoid[size]; - } - - CarvedVoid[] voidByY = scratch.voidByY; - boolean allowLava = profile.allowLava(); - - for (int y = minY; y <= maxY; y++) { - int offset = y - minY; - if (y > lavaHeight) { - voidByY[offset] = CarvedVoid.OPEN; - continue; - } - voidByY[offset] = allowLava ? CarvedVoid.LAVA : CarvedVoid.AIR; - } - - return voidByY; - } - - private CarvedVoid resolveVoid(CaveCarveScratch scratch, CarvedVoid verticalVoid, int x, int y, int z, - int columnIndex, int[] fluidMaxY, double localThreshold) { - if (verticalVoid != CarvedVoid.LAVA - && y <= fluidMaxY[columnIndex] - && isAquiferCandidate(scratch, x, y, z, localThreshold)) { - return CarvedVoid.FLUID; - } - return verticalVoid; - } - - private boolean isAquiferCandidate(CaveCarveScratch scratch, int x, int y, int z, double localThreshold) { - double depthFactor = Math.max(0D, Math.min(1.5D, (fluidHeight - y) / 48D)); - double cutoff = 0.35D + (depthFactor * 0.2D); - if (detailDensity.signed(x, y * 0.5D, z) <= cutoff) { - return false; - } - return !fluidRequiresFloor || hasAquiferCupSupport(scratch, x, y, z, localThreshold); - } - - private boolean isAquiferCandidate(int x, int y, int z, double localThreshold) { - return isAquiferCandidate(scratchCache.get(), x, y, z, localThreshold); - } - - private boolean hasAquiferCupSupport(CaveCarveScratch scratch, int x, int y, int z, double threshold) { - int floorY = Math.max(0, y - 1); - int deepFloorY = Math.max(0, y - 2); - int aboveY = Math.min(aquiferCeilingY, y + 1); - if (!isDensitySolid(scratch, x, floorY, z, threshold)) { - return false; - } - if (!isDensitySolid(scratch, x, deepFloorY, z, threshold - 0.05D)) { - return false; - } - - int support = 0; - if (isDensitySolid(scratch, x + 1, y, z, threshold)) { - support++; - } - if (isDensitySolid(scratch, x - 1, y, z, threshold)) { - support++; - } - if (isDensitySolid(scratch, x, y, z + 1, threshold)) { - support++; - } - if (isDensitySolid(scratch, x, y, z - 1, threshold)) { - support++; - } - if (isDensitySolid(scratch, x, aboveY, z, threshold)) { - support++; - } - return support >= 4; - } - - private boolean isDensitySolid(CaveCarveScratch scratch, int x, int y, int z, double threshold) { - return sampleDensityOptimized(scratch, x, y, z) > threshold; - } - - private void writeVoid(MantleLayer voids, int x, int y, int z, CarvedVoid carvedVoid, CaveFluidSupportPlan fluidSupportPlan) { - voids.set(x, y, z, carvedVoid); - if (fluidSupportPlan != null && carvedVoid == CarvedVoid.FLUID) { - fluidSupportPlan.add(x & LOCAL_MASK, y, z & LOCAL_MASK); - } - } - - private double clampColumnWeight(double weight) { - if (Double.isNaN(weight) || Double.isInfinite(weight)) { - return 0D; - } - - if (weight <= 0D) { - return 0D; - } - - if (weight >= 1D) { - return 1D; - } - - return weight; - } - - private double signed(double value) { - return (value * 2D) - 1D; - } - - private double applySurfaceCeilingFade( - CaveCarveScratch scratch, - double threshold, - int columnIndex, - int y, - int minY - ) { - if (!scratch.surfaceCeilingColumn[columnIndex]) { - return threshold; - } - - int ceilingDistance = scratch.columnMaxY[columnIndex] - y; - if (ceilingDistance < 0 || ceilingDistance >= SURFACE_CEILING_FADE_DEPTH) { - return threshold; - } - - double closureThreshold = scratch.surfaceClosureThreshold[y - minY]; - if (threshold <= closureThreshold) { - return threshold; - } - - double progress = ceilingDistance / (double) SURFACE_CEILING_FADE_DEPTH; - double smooth = progress * progress * (3D - (2D * progress)); - return closureThreshold + ((threshold - closureThreshold) * smooth); - } - - private void prepareSurfaceClosureThresholdTable(CaveCarveScratch scratch, int minY, int maxY) { - int size = Math.max(0, maxY - minY + 1); - if (scratch.surfaceClosureThreshold.length < size) { - scratch.surfaceClosureThreshold = new double[size]; - } - - double baseMinimum = -Math.abs(baseWeight) - Math.abs(detailWeight); - for (int y = minY; y <= maxY; y++) { - double minimumDensity = baseMinimum; - for (CaveFieldModuleState module : modules) { - if (y < module.minY || y > module.maxY) { - continue; - } - minimumDensity += Math.min(module.minContribution, module.maxContribution); - } - scratch.surfaceClosureThreshold[y - minY] = - (minimumDensity * inverseNormalization) - SURFACE_CEILING_SOLID_EPSILON; - } - } - - private double[] prepareVerticalEdgeFadeTable(CaveCarveScratch scratch, int minY, int maxY) { - int size = Math.max(0, maxY - minY + 1); - if (scratch.verticalEdgeFade.length < size) { - scratch.verticalEdgeFade = new double[size]; - } - - double[] verticalEdgeFade = scratch.verticalEdgeFade; - int fadeRange = Math.max(0, profile.verticalEdgeFade()); - double fadeStrength = Math.max(0D, profile.verticalEdgeFadeStrength()); - if (size <= 0 || fadeRange <= 0 || maxY <= minY || fadeStrength <= 0D) { - Arrays.fill(verticalEdgeFade, 0, size, 0D); - return verticalEdgeFade; - } - - for (int y = minY; y <= maxY; y++) { - int floorDistance = y - minY; - int ceilingDistance = maxY - y; - int edgeDistance = Math.min(floorDistance, ceilingDistance); - int offsetIndex = y - minY; - if (edgeDistance >= fadeRange) { - verticalEdgeFade[offsetIndex] = 0D; - continue; - } - - double t = Math.max(0D, Math.min(1D, edgeDistance / (double) fadeRange)); - double smooth = t * t * (3D - (2D * t)); - verticalEdgeFade[offsetIndex] = (1D - smooth) * fadeStrength; - } - - return verticalEdgeFade; - } -} diff --git a/module/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/module/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java index f3888a9c0..b3ca05162 100644 --- a/module/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java +++ b/module/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -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) { diff --git a/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileSampler.java b/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileSampler.java deleted file mode 100644 index 2ef0abc12..000000000 --- a/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileSampler.java +++ /dev/null @@ -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 . - */ - -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 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; - } - } -} diff --git a/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredByLevel.java b/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredByLevel.java index dd92f3c57..8a934f347 100644 --- a/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredByLevel.java +++ b/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredByLevel.java @@ -65,6 +65,11 @@ public final class DeclaredByLevel { 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); diff --git a/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredCaveProfiles.java b/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredCaveProfiles.java deleted file mode 100644 index b0d132f78..000000000 --- a/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredCaveProfiles.java +++ /dev/null @@ -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 . - */ - -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 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); - } -} diff --git a/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java b/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java index dc024227a..b2c0bfcf8 100644 --- a/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java +++ b/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java @@ -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; diff --git a/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java b/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java index 70e90b23e..5fb31e34d 100644 --- a/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java +++ b/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java @@ -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); - } } diff --git a/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java b/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java index e06cbb3e8..8e9f6b631 100644 --- a/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java +++ b/module/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java @@ -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 bottomCache = new AtomicCache<>(); private final AtomicCache wallWarpCache = new AtomicCache<>(); private final AtomicCache carveCache = new AtomicCache<>(); - private final AtomicCache 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 carvingBiome() { String carving = settings.carving(); Optional entry = world.dimensionCarving(carving); diff --git a/module/src/main/java/art/arcane/iris/modules/carve/Cave.java b/module/src/main/java/art/arcane/iris/modules/carve/Cave.java new file mode 100644 index 000000000..40195a6cc --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/Cave.java @@ -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 . + */ + +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 tunnel() { + return Optional.ofNullable(tunnel); + } + + public Optional cavern() { + return Optional.ofNullable(cavern); + } + + public Optional 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; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CaveCavern.java b/module/src/main/java/art/arcane/iris/modules/carve/CaveCavern.java new file mode 100644 index 000000000..a60f9a05b --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/CaveCavern.java @@ -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 . + */ + +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 pillars() { + return Optional.ofNullable(pillars); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CaveList.java b/module/src/main/java/art/arcane/iris/modules/carve/CaveList.java new file mode 100644 index 000000000..551b8ce62 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/CaveList.java @@ -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 . + */ + +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 caves = List.of(); + + public CaveList() { + } + + public CaveList(List caves) { + this.caves = List.copyOf(caves); + } + + public List caves() { + return caves == null ? List.of() : Collections.unmodifiableList(caves); + } + + @Override + public Set usedBiomes(PackResources pack, PackSettings dimension) { + Set 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; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CavePillars.java b/module/src/main/java/art/arcane/iris/modules/carve/CavePillars.java new file mode 100644 index 000000000..bd0da4f55 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/CavePillars.java @@ -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 . + */ + +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; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CaveProfile.java b/module/src/main/java/art/arcane/iris/modules/carve/CaveProfile.java deleted file mode 100644 index 4f57b7879..000000000 --- a/module/src/main/java/art/arcane/iris/modules/carve/CaveProfile.java +++ /dev/null @@ -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 . - */ - -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 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 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 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; - } -} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CaveResources.java b/module/src/main/java/art/arcane/iris/modules/carve/CaveResources.java new file mode 100644 index 000000000..9b3a9cbe5 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/CaveResources.java @@ -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 . + */ + +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 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; + } + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CaveTunnel.java b/module/src/main/java/art/arcane/iris/modules/carve/CaveTunnel.java new file mode 100644 index 000000000..23ebc5dea --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/CaveTunnel.java @@ -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 . + */ + +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; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/field/CarveSink.java b/module/src/main/java/art/arcane/iris/modules/carve/field/CarveSink.java new file mode 100644 index 000000000..78c5d71a6 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/field/CarveSink.java @@ -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 . + */ + +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); +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/field/CaveCarver.java b/module/src/main/java/art/arcane/iris/modules/carve/field/CaveCarver.java new file mode 100644 index 000000000..a3e74b741 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/field/CaveCarver.java @@ -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 . + */ + +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 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); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/field/CaveLimits.java b/module/src/main/java/art/arcane/iris/modules/carve/field/CaveLimits.java new file mode 100644 index 000000000..ea6a6cda5 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/field/CaveLimits.java @@ -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 . + */ + +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)); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/field/CaveNoise.java b/module/src/main/java/art/arcane/iris/modules/carve/field/CaveNoise.java new file mode 100644 index 000000000..e3d483d23 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/field/CaveNoise.java @@ -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 . + */ + +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)); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/field/CavernShape.java b/module/src/main/java/art/arcane/iris/modules/carve/field/CavernShape.java new file mode 100644 index 000000000..111e8db8f --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/field/CavernShape.java @@ -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 . + */ + +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; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/field/ChunkLattice.java b/module/src/main/java/art/arcane/iris/modules/carve/field/ChunkLattice.java new file mode 100644 index 000000000..b0029cb42 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/field/ChunkLattice.java @@ -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 . + */ + +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; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/field/Field3.java b/module/src/main/java/art/arcane/iris/modules/carve/field/Field3.java new file mode 100644 index 000000000..c99150301 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/field/Field3.java @@ -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 . + */ + +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); +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/field/FieldStats.java b/module/src/main/java/art/arcane/iris/modules/carve/field/FieldStats.java new file mode 100644 index 000000000..58642d571 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/field/FieldStats.java @@ -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 . + */ + +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]; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/field/LatticeCell.java b/module/src/main/java/art/arcane/iris/modules/carve/field/LatticeCell.java new file mode 100644 index 000000000..3d7d1b723 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/field/LatticeCell.java @@ -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 . + */ + +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); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/field/LatticeShape.java b/module/src/main/java/art/arcane/iris/modules/carve/field/LatticeShape.java new file mode 100644 index 000000000..a7b023600 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/field/LatticeShape.java @@ -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 . + */ + +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 = 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; + } + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/field/TunnelShape.java b/module/src/main/java/art/arcane/iris/modules/carve/field/TunnelShape.java new file mode 100644 index 000000000..be07ba9fe --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/field/TunnelShape.java @@ -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 . + */ + +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. + * + *

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)); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/floating/FloatingChildBiome.java b/module/src/main/java/art/arcane/iris/modules/floating/FloatingChildBiome.java index a0dd2ecd4..0e3aac5ca 100644 --- a/module/src/main/java/art/arcane/iris/modules/floating/FloatingChildBiome.java +++ b/module/src/main/java/art/arcane/iris/modules/floating/FloatingChildBiome.java @@ -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).")