Merge branch 'wave3b/5'

# Conflicts:
#	README.md
#	builtin-modules.txt
This commit is contained in:
piexel committed 2026-10-15 07:08:36 +02:00
commit 4644d94331
32 files changed
+2080 -1786

No files matched your search

+15 -6
View File
@@ -145,16 +145,17 @@ naming the class and what it uses. A VolmLib class that Iris's Bukkit jar strips
`core/volmlib-left-out-of-bukkit-jar.txt`, which its shadowJar reads too) is on that classpath but missing on a `core/volmlib-left-out-of-bukkit-jar.txt`, which its shadowJar reads too) is on that classpath but missing on a
server, so the check treats it as missing and fails the task naming it. `check` runs the task. server, so the check treats it as missing and fails the task naming it. `check` runs the task.
The jar holds `iris:post`, `iris:perfection`, `iris:matter`, `iris:loot`, `iris:spawn` and `iris:vanilla-features`, and the object placement stages The jar holds `iris:post`, `iris:perfection`, `iris:matter`, `iris:loot`, `iris:spawn`, `iris:vanilla-features` and
`iris:prepare`, `iris:anchor`, `iris:validate`, `iris:bore`, `iris:blocks`, `iris:stilt`, `iris:vacuum` and `iris:snow`. They are `iris:carve`, and the object placement stages `iris:prepare`, `iris:anchor`, `iris:validate`, `iris:bore`, `iris:blocks`, `iris:stilt`, `iris:vacuum` and `iris:snow`. They are
written against IrisApi and `art.arcane.iris.builtin` alone: the chunk's `BlockState` hunk, the block registry's traits and written against IrisApi and `art.arcane.iris.builtin` alone: the chunk's `BlockState` hunk, the block registry's traits and
`canPlaceOn`, the terrain sampler (heights around the chunk, slope, fluid height, where the upper dimension begins) and the `canPlaceOn`, the terrain sampler (heights around the chunk, slope, fluid height, where the upper dimension begins) and the
mantle's planned blocks; the placement stages read the placement being run through the `ObjectPlacement` facade, and the loot and mantle's planned blocks; the placement stages read the placement being run through the `ObjectPlacement` facade, and the loot and
spawn services, which have no chunk to ask, ask `LiveWorld` (both below). Without the jar a pack's world has no loot, block drops, spawn services, which have no chunk to ask, ask `LiveWorld` (both below). Without the jar a pack's world has no caves, vanilla
entity spawns or ambient effects, and its biomes' `loot`, `blockDrops`, `entitySpawners` and `effects` are not read. placed features, loot, block drops, entity spawns or ambient effects, and its biomes' `loot`, `blockDrops`, `entitySpawners` and
`effects` are not read.
Iris no longer compiles them in (`IrisModuleHost.generationModules()`), so a pack gets them by putting Iris no longer compiles them in (`IrisModuleHost.generationModules()`), so a pack gets them by putting
`iris-builtins.jar` into its `modules` folder; the built-ins that order after their stages (`iris:floating`, `iris-builtins.jar` into its `modules` folder; the built-ins that order after their stages (`iris:floating`,
`iris:decorant`, `iris:custom`) only order, so a pack without the jar still loads. Iris warns once per pack folder `iris:objects`, `iris:decorant`, `iris:custom`) only order, so a pack without the jar still loads. Iris warns once per pack folder
when a pack loads none of the jar's modules (`IrisModuleHost.JAR_MODULE_IDS`, which a test keeps equal to when a pack loads none of the jar's modules (`IrisModuleHost.JAR_MODULE_IDS`, which a test keeps equal to
`builtin-modules.txt`): add a module to the jar and to that list together. `builtin-modules.txt`): add a module to the jar and to that list together.
@@ -173,4 +174,12 @@ Iris's `IrisObjectPlacement`), the terrain questions of its placer and the world
and the block operations only the platform can do (turning a state with the object, merging two states, matching, traits of the and the block operations only the platform can do (turning a state with the object, merging two states, matching, traits of the
placement's own states). Its types answer with IrisApi, VolmLib and built-in values only. `prepare.PreparedPlacement`, the output of placement's own states). Its types answer with IrisApi, VolmLib and built-in values only. `prepare.PreparedPlacement`, the output of
`iris:prepare/transforms`, lives in the exposed package too, because `IrisStages` names it. `iris:post` reads its switches `iris:prepare/transforms`, lives in the exposed package too, because `IrisStages` names it. `iris:post` reads its switches
(`postProcessingWalls`, `postProcessingSlabs`) and the biome's `wall` and `slab` as module settings through its context. (`postProcessingWalls`, `postProcessingSlabs`) and the biome's `wall` and `slab` as module settings through its context.
`iris:carve` also reads the mantle's matter slices through `MatterMantle` (a facade Iris's mantle implements: the chunk of
`MatterCavern`s and markers it plans and applies, which the platform and the rest of Iris read as slices, not as module layers) and asks
`CaveDressing` for what the biome layers, decorators and fluid palette give a cave's walls, floor and ceiling. `CaveDressing` is
transitional: it goes when `iris:terrain` and `iris:decorant` are modules of the same jar and carve asks their classes directly.
A cave's dimension, region and biome settings are found by the id the layout's biome samples carry (`DeclaredByLevel`), its
absolute world Y bands convert with `PackWorld.minHeight()`, and its noise reads `NoiseSampler.signed(...)` (Iris's memoised signed read)
and `scaled(...)`. `caveLavaHeight` and `upperDimensionCarving` are its dimension settings.
+21
View File
@@ -39,3 +39,24 @@ include art/arcane/iris/engine/object/placement/IrisSurfaceSupport*.class
include art/arcane/iris/engine/object/placement/IrisObjectVacuum.class include art/arcane/iris/engine/object/placement/IrisObjectVacuum.class
module art.arcane.iris.engine.framework.vanillafeatures.VanillaFeaturesModule module art.arcane.iris.engine.framework.vanillafeatures.VanillaFeaturesModule
include art/arcane/iris/engine/framework/vanillafeatures/** include art/arcane/iris/engine/framework/vanillafeatures/**
module art.arcane.iris.engine.modifier.CarveModule
include art/arcane/iris/engine/modifier/CaveApplying*.class
include art/arcane/iris/engine/modifier/CaveBiomeBands*.class
include art/arcane/iris/engine/modifier/CaveBiomeCache.class
include art/arcane/iris/engine/modifier/CaveBlockClasses.class
include art/arcane/iris/engine/modifier/CarveColumnMask.class
include art/arcane/iris/engine/modifier/CarveWallBuffer*.class
include art/arcane/iris/engine/modifier/IrisCarveScratch.class
include art/arcane/iris/engine/mantle/components/CarveOrphanSweep*.class
include art/arcane/iris/engine/mantle/components/CarveWorld.class
include art/arcane/iris/engine/mantle/components/CaveCarveScratch*.class
include art/arcane/iris/engine/mantle/components/CaveCarving*.class
include art/arcane/iris/engine/mantle/components/CaveFieldModuleState.class
include art/arcane/iris/engine/mantle/components/CaveFluidSupportPlan*.class
include art/arcane/iris/engine/mantle/components/IrisCaveCarver3D*.class
include art/arcane/iris/engine/mantle/components/SurfaceFluidBoundaryPlan*.class
include art/arcane/iris/engine/object/terrain/carving/CarvingResolver*.class
include art/arcane/iris/engine/object/terrain/carving/CaveProfileSampler*.class
include art/arcane/iris/engine/object/terrain/carving/DeclaredByLevel.class
include art/arcane/iris/engine/object/terrain/carving/DeclaredCaveProfiles.class
include art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.class
@@ -0,0 +1,88 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.builtin;
import art.arcane.iris.builtin.decorant.DecorationPart;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.block.BlockState;
import com.volmit.hunk.Hunk;
import com.volmit.resource.ResourceId;
import com.volmit.world.PackWorld;
import java.util.List;
/**
* What a cave's floor, ceiling and walls get from the rest of Iris's terrain and decoration: the blocks of a biome's layers
* and wall, its decorators and the fluid of the dimension's palette. Those features keep their workers per world and are
* ported on their own; until they are modules this narrow interface is the one thing {@code iris:carve} needs from them, in
* IrisApi's types, and Iris's worlds implement it ({@link Source}).
*
* <p>Transitional: when {@code iris:terrain} and {@code iris:decorant} are modules of the same jar, {@code iris:carve} asks
* their classes directly and this interface goes.
*
* <p>The methods that give a block take the {@code chunk} hunk the block is for. A block read from here and written to that
* hunk keeps the identity of a content plugin's custom block, as it did when the layers wrote the platform's states themselves.
*/
public interface CaveDressing {
/** The dressing of {@code world}, which must be a world Iris generates. */
static CaveDressing of(PackWorld world) {
if (world instanceof Source source) {
return source.caveDressing();
}
throw new IllegalArgumentException("Built-in modules generate Iris's own worlds, not " + world);
}
/** Iris's worlds answer for their dressing. */
interface Source {
CaveDressing caveDressing();
}
/** Whether the dimension's fluid palette gives a fluid (water, lava) at the column; false where it gives none. */
boolean fluidPresentAt(int x, int z);
/** The block the dimension's fluid palette gives at the column; null where it gives none. */
BlockState fluidAt(Hunk<BlockState> chunk, int x, int z);
/** The block the biome's wall gives at the position; null where the biome has no wall or the layer gives none. */
BlockState wall(Hunk<BlockState> chunk, ResourceId biome, RNG rng, int x, int y, int z);
/** The blocks the biome's surface layers stack up to at the column, top first, at most {@code depth} of them. */
List<BlockState> floorLayers(Hunk<BlockState> chunk, ResourceId biome, int x, int z, RNG rng, int depth, int floorY);
/** The blocks the biome's cave ceiling layers stack up to at the column, nearest the ceiling first, at most {@code depth} of them. */
List<BlockState> ceilingLayers(Hunk<BlockState> chunk, ResourceId biome, int x, int z, RNG rng, int depth, int ceilingY);
/** Whether the biome has a decorator for {@code part}. */
boolean hasDecorators(ResourceId biome, DecorationPart part);
/**
* Decorates a cave's floor in the column at {@code chunk}'s {@code localX}, {@code localZ} (world {@code x}, {@code z}) above
* the block at {@code floorY}, with the biome's decorators for {@link DecorationPart#NONE}, in a space {@code airThickness} high.
*/
void decorateFloor(Hunk<BlockState> chunk, int localX, int localZ, int x, int z, ResourceId biome, int floorY, int airThickness);
/** Decorates a cave's ceiling the same way, from the block at {@code ceilingY} down, with the decorators for {@link DecorationPart#CEILING}. */
void decorateCeiling(Hunk<BlockState> chunk, int localX, int localZ, int x, int z, ResourceId biome, int ceilingY, int airThickness);
/**
* {@code layer}, the block a layer wants in the place of the ore {@code existing}, as the deepslate or the stone variant
* of the ore that fits the rock {@code existing} is; {@code layer} itself where it has no variant.
*/
BlockState deepSlateOre(Hunk<BlockState> chunk, BlockState existing, BlockState layer);
}
@@ -0,0 +1,59 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.builtin;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.matter.Matter;
import com.volmit.host.ReadOnlyMantle;
import com.volmit.mantle.Mantle;
/**
* Iris's mantle as the matter slices it stores, for the built-ins whose data the platform and the rest of Iris read as
* slices rather than through a {@link com.volmit.mantle.MantleLayer}: caves ({@code MatterCavern}) and markers. The
* slices are VolmLib's own types, which a pack module may use as well; Iris's worlds implement this next to
* {@link Mantle}, and {@link #of(Mantle)} reaches it from an invocation's mantle.
*
* <p>Heights are as the mantle stores them: above the dimension's bottom. A chunk the invocation reaches is pinned for
* as long as the invocation runs; callers neither release it nor keep it afterwards.
*/
public interface MatterMantle {
/**
* The matter side of {@code mantle}, which must be a mantle Iris hands to its stages. A chunk stage's mantle is read-only
* to the stage; the matter behind it is not, and a built-in chunk stage that writes markers into it (the caves' floors and
* ceilings) is why this reaches through.
*/
static MatterMantle of(Mantle mantle) {
if (mantle instanceof ReadOnlyMantle readOnly) {
return of(readOnly.host());
}
if (mantle instanceof MatterMantle matter) {
return matter;
}
throw new IllegalArgumentException("Built-in modules write Iris's own mantle, not " + mantle);
}
/** The mantle chunk at chunk coordinates {@code chunkX}, {@code chunkZ}, or null outside what the invocation reaches. */
MantleChunk<Matter> chunk(int chunkX, int chunkZ);
/**
* The mantle chunk at those coordinates if the world holds it in memory, wherever it is, or null. It is never loaded
* or created for the call and not pinned, so read it at once and do not keep it.
*/
MantleChunk<Matter> loadedChunk(int chunkX, int chunkZ);
}
@@ -0,0 +1,49 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.builtin.carve;
import com.volmit.FeatureAttachment.Target;
import com.volmit.IrisFeature;
import com.volmit.config.Desc;
import com.volmit.config.Feature;
import com.volmit.config.MaxNumber;
import com.volmit.config.MinNumber;
/** A dimension's {@code caveLavaHeight}, written as the bare number. */
@Desc("The subterranean fluid (cave lava) layer height, in engine-local Y where 0 is the bottom of the dimension, not world Y. With the default -64..320 height, 8 means world Y -56.")
@Feature(id = "iris:carve/lava-height", name = "Cave lava height", key = "caveLavaHeight", root = "height", targets = Target.DIMENSION)
public final class CaveLavaHeightSettings implements IrisFeature {
public static final int DEFAULT_HEIGHT = 8;
@MinNumber(0)
@MaxNumber(318)
@Desc("The subterranean fluid (cave lava) layer height, in engine-local Y where 0 is the bottom of the dimension, not world Y. With the default -64..320 height, 8 means world Y -56.")
private int height = DEFAULT_HEIGHT;
public CaveLavaHeightSettings() {
}
public CaveLavaHeightSettings(int height) {
this.height = height;
}
public int height() {
return height;
}
}
@@ -0,0 +1,43 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.builtin.carve;
import com.volmit.FeatureAttachment.Target;
import com.volmit.IrisFeature;
import com.volmit.config.Desc;
import com.volmit.config.Feature;
/** A dimension's {@code upperDimensionCarving}, written as the bare boolean. */
@Desc("When true, cave carving will cut through the upper dimension terrain. When false, the upper terrain is a solid untouched mass.")
@Feature(id = "iris:carve/upper-dimension", name = "Upper dimension carving", key = "upperDimensionCarving", root = "enabled", targets = Target.DIMENSION)
public final class UpperDimensionCarvingSettings implements IrisFeature {
@Desc("When true, cave carving will cut through the upper dimension terrain. When false, the upper terrain is a solid untouched mass.")
private boolean enabled = false;
public UpperDimensionCarvingSettings() {
}
public UpperDimensionCarvingSettings(boolean enabled) {
this.enabled = enabled;
}
public boolean enabled() {
return enabled;
}
}
@@ -1,5 +1,6 @@
package art.arcane.iris.engine.framework; package art.arcane.iris.engine.framework;
import art.arcane.iris.builtin.carve.CaveLavaHeightSettings;
import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.builtin.structure.StructureAnchorMode; import art.arcane.iris.builtin.structure.StructureAnchorMode;
import art.arcane.iris.builtin.structure.StructurePlacement; import art.arcane.iris.builtin.structure.StructurePlacement;
@@ -291,7 +292,7 @@ public final class StructureCaveAnchorResolver {
placement.underwater(), placement.underwater(),
cavern, cavern,
mantleY, mantleY,
engine.getDimension().getCaveLavaHeight()); engine.getDimension().getModuleSettings().find(CaveLavaHeightSettings.class).map(CaveLavaHeightSettings::height).orElse(CaveLavaHeightSettings.DEFAULT_HEIGHT));
} }
static boolean acceptsAnchorFluid( static boolean acceptsAnchorFluid(
@@ -0,0 +1,29 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle.components;
import com.volmit.noise.NoiseFactory;
/**
* What the cave carvers need to know about one world that does not change while it runs: the noise the world's pack builds,
* the carve seed, the dimension's height, its fluid and cave-lava heights (above the dimension's bottom) and the platform's Y of
* its bottom, which converts the absolute world Y of a cave biome band.
*/
public record CarveWorld(NoiseFactory noise, long carveSeed, int height, int fluidHeight, int lavaHeight, int minHeight) {
}
@@ -18,31 +18,19 @@
package art.arcane.iris.engine.mantle.components; package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.CaveDressing;
import art.arcane.iris.builtin.MatterMantle;
import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.builtin.carve.CaveProfile;
import art.arcane.iris.core.modules.IrisValues;
import art.arcane.iris.engine.IrisComplex;
import art.arcane.iris.engine.UpperDimensionContext;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.mantle.MantleWriter;
import art.arcane.iris.engine.terrain.TerrainPalettes;
import art.arcane.iris.engine.object.terrain.carving.CaveProfiles;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry;
import art.arcane.iris.engine.modifier.CaveBiomeBands;
import art.arcane.iris.engine.object.terrain.carving.CarvingBands;
import art.arcane.iris.engine.object.terrain.carving.CarvingResolver; import art.arcane.iris.engine.object.terrain.carving.CarvingResolver;
import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.engine.object.terrain.carving.DeclaredCaveProfiles;
import art.arcane.iris.engine.object.value.IrisRange; import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.util.common.data.B;
import art.arcane.iris.util.project.context.ChunkContext;
import art.arcane.iris.util.project.stream.ProceduralStream;
import art.arcane.iris.util.project.stream.utility.ChunkFillableDoubleStream2D;
import art.arcane.iris.util.simd.SimdKernels;
import art.arcane.iris.util.simd.SimdSupport;
import art.arcane.volmlib.util.documentation.ChunkCoordinates;
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; import com.volmit.config.Range;
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.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@@ -59,6 +47,8 @@ public class CaveCarving {
private static final int CHUNK_SIZE = 16; private static final int CHUNK_SIZE = 16;
private static final int CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE; private static final int CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE;
private static final int BLEND_RADIUS = 3; private static final int BLEND_RADIUS = 3;
/** 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 int FIELD_SIZE = CHUNK_SIZE + (BLEND_RADIUS * 2);
private static final double MIN_WEIGHT = 0.08D; private static final double MIN_WEIGHT = 0.08D;
private static final double THRESHOLD_PENALTY = 0.24D; private static final double THRESHOLD_PENALTY = 0.24D;
@@ -70,7 +60,11 @@ public class CaveCarving {
private static final double[] KERNEL_WEIGHT = new double[KERNEL_SIZE]; private static final double[] KERNEL_WEIGHT = new double[KERNEL_SIZE];
private static final ThreadLocal<BlendScratch> BLEND_SCRATCH = ThreadLocal.withInitial(BlendScratch::new); private static final ThreadLocal<BlendScratch> BLEND_SCRATCH = ThreadLocal.withInitial(BlendScratch::new);
private final Engine engine; private final CarveWorld world;
private final DeclaredCaveProfiles declaredProfiles;
private final CarvingResolver resolver;
private final CaveDressing dressing;
private final boolean upperDimensionCarving;
private final Object profileCarverLock = new Object(); private final Object profileCarverLock = new Object();
private volatile Map<CaveProfile, IrisCaveCarver3D> profileCarvers = new IdentityHashMap<>(); private volatile Map<CaveProfile, IrisCaveCarver3D> profileCarvers = new IdentityHashMap<>();
@@ -87,20 +81,20 @@ public class CaveCarving {
} }
} }
public CaveCarving(Engine engine) { public CaveCarving(PackWorld packWorld, CarveWorld world, boolean upperDimensionCarving) {
this.engine = engine; this.world = world;
this.declaredProfiles = DeclaredCaveProfiles.of(packWorld);
this.resolver = CarvingResolver.of(packWorld);
this.dressing = CaveDressing.of(packWorld);
this.upperDimensionCarving = upperDimensionCarving;
} }
/** Carves the caves of the chunk at chunk coordinates {@code x}, {@code z} into {@code writer}. */ /** Carves the caves of the chunk at chunk coordinates {@code x}, {@code z} into {@code mantle}, reading the terrain around it from {@code terrain}. */
public void carve(MantleWriter writer, int x, int z, ChunkContext context) { public void carve(MatterMantle mantle, TerrainSampler terrain, int x, int z) {
IrisComplex complex = context.getComplex();
CarvingResolver.State resolverState = new CarvingResolver.State();
BlendScratch blendScratch = BLEND_SCRATCH.get(); BlendScratch blendScratch = BLEND_SCRATCH.get();
int[] chunkSurfaceHeights = prepareChunkSurfaceHeights(x, z, context, blendScratch.chunkSurfaceHeights); int[] chunkSurfaceHeights = prepareChunkSurfaceHeights(x, z, terrain, blendScratch.chunkSurfaceHeights);
PrecisionStopwatch resolveStopwatch = PrecisionStopwatch.start(); List<WeightedProfile> weightedProfiles = resolveWeightedProfiles(x, z, terrain);
List<WeightedProfile> weightedProfiles = resolveWeightedProfiles(x, z, complex, resolverState); int fluidHeight = world.fluidHeight();
engine.getMetrics().getCarveResolve().put(resolveStopwatch.getMilliseconds());
int fluidHeight = engine.getDimension().getFluidHeight();
int[] surfaceFluidBoundaryStartY = blendScratch.surfaceFluidBoundaryStartY; int[] surfaceFluidBoundaryStartY = blendScratch.surfaceFluidBoundaryStartY;
SurfaceFluidBoundaryPlan.fill( SurfaceFluidBoundaryPlan.fill(
chunkSurfaceHeights, chunkSurfaceHeights,
@@ -113,27 +107,30 @@ public class CaveCarving {
); );
CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan(); CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan();
for (WeightedProfile weightedProfile : weightedProfiles) { for (WeightedProfile weightedProfile : weightedProfiles) {
carveProfile(weightedProfile, writer, x, z, chunkSurfaceHeights, surfaceFluidBoundaryStartY, fluidSupportPlan); carveProfile(weightedProfile, mantle, x, z, chunkSurfaceHeights, surfaceFluidBoundaryStartY, fluidSupportPlan);
} }
UpperDimensionContext upperCtx = engine.getUpperContext(); if (upperDimensionCarving && hasUpperDimension(terrain, x, z)) {
if (upperCtx != null && engine.getDimension().isUpperDimensionCarving()) { carveUpperTerrain(terrain, weightedProfiles, mantle, x, z, fluidSupportPlan);
carveUpperTerrain(upperCtx, weightedProfiles, writer, x, z, chunkSurfaceHeights, fluidSupportPlan);
} }
fluidSupportPlan.resolve(writer.acquireChunk(x, z)); fluidSupportPlan.resolve(mantle.chunk(x, z));
if (!weightedProfiles.isEmpty()) { if (!weightedProfiles.isEmpty()) {
CarveOrphanSweep.sweepChunk( CarveOrphanSweep.sweepChunk(
writer.acquireChunk(x, z), mantle.chunk(x, z),
chunkSurfaceHeights, chunkSurfaceHeights,
maxSurfaceBreakDepth(weightedProfiles), maxSurfaceBreakDepth(weightedProfiles),
writer.getMantle().getWorldHeight() - 1, world.height() - 1,
surfaceFluidBoundaryStartY, surfaceFluidBoundaryStartY,
fluidHeight fluidHeight
); );
} }
} }
private static boolean hasUpperDimension(TerrainSampler terrain, int chunkX, int chunkZ) {
return terrain.upperDimensionY(PowerOfTwoCoordinates.chunkToBlock(chunkX), PowerOfTwoCoordinates.chunkToBlock(chunkZ)).isPresent();
}
private static int maxSurfaceBreakDepth(List<WeightedProfile> weightedProfiles) { private static int maxSurfaceBreakDepth(List<WeightedProfile> weightedProfiles) {
int maxDepth = 0; int maxDepth = 0;
for (WeightedProfile weightedProfile : weightedProfiles) { for (WeightedProfile weightedProfile : weightedProfiles) {
@@ -142,21 +139,19 @@ public class CaveCarving {
return maxDepth; return maxDepth;
} }
@ChunkCoordinates private void carveProfile(WeightedProfile weightedProfile, MatterMantle mantle, int cx, int cz,
private void carveProfile(WeightedProfile weightedProfile, MantleWriter writer, int cx, int cz,
int[] chunkSurfaceHeights, int[] surfaceFluidBoundaryStartY, int[] chunkSurfaceHeights, int[] surfaceFluidBoundaryStartY,
CaveFluidSupportPlan fluidSupportPlan) { CaveFluidSupportPlan fluidSupportPlan) {
IrisCaveCarver3D carver = getCarver(weightedProfile.profile); IrisCaveCarver3D carver = getCarver(weightedProfile.profile);
carver.carve(writer, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY, carver.carve(mantle, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY,
weightedProfile.worldYRange, chunkSurfaceHeights, surfaceFluidBoundaryStartY, null, fluidSupportPlan); weightedProfile.worldYRange, chunkSurfaceHeights, surfaceFluidBoundaryStartY, null, fluidSupportPlan);
} }
private void carveUpperTerrain(UpperDimensionContext upperCtx, List<WeightedProfile> normalProfiles, private void carveUpperTerrain(TerrainSampler terrain, List<WeightedProfile> normalProfiles,
MantleWriter writer, int cx, int cz, int[] lowerSurfaceHeights, MatterMantle mantle, int cx, int cz,
CaveFluidSupportPlan fluidSupportPlan) { CaveFluidSupportPlan fluidSupportPlan) {
int chunkHeight = engine.getHeight(); int chunkHeight = world.height();
int worldMinHeight = engine.getWorld().minHeight(); int worldMinHeight = world.minHeight();
int gap = engine.getDimension().getUpperDimensionGap();
int baseX = PowerOfTwoCoordinates.chunkToBlock(cx); int baseX = PowerOfTwoCoordinates.chunkToBlock(cx);
int baseZ = PowerOfTwoCoordinates.chunkToBlock(cz); int baseZ = PowerOfTwoCoordinates.chunkToBlock(cz);
@@ -165,9 +160,7 @@ public class CaveCarving {
int worldX = baseX + localX; int worldX = baseX + localX;
for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) {
int worldZ = baseZ + localZ; int worldZ = baseZ + localZ;
int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); int upperY = terrain.upperDimensionY(worldX, worldZ).getAsInt();
int rawUpper = upperCtx.getUpperSurfaceY(worldX, worldZ);
int upperY = Math.max(rawUpper, lowerSurfaceHeights[columnIndex] + gap);
if (upperY < minUpperSurfaceY) { if (upperY < minUpperSurfaceY) {
minUpperSurfaceY = upperY; minUpperSurfaceY = upperY;
} }
@@ -178,34 +171,34 @@ public class CaveCarving {
return; return;
} }
IrisRange upperYRange = new IrisRange( Range upperYRange = Range.of(
minUpperSurfaceY + worldMinHeight, minUpperSurfaceY + worldMinHeight,
chunkHeight - 1 + worldMinHeight chunkHeight - 1 + worldMinHeight
); );
IrisRange fullVerticalRange = new IrisRange(0, chunkHeight); Range fullVerticalRange = Range.of(0, chunkHeight);
int[] ceilingSurfaceHeights = new int[CHUNK_AREA]; int[] ceilingSurfaceHeights = new int[CHUNK_AREA];
Arrays.fill(ceilingSurfaceHeights, chunkHeight - 1); Arrays.fill(ceilingSurfaceHeights, chunkHeight - 1);
for (WeightedProfile weightedProfile : normalProfiles) { for (WeightedProfile weightedProfile : normalProfiles) {
IrisRange constrainedRange; Range constrainedRange;
if (weightedProfile.worldYRange != null) { if (weightedProfile.worldYRange != null) {
double min = Math.max(weightedProfile.worldYRange.getMin(), upperYRange.getMin()); double min = Math.max(weightedProfile.worldYRange.min(), upperYRange.min());
double max = Math.min(weightedProfile.worldYRange.getMax(), upperYRange.getMax()); double max = Math.min(weightedProfile.worldYRange.max(), upperYRange.max());
if (min >= max) { if (min >= max) {
continue; continue;
} }
constrainedRange = new IrisRange(min, max); constrainedRange = Range.of(min, max);
} else { } else {
constrainedRange = upperYRange; constrainedRange = upperYRange;
} }
IrisCaveCarver3D carver = getCarver(weightedProfile.profile); IrisCaveCarver3D carver = getCarver(weightedProfile.profile);
carver.carve(writer, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY, carver.carve(mantle, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY,
constrainedRange, ceilingSurfaceHeights, null, fullVerticalRange, fluidSupportPlan); constrainedRange, ceilingSurfaceHeights, null, fullVerticalRange, fluidSupportPlan);
} }
} }
private List<WeightedProfile> resolveWeightedProfiles(int chunkX, int chunkZ, IrisComplex complex, CarvingResolver.State resolverState) { private List<WeightedProfile> resolveWeightedProfiles(int chunkX, int chunkZ, TerrainSampler terrain) {
BlendScratch blendScratch = BLEND_SCRATCH.get(); BlendScratch blendScratch = BLEND_SCRATCH.get();
CaveProfile[] profileField = blendScratch.profileField; CaveProfile[] profileField = blendScratch.profileField;
Map<CaveProfile, double[]> columnProfileWeights = blendScratch.columnProfileWeights; Map<CaveProfile, double[]> columnProfileWeights = blendScratch.columnProfileWeights;
@@ -215,7 +208,7 @@ public class CaveCarving {
double[] kernelProfileWeights = blendScratch.kernelProfileWeights; double[] kernelProfileWeights = blendScratch.kernelProfileWeights;
activeProfiles.clear(); activeProfiles.clear();
profileOrder.clear(); profileOrder.clear();
fillProfileField(profileField, chunkX, chunkZ, complex, resolverState, blendScratch); fillProfileField(profileField, chunkX, chunkZ, terrain, blendScratch);
for (int localX = 0; localX < CHUNK_SIZE; localX++) { for (int localX = 0; localX < CHUNK_SIZE; localX++) {
for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) {
@@ -285,7 +278,7 @@ public class CaveCarving {
// averageWeight ranks and orders carve passes, so it must be bit-identical across // averageWeight ranks and orders carve passes, so it must be bit-identical across
// installations: kernels.sum reassociates FP addition under the vector kernel, // installations: kernels.sum reassociates FP addition under the vector kernel,
// making profile order depend on a JVM flag. max() is order-independent and safe. // making profile order depend on a JVM flag. max() is order-independent and safe.
double maxWeight = SimdSupport.kernels().max(weights, weights.length); double maxWeight = maxOf(weights);
if (maxWeight < MIN_WEIGHT) { if (maxWeight < MIN_WEIGHT) {
continue; continue;
@@ -296,14 +289,14 @@ public class CaveCarving {
} }
List<WeightedProfile> blendedProfiles = limitAndMergeBlendedProfiles(columnWeightedProfiles, MAX_BLENDED_PROFILE_PASSES, CHUNK_AREA); List<WeightedProfile> blendedProfiles = limitAndMergeBlendedProfiles(columnWeightedProfiles, MAX_BLENDED_PROFILE_PASSES, CHUNK_AREA);
List<WeightedProfile> resolvedProfiles = resolveDimensionCarvingProfiles(chunkX, chunkZ, resolverState, blendScratch); List<WeightedProfile> resolvedProfiles = resolveDimensionCarvingProfiles(chunkX, chunkZ, blendScratch);
resolvedProfiles.addAll(blendedProfiles); resolvedProfiles.addAll(blendedProfiles);
return resolvedProfiles; return resolvedProfiles;
} }
private List<WeightedProfile> resolveDimensionCarvingProfiles(int chunkX, int chunkZ, CarvingResolver.State resolverState, BlendScratch blendScratch) { private List<WeightedProfile> resolveDimensionCarvingProfiles(int chunkX, int chunkZ, BlendScratch blendScratch) {
List<WeightedProfile> weightedProfiles = new ArrayList<>(); List<WeightedProfile> weightedProfiles = new ArrayList<>();
List<ResolvedCarvingEntry> entries = CarvingBands.of(engine).entries(); List<ResolvedCarvingEntry> entries = resolver.entries();
if (entries.isEmpty()) { if (entries.isEmpty()) {
return weightedProfiles; return weightedProfiles;
} }
@@ -316,25 +309,25 @@ public class CaveCarving {
continue; continue;
} }
IrisBiome rootBiome = CarvingResolver.resolveEntryBiome(engine, entry, resolverState); PackBiome rootBiome = resolver.entryBiome(entry);
if (rootBiome == null) { if (rootBiome == null) {
continue; continue;
} }
ResolvedCarvingEntry[] columnPlan = dimensionColumnPlans.computeIfAbsent(entry, key -> new ResolvedCarvingEntry[CHUNK_AREA]); ResolvedCarvingEntry[] columnPlan = dimensionColumnPlans.computeIfAbsent(entry, key -> new ResolvedCarvingEntry[CHUNK_AREA]);
buildDimensionColumnPlan(columnPlan, chunkX, chunkZ, entry, resolverState); buildDimensionColumnPlan(columnPlan, chunkX, chunkZ, entry);
Map<CaveProfile, double[]> rootProfileColumnWeights = new IdentityHashMap<>(); Map<CaveProfile, double[]> rootProfileColumnWeights = new IdentityHashMap<>();
List<CaveProfile> rootProfileOrder = new ArrayList<>(); List<CaveProfile> rootProfileOrder = new ArrayList<>();
IrisRange worldYRange = entry.worldYRange() == null ? null : IrisValues.range(entry.worldYRange()); Range worldYRange = entry.worldYRange();
for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) {
ResolvedCarvingEntry resolvedEntry = columnPlan[columnIndex]; ResolvedCarvingEntry resolvedEntry = columnPlan[columnIndex];
IrisBiome resolvedBiome = CarvingResolver.resolveEntryBiome(engine, resolvedEntry, resolverState); PackBiome resolvedBiome = resolver.entryBiome(resolvedEntry);
if (resolvedBiome == null) { if (resolvedBiome == null) {
continue; continue;
} }
CaveProfile profile = CaveProfiles.declaredBy(resolvedBiome); CaveProfile profile = declaredProfiles.ofBiome(resolvedBiome.id());
if (!isProfileEnabled(profile)) { if (!isProfileEnabled(profile)) {
continue; continue;
} }
@@ -356,7 +349,7 @@ public class CaveCarving {
return weightedProfiles; return weightedProfiles;
} }
private void buildDimensionColumnPlan(ResolvedCarvingEntry[] columnPlan, int chunkX, int chunkZ, ResolvedCarvingEntry entry, CarvingResolver.State resolverState) { private void buildDimensionColumnPlan(ResolvedCarvingEntry[] columnPlan, int chunkX, int chunkZ, ResolvedCarvingEntry entry) {
int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX); int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX);
int baseZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); int baseZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ);
for (int localX = 0; localX < CHUNK_SIZE; localX++) { for (int localX = 0; localX < CHUNK_SIZE; localX++) {
@@ -364,30 +357,22 @@ public class CaveCarving {
for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) {
int worldZ = baseZ + localZ; int worldZ = baseZ + localZ;
int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ);
columnPlan[columnIndex] = CarvingResolver.resolveFromRoot(engine, entry, worldX, worldZ, resolverState); columnPlan[columnIndex] = resolver.resolveFromRoot(entry, worldX, worldZ);
} }
} }
} }
private void fillProfileField(CaveProfile[] profileField, int chunkX, int chunkZ, IrisComplex complex, CarvingResolver.State resolverState, BlendScratch blendScratch) { private void fillProfileField(CaveProfile[] profileField, int chunkX, int chunkZ, TerrainSampler terrain, BlendScratch blendScratch) {
int startX = PowerOfTwoCoordinates.chunkToBlock(chunkX) - BLEND_RADIUS; int startX = PowerOfTwoCoordinates.chunkToBlock(chunkX) - BLEND_RADIUS;
int startZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ) - BLEND_RADIUS; int startZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ) - BLEND_RADIUS;
prefillProfileFieldSamples(startX, startZ, complex, blendScratch); prefillFieldHeightsAndFluid(terrain, startX, startZ, blendScratch);
for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) { for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) {
int worldX = startX + fieldX; int worldX = startX + fieldX;
for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) { for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) {
int worldZ = startZ + fieldZ; int worldZ = startZ + fieldZ;
int fieldIndex = (fieldX * FIELD_SIZE) + fieldZ; int fieldIndex = (fieldX * FIELD_SIZE) + fieldZ;
profileField[fieldIndex] = resolveColumnProfile( profileField[fieldIndex] = resolveColumnProfile(terrain, worldX, worldZ, blendScratch.fieldSurfaceHeights[fieldIndex]);
worldX,
worldZ,
blendScratch.fieldSurfaceHeights[fieldIndex],
blendScratch.fieldRegions[fieldIndex],
blendScratch.fieldSurfaceBiomes[fieldIndex],
blendScratch.fieldCaveBiomes[fieldIndex],
resolverState
);
} }
} }
} }
@@ -402,65 +387,34 @@ public class CaveCarving {
return -1; return -1;
} }
private CaveProfile resolveColumnProfile( /**
int worldX, * The profile that carves a column: the dimension's, replaced by the region's, the surface biome's and the cave biome's
int worldZ, * wherever they declare an enabled one. The cave biome is the one the world places at the depth below the surface this
double surfaceHeight, * column's caves start at ({@link #CAVE_SAMPLE_DEPTH_BELOW_SURFACE_BLOCKS}), after the dimension's carving bands.
IrisRegion region, */
IrisBiome surfaceBiome, private CaveProfile resolveColumnProfile(TerrainSampler terrain, int worldX, int worldZ, double surfaceHeight) {
IrisBiome caveBiome,
CarvingResolver.State resolverState
) {
CaveProfile resolved = null; CaveProfile resolved = null;
CaveProfile dimensionProfile = CaveProfiles.declaredBy(engine.getDimension()); CaveProfile dimensionProfile = declaredProfiles.ofDimension();
if (isProfileEnabled(dimensionProfile)) { if (isProfileEnabled(dimensionProfile)) {
resolved = dimensionProfile; resolved = dimensionProfile;
} }
if (region != null) {
CaveProfile regionProfile = CaveProfiles.declaredBy(region);
if (isProfileEnabled(regionProfile)) {
resolved = regionProfile;
}
}
if (surfaceBiome != null) {
CaveProfile surfaceProfile = CaveProfiles.declaredBy(surfaceBiome);
if (isProfileEnabled(surfaceProfile)) {
resolved = surfaceProfile;
}
}
int roundedSurfaceY = (int) Math.round(surfaceHeight); int roundedSurfaceY = (int) Math.round(surfaceHeight);
int sampleY = Math.max(1, roundedSurfaceY - 56); int sampleY = Math.max(1, roundedSurfaceY - CAVE_SAMPLE_DEPTH_BELOW_SURFACE_BLOCKS);
int worldY = sampleY + engine.getWorld().minHeight(); BiomeSample sample = terrain.biome(worldX, sampleY, worldZ);
ResolvedCarvingEntry rootCarvingEntry = CarvingResolver.resolveRootEntry(engine, worldY, resolverState);
IrisBiome resolvedCarvingBiome = null;
if (rootCarvingEntry != null) {
ResolvedCarvingEntry resolvedCarvingEntry = CarvingResolver.resolveFromRoot(engine, rootCarvingEntry, worldX, worldZ, resolverState);
resolvedCarvingBiome = CarvingResolver.resolveEntryBiome(engine, resolvedCarvingEntry, resolverState);
if (resolvedCarvingBiome != null) {
caveBiome = resolvedCarvingBiome;
}
}
if (caveBiome != null) {
IrisBiome effectiveCaveBiome = caveBiome;
if (resolvedCarvingBiome == null && surfaceBiome != null) {
if (surfaceBiome != null) {
int truncatedSurfaceY = (int) surfaceHeight;
int depthBelowSurface = truncatedSurfaceY - sampleY;
if (depthBelowSurface <= 0) {
effectiveCaveBiome = surfaceBiome;
} else {
int minDepth = Math.max(0, CaveBiomeBands.minDepthBelowSurface(caveBiome));
if (depthBelowSurface < minDepth) {
effectiveCaveBiome = surfaceBiome;
}
}
}
}
CaveProfile caveProfile = CaveProfiles.declaredBy(effectiveCaveBiome); 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)) { if (isProfileEnabled(caveProfile)) {
resolved = caveProfile; resolved = caveProfile;
} }
@@ -469,37 +423,14 @@ public class CaveCarving {
return resolved; return resolved;
} }
private void prefillProfileFieldSamples(int startX, int startZ, IrisComplex complex, BlendScratch blendScratch) { private void prefillFieldHeightsAndFluid(TerrainSampler terrain, int startX, int startZ, BlendScratch blendScratch) {
fillFieldHeights(complex.getHeightStream(), startX, startZ, blendScratch.fieldSurfaceHeights);
fillFieldFluidPresence(TerrainPalettes.of(engine), startX, startZ, blendScratch.fieldHasFluid);
fillFieldObjects(complex.getRegionStream(), startX, startZ, blendScratch.fieldRegions);
fillFieldObjects(complex.getTrueBiomeStream(), startX, startZ, blendScratch.fieldSurfaceBiomes);
fillFieldObjects(complex.getCaveBiomeStream(), startX, startZ, blendScratch.fieldCaveBiomes);
}
private <T> void fillFieldObjects(ProceduralStream<T> stream, int startX, int startZ, T[] target) {
for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) { for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) {
int worldX = startX + fieldX; int worldX = startX + fieldX;
for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) { for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) {
target[(fieldX * FIELD_SIZE) + fieldZ] = stream.get(worldX, startZ + fieldZ); int worldZ = startZ + fieldZ;
} int fieldIndex = (fieldX * FIELD_SIZE) + fieldZ;
} blendScratch.fieldSurfaceHeights[fieldIndex] = terrain.surfaceY(worldX, worldZ);
} blendScratch.fieldHasFluid[fieldIndex] = dressing.fluidPresentAt(worldX, worldZ);
private void fillFieldHeights(ProceduralStream<Double> stream, int startX, int startZ, double[] target) {
for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) {
int worldX = startX + fieldX;
for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) {
target[(fieldX * FIELD_SIZE) + fieldZ] = stream.getDouble(worldX, startZ + fieldZ);
}
}
}
private void fillFieldFluidPresence(TerrainPalettes palettes, int startX, int startZ, boolean[] target) {
for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) {
int worldX = startX + fieldX;
for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) {
target[(fieldX * FIELD_SIZE) + fieldZ] = B.isFluid(palettes.fluidAt(worldX, startZ + fieldZ));
} }
} }
} }
@@ -510,7 +441,7 @@ public class CaveCarving {
return carver; return carver;
} }
IrisCaveCarver3D createdCarver = new IrisCaveCarver3D(engine, profile); IrisCaveCarver3D createdCarver = new IrisCaveCarver3D(world, profile);
synchronized (profileCarverLock) { synchronized (profileCarverLock) {
IrisCaveCarver3D published = profileCarvers.get(profile); IrisCaveCarver3D published = profileCarvers.get(profile);
if (published != null) { if (published != null) {
@@ -528,39 +459,25 @@ public class CaveCarving {
return profile != null && profile.enabled(); return profile != null && profile.enabled();
} }
private int[] prepareChunkSurfaceHeights(int chunkX, int chunkZ, ChunkContext context, int[] scratch) { private int[] prepareChunkSurfaceHeights(int chunkX, int chunkZ, TerrainSampler terrain, int[] scratch) {
int[] surfaceHeights = scratch;
int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX); int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX);
int baseZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); int baseZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ);
boolean useContextHeight = context != null
&& context.getHeight() != null
&& context.getX() == baseX
&& context.getZ() == baseZ;
double[] cachedChunkHeights = null;
if (!useContextHeight && context != null) {
ProceduralStream<Double> heightStream = context.getComplex().getHeightStream();
if (heightStream instanceof ChunkFillableDoubleStream2D cachedHeightStream) {
cachedChunkHeights = BLEND_SCRATCH.get().chunkSurfaceHeightSamples;
cachedHeightStream.fillChunkDoubles(baseX, baseZ, cachedChunkHeights);
}
}
for (int localX = 0; localX < CHUNK_SIZE; localX++) { for (int localX = 0; localX < CHUNK_SIZE; localX++) {
int worldX = baseX + localX; int worldX = baseX + localX;
for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) {
int worldZ = baseZ + localZ;
int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ);
if (useContextHeight) { scratch[columnIndex] = (int) Math.round(terrain.surfaceY(worldX, baseZ + localZ));
surfaceHeights[columnIndex] = context.getRoundedHeight(localX, localZ);
continue;
}
if (cachedChunkHeights != null) {
surfaceHeights[columnIndex] = (int) Math.round(cachedChunkHeights[(localZ << 4) + localX]);
continue;
}
surfaceHeights[columnIndex] = engine.getHeight(worldX, worldZ);
} }
} }
return surfaceHeights; return scratch;
}
private static double maxOf(double[] values) {
double max = Double.NEGATIVE_INFINITY;
for (double value : values) {
max = Math.max(max, value);
}
return max;
} }
private static List<WeightedProfile> limitAndMergeBlendedProfiles(List<WeightedProfile> blendedProfiles, int maxProfiles) { private static List<WeightedProfile> limitAndMergeBlendedProfiles(List<WeightedProfile> blendedProfiles, int maxProfiles) {
@@ -664,10 +581,10 @@ public class CaveCarving {
private final CaveProfile profile; private final CaveProfile profile;
private final double[] columnWeights; private final double[] columnWeights;
private final double averageWeight; private final double averageWeight;
private final IrisRange worldYRange; private final Range worldYRange;
private final int sequence; private final int sequence;
private WeightedProfile(CaveProfile profile, double[] columnWeights, double averageWeight, IrisRange worldYRange, int sequence) { private WeightedProfile(CaveProfile profile, double[] columnWeights, double averageWeight, Range worldYRange, int sequence) {
this.profile = profile; this.profile = profile;
this.columnWeights = columnWeights; this.columnWeights = columnWeights;
this.averageWeight = averageWeight; this.averageWeight = averageWeight;
@@ -690,11 +607,7 @@ public class CaveCarving {
private final List<CaveProfile> profileOrder = new ArrayList<>(); private final List<CaveProfile> profileOrder = new ArrayList<>();
private final double[] fieldSurfaceHeights = new double[FIELD_SIZE * FIELD_SIZE]; private final double[] fieldSurfaceHeights = new double[FIELD_SIZE * FIELD_SIZE];
private final boolean[] fieldHasFluid = new boolean[FIELD_SIZE * FIELD_SIZE]; private final boolean[] fieldHasFluid = new boolean[FIELD_SIZE * FIELD_SIZE];
private final IrisRegion[] fieldRegions = new IrisRegion[FIELD_SIZE * FIELD_SIZE];
private final IrisBiome[] fieldSurfaceBiomes = new IrisBiome[FIELD_SIZE * FIELD_SIZE];
private final IrisBiome[] fieldCaveBiomes = new IrisBiome[FIELD_SIZE * FIELD_SIZE];
private final int[] chunkSurfaceHeights = new int[CHUNK_AREA]; private final int[] chunkSurfaceHeights = new int[CHUNK_AREA];
private final int[] surfaceFluidBoundaryStartY = new int[CHUNK_AREA]; private final int[] surfaceFluidBoundaryStartY = new int[CHUNK_AREA];
private final double[] chunkSurfaceHeightSamples = new double[CHUNK_AREA];
} }
} }
@@ -18,12 +18,12 @@
package art.arcane.iris.engine.mantle.components; package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.engine.object.terrain.carving.ResolvedCaveProfile; import art.arcane.iris.builtin.carve.CaveFieldModule;
import art.arcane.iris.engine.object.value.IrisRange; import com.volmit.config.Range;
import art.arcane.iris.util.project.noise.CNG; import com.volmit.noise.NoiseSampler;
final class CaveFieldModuleState { final class CaveFieldModuleState {
final CNG density; final NoiseSampler density;
final int minY; final int minY;
final int maxY; final int maxY;
final double weight; final double weight;
@@ -32,11 +32,11 @@ final class CaveFieldModuleState {
final double minContribution; final double minContribution;
final double maxContribution; final double maxContribution;
CaveFieldModuleState(ResolvedCaveProfile.Module module, CNG density) { CaveFieldModuleState(CaveFieldModule module, NoiseSampler density) {
IrisRange range = module.verticalRange(); Range range = module.verticalRange();
this.density = density; this.density = density;
this.minY = (int) Math.floor(range.getMin()); this.minY = (int) Math.floor(range.min());
this.maxY = (int) Math.ceil(range.getMax()); this.maxY = (int) Math.ceil(range.max());
this.weight = module.weight(); this.weight = module.weight();
this.threshold = module.threshold(); this.threshold = module.threshold();
this.invert = module.invert(); this.invert = module.invert();
@@ -47,12 +47,12 @@ final class CaveFieldModuleState {
} }
double sample(double x, int y, double z) { double sample(double x, int y, double z) {
double sampled = density.noiseFastSigned3D(x, y, z); double sampled = density.signed(x, y, z);
return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight; return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight;
} }
double sample(double x, double y, double z) { double sample(double x, double y, double z) {
double sampled = density.noiseFastSigned3D(x, y, z); double sampled = density.signed(x, y, z);
return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight; return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight;
} }
} }
@@ -18,22 +18,19 @@
package art.arcane.iris.engine.mantle.components; package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.MatterMantle;
import art.arcane.iris.builtin.carve.CaveFieldModule;
import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.builtin.carve.CaveProfile;
import art.arcane.iris.engine.object.terrain.carving.ResolvedCaveProfile;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.mantle.MantleWriter;
import art.arcane.iris.engine.object.value.IrisRange;
import art.arcane.iris.engine.object.noise.IrisStyledRange;
import art.arcane.iris.util.project.noise.CNG;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk; import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.math.M; import art.arcane.volmlib.util.math.M;
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.matter.Matter; import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.MatterCavern; import art.arcane.volmlib.util.matter.MatterCavern;
import art.arcane.volmlib.util.matter.MatterSlice; import art.arcane.volmlib.util.matter.MatterSlice;
import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; import com.volmit.config.Range;
import com.volmit.noise.NoiseSampler;
import com.volmit.noise.NoiseStyle;
import com.volmit.noise.StyledRange;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@@ -51,15 +48,13 @@ public class IrisCaveCarver3D {
private static final int SURFACE_CEILING_FADE_DEPTH = 12; private static final int SURFACE_CEILING_FADE_DEPTH = 12;
private static final double SURFACE_CEILING_SOLID_EPSILON = 0.000001D; private static final double SURFACE_CEILING_SOLID_EPSILON = 0.000001D;
private final Engine engine;
private final IrisData data;
private final CaveProfile profile; private final CaveProfile profile;
private final ResolvedCaveProfile resolved; private final NoiseSampler baseDensity;
private final CNG baseDensity; private final NoiseSampler detailDensity;
private final CNG detailDensity; private final NoiseSampler warpDensity;
private final CNG warpDensity; private final NoiseSampler surfaceBreakDensity;
private final CNG surfaceBreakDensity; private final NoiseSampler thresholdNoise;
private final RNG thresholdRng; private final int lavaHeight;
private final CaveFieldModuleState[] modules; private final CaveFieldModuleState[] modules;
private final double inverseNormalization; private final double inverseNormalization;
private final MatterCavern carveAir; private final MatterCavern carveAir;
@@ -80,25 +75,24 @@ public class IrisCaveCarver3D {
private final int fluidMinDepthBelowSurface; private final int fluidMinDepthBelowSurface;
private final int fluidHeight; private final int fluidHeight;
private final int aquiferCeilingY; private final int aquiferCeilingY;
private final int minHeight;
private final int worldHeight;
private final ThreadLocal<CaveCarveScratch> scratchCache = ThreadLocal.withInitial(CaveCarveScratch::new); private final ThreadLocal<CaveCarveScratch> scratchCache = ThreadLocal.withInitial(CaveCarveScratch::new);
public IrisCaveCarver3D(Engine engine, CaveProfile profile) { public IrisCaveCarver3D(CarveWorld world, CaveProfile profile) {
this.engine = engine;
this.data = engine.getData();
this.profile = profile; this.profile = profile;
this.resolved = ResolvedCaveProfile.of(profile);
this.carveAir = new MatterCavern(true, "", LIQUID_AIR); this.carveAir = new MatterCavern(true, "", LIQUID_AIR);
this.carveFluid = new MatterCavern(true, "", LIQUID_FLUID); this.carveFluid = new MatterCavern(true, "", LIQUID_FLUID);
this.carveLava = new MatterCavern(true, "", LIQUID_LAVA); this.carveLava = new MatterCavern(true, "", LIQUID_LAVA);
this.carveForcedAir = new MatterCavern(true, "", LIQUID_FORCED_AIR); this.carveForcedAir = new MatterCavern(true, "", LIQUID_FORCED_AIR);
List<CaveFieldModuleState> moduleStates = new ArrayList<>(); List<CaveFieldModuleState> moduleStates = new ArrayList<>();
RNG baseRng = new RNG(engine.getSeedManager().getCarve()); long carveSeed = world.carveSeed();
this.baseDensity = resolved.baseDensityStyle().create(baseRng.nextParallelRNG(934_447), data); this.baseDensity = world.noise().sampler(profile.baseDensityStyle(), carveSeed + 934_447);
this.detailDensity = resolved.detailDensityStyle().create(baseRng.nextParallelRNG(612_991), data); this.detailDensity = world.noise().sampler(profile.detailDensityStyle(), carveSeed + 612_991);
this.warpDensity = resolved.warpStyle().create(baseRng.nextParallelRNG(770_713), data); this.warpDensity = world.noise().sampler(profile.warpStyle(), carveSeed + 770_713);
this.surfaceBreakDensity = resolved.surfaceBreakStyle().create(baseRng.nextParallelRNG(341_219), data); this.surfaceBreakDensity = world.noise().sampler(profile.surfaceBreakStyle(), carveSeed + 341_219);
this.thresholdRng = baseRng.nextParallelRNG(489_112); this.thresholdNoise = world.noise().sampler(profile.densityThreshold().style(), carveSeed + 489_112);
this.baseWeight = profile.baseWeight(); this.baseWeight = profile.baseWeight();
this.detailWeight = profile.detailWeight(); this.detailWeight = profile.detailWeight();
this.warpStrength = profile.warpStrength(); this.warpStrength = profile.warpStrength();
@@ -107,13 +101,16 @@ public class IrisCaveCarver3D {
this.allowFluid = profile.allowFluid(); this.allowFluid = profile.allowFluid();
this.fluidRequiresFloor = profile.fluidRequiresFloor(); this.fluidRequiresFloor = profile.fluidRequiresFloor();
this.fluidMinDepthBelowSurface = Math.max(0, profile.fluidMinDepthBelowSurface()); this.fluidMinDepthBelowSurface = Math.max(0, profile.fluidMinDepthBelowSurface());
this.fluidHeight = engine.getDimension().getFluidHeight(); this.fluidHeight = world.fluidHeight();
this.aquiferCeilingY = engine.getHeight() - 1; 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); double weight = Math.abs(baseWeight) + Math.abs(detailWeight);
int index = 0; int index = 0;
for (ResolvedCaveProfile.Module module : resolved.modules()) { for (CaveFieldModule module : profile.modules()) {
CNG moduleDensity = module.style().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), data); NoiseSampler moduleDensity = world.noise().sampler(module.style(), carveSeed + 1_000_003L + (index * 65_537L));
CaveFieldModuleState state = new CaveFieldModuleState(module, moduleDensity); CaveFieldModuleState state = new CaveFieldModuleState(module, moduleDensity);
moduleStates.add(state); moduleStates.add(state);
weight += Math.abs(state.weight); weight += Math.abs(state.weight);
@@ -129,249 +126,183 @@ public class IrisCaveCarver3D {
detailMaxContribution = detailWeight; detailMaxContribution = detailWeight;
} }
public int carve(MantleWriter writer, int chunkX, int chunkZ) {
CaveCarveScratch scratch = scratchCache.get();
if (!scratch.fullWeightsInitialized) {
Arrays.fill(scratch.fullWeights, 1D);
scratch.fullWeightsInitialized = true;
}
return carve(writer, chunkX, chunkZ, scratch.fullWeights, 0D, 0D, null, null);
}
public int carve( public int carve(
MantleWriter writer, MatterMantle mantle,
int chunkX,
int chunkZ,
double[] columnWeights,
double minWeight,
double thresholdPenalty
) {
return carve(writer, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, null, null);
}
public int carve(
MantleWriter writer,
int chunkX, int chunkX,
int chunkZ, int chunkZ,
double[] columnWeights, double[] columnWeights,
double minWeight, double minWeight,
double thresholdPenalty, double thresholdPenalty,
IrisRange worldYRange Range worldYRange,
int[] surfaceHeights
) { ) {
return carve(writer, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, worldYRange, null); return carve(mantle, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, worldYRange, surfaceHeights, null);
} }
public int carve( public int carve(
MantleWriter writer, MatterMantle mantle,
int chunkX, int chunkX,
int chunkZ, int chunkZ,
double[] columnWeights, double[] columnWeights,
double minWeight, double minWeight,
double thresholdPenalty, double thresholdPenalty,
IrisRange worldYRange, Range worldYRange,
int[] precomputedSurfaceHeights int[] surfaceHeights,
) { Range overrideVerticalRange
return carve(writer, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, worldYRange, precomputedSurfaceHeights, null);
}
public int carve(
MantleWriter writer,
int chunkX,
int chunkZ,
double[] columnWeights,
double minWeight,
double thresholdPenalty,
IrisRange worldYRange,
int[] precomputedSurfaceHeights,
IrisRange overrideVerticalRange
) { ) {
CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan(); CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan();
int carved = carve(writer, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, int carved = carve(mantle, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty,
worldYRange, precomputedSurfaceHeights, null, overrideVerticalRange, fluidSupportPlan); worldYRange, surfaceHeights, null, overrideVerticalRange, fluidSupportPlan);
fluidSupportPlan.resolve(writer.acquireChunk(chunkX, chunkZ)); fluidSupportPlan.resolve(mantle.chunk(chunkX, chunkZ));
return carved; return carved;
} }
/** {@code surfaceHeights} are the rounded heights of the chunk's columns, packed as {@link PowerOfTwoCoordinates#packLocal16}. */
int carve( int carve(
MantleWriter writer, MatterMantle mantle,
int chunkX, int chunkX,
int chunkZ, int chunkZ,
double[] columnWeights, double[] columnWeights,
double minWeight, double minWeight,
double thresholdPenalty, double thresholdPenalty,
IrisRange worldYRange, Range worldYRange,
int[] precomputedSurfaceHeights, int[] surfaceHeights,
int[] surfaceFluidBoundaryStartY, int[] surfaceFluidBoundaryStartY,
IrisRange overrideVerticalRange, Range overrideVerticalRange,
CaveFluidSupportPlan fluidSupportPlan CaveFluidSupportPlan fluidSupportPlan
) { ) {
PrecisionStopwatch applyStopwatch = PrecisionStopwatch.start(); CaveCarveScratch scratch = scratchCache.get();
try { if (columnWeights == null || columnWeights.length < 256) {
CaveCarveScratch scratch = scratchCache.get(); if (!scratch.fullWeightsInitialized) {
if (columnWeights == null || columnWeights.length < 256) { Arrays.fill(scratch.fullWeights, 1D);
if (!scratch.fullWeightsInitialized) { scratch.fullWeightsInitialized = true;
Arrays.fill(scratch.fullWeights, 1D);
scratch.fullWeightsInitialized = true;
}
columnWeights = scratch.fullWeights;
} }
columnWeights = scratch.fullWeights;
}
double resolvedMinWeight = Math.max(0D, Math.min(1D, minWeight)); double resolvedMinWeight = Math.max(0D, Math.min(1D, minWeight));
double resolvedThresholdPenalty = Math.max(0D, thresholdPenalty); double resolvedThresholdPenalty = Math.max(0D, thresholdPenalty);
int worldHeight = writer.getMantle().getWorldHeight(); Range effectiveVerticalRange = overrideVerticalRange != null ? overrideVerticalRange : profile.verticalRange();
IrisRange effectiveVerticalRange = overrideVerticalRange != null ? overrideVerticalRange : resolved.verticalRange(); int minY = Math.max(0, (int) Math.floor(effectiveVerticalRange.min()));
int minY = Math.max(0, (int) Math.floor(effectiveVerticalRange.getMin())); int maxY = Math.min(worldHeight - 1, (int) Math.ceil(effectiveVerticalRange.max()));
int maxY = Math.min(worldHeight - 1, (int) Math.ceil(effectiveVerticalRange.getMax())); if (worldYRange != null) {
if (worldYRange != null) { int rangeMinY = (int) Math.floor(worldYRange.min() - minHeight);
int worldMinHeight = engine.getWorld().minHeight(); int rangeMaxY = (int) Math.ceil(worldYRange.max() - minHeight);
int rangeMinY = (int) Math.floor(worldYRange.getMin() - worldMinHeight); minY = Math.max(minY, rangeMinY);
int rangeMaxY = (int) Math.ceil(worldYRange.getMax() - worldMinHeight); maxY = Math.min(maxY, rangeMaxY);
minY = Math.max(minY, rangeMinY); }
maxY = Math.min(maxY, rangeMaxY); int sampleStep = Math.max(1, profile.sampleStep());
} boolean exactSampling = sampleStep <= 2;
int sampleStep = Math.max(1, profile.sampleStep()); boolean adaptiveSampling = exactSampling && profile.adaptiveSampling();
boolean exactSampling = sampleStep <= 2; int adaptiveSampleStep = Math.max(2, profile.adaptiveSampleStep());
boolean adaptiveSampling = exactSampling && profile.adaptiveSampling(); double adaptiveThresholdMargin = Math.max(0D, profile.adaptiveThresholdMargin());
int adaptiveSampleStep = Math.max(2, profile.adaptiveSampleStep()); int surfaceClearance = Math.max(0, profile.surfaceClearance());
double adaptiveThresholdMargin = Math.max(0D, profile.adaptiveThresholdMargin()); int surfaceBreakDepth = Math.max(0, profile.surfaceBreakDepth());
int surfaceClearance = Math.max(0, profile.surfaceClearance()); double surfaceBreakNoiseThreshold = profile.surfaceBreakNoiseThreshold();
int surfaceBreakDepth = Math.max(0, profile.surfaceBreakDepth()); double surfaceBreakThresholdBoost = Math.max(0, profile.surfaceBreakThresholdBoost());
double surfaceBreakNoiseThreshold = profile.surfaceBreakNoiseThreshold(); boolean allowSurfaceBreak = profile.allowSurfaceBreak();
double surfaceBreakThresholdBoost = Math.max(0, profile.surfaceBreakThresholdBoost()); if (maxY < minY) {
boolean allowSurfaceBreak = profile.allowSurfaceBreak(); return 0;
if (maxY < minY) { }
return 0;
MantleChunk<Matter> chunk = mantle.chunk(chunkX, chunkZ);
if (chunk == null) {
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);
MatterCavern[] matterByY = prepareMatterByYTable(scratch, minY, maxY);
prepareSectionCaches(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]);
} }
}
MantleChunk<Matter> chunk = writer.acquireChunk(chunkX, chunkZ); int carved;
if (chunk == null) { if (exactSampling) {
return 0; if (adaptiveSampling) {
} carved = carvePassAdaptive(
chunk,
int x0 = PowerOfTwoCoordinates.chunkToBlock(chunkX); x0,
int z0 = PowerOfTwoCoordinates.chunkToBlock(chunkZ); z0,
int[] columnMaxY = scratch.columnMaxY; minY,
int[] fluidMaxY = scratch.fluidMaxY; maxY,
int[] surfaceBreakFloorY = scratch.surfaceBreakFloorY; adaptiveSampleStep,
boolean[] surfaceBreakColumn = scratch.surfaceBreakColumn; adaptiveThresholdMargin,
boolean[] surfaceCeilingColumn = scratch.surfaceCeilingColumn; surfaceBreakThresholdBoost,
double[] columnThreshold = scratch.columnThreshold; columnMaxY,
double[] clampedWeights = scratch.clampedColumnWeights; fluidMaxY,
double[] verticalEdgeFade = prepareVerticalEdgeFadeTable(scratch, minY, maxY); surfaceFluidBoundaryStartY,
prepareSurfaceClosureThresholdTable(scratch, minY, maxY); surfaceBreakFloorY,
MatterCavern[] matterByY = prepareMatterByYTable(scratch, minY, maxY); surfaceBreakColumn,
prepareSectionCaches(scratch, minY, maxY); columnThreshold,
clampedWeights,
// IrisStyledRange.get() resolves its CNG per call, which costs a cache-key allocation, verticalEdgeFade,
// a capturing lambda and a shared LRU touch. The CNG is constant for (thresholdRng, data), matterByY,
// so resolve it once here and replicate the min==max / isFlat short circuits verbatim. fluidRequiresFloor ? fluidSupportPlan : null,
IrisStyledRange densityThreshold = resolved.densityThreshold(); resolvedMinWeight,
double thresholdMin = densityThreshold.getMin(); resolvedThresholdPenalty,
double thresholdMax = densityThreshold.getMax(); 0D,
double thresholdBias = profile.thresholdBias(); false
CNG thresholdDensity = null; );
double constantThreshold = 0D;
if (thresholdMin == thresholdMax) {
constantThreshold = thresholdMin;
} else if (densityThreshold.getStyle().isFlat()) {
constantThreshold = M.lerp(thresholdMin, thresholdMax, 0.5);
} else { } else {
thresholdDensity = densityThreshold.getStyle().create(thresholdRng, data); carved = carvePassExact(
}
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;
if (precomputedSurfaceHeights != null && precomputedSurfaceHeights.length > index) {
columnSurfaceY = precomputedSurfaceHeights[index];
} else {
columnSurfaceY = engine.getHeight(x, z);
}
int unclampedClearanceTopY = columnSurfaceY - surfaceClearance;
int clearanceTopY = Math.min(maxY, Math.max(minY, unclampedClearanceTopY));
boolean breakColumn = allowSurfaceBreak
&& surfaceBreakDensity.noiseFastSigned2D(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
: thresholdDensity.fitDouble(thresholdMin, thresholdMax, x, z)) - thresholdBias;
clampedWeights[index] = clampColumnWeight(columnWeights[index]);
}
}
int carved;
if (exactSampling) {
if (adaptiveSampling) {
carved = carvePassAdaptive(
chunk,
x0,
z0,
minY,
maxY,
adaptiveSampleStep,
adaptiveThresholdMargin,
surfaceBreakThresholdBoost,
columnMaxY,
fluidMaxY,
surfaceFluidBoundaryStartY,
surfaceBreakFloorY,
surfaceBreakColumn,
columnThreshold,
clampedWeights,
verticalEdgeFade,
matterByY,
fluidRequiresFloor ? fluidSupportPlan : null,
resolvedMinWeight,
resolvedThresholdPenalty,
0D,
false
);
} else {
carved = carvePassExact(
chunk,
x0,
z0,
minY,
maxY,
surfaceBreakThresholdBoost,
columnMaxY,
fluidMaxY,
surfaceFluidBoundaryStartY,
surfaceBreakFloorY,
surfaceBreakColumn,
columnThreshold,
clampedWeights,
verticalEdgeFade,
matterByY,
fluidRequiresFloor ? fluidSupportPlan : null,
resolvedMinWeight,
resolvedThresholdPenalty,
0D,
false
);
}
} else {
int latticeStep = sampleStep;
carved = carvePassLattice(
chunk, chunk,
x0, x0,
z0, z0,
minY, minY,
maxY, maxY,
latticeStep,
surfaceBreakThresholdBoost, surfaceBreakThresholdBoost,
columnMaxY, columnMaxY,
fluidMaxY, fluidMaxY,
@@ -388,37 +319,60 @@ public class IrisCaveCarver3D {
0D, 0D,
false false
); );
if (carved == 0 && hasFallbackCandidates(columnMaxY, clampedWeights, minY, resolvedMinWeight)) {
carved += carvePassFallback(
chunk,
x0,
z0,
minY,
maxY,
sampleStep,
surfaceBreakThresholdBoost,
columnMaxY,
fluidMaxY,
surfaceFluidBoundaryStartY,
surfaceBreakFloorY,
surfaceBreakColumn,
columnThreshold,
clampedWeights,
verticalEdgeFade,
matterByY,
fluidRequiresFloor ? fluidSupportPlan : null,
resolvedMinWeight,
resolvedThresholdPenalty,
0D,
false
);
}
} }
} else {
return carved; int latticeStep = sampleStep;
} finally { carved = carvePassLattice(
engine.getMetrics().getCarveApply().put(applyStopwatch.getMilliseconds()); chunk,
x0,
z0,
minY,
maxY,
latticeStep,
surfaceBreakThresholdBoost,
columnMaxY,
fluidMaxY,
surfaceFluidBoundaryStartY,
surfaceBreakFloorY,
surfaceBreakColumn,
columnThreshold,
clampedWeights,
verticalEdgeFade,
matterByY,
fluidRequiresFloor ? fluidSupportPlan : null,
resolvedMinWeight,
resolvedThresholdPenalty,
0D,
false
);
if (carved == 0 && hasFallbackCandidates(columnMaxY, clampedWeights, minY, resolvedMinWeight)) {
carved += carvePassFallback(
chunk,
x0,
z0,
minY,
maxY,
sampleStep,
surfaceBreakThresholdBoost,
columnMaxY,
fluidMaxY,
surfaceFluidBoundaryStartY,
surfaceBreakFloorY,
surfaceBreakColumn,
columnThreshold,
clampedWeights,
verticalEdgeFade,
matterByY,
fluidRequiresFloor ? fluidSupportPlan : null,
resolvedMinWeight,
resolvedThresholdPenalty,
0D,
false
);
}
} }
return carved;
} }
private int carvePassExact( private int carvePassExact(
@@ -1670,7 +1624,7 @@ public class IrisCaveCarver3D {
} }
private boolean classifyDensityPointNoWarpNoModules(int x, int y, int z, double thresholdLimit) { private boolean classifyDensityPointNoWarpNoModules(int x, int y, int z, double thresholdLimit) {
double density = baseDensity.noiseFastSigned3D(x, y, z) * baseWeight; double density = baseDensity.signed(x, y, z) * baseWeight;
if ((density + detailMinContribution) > thresholdLimit) { if ((density + detailMinContribution) > thresholdLimit) {
return false; return false;
} }
@@ -1678,7 +1632,7 @@ public class IrisCaveCarver3D {
return true; return true;
} }
density += detailDensity.noiseFastSigned3D(x, y, z) * detailWeight; density += detailDensity.signed(x, y, z) * detailWeight;
return density <= thresholdLimit; return density <= thresholdLimit;
} }
@@ -1696,7 +1650,7 @@ public class IrisCaveCarver3D {
return classifyDensityPointNoWarpNoModules(x, y, z, thresholdLimit); return classifyDensityPointNoWarpNoModules(x, y, z, thresholdLimit);
} }
double density = baseDensity.noiseFastSigned3D(x, y, z) * baseWeight; double density = baseDensity.signed(x, y, z) * baseWeight;
if ((density + detailMinContribution + remainingMin[0]) > thresholdLimit) { if ((density + detailMinContribution + remainingMin[0]) > thresholdLimit) {
return false; return false;
} }
@@ -1704,7 +1658,7 @@ public class IrisCaveCarver3D {
return true; return true;
} }
density += detailDensity.noiseFastSigned3D(x, y, z) * detailWeight; density += detailDensity.signed(x, y, z) * detailWeight;
if ((density + remainingMin[0]) > thresholdLimit) { if ((density + remainingMin[0]) > thresholdLimit) {
return false; return false;
} }
@@ -1746,7 +1700,7 @@ public class IrisCaveCarver3D {
double warpedX = x + (warpA * warpStrength); double warpedX = x + (warpA * warpStrength);
double warpedY = y + (warpB * warpStrength); double warpedY = y + (warpB * warpStrength);
double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength);
double density = baseDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * baseWeight; double density = baseDensity.signed(warpedX, warpedY, warpedZ) * baseWeight;
if ((density + detailMinContribution) > thresholdLimit) { if ((density + detailMinContribution) > thresholdLimit) {
return false; return false;
} }
@@ -1754,7 +1708,7 @@ public class IrisCaveCarver3D {
return true; return true;
} }
density += detailDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * detailWeight; density += detailDensity.signed(warpedX, warpedY, warpedZ) * detailWeight;
return density <= thresholdLimit; return density <= thresholdLimit;
} }
@@ -1782,7 +1736,7 @@ public class IrisCaveCarver3D {
double warpedX = x + (warpA * warpStrength); double warpedX = x + (warpA * warpStrength);
double warpedY = y + (warpB * warpStrength); double warpedY = y + (warpB * warpStrength);
double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength);
double density = baseDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * baseWeight; double density = baseDensity.signed(warpedX, warpedY, warpedZ) * baseWeight;
if ((density + detailMinContribution + remainingMin[0]) > thresholdLimit) { if ((density + detailMinContribution + remainingMin[0]) > thresholdLimit) {
return false; return false;
} }
@@ -1790,7 +1744,7 @@ public class IrisCaveCarver3D {
return true; return true;
} }
density += detailDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * detailWeight; density += detailDensity.signed(warpedX, warpedY, warpedZ) * detailWeight;
if ((density + remainingMin[0]) > thresholdLimit) { if ((density + remainingMin[0]) > thresholdLimit) {
return false; return false;
} }
@@ -2008,8 +1962,8 @@ public class IrisCaveCarver3D {
} }
private double sampleDensityNoWarpNoModules(int x, int y, int z) { private double sampleDensityNoWarpNoModules(int x, int y, int z) {
double density = baseDensity.noiseFastSigned3D(x, y, z) * baseWeight; double density = baseDensity.signed(x, y, z) * baseWeight;
density += detailDensity.noiseFastSigned3D(x, y, z) * detailWeight; density += detailDensity.signed(x, y, z) * detailWeight;
return density * inverseNormalization; return density * inverseNormalization;
} }
@@ -2020,11 +1974,11 @@ public class IrisCaveCarver3D {
} }
CaveFieldModuleState[] localModules = scratch.activeModules; CaveFieldModuleState[] localModules = scratch.activeModules;
double density = baseDensity.noiseFastSigned3D(x, y, z) * baseWeight; double density = baseDensity.signed(x, y, z) * baseWeight;
density += detailDensity.noiseFastSigned3D(x, y, z) * detailWeight; density += detailDensity.signed(x, y, z) * detailWeight;
for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) {
CaveFieldModuleState module = localModules[moduleIndex]; CaveFieldModuleState module = localModules[moduleIndex];
double moduleDensity = module.density.noiseFastSigned3D(x, y, z) - module.threshold; double moduleDensity = module.density.signed(x, y, z) - module.threshold;
if (module.invert) { if (module.invert) {
moduleDensity = -moduleDensity; moduleDensity = -moduleDensity;
} }
@@ -2045,8 +1999,8 @@ public class IrisCaveCarver3D {
double warpedX = x + (warpA * warpStrength); double warpedX = x + (warpA * warpStrength);
double warpedY = y + (warpB * warpStrength); double warpedY = y + (warpB * warpStrength);
double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength);
double density = baseDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * baseWeight; double density = baseDensity.signed(warpedX, warpedY, warpedZ) * baseWeight;
density += detailDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * detailWeight; density += detailDensity.signed(warpedX, warpedY, warpedZ) * detailWeight;
return density * inverseNormalization; return density * inverseNormalization;
} }
@@ -2070,11 +2024,11 @@ public class IrisCaveCarver3D {
double warpedX = x + (warpA * warpStrength); double warpedX = x + (warpA * warpStrength);
double warpedY = y + (warpB * warpStrength); double warpedY = y + (warpB * warpStrength);
double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength);
double density = baseDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * baseWeight; double density = baseDensity.signed(warpedX, warpedY, warpedZ) * baseWeight;
density += detailDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * detailWeight; density += detailDensity.signed(warpedX, warpedY, warpedZ) * detailWeight;
for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) {
CaveFieldModuleState module = localModules[moduleIndex]; CaveFieldModuleState module = localModules[moduleIndex];
double moduleDensity = module.density.noiseFastSigned3D(warpedX, warpedY, warpedZ) - module.threshold; double moduleDensity = module.density.signed(warpedX, warpedY, warpedZ) - module.threshold;
if (module.invert) { if (module.invert) {
moduleDensity = -moduleDensity; moduleDensity = -moduleDensity;
} }
@@ -2098,8 +2052,8 @@ public class IrisCaveCarver3D {
scratch.warpCacheX[slot] = sx; scratch.warpCacheX[slot] = sx;
scratch.warpCacheY[slot] = sy; scratch.warpCacheY[slot] = sy;
scratch.warpCacheZ[slot] = sz; scratch.warpCacheZ[slot] = sz;
scratch.warpCacheA[slot] = warpDensity.noiseFastSigned3D(sx, sy, sz); scratch.warpCacheA[slot] = warpDensity.signed(sx, sy, sz);
scratch.warpCacheB[slot] = warpDensity.noiseFastSigned3D(sx + 31.37D, sy - 17.21D, sz + 23.91D); scratch.warpCacheB[slot] = warpDensity.signed(sx + 31.37D, sy - 17.21D, sz + 23.91D);
return slot; return slot;
} }
@@ -2183,7 +2137,6 @@ public class IrisCaveCarver3D {
MatterCavern[] matterByY = scratch.matterByY; MatterCavern[] matterByY = scratch.matterByY;
boolean allowLava = profile.allowLava(); boolean allowLava = profile.allowLava();
int lavaHeight = engine.getDimension().getCaveLavaHeight();
for (int y = minY; y <= maxY; y++) { for (int y = minY; y <= maxY; y++) {
int offset = y - minY; int offset = y - minY;
@@ -2215,7 +2168,7 @@ public class IrisCaveCarver3D {
private boolean isAquiferCandidate(CaveCarveScratch scratch, int x, int y, int z, double localThreshold) { 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 depthFactor = Math.max(0D, Math.min(1.5D, (fluidHeight - y) / 48D));
double cutoff = 0.35D + (depthFactor * 0.2D); double cutoff = 0.35D + (depthFactor * 0.2D);
if (detailDensity.noiseFastSigned3D(x, y * 0.5D, z) <= cutoff) { if (detailDensity.signed(x, y * 0.5D, z) <= cutoff) {
return false; return false;
} }
return !fluidRequiresFloor || hasAquiferCupSupport(scratch, x, y, z, localThreshold); return !fluidRequiresFloor || hasAquiferCupSupport(scratch, x, y, z, localThreshold);
@@ -63,7 +63,8 @@ public final class ObjectModule implements IrisModule, ModuleLifecycle {
@Override @Override
public void install(StageGraph graph) { public void install(StageGraph graph) {
graph.define(IrisStages.Objects.PLACE).requires(IrisStages.Carve.CAVES).reach(this::reach).run(ObjectModule::place); // Ordering only: iris:carve ships in the built-ins jar, which a pack may not have.
graph.define(IrisStages.Objects.PLACE).softAfter(IrisStages.Carve.CAVES.ref()).reach(this::reach).run(ObjectModule::place);
} }
@Override @Override
@@ -19,6 +19,7 @@
package art.arcane.iris.engine.mantle.components; package art.arcane.iris.engine.mantle.components;
import art.arcane.iris.builtin.carve.CaveLavaHeightSettings;
import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.anchor.PlaceTrait;
import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.carve.CarvingMode;
import art.arcane.iris.builtin.carve.CaveAnchorMode; import art.arcane.iris.builtin.carve.CaveAnchorMode;
@@ -585,7 +586,7 @@ public class ObjectPlacing {
underwater, underwater,
writer.getDataIfPresent(candidateX, candidateY, candidateZ, MatterCavern.class), writer.getDataIfPresent(candidateX, candidateY, candidateZ, MatterCavern.class),
candidateY, candidateY,
engine.getDimension().getCaveLavaHeight())) { engine.getDimension().getModuleSettings().find(CaveLavaHeightSettings.class).map(CaveLavaHeightSettings::height).orElse(CaveLavaHeightSettings.DEFAULT_HEIGHT))) {
continue; continue;
} }
return new CavePlacementAnchor(candidateX, candidateY, candidateZ); return new CavePlacementAnchor(candidateX, candidateY, candidateZ);
@@ -0,0 +1,95 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.modifier;
import java.util.Arrays;
final class CarveColumnMask {
private long[] words = new long[8];
private int maxWord = -1;
void add(int y) {
if (y < 0) {
return;
}
int wordIndex = y >> 6;
if (wordIndex >= words.length) {
words = Arrays.copyOf(words, Math.max(words.length << 1, wordIndex + 1));
}
words[wordIndex] |= 1L << (y & 63);
if (wordIndex > maxWord) {
maxWord = wordIndex;
}
}
int nextSetBit(int fromBit) {
if (maxWord < 0) {
return -1;
}
int startBit = Math.max(0, fromBit);
int wordIndex = startBit >> 6;
if (wordIndex > maxWord) {
return -1;
}
long word = words[wordIndex] & (-1L << (startBit & 63));
while (true) {
if (word != 0L) {
return (wordIndex << 6) + Long.numberOfTrailingZeros(word);
}
wordIndex++;
if (wordIndex > maxWord) {
return -1;
}
word = words[wordIndex];
}
}
boolean isEmpty() {
return maxWord < 0;
}
boolean contains(int y) {
if (y < 0) {
return false;
}
int wordIndex = y >> 6;
if (wordIndex > maxWord) {
return false;
}
return (words[wordIndex] & (1L << (y & 63))) != 0L;
}
void clear() {
if (maxWord < 0) {
return;
}
for (int index = 0; index <= maxWord; index++) {
words[index] = 0L;
}
maxWord = -1;
}
}
@@ -18,36 +18,50 @@
package art.arcane.iris.engine.modifier; package art.arcane.iris.engine.modifier;
import art.arcane.iris.builtin.IrisSeed;
import art.arcane.iris.builtin.IrisStages;
import art.arcane.iris.builtin.MatterMantle;
import art.arcane.iris.builtin.carve.CarvingBiomeSettings; import art.arcane.iris.builtin.carve.CarvingBiomeSettings;
import art.arcane.iris.builtin.carve.CarvingEnabledSettings; import art.arcane.iris.builtin.carve.CarvingEnabledSettings;
import art.arcane.iris.builtin.carve.CarvingSettings; import art.arcane.iris.builtin.carve.CarvingSettings;
import art.arcane.iris.builtin.carve.CaveDepthSettings; import art.arcane.iris.builtin.carve.CaveDepthSettings;
import art.arcane.iris.builtin.carve.CaveLavaHeightSettings;
import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.builtin.carve.CaveProfile;
import com.volmit.FeatureRegistry; import art.arcane.iris.builtin.carve.UpperDimensionCarvingSettings;
import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.engine.mantle.components.CarveWorld;
import art.arcane.iris.core.modules.IrisChunk;
import art.arcane.iris.core.modules.IrisMantleChunk;
import art.arcane.iris.engine.mantle.components.CaveCarving; import art.arcane.iris.engine.mantle.components.CaveCarving;
import art.arcane.iris.engine.object.world.dimension.IrisDimension; import com.volmit.FeatureRegistry;
import com.volmit.IrisFeature;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.ModuleInfo; import com.volmit.ModuleInfo;
import com.volmit.ModuleLog; import com.volmit.config.FeatureSettings;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.FeatureAttachment.Target;
import com.volmit.hunk.Hunk;
import com.volmit.block.BlockState;
import com.volmit.service.CaveBiomes; import com.volmit.service.CaveBiomes;
import com.volmit.stage.ChunkStageContext; import com.volmit.stage.ChunkStageContext;
import com.volmit.stage.MantleStageContext; import com.volmit.stage.MantleStageContext;
import com.volmit.stage.StageGraph; import com.volmit.stage.StageGraph;
import com.volmit.world.PackWorld;
import com.volmit.world.TerrainSampler;
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 * 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 * 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 * terrain. The mantle stage is a port of what was Iris's carving mantle component, its work done by
* {@link CaveCarving}, one per engine runtime. The chunk stage's work is done by {@link CaveApplying}. * {@link CaveCarving}, one per world. The chunk stage's work is done by {@link CaveApplying}.
*/ */
public final class CarveModule implements IrisModule { public final class CarveModule implements IrisModule {
private static final String VERSION = "built-in"; private static final String VERSION = "built-in";
/** Blended cave walls reach one block past the chunk. */ /** Blended cave walls reach one block past the chunk. */
private static final int CAVE_REACH_BLOCKS = 1; private static final int CAVE_REACH_BLOCKS = 1;
private static final int CHUNK_SHIFT = 4; private static final int CHUNK_SHIFT = 4;
/** The centre column of a chunk, where per-chunk settings are read. */
private static final int CHUNK_CENTRE_BLOCKS = 7;
@Override @Override
public ModuleInfo info() { public ModuleInfo info() {
@@ -61,6 +75,8 @@ public final class CarveModule implements IrisModule {
registry.registerSettings(CarvingEnabledSettings.class); registry.registerSettings(CarvingEnabledSettings.class);
registry.registerSettings(CarvingBiomeSettings.class); registry.registerSettings(CarvingBiomeSettings.class);
registry.registerSettings(CaveDepthSettings.class); registry.registerSettings(CaveDepthSettings.class);
registry.registerSettings(CaveLavaHeightSettings.class);
registry.registerSettings(UpperDimensionCarvingSettings.class);
registry.registerService(CaveBiomes.class, new CaveBiomeBands()); registry.registerService(CaveBiomes.class, new CaveBiomeBands());
} }
@@ -71,28 +87,58 @@ public final class CarveModule implements IrisModule {
} }
private static void planCaves(MantleStageContext context) { private static void planCaves(MantleStageContext context) {
IrisMantleChunk chunk = IrisMantleChunk.current(); if (!carves(context.settings(), context.originX(), context.originZ())) {
if (!carves(chunk.engine().getDimension())) {
return; return;
} }
chunk.state(CaveCarving.class, CaveCarving::new).carve(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); MatterMantle mantle = MatterMantle.of(context.mantle());
caveCarving(context.world(), context.terrain(), context.settings(), context.originX(), context.originZ())
.carve(mantle, context.terrain(), context.originX() >> CHUNK_SHIFT, context.originZ() >> CHUNK_SHIFT);
} }
private static void applyCaves(ChunkStageContext context) { private static void applyCaves(ChunkStageContext context) {
IrisChunk chunk = IrisChunk.current(); MatterMantle mantle = MatterMantle.of(context.mantle());
if (chunk.bypassesMantleStages()) { Hunk<BlockState> blocks = context.hunk(BlockState.class);
return; caveApplying(context.world(), context.terrain(), context.settings(), context.originX(), context.originZ())
} .apply(mantle, context.terrain(), context.originX() >> CHUNK_SHIFT, context.originZ() >> CHUNK_SHIFT, blocks);
ModuleLog log = context.log(); }
chunk.state(CaveApplying.class, generating -> new CaveApplying(generating, log)).apply(chunk.originX() >> CHUNK_SHIFT, chunk.originZ() >> CHUNK_SHIFT,
chunk.blocks(), chunk.multicore(), chunk.context()); private static CaveCarving caveCarving(PackWorld world, TerrainSampler terrain, FeatureSettings settings, int originX, int originZ) {
return world.state(CaveCarving.class, generating -> new CaveCarving(generating, carveWorld(generating, terrain),
upperDimensionCarving(settings, originX, originZ)));
}
private static CaveApplying caveApplying(PackWorld world, TerrainSampler terrain, FeatureSettings settings, int originX, int originZ) {
return world.state(CaveApplying.class, generating -> new CaveApplying(generating, carveWorld(generating, terrain),
upperDimensionCarving(settings, originX, originZ)));
}
/** What the carvers need of the world, from the dimension's settings and the first terrain they see (constant for the world). */
private static CarveWorld carveWorld(PackWorld world, TerrainSampler terrain) {
int lavaHeight = dimensionSetting(world, CaveLavaHeightSettings.class, CaveLavaHeightSettings::height, CaveLavaHeightSettings.DEFAULT_HEIGHT);
return new CarveWorld(world.resources().noise(), IrisSeed.CARVE.of(world), terrain.bounds().maxY(), terrain.fluidHeight(), lavaHeight,
world.minHeight());
}
private static boolean upperDimensionCarving(FeatureSettings settings, int originX, int originZ) {
return dimensionEntry(settings, UpperDimensionCarvingSettings.class, originX + CHUNK_CENTRE_BLOCKS, originZ + CHUNK_CENTRE_BLOCKS)
.map(UpperDimensionCarvingSettings::enabled).orElse(false);
} }
/** /**
* A dimension turns carving off with {@code carvingEnabled}. Listing {@code CARVED} in {@code disabledComponents} * A dimension turns carving off with {@code carvingEnabled}. Listing {@code CARVED} in {@code disabledComponents}
* also does: Iris then skips this stage's mantle pass like any disabled component. * also does: Iris then skips this stage's mantle pass like any disabled component.
*/ */
private static boolean carves(IrisDimension dimension) { private static boolean carves(FeatureSettings settings, int originX, int originZ) {
return dimension.getModuleSettings().find(CarvingEnabledSettings.class).map(CarvingEnabledSettings::enabled).orElse(true); return dimensionEntry(settings, CarvingEnabledSettings.class, originX + CHUNK_CENTRE_BLOCKS, originZ + CHUNK_CENTRE_BLOCKS)
.map(CarvingEnabledSettings::enabled).orElse(true);
}
private static <F extends IrisFeature> Optional<F> dimensionEntry(FeatureSettings settings, Class<F> type, int x, int z) {
return settings.at(type, x, z).stream().filter(entry -> entry.level() == Target.DIMENSION).map(Entry::value).findFirst();
}
private static <F extends IrisFeature, V> V dimensionSetting(PackWorld world, Class<F> type, Function<F, V> read, V fallback) {
return world.settings().declared(type).stream().filter(entry -> entry.level() == Target.DIMENSION).map(Entry::value).map(read)
.findFirst().orElse(fallback);
} }
} }
@@ -0,0 +1,166 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.modifier;
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
import art.arcane.volmlib.util.matter.MatterCavern;
import java.util.Arrays;
final class CarveWallBuffer {
private static final int EMPTY_KEY = -1;
private static final double LOAD_FACTOR = 0.75D;
private int[] keys;
private MatterCavern[] values;
private int mask;
private int resizeAt;
private int size;
CarveWallBuffer(int expectedSize) {
int capacity = 1;
int minimumCapacity = Math.max(8, expectedSize);
while (capacity < minimumCapacity) {
capacity <<= 1;
}
keys = new int[capacity];
Arrays.fill(keys, EMPTY_KEY);
values = new MatterCavern[capacity];
mask = capacity - 1;
resizeAt = Math.max(1, (int) (capacity * LOAD_FACTOR));
}
void put(int x, int y, int z, MatterCavern value) {
int key = pack(x, y, z);
int index = mix(key) & mask;
while (true) {
int existingKey = keys[index];
if (existingKey == EMPTY_KEY) {
keys[index] = key;
values[index] = value;
size++;
if (size >= resizeAt) {
resize();
}
return;
}
if (existingKey == key) {
values[index] = value;
return;
}
index = (index + 1) & mask;
}
}
MatterCavern get(int x, int y, int z) {
int key = pack(x, y, z);
int index = mix(key) & mask;
while (true) {
int existingKey = keys[index];
if (existingKey == EMPTY_KEY) {
return null;
}
if (existingKey == key) {
return values[index];
}
index = (index + 1) & mask;
}
}
void forEach(Consumer consumer) {
for (int index = 0; index < keys.length; index++) {
int key = keys[index];
if (key == EMPTY_KEY) {
continue;
}
MatterCavern cavern = values[index];
if (cavern != null) {
consumer.accept(unpackX(key), unpackY(key), unpackZ(key), cavern);
}
}
}
void clear() {
Arrays.fill(keys, EMPTY_KEY);
Arrays.fill(values, null);
size = 0;
}
private void resize() {
int[] oldKeys = keys;
MatterCavern[] oldValues = values;
int nextCapacity = oldKeys.length << 1;
keys = new int[nextCapacity];
Arrays.fill(keys, EMPTY_KEY);
values = new MatterCavern[nextCapacity];
mask = nextCapacity - 1;
resizeAt = Math.max(1, (int) (nextCapacity * LOAD_FACTOR));
size = 0;
for (int index = 0; index < oldKeys.length; index++) {
int key = oldKeys[index];
MatterCavern value = oldValues[index];
if (key != EMPTY_KEY && value != null) {
reinsert(key, value);
}
}
}
private void reinsert(int key, MatterCavern value) {
int index = mix(key) & mask;
while (keys[index] != EMPTY_KEY) {
index = (index + 1) & mask;
}
keys[index] = key;
values[index] = value;
size++;
}
private int pack(int x, int y, int z) {
return (y << 8) | PowerOfTwoCoordinates.packLocal16(x & 15, z & 15);
}
private int unpackX(int key) {
return PowerOfTwoCoordinates.unpackLocal16X(key & 255);
}
private int unpackY(int key) {
return key >> 8;
}
private int unpackZ(int key) {
return PowerOfTwoCoordinates.unpackLocal16Z(key);
}
private int mix(int value) {
int mixed = value * 0x9E3779B9;
return mixed ^ (mixed >>> 16);
}
@FunctionalInterface
interface Consumer {
void accept(int x, int y, int z, MatterCavern cavern);
}
}
File diff suppressed because it is too large. Load diff
@@ -19,11 +19,10 @@
package art.arcane.iris.engine.modifier; package art.arcane.iris.engine.modifier;
import art.arcane.iris.builtin.carve.CaveDepthSettings; import art.arcane.iris.builtin.carve.CaveDepthSettings;
import art.arcane.iris.core.modules.IrisPackWorld;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.object.terrain.carving.CarvingResolver; import art.arcane.iris.engine.object.terrain.carving.CarvingResolver;
import art.arcane.iris.engine.object.terrain.carving.DeclaredByLevel;
import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry; import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry;
import art.arcane.iris.engine.object.world.biome.IrisBiome; import com.volmit.resource.ResourceId;
import com.volmit.service.CaveBiomes; import com.volmit.service.CaveBiomes;
import com.volmit.world.PackWorld; import com.volmit.world.PackWorld;
@@ -36,13 +35,13 @@ import java.util.Optional;
public final class CaveBiomeBands implements CaveBiomes { public final class CaveBiomeBands implements CaveBiomes {
@Override @Override
public Optional<String> overriddenBiome(PackWorld world, int x, int y, int z) { public Optional<String> overriddenBiome(PackWorld world, int x, int y, int z) {
Engine engine = IrisPackWorld.of(world).engine(); CarvingResolver resolver = CarvingResolver.of(world);
ResolvedCarvingEntry rootEntry = CarvingResolver.resolveRootEntry(engine, y + engine.getWorld().minHeight(), null); ResolvedCarvingEntry rootEntry = resolver.rootEntryAt(y);
if (rootEntry == null) { if (rootEntry == null) {
return Optional.empty(); return Optional.empty();
} }
ResolvedCarvingEntry entry = CarvingResolver.resolveFromRoot(engine, rootEntry, x, z, null); ResolvedCarvingEntry entry = resolver.resolveFromRoot(rootEntry, x, z);
if (CarvingResolver.resolveEntryBiome(engine, entry, null) == null) { if (resolver.entryBiome(entry) == null) {
return Optional.empty(); return Optional.empty();
} }
return Optional.of(entry.biomeKey().trim()); return Optional.of(entry.biomeKey().trim());
@@ -50,12 +49,25 @@ public final class CaveBiomeBands implements CaveBiomes {
@Override @Override
public int minDepthBelowSurface(PackWorld world, String biomeKey) { public int minDepthBelowSurface(PackWorld world, String biomeKey) {
IrisBiome biome = IrisPackWorld.of(world).engine().getData().getBiomeLoader().load(biomeKey); return Depths.of(world).minDepthBelowSurface(world.resources().idOf(biomeKey));
return biome == null ? 0 : minDepthBelowSurface(biome);
} }
/** How many blocks below the surface {@code biome}'s caves begin, as its {@code caveMinDepthBelowSurface} says; 0 where it says none. */ /** The minimum depths the world's biomes declare ({@code caveMinDepthBelowSurface}), found by biome id. */
public static int minDepthBelowSurface(IrisBiome biome) { private static final class Depths {
return biome.getModuleSettings().find(CaveDepthSettings.class).map(CaveDepthSettings::depth).orElse(0); private final DeclaredByLevel<CaveDepthSettings> declared;
private Depths(PackWorld world) {
this.declared = DeclaredByLevel.of(world, CaveDepthSettings.class);
}
static Depths of(PackWorld world) {
return world.state(Depths.class, Depths::new);
}
/** How many blocks below the surface the biome's caves begin, as its {@code caveMinDepthBelowSurface} says; 0 where it says none. */
int minDepthBelowSurface(ResourceId biome) {
CaveDepthSettings depth = declared.ofBiome(biome);
return depth == null ? 0 : depth.depth();
}
} }
} }
@@ -0,0 +1,99 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.modifier;
import com.volmit.resource.ResourceId;
import java.util.Arrays;
/**
* The cave biomes one chunk's caves have sampled so far, by block position (see {@link art.arcane.volmlib.util.math.BlockPosition#toLong}):
* a cave wall asks for the biome around it five times, and the next wall block asks again for most of them. Open addressing on
* longs, which spares the boxing a map of {@link Long} would do on this hot path; only biomes that exist are kept.
*/
final class CaveBiomeCache {
private static final double LOAD_FACTOR = 0.5D;
private static final long EMPTY_KEY = Long.MIN_VALUE;
private long[] keys;
private ResourceId[] values;
private int mask;
private int size;
CaveBiomeCache(int expectedSize) {
int capacity = 8;
while (capacity * LOAD_FACTOR < expectedSize) {
capacity <<= 1;
}
allocate(capacity);
}
/** The biome kept for {@code key}; null where none is. */
ResourceId get(long key) {
int index = slot(key);
while (keys[index] != EMPTY_KEY) {
if (keys[index] == key) {
return values[index];
}
index = (index + 1) & mask;
}
return null;
}
void put(long key, ResourceId biome) {
if ((size + 1) > keys.length * LOAD_FACTOR) {
grow();
}
int index = slot(key);
while (keys[index] != EMPTY_KEY) {
if (keys[index] == key) {
values[index] = biome;
return;
}
index = (index + 1) & mask;
}
keys[index] = key;
values[index] = biome;
size++;
}
private int slot(long key) {
long mixed = key * 0x9E3779B97F4A7C15L;
return (int) (mixed ^ (mixed >>> 32)) & mask;
}
private void allocate(int capacity) {
keys = new long[capacity];
Arrays.fill(keys, EMPTY_KEY);
values = new ResourceId[capacity];
mask = capacity - 1;
size = 0;
}
private void grow() {
long[] oldKeys = keys;
ResourceId[] oldValues = values;
allocate(oldKeys.length << 1);
for (int index = 0; index < oldKeys.length; index++) {
if (oldKeys[index] != EMPTY_KEY) {
put(oldKeys[index], oldValues[index]);
}
}
}
}
@@ -0,0 +1,89 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.modifier;
import com.volmit.block.BlockRegistry;
import com.volmit.block.BlockState;
import com.volmit.block.BlockTrait;
import java.util.IdentityHashMap;
import java.util.Map;
/**
* What the cave passes of one chunk ask about blocks, answered from memory. A chunk holds few distinct states and a cave pass asks
* about them per block, so each state instance (the hunk hands out one per distinct state) is classified once.
*/
final class CaveBlockClasses {
private static final int SOLID = 1;
private static final int FLUID = 2;
private static final int AIR = 4;
private static final int ORE = 8;
private static final int DECORATION = 16;
private static final int GRAVITY = 32;
private final BlockRegistry blocks;
private final Map<BlockState, Integer> classes = new IdentityHashMap<>();
CaveBlockClasses(BlockRegistry blocks) {
this.blocks = blocks;
}
boolean isSolid(BlockState state) {
return (classesOf(state) & SOLID) != 0;
}
boolean isFluid(BlockState state) {
return (classesOf(state) & FLUID) != 0;
}
boolean isAir(BlockState state) {
return (classesOf(state) & AIR) != 0;
}
boolean isOre(BlockState state) {
return (classesOf(state) & ORE) != 0;
}
boolean isDecorant(BlockState state) {
return (classesOf(state) & DECORATION) != 0;
}
boolean hasGravity(BlockState state) {
return state != null && (classesOf(state) & GRAVITY) != 0;
}
private int classesOf(BlockState state) {
Integer known = classes.get(state);
if (known != null) {
return known;
}
int computed = classify(state);
classes.put(state, computed);
return computed;
}
private int classify(BlockState state) {
return flag(state, BlockTrait.SOLID, SOLID) | flag(state, BlockTrait.FLUID, FLUID) | flag(state, BlockTrait.AIR, AIR)
| flag(state, BlockTrait.ORE, ORE) | flag(state, BlockTrait.DECORATION, DECORATION) | flag(state, BlockTrait.GRAVITY, GRAVITY);
}
private int flag(BlockState state, BlockTrait trait, int bit) {
return blocks.hasTrait(state, trait) ? bit : 0;
}
}
@@ -18,11 +18,8 @@
package art.arcane.iris.engine.modifier; package art.arcane.iris.engine.modifier;
import art.arcane.iris.engine.object.world.biome.IrisBiome; import com.volmit.resource.ResourceId;
import art.arcane.volmlib.util.matter.MatterCavern;
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@@ -31,7 +28,7 @@ final class IrisCarveScratch {
final CarveColumnMask[] boundaryMasks = new CarveColumnMask[256]; final CarveColumnMask[] boundaryMasks = new CarveColumnMask[256];
final int[] surfaceHeights = new int[256]; final int[] surfaceHeights = new int[256];
final CarveWallBuffer walls = new CarveWallBuffer(512); final CarveWallBuffer walls = new CarveWallBuffer(512);
final Map<String, IrisBiome> customBiomeCache = new HashMap<>(); final Map<String, ResourceId> customBiomeCache = new HashMap<>();
int[] upperSurfaceHeights; int[] upperSurfaceHeights;
boolean customCaveBiomePresent; boolean customCaveBiomePresent;
@@ -59,219 +56,3 @@ final class IrisCarveScratch {
customCaveBiomePresent = false; customCaveBiomePresent = false;
} }
} }
final class CarveColumnMask {
private long[] words = new long[8];
private int maxWord = -1;
void add(int y) {
if (y < 0) {
return;
}
int wordIndex = y >> 6;
if (wordIndex >= words.length) {
words = Arrays.copyOf(words, Math.max(words.length << 1, wordIndex + 1));
}
words[wordIndex] |= 1L << (y & 63);
if (wordIndex > maxWord) {
maxWord = wordIndex;
}
}
int nextSetBit(int fromBit) {
if (maxWord < 0) {
return -1;
}
int startBit = Math.max(0, fromBit);
int wordIndex = startBit >> 6;
if (wordIndex > maxWord) {
return -1;
}
long word = words[wordIndex] & (-1L << (startBit & 63));
while (true) {
if (word != 0L) {
return (wordIndex << 6) + Long.numberOfTrailingZeros(word);
}
wordIndex++;
if (wordIndex > maxWord) {
return -1;
}
word = words[wordIndex];
}
}
boolean isEmpty() {
return maxWord < 0;
}
boolean contains(int y) {
if (y < 0) {
return false;
}
int wordIndex = y >> 6;
if (wordIndex > maxWord) {
return false;
}
return (words[wordIndex] & (1L << (y & 63))) != 0L;
}
void clear() {
if (maxWord < 0) {
return;
}
for (int index = 0; index <= maxWord; index++) {
words[index] = 0L;
}
maxWord = -1;
}
}
final class CarveWallBuffer {
private static final int EMPTY_KEY = -1;
private static final double LOAD_FACTOR = 0.75D;
private int[] keys;
private MatterCavern[] values;
private int mask;
private int resizeAt;
private int size;
CarveWallBuffer(int expectedSize) {
int capacity = 1;
int minimumCapacity = Math.max(8, expectedSize);
while (capacity < minimumCapacity) {
capacity <<= 1;
}
keys = new int[capacity];
Arrays.fill(keys, EMPTY_KEY);
values = new MatterCavern[capacity];
mask = capacity - 1;
resizeAt = Math.max(1, (int) (capacity * LOAD_FACTOR));
}
void put(int x, int y, int z, MatterCavern value) {
int key = pack(x, y, z);
int index = mix(key) & mask;
while (true) {
int existingKey = keys[index];
if (existingKey == EMPTY_KEY) {
keys[index] = key;
values[index] = value;
size++;
if (size >= resizeAt) {
resize();
}
return;
}
if (existingKey == key) {
values[index] = value;
return;
}
index = (index + 1) & mask;
}
}
MatterCavern get(int x, int y, int z) {
int key = pack(x, y, z);
int index = mix(key) & mask;
while (true) {
int existingKey = keys[index];
if (existingKey == EMPTY_KEY) {
return null;
}
if (existingKey == key) {
return values[index];
}
index = (index + 1) & mask;
}
}
void forEach(Consumer consumer) {
for (int index = 0; index < keys.length; index++) {
int key = keys[index];
if (key == EMPTY_KEY) {
continue;
}
MatterCavern cavern = values[index];
if (cavern != null) {
consumer.accept(unpackX(key), unpackY(key), unpackZ(key), cavern);
}
}
}
void clear() {
Arrays.fill(keys, EMPTY_KEY);
Arrays.fill(values, null);
size = 0;
}
private void resize() {
int[] oldKeys = keys;
MatterCavern[] oldValues = values;
int nextCapacity = oldKeys.length << 1;
keys = new int[nextCapacity];
Arrays.fill(keys, EMPTY_KEY);
values = new MatterCavern[nextCapacity];
mask = nextCapacity - 1;
resizeAt = Math.max(1, (int) (nextCapacity * LOAD_FACTOR));
size = 0;
for (int index = 0; index < oldKeys.length; index++) {
int key = oldKeys[index];
MatterCavern value = oldValues[index];
if (key != EMPTY_KEY && value != null) {
reinsert(key, value);
}
}
}
private void reinsert(int key, MatterCavern value) {
int index = mix(key) & mask;
while (keys[index] != EMPTY_KEY) {
index = (index + 1) & mask;
}
keys[index] = key;
values[index] = value;
size++;
}
private int pack(int x, int y, int z) {
return (y << 8) | PowerOfTwoCoordinates.packLocal16(x & 15, z & 15);
}
private int unpackX(int key) {
return PowerOfTwoCoordinates.unpackLocal16X(key & 255);
}
private int unpackY(int key) {
return key >> 8;
}
private int unpackZ(int key) {
return PowerOfTwoCoordinates.unpackLocal16Z(key);
}
private int mix(int value) {
int mixed = value * 0x9E3779B9;
return mixed ^ (mixed >>> 16);
}
@FunctionalInterface
interface Consumer {
void accept(int x, int y, int z, MatterCavern cavern);
}
}
@@ -45,6 +45,7 @@ public final class PostModule implements IrisModule {
@Override @Override
public void install(StageGraph graph) { public void install(StageGraph graph) {
graph.define(IrisStages.Post.SMOOTH).requires(IrisStages.Carve.APPLY).run(SurfaceSmoothing::smooth); // Ordering only: iris:carve ships in the built-ins jar, which a pack may not have.
graph.define(IrisStages.Post.SMOOTH).softAfter(IrisStages.Carve.APPLY.ref()).run(SurfaceSmoothing::smooth);
} }
} }
@@ -1,71 +0,0 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.object.terrain.carving;
import art.arcane.iris.builtin.carve.CarvingEntry;
import art.arcane.iris.builtin.carve.CarvingSettings;
import art.arcane.iris.engine.framework.Engine;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* What the carve module keeps for one world: the cave biome bands its dimension declares ({@link CarvingSettings}) made ready
* ({@link ResolvedCarvingEntry}), in the order the dimension lists them, and by id.
*/
public final class CarvingBands {
private final List<ResolvedCarvingEntry> entries;
private final Map<String, ResolvedCarvingEntry> index;
CarvingBands(List<CarvingEntry> declared) {
this.entries = declared.stream().filter(Objects::nonNull).map(ResolvedCarvingEntry::new).toList();
this.index = indexById(entries);
}
CarvingBands(Engine engine) {
this(engine.getDimension().getModuleSettings().find(CarvingSettings.class).map(CarvingSettings::entries).orElse(List.of()));
}
/** The bands of the world {@code engine} generates now. */
public static CarvingBands of(Engine engine) {
return engine.getGeneration().state(CarvingBands.class, CarvingBands::new);
}
/** Every declared entry, enabled or not. */
public List<ResolvedCarvingEntry> entries() {
return entries;
}
/** The entries by their trimmed ids; entries without an id are not in it, and the last of several with one id is. */
public Map<String, ResolvedCarvingEntry> index() {
return index;
}
private static Map<String, ResolvedCarvingEntry> indexById(List<ResolvedCarvingEntry> entries) {
Map<String, ResolvedCarvingEntry> index = new HashMap<>();
for (ResolvedCarvingEntry entry : entries) {
if (!entry.id().isBlank()) {
index.put(entry.id().trim(), entry);
}
}
return Map.copyOf(index);
}
}
@@ -1,78 +1,122 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.object.terrain.carving; package art.arcane.iris.engine.object.terrain.carving;
import art.arcane.iris.engine.object.value.IRare; import art.arcane.iris.builtin.IrisSeed;
import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.builtin.carve.CarvingEntry;
import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.builtin.carve.CarvingSettings;
import art.arcane.iris.engine.framework.Engine; import com.volmit.ModuleLog;
import art.arcane.iris.engine.object.world.dimension.IrisDimension; import com.volmit.config.FeatureSettings.Entry;
import art.arcane.iris.util.project.interpolation.IrisInterpolation;
import art.arcane.iris.util.project.noise.CNG;
import com.volmit.config.Range; import com.volmit.config.Range;
import com.volmit.FeatureAttachment.Target;
import com.volmit.noise.NoiseSampler;
import com.volmit.resource.PackResources;
import com.volmit.world.PackBiome;
import com.volmit.world.PackWorld;
import java.lang.ref.WeakReference;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
/** /**
* Picks the dimension's carving entry for a position: the last enabled root entry whose world Y band holds the height, * What the carve module keeps for one world about the cave biome bands its dimension declares ({@link CarvingSettings}): the
* then, through the entries' children, the one a noise pattern selects at the column. The state a caller passes (or, when * entries made ready ({@link ResolvedCarvingEntry}), in the order the dimension lists them and by id, and the picks among them.
* it passes none, the thread's) keeps the picks and the entries' biomes, so a caller resolving many positions reuses them. * A pick is the dimension's last enabled root entry whose world Y band holds a height, then, through the entries' children, the
* one a noise pattern selects at a column.
*/ */
public final class CarvingResolver { public final class CarvingResolver {
private static final int MAX_CHILD_DEPTH = 32; private static final int MAX_CHILD_DEPTH = 32;
private static final long CHILD_SEED_SALT = 0x9E3779B97F4A7C15L; private static final long CHILD_SEED_SALT = 0x9E3779B97F4A7C15L;
private static final ThreadLocal<WeakReference<State>> THREAD_STATE =
ThreadLocal.withInitial(() -> new WeakReference<>(null));
private CarvingResolver() { private final PackResources resources;
private final ModuleLog log;
private final int minHeight;
private final long childSeed;
private final List<ResolvedCarvingEntry> entries;
private final Map<String, ResolvedCarvingEntry> index;
private final Map<Integer, Optional<ResolvedCarvingEntry>> rootEntriesByWorldY = new ConcurrentHashMap<>();
private final Map<ResolvedCarvingEntry, ParentSelectionPlan> selectionPlans = new ConcurrentHashMap<>();
CarvingResolver(PackWorld world, List<CarvingEntry> declared) {
this.resources = world.resources();
this.log = world.log();
this.minHeight = world.minHeight();
this.childSeed = IrisSeed.CARVE.of(world) ^ CHILD_SEED_SALT;
this.entries = declared.stream().filter(Objects::nonNull).map(ResolvedCarvingEntry::new).toList();
this.index = indexById(entries);
} }
public static ResolvedCarvingEntry resolveRootEntry(Engine engine, int worldY) { /** The bands of the world {@code world} generates now. */
return resolveRootEntry(engine, worldY, threadState()); public static CarvingResolver of(PackWorld world) {
return world.state(CarvingResolver.class, generating -> new CarvingResolver(generating, dimensionEntries(generating)));
} }
public static ResolvedCarvingEntry resolveRootEntry(Engine engine, int worldY, State state) { private static List<CarvingEntry> dimensionEntries(PackWorld world) {
State resolvedState = state == null ? threadState() : state; List<CarvingEntry> dimensionEntries = new ArrayList<>();
resolvedState.bind(engine); for (Entry<CarvingSettings> entry : world.settings().declared(CarvingSettings.class)) {
if (resolvedState.rootEntriesByWorldY.containsKey(worldY)) { if (entry.level() == Target.DIMENSION) {
return resolvedState.rootEntriesByWorldY.get(worldY); dimensionEntries.addAll(entry.value().entries());
}
} }
return dimensionEntries;
}
List<ResolvedCarvingEntry> entries = resolvedState.bands.entries(); /** Every declared entry, enabled or not. */
if (entries.isEmpty()) { public List<ResolvedCarvingEntry> entries() {
resolvedState.rootEntriesByWorldY.put(worldY, null); return entries;
return null; }
}
/** The entries by their trimmed ids; entries without an id are not in it, and the last of several with one id is. */
public Map<String, ResolvedCarvingEntry> index() {
return index;
}
/** The root entry for a height above the dimension's bottom; null where no enabled entry with a biome holds it. */
public ResolvedCarvingEntry rootEntryAt(int y) {
return rootEntryAtWorldY(y + minHeight);
}
/** The root entry for a world Y as packs write them; null where no enabled entry with a biome holds it. */
public ResolvedCarvingEntry rootEntryAtWorldY(int worldY) {
return rootEntriesByWorldY.computeIfAbsent(worldY, this::pickRootEntry).orElse(null);
}
private Optional<ResolvedCarvingEntry> pickRootEntry(int worldY) {
ResolvedCarvingEntry resolved = null; ResolvedCarvingEntry resolved = null;
for (ResolvedCarvingEntry entry : entries) { for (ResolvedCarvingEntry entry : entries) {
if (!isRootCandidate(engine, entry, worldY, resolvedState)) { if (isRootCandidate(entry, worldY)) {
continue; resolved = entry;
} }
resolved = entry;
} }
return Optional.ofNullable(resolved);
resolvedState.rootEntriesByWorldY.put(worldY, resolved);
return resolved;
} }
public static ResolvedCarvingEntry resolveFromRoot(Engine engine, ResolvedCarvingEntry rootEntry, int worldX, int worldZ) { public ResolvedCarvingEntry resolveFromRoot(ResolvedCarvingEntry rootEntry, int worldX, int worldZ) {
return resolveFromRoot(engine, rootEntry, worldX, worldZ, threadState());
}
public static ResolvedCarvingEntry resolveFromRoot(Engine engine, ResolvedCarvingEntry rootEntry, int worldX, int worldZ, State state) {
State resolvedState = state == null ? threadState() : state;
resolvedState.bind(engine);
if (rootEntry == null) { if (rootEntry == null) {
return null; return null;
} }
IrisBiome rootBiome = resolveEntryBiome(engine, rootEntry, resolvedState); PackBiome rootBiome = entryBiome(rootEntry);
if (rootBiome == null) { if (rootBiome == null) {
return null; return null;
} }
@@ -82,11 +126,10 @@ public final class CarvingResolver {
return rootEntry; return rootEntry;
} }
Map<String, ResolvedCarvingEntry> entryIndex = resolvedState.bands.index();
ResolvedCarvingEntry current = rootEntry; ResolvedCarvingEntry current = rootEntry;
int depth = remainingDepth; int depth = remainingDepth;
while (depth > 0) { while (depth > 0) {
ResolvedCarvingEntry selected = selectChild(engine, current, worldX, worldZ, entryIndex, resolvedState); ResolvedCarvingEntry selected = selectChild(current, worldX, worldZ);
if (selected == null || selected == current) { if (selected == null || selected == current) {
break; break;
} }
@@ -102,30 +145,12 @@ public final class CarvingResolver {
return current; return current;
} }
public static IrisBiome resolveEntryBiome(Engine engine, ResolvedCarvingEntry entry) { /** The pack biome the entry names; null when it names none or the pack has no such biome. */
return resolveEntryBiome(engine, entry, null); public PackBiome entryBiome(ResolvedCarvingEntry entry) {
return entry == null ? null : entry.realBiome(resources, log);
} }
public static IrisBiome resolveEntryBiome(Engine engine, ResolvedCarvingEntry entry, State state) { private boolean isRootCandidate(ResolvedCarvingEntry entry, int worldY) {
if (entry == null) {
return null;
}
if (state == null) {
return entry.realBiome(engine.getData());
}
state.bind(engine);
if (state.biomeCache.containsKey(entry)) {
return state.biomeCache.get(entry);
}
IrisBiome biome = entry.realBiome(engine.getData());
state.biomeCache.put(entry, biome);
return biome;
}
private static boolean isRootCandidate(Engine engine, ResolvedCarvingEntry entry, int worldY, State state) {
if (entry == null || !entry.enabled()) { if (entry == null || !entry.enabled()) {
return false; return false;
} }
@@ -135,41 +160,28 @@ public final class CarvingResolver {
return false; return false;
} }
return resolveEntryBiome(engine, entry, state) != null; return entryBiome(entry) != null;
} }
private static ResolvedCarvingEntry selectChild( private ResolvedCarvingEntry selectChild(ResolvedCarvingEntry parent, int worldX, int worldZ) {
Engine engine,
ResolvedCarvingEntry parent,
int worldX,
int worldZ,
Map<String, ResolvedCarvingEntry> entryIndex,
State state
) {
List<String> children = parent.children(); List<String> children = parent.children();
if (children.isEmpty()) { if (children.isEmpty()) {
return parent; return parent;
} }
IrisBiome parentBiome = resolveEntryBiome(engine, parent, state); PackBiome parentBiome = entryBiome(parent);
if (parentBiome == null) { if (parentBiome == null) {
return parent; return parent;
} }
ParentSelectionPlan selectionPlan = state.selectionPlans.get(parent); ParentSelectionPlan selectionPlan = selectionPlans.computeIfAbsent(parent, key -> buildSelectionPlan(key, parentBiome));
if (selectionPlan == null) {
selectionPlan = buildSelectionPlan(engine, parent, parentBiome, entryIndex, state);
state.selectionPlans.put(parent, selectionPlan);
}
if (selectionPlan.parentOnly) { if (selectionPlan.parentOnly) {
return parent; return parent;
} }
long seed = resolveChildSeed(engine, state); NoiseSampler childGenerator = parent.childrenGenerator(childSeed, resources);
CNG childGenerator = parent.childrenGenerator(seed, engine.getData()); double sample = childGenerator.sample(worldX, worldZ);
double sample = childGenerator.noiseFast2D(worldX, worldZ); int selectedIndex = (int) Math.round(sample * selectionPlan.maxIndex);
int selectedIndex = (int) Math.round(IrisInterpolation.lerp(0, selectionPlan.maxIndex, sample));
CarvingChoice selected = selectionPlan.get(selectedIndex); CarvingChoice selected = selectionPlan.get(selectedIndex);
if (selected == null || selected.entry == null) { if (selected == null || selected.entry == null) {
return parent; return parent;
@@ -178,25 +190,19 @@ public final class CarvingResolver {
return selected.entry; return selected.entry;
} }
private static ParentSelectionPlan buildSelectionPlan( private ParentSelectionPlan buildSelectionPlan(ResolvedCarvingEntry parent, PackBiome parentBiome) {
Engine engine,
ResolvedCarvingEntry parent,
IrisBiome parentBiome,
Map<String, ResolvedCarvingEntry> entryIndex,
State state
) {
List<CarvingChoice> options = new ArrayList<>(); List<CarvingChoice> options = new ArrayList<>();
for (String childId : parent.children()) { for (String childId : parent.children()) {
if (childId == null || childId.isBlank()) { if (childId == null || childId.isBlank()) {
continue; continue;
} }
ResolvedCarvingEntry child = entryIndex.get(childId.trim()); ResolvedCarvingEntry child = index.get(childId.trim());
if (child == null || !child.enabled()) { if (child == null || !child.enabled()) {
continue; continue;
} }
IrisBiome childBiome = resolveEntryBiome(engine, child, state); PackBiome childBiome = entryBiome(child);
if (childBiome == null) { if (childBiome == null) {
continue; continue;
} }
@@ -243,13 +249,12 @@ public final class CarvingResolver {
return mapped.toArray(new CarvingChoice[0]); return mapped.toArray(new CarvingChoice[0]);
} }
private static int rarity(IrisBiome biome) { private static int rarity(PackBiome biome) {
if (biome == null) { if (biome == null) {
return 1; return 1;
} }
int rarity = biome.getRarity(); return Math.max(biome.rarity(), 1);
return Math.max(rarity, 1);
} }
private static int clampDepth(int depth) { private static int clampDepth(int depth) {
@@ -260,56 +265,14 @@ public final class CarvingResolver {
return Math.min(depth, MAX_CHILD_DEPTH); return Math.min(depth, MAX_CHILD_DEPTH);
} }
private static long resolveChildSeed(Engine engine, State state) { private static Map<String, ResolvedCarvingEntry> indexById(List<ResolvedCarvingEntry> entries) {
if (state.childSeed == null) { Map<String, ResolvedCarvingEntry> index = new HashMap<>();
state.childSeed = engine.getSeedManager().getCarve() ^ CHILD_SEED_SALT; for (ResolvedCarvingEntry entry : entries) {
} if (!entry.id().isBlank()) {
index.put(entry.id().trim(), entry);
return state.childSeed;
}
private static State threadState() {
WeakReference<State> reference = THREAD_STATE.get();
State state = reference.get();
if (state != null) {
return state;
}
State replacement = new State();
THREAD_STATE.set(new WeakReference<>(replacement));
return replacement;
}
public static final class State {
private final Map<Integer, ResolvedCarvingEntry> rootEntriesByWorldY = new HashMap<>();
private final Map<ResolvedCarvingEntry, ParentSelectionPlan> selectionPlans = new IdentityHashMap<>();
private final Map<ResolvedCarvingEntry, IrisBiome> biomeCache = new IdentityHashMap<>();
private WeakReference<Engine> engineIdentity;
private WeakReference<IrisDimension> dimensionIdentity;
private WeakReference<IrisData> dataIdentity;
private CarvingBands bands;
private Long childSeed;
private void bind(Engine engine) {
IrisDimension dimension = engine.getDimension();
IrisData data = engine.getData();
if (references(engineIdentity, engine)
&& references(dimensionIdentity, dimension)
&& references(dataIdentity, data)) {
return;
} }
engineIdentity = new WeakReference<>(engine);
dimensionIdentity = new WeakReference<>(dimension);
dataIdentity = new WeakReference<>(data);
bands = CarvingBands.of(engine);
rootEntriesByWorldY.clear();
selectionPlans.clear();
biomeCache.clear();
childSeed = null;
}
private static boolean references(WeakReference<?> identity, Object value) {
return identity != null && identity.get() == value;
} }
return Map.copyOf(index);
} }
private static final class ParentSelectionPlan { private static final class ParentSelectionPlan {
@@ -350,18 +313,6 @@ public final class CarvingResolver {
} }
} }
private static final class CarvingChoice implements IRare { private record CarvingChoice(ResolvedCarvingEntry entry, int rarity) {
private final ResolvedCarvingEntry entry;
private final int rarity;
private CarvingChoice(ResolvedCarvingEntry entry, int rarity) {
this.entry = entry;
this.rarity = rarity;
}
@Override
public int getRarity() {
return rarity;
}
} }
} }
@@ -18,26 +18,26 @@
package art.arcane.iris.engine.object.terrain.carving; package art.arcane.iris.engine.object.terrain.carving;
import art.arcane.iris.builtin.carve.CaveFieldModule;
import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.builtin.carve.CaveProfile;
import art.arcane.iris.engine.object.value.IrisRange; import art.arcane.volmlib.util.math.M;
import art.arcane.iris.core.loader.IrisData; import com.volmit.config.Range;
import art.arcane.iris.engine.framework.Engine; import com.volmit.noise.NoiseFactory;
import art.arcane.iris.util.project.noise.CNG; import com.volmit.noise.NoiseSampler;
import art.arcane.volmlib.util.math.RNG; import com.volmit.noise.NoiseStyle;
import com.volmit.noise.StyledRange;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
public final class IrisCaveProfileSampler { public final class CaveProfileSampler {
private static final double FLOATING_THRESHOLD_BIAS_SCALE = 0.2D; private static final double FLOATING_THRESHOLD_BIAS_SCALE = 0.2D;
private final IrisData data;
private final CaveProfile profile; private final CaveProfile profile;
private final ResolvedCaveProfile resolved; private final NoiseSampler baseDensity;
private final CNG baseDensity; private final NoiseSampler detailDensity;
private final CNG detailDensity; private final NoiseSampler warpDensity;
private final CNG warpDensity; private final NoiseSampler thresholdNoise;
private final RNG thresholdRng;
private final ModuleState[] modules; private final ModuleState[] modules;
private final double inverseNormalization; private final double inverseNormalization;
private final double baseWeight; private final double baseWeight;
@@ -47,16 +47,13 @@ public final class IrisCaveProfileSampler {
private final boolean hasWarp; private final boolean hasWarp;
private final boolean hasModules; private final boolean hasModules;
public IrisCaveProfileSampler(Engine engine, CaveProfile profile) { public CaveProfileSampler(NoiseFactory noise, long carveSeed, CaveProfile profile) {
this.data = engine.getData();
this.profile = profile; this.profile = profile;
this.resolved = ResolvedCaveProfile.of(profile);
List<ModuleState> moduleStates = new ArrayList<>(); List<ModuleState> moduleStates = new ArrayList<>();
RNG baseRng = new RNG(engine.getSeedManager().getCarve()); this.baseDensity = noise.sampler(profile.baseDensityStyle(), carveSeed + 934_447);
this.baseDensity = resolved.baseDensityStyle().create(baseRng.nextParallelRNG(934_447), data); this.detailDensity = noise.sampler(profile.detailDensityStyle(), carveSeed + 612_991);
this.detailDensity = resolved.detailDensityStyle().create(baseRng.nextParallelRNG(612_991), data); this.warpDensity = noise.sampler(profile.warpStyle(), carveSeed + 770_713);
this.warpDensity = resolved.warpStyle().create(baseRng.nextParallelRNG(770_713), data); this.thresholdNoise = noise.sampler(profile.densityThreshold().style(), carveSeed + 489_112);
this.thresholdRng = baseRng.nextParallelRNG(489_112);
this.baseWeight = profile.baseWeight(); this.baseWeight = profile.baseWeight();
this.detailWeight = profile.detailWeight(); this.detailWeight = profile.detailWeight();
this.warpStrength = profile.warpStrength(); this.warpStrength = profile.warpStrength();
@@ -64,8 +61,8 @@ public final class IrisCaveProfileSampler {
double weight = Math.abs(baseWeight) + Math.abs(detailWeight); double weight = Math.abs(baseWeight) + Math.abs(detailWeight);
int index = 0; int index = 0;
for (ResolvedCaveProfile.Module module : resolved.modules()) { for (CaveFieldModule module : profile.modules()) {
CNG moduleDensity = module.style().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), data); NoiseSampler moduleDensity = noise.sampler(module.style(), carveSeed + 1_000_003L + (index * 65_537L));
ModuleState state = new ModuleState(module, moduleDensity); ModuleState state = new ModuleState(module, moduleDensity);
moduleStates.add(state); moduleStates.add(state);
weight += Math.abs(state.weight); weight += Math.abs(state.weight);
@@ -76,7 +73,7 @@ public final class IrisCaveProfileSampler {
double normalization = weight <= 0 ? 1D : weight; double normalization = weight <= 0 ? 1D : weight;
this.inverseNormalization = 1D / normalization; this.inverseNormalization = 1D / normalization;
this.hasModules = modules.length > 0; this.hasModules = modules.length > 0;
this.enabled = profile.enabled() && baseDensity != null && detailDensity != null && (!hasWarp || warpDensity != null); this.enabled = profile.enabled();
} }
public boolean shouldCarve(int x, int y, int z, double floatingCarveThreshold) { public boolean shouldCarve(int x, int y, int z, double floatingCarveThreshold) {
@@ -84,11 +81,23 @@ public final class IrisCaveProfileSampler {
return false; return false;
} }
double threshold = resolved.densityThreshold().get(thresholdRng, x, z, data) - profile.thresholdBias(); double threshold = thresholdAt(x, z) - profile.thresholdBias();
threshold += floatingThresholdBias(floatingCarveThreshold); threshold += floatingThresholdBias(floatingCarveThreshold);
return sampleDensity(x, y, z) <= threshold; 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) { double sampleDensity(int x, int y, int z) {
if (hasWarp) { if (hasWarp) {
return sampleDensityWarped(x, y, z); return sampleDensityWarped(x, y, z);
@@ -98,8 +107,8 @@ public final class IrisCaveProfileSampler {
} }
private double sampleDensityUnwarped(int x, int y, int z) { private double sampleDensityUnwarped(int x, int y, int z) {
double density = baseDensity.noiseFastSigned3D(x, y, z) * baseWeight; double density = baseDensity.signed(x, y, z) * baseWeight;
density += detailDensity.noiseFastSigned3D(x, y, z) * detailWeight; density += detailDensity.signed(x, y, z) * detailWeight;
if (hasModules) { if (hasModules) {
for (ModuleState module : modules) { for (ModuleState module : modules) {
if (!module.isActive(y)) { if (!module.isActive(y)) {
@@ -114,13 +123,13 @@ public final class IrisCaveProfileSampler {
} }
private double sampleDensityWarped(int x, int y, int z) { private double sampleDensityWarped(int x, int y, int z) {
double warpA = warpDensity.noiseFastSigned3D(x, y, z); double warpA = warpDensity.signed(x, y, z);
double warpB = warpDensity.noiseFastSigned3D(x + 31.37D, y - 17.21D, z + 23.91D); double warpB = warpDensity.signed(x + 31.37D, y - 17.21D, z + 23.91D);
double warpedX = x + (warpA * warpStrength); double warpedX = x + (warpA * warpStrength);
double warpedY = y + (warpB * warpStrength); double warpedY = y + (warpB * warpStrength);
double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength);
double density = baseDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * baseWeight; double density = baseDensity.signed(warpedX, warpedY, warpedZ) * baseWeight;
density += detailDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * detailWeight; density += detailDensity.signed(warpedX, warpedY, warpedZ) * detailWeight;
if (hasModules) { if (hasModules) {
for (ModuleState module : modules) { for (ModuleState module : modules) {
if (!module.isActive(y)) { if (!module.isActive(y)) {
@@ -140,18 +149,18 @@ public final class IrisCaveProfileSampler {
} }
private static final class ModuleState { private static final class ModuleState {
private final CNG density; private final NoiseSampler density;
private final int minY; private final int minY;
private final int maxY; private final int maxY;
private final double weight; private final double weight;
private final double threshold; private final double threshold;
private final boolean invert; private final boolean invert;
private ModuleState(ResolvedCaveProfile.Module module, CNG density) { private ModuleState(CaveFieldModule module, NoiseSampler density) {
IrisRange range = module.verticalRange(); Range range = module.verticalRange();
this.density = density; this.density = density;
this.minY = (int) Math.floor(range.getMin()); this.minY = (int) Math.floor(range.min());
this.maxY = (int) Math.ceil(range.getMax()); this.maxY = (int) Math.ceil(range.max());
this.weight = module.weight(); this.weight = module.weight();
this.threshold = module.threshold(); this.threshold = module.threshold();
this.invert = module.invert(); this.invert = module.invert();
@@ -162,7 +171,7 @@ public final class IrisCaveProfileSampler {
} }
private double sample(double x, double y, double z) { private double sample(double x, double y, double z) {
double sampled = density.noiseFastSigned3D(x, y, z); double sampled = density.signed(x, y, z);
return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight; return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight;
} }
} }
@@ -0,0 +1,83 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.object.terrain.carving;
import com.volmit.FeatureAttachment.Target;
import com.volmit.IrisFeature;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.resource.ResourceId;
import com.volmit.world.PackWorld;
import java.util.HashMap;
import java.util.Map;
/**
* The settings of one type that a world's dimension, regions and biomes declare, found again by the id region and biome
* samples carry ({@code overworld:desert/dunes}), which is how the layout names the region or biome of a column. A settings
* entry names its source by kind ({@code overworld:biome/desert/dunes}), so the kind is taken off the id.
*
* <p>Only the regions and biomes the dimension reaches declare anything here ({@link com.volmit.config.PackSettings#declared}).
*/
public final class DeclaredByLevel<F extends IrisFeature> {
private final F dimension;
private final Map<ResourceId, F> regions;
private final Map<ResourceId, F> biomes;
private DeclaredByLevel(F dimension, Map<ResourceId, F> regions, Map<ResourceId, F> biomes) {
this.dimension = dimension;
this.regions = Map.copyOf(regions);
this.biomes = Map.copyOf(biomes);
}
public static <F extends IrisFeature> DeclaredByLevel<F> of(PackWorld world, Class<F> type) {
F dimension = null;
Map<ResourceId, F> regions = new HashMap<>();
Map<ResourceId, F> biomes = new HashMap<>();
for (Entry<F> entry : world.settings().declared(type)) {
if (entry.level() == Target.DIMENSION) {
dimension = entry.value();
} else if (entry.level() == Target.REGION) {
regions.putIfAbsent(sampleId(entry.source()), entry.value());
} else if (entry.level() == Target.BIOME) {
biomes.putIfAbsent(sampleId(entry.source()), entry.value());
}
}
return new DeclaredByLevel<>(dimension, regions, biomes);
}
/** The dimension's declaration; null when it declares none. */
public F ofDimension() {
return dimension;
}
/** The declaration of the region with this id; null when it declares none. */
public F ofRegion(ResourceId region) {
return regions.get(region);
}
/** The declaration of the biome with this id; null when it declares none. */
public F ofBiome(ResourceId biome) {
return biomes.get(biome);
}
private static ResourceId sampleId(ResourceId source) {
String path = source.path();
return new ResourceId(source.namespace(), path.substring(path.indexOf('/') + 1));
}
}
@@ -0,0 +1,52 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.object.terrain.carving;
import art.arcane.iris.builtin.carve.CaveProfile;
import com.volmit.resource.ResourceId;
import com.volmit.world.PackWorld;
/**
* What the carve module keeps for one world: the cave profiles its dimension, regions and biomes declare ({@code caveProfile}).
* A profile that is not declared is as good as one that is not enabled, so the lookups answer null for it.
*/
public final class DeclaredCaveProfiles {
private final DeclaredByLevel<CaveProfile> declared;
private DeclaredCaveProfiles(PackWorld world) {
this.declared = DeclaredByLevel.of(world, CaveProfile.class);
}
/** The profiles of the world {@code world}. */
public static DeclaredCaveProfiles of(PackWorld world) {
return world.state(DeclaredCaveProfiles.class, DeclaredCaveProfiles::new);
}
public CaveProfile ofDimension() {
return declared.ofDimension();
}
public CaveProfile ofRegion(ResourceId region) {
return declared.ofRegion(region);
}
public CaveProfile ofBiome(ResourceId biome) {
return declared.ofBiome(biome);
}
}
@@ -19,21 +19,20 @@
package art.arcane.iris.engine.object.terrain.carving; package art.arcane.iris.engine.object.terrain.carving;
import art.arcane.iris.builtin.carve.CarvingEntry; import art.arcane.iris.builtin.carve.CarvingEntry;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.modules.IrisValues;
import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.volmlib.util.cache.AtomicCache;
import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; import com.volmit.ModuleLog;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.util.project.noise.CNG;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.config.Range; import com.volmit.config.Range;
import com.volmit.noise.NoiseSampler;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceKey;
import com.volmit.world.PackBiome;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
/** /**
* One {@link CarvingEntry} made ready for one world: the biome it names, loaded from the pack when first asked for, and the * One {@link CarvingEntry} made ready for one world: the biome it names, found in the pack when first asked for, and the
* noise that splits it into child entries, built once per seed. What the entry describes stays in the settings. * noise that splits it into child entries, built once per seed. What the entry describes stays in the settings.
*/ */
public final class ResolvedCarvingEntry { public final class ResolvedCarvingEntry {
@@ -42,13 +41,11 @@ public final class ResolvedCarvingEntry {
private static final double MIN_CHILD_SCALE = 0.0001D; private static final double MIN_CHILD_SCALE = 0.0001D;
private final CarvingEntry settings; private final CarvingEntry settings;
private final IrisGeneratorStyle childStyle; private final AtomicCache<PackBiome> realBiome = new AtomicCache<>(true);
private final AtomicCache<IrisBiome> realBiome = new AtomicCache<>(true); private final Map<Long, NoiseSampler> childGenerators = new ConcurrentHashMap<>();
private final Map<Long, CNG> childGenerators = new ConcurrentHashMap<>();
ResolvedCarvingEntry(CarvingEntry settings) { ResolvedCarvingEntry(CarvingEntry settings) {
this.settings = settings; this.settings = settings;
this.childStyle = IrisValues.generatorStyle(settings.childStyle());
} }
public String id() { public String id() {
@@ -77,25 +74,29 @@ public final class ResolvedCarvingEntry {
} }
/** The pack biome the entry names; null when it names none or the pack has no such biome. */ /** The pack biome the entry names; null when it names none or the pack has no such biome. */
public IrisBiome realBiome(IrisData data) { public PackBiome realBiome(PackResources resources, ModuleLog log) {
return realBiome.aquire(() -> { return realBiome.aquire(() -> {
String biomeKey = settings.biome(); String biomeKey = settings.biome();
if (biomeKey.isBlank()) { if (biomeKey.isBlank()) {
return null; return null;
} }
return data.getBiomeLoader().load(biomeKey.trim()); try {
return resources.find(new ResourceKey<>(resources.idOf(biomeKey.trim()), PackBiome.class)).orElse(null);
} catch (IllegalStateException unreadable) {
log.warnOnce("carving-biome:" + biomeKey, "The biome " + biomeKey + " of a carving entry cannot be loaded: " + unreadable.getMessage());
return null;
}
}); });
} }
/** The noise that picks between the entry and its children, seeded by {@code seed} and the entry's id. */ /** The noise that picks between the entry and its children, seeded by {@code seed} and the entry's id. */
public CNG childrenGenerator(long seed, IrisData data) { public NoiseSampler childrenGenerator(long seed, PackResources resources) {
long idHash = settings.id().trim().hashCode(); long idHash = settings.id().trim().hashCode();
long generatorSeed = seed ^ (idHash << 32) ^ CHILD_GENERATOR_SALT; long generatorSeed = seed ^ (idHash << 32) ^ CHILD_GENERATOR_SALT;
return childGenerators.computeIfAbsent(generatorSeed, key -> { return childGenerators.computeIfAbsent(generatorSeed, key -> {
double scale = Math.max(MIN_CHILD_SCALE, settings.childShrinkFactor()); double scale = Math.max(MIN_CHILD_SCALE, settings.childShrinkFactor());
RNG random = new RNG(key); return resources.noise().sampler(settings.childStyle(), key + CHILD_GENERATOR_SIGNATURE).scaled(scale);
return childStyle.create(random.nextParallelRNG(CHILD_GENERATOR_SIGNATURE), data).bake().scale(scale).bake();
}); });
} }
} }
@@ -1,123 +0,0 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.object.terrain.carving;
import art.arcane.iris.builtin.carve.CaveFieldModule;
import art.arcane.iris.builtin.carve.CaveProfile;
import art.arcane.iris.core.modules.IrisValues;
import art.arcane.iris.engine.object.noise.IrisGeneratorStyle;
import art.arcane.iris.engine.object.noise.IrisStyledRange;
import art.arcane.iris.engine.object.value.IrisRange;
import java.util.List;
/**
* The parts of a {@link CaveProfile} that the carvers read as Iris's own noise and range types, made once per carver:
* the generator styles that build the cave fields, the ranges and the extra field modules. The carvers read these
* through Iris's generators because those keep Iris's coordinate caches and fast signed reads, which the cave
* hot paths rely on.
*/
public final class ResolvedCaveProfile {
private final IrisRange verticalRange;
private final IrisGeneratorStyle baseDensityStyle;
private final IrisGeneratorStyle detailDensityStyle;
private final IrisGeneratorStyle warpStyle;
private final IrisGeneratorStyle surfaceBreakStyle;
private final IrisStyledRange densityThreshold;
private final List<Module> modules;
private ResolvedCaveProfile(CaveProfile settings) {
this.verticalRange = IrisValues.range(settings.verticalRange());
this.baseDensityStyle = IrisValues.generatorStyle(settings.baseDensityStyle());
this.detailDensityStyle = IrisValues.generatorStyle(settings.detailDensityStyle());
this.warpStyle = IrisValues.generatorStyle(settings.warpStyle());
this.surfaceBreakStyle = IrisValues.generatorStyle(settings.surfaceBreakStyle());
this.densityThreshold = IrisValues.styledRange(settings.densityThreshold());
this.modules = settings.modules().stream().map(Module::new).toList();
}
public static ResolvedCaveProfile of(CaveProfile settings) {
return new ResolvedCaveProfile(settings);
}
public IrisRange verticalRange() {
return verticalRange;
}
public IrisGeneratorStyle baseDensityStyle() {
return baseDensityStyle;
}
public IrisGeneratorStyle detailDensityStyle() {
return detailDensityStyle;
}
public IrisGeneratorStyle warpStyle() {
return warpStyle;
}
public IrisGeneratorStyle surfaceBreakStyle() {
return surfaceBreakStyle;
}
public IrisStyledRange densityThreshold() {
return densityThreshold;
}
public List<Module> modules() {
return modules;
}
/** One {@link CaveFieldModule} with its style and range as Iris's types. */
public static final class Module {
private final IrisGeneratorStyle style;
private final double weight;
private final double threshold;
private final IrisRange verticalRange;
private final boolean invert;
private Module(CaveFieldModule settings) {
this.style = IrisValues.generatorStyle(settings.style());
this.weight = settings.weight();
this.threshold = settings.threshold();
this.verticalRange = IrisValues.range(settings.verticalRange());
this.invert = settings.invert();
}
public IrisGeneratorStyle style() {
return style;
}
public double weight() {
return weight;
}
public double threshold() {
return threshold;
}
public IrisRange verticalRange() {
return verticalRange;
}
public boolean invert() {
return invert;
}
}
}
@@ -19,7 +19,7 @@
package art.arcane.iris.engine.object.terrain.floating; package art.arcane.iris.engine.object.terrain.floating;
import art.arcane.iris.builtin.floating.FloatingChildBiome; import art.arcane.iris.builtin.floating.FloatingChildBiome;
import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfileSampler; import art.arcane.iris.engine.object.terrain.carving.CaveProfileSampler;
import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.Engine;
@@ -415,7 +415,7 @@ public final class FloatingIslandSample {
CNG wallWarp = entry.getWallWarpCng(baseSeed, data); CNG wallWarp = entry.getWallWarpCng(baseSeed, data);
double warpAmp = Math.max(0, entry.settings().wallWarpAmplitude()); double warpAmp = Math.max(0, entry.settings().wallWarpAmplitude());
double effectiveWarpAmp = effectiveWallWarpAmplitude(warpAmp, edgeFade); double effectiveWarpAmp = effectiveWallWarpAmplitude(warpAmp, edgeFade);
IrisCaveProfileSampler carvingProfileSampler = entry.getCarvingProfileSampler(engine, data); CaveProfileSampler carvingProfileSampler = entry.getCarvingProfileSampler(engine, data);
CNG carve = carvingProfileSampler == null && !entry.hasCarvingReference() ? entry.getCarveCng(baseSeed, data) : null; CNG carve = carvingProfileSampler == null && !entry.hasCarvingReference() ? entry.getCarveCng(baseSeed, data) : null;
double carveThreshold = entry.settings().carveThreshold(); double carveThreshold = entry.settings().carveThreshold();
boolean useWarp = wallWarp != null && effectiveWarpAmp > 0; boolean useWarp = wallWarp != null && effectiveWarpAmp > 0;
@@ -484,7 +484,7 @@ public final class FloatingIslandSample {
return amplitude * fade; return amplitude * fade;
} }
static boolean directCarveEnabled(ResolvedFloatingChild entry, IrisCaveProfileSampler carvingProfileSampler, CNG carve, double carveThreshold) { static boolean directCarveEnabled(ResolvedFloatingChild entry, CaveProfileSampler carvingProfileSampler, CNG carve, double carveThreshold) {
return carvingProfileSampler == null && (entry == null || !entry.hasCarvingReference()) && carve != null && carveThreshold < 1.0; return carvingProfileSampler == null && (entry == null || !entry.hasCarvingReference()) && carve != null && carveThreshold < 1.0;
} }
@@ -500,7 +500,7 @@ public final class FloatingIslandSample {
}); });
} }
static int carveSolidInterior(boolean[] solidMask, boolean[] lateralCarveMask, int botY, int wx, int wz, IrisCaveProfileSampler carve, double carveThreshold) { 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)); return carveSolidInterior(solidMask, lateralCarveMask, botY, wx, wz, (x, y, z) -> carve.shouldCarve(x, y, z, carveThreshold));
} }
@@ -18,6 +18,8 @@
package art.arcane.iris.engine.object.terrain.floating; package art.arcane.iris.engine.object.terrain.floating;
import art.arcane.iris.builtin.carve.CarvingEntry;
import art.arcane.iris.builtin.carve.CarvingSettings;
import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.builtin.carve.CaveProfile;
import art.arcane.iris.builtin.floating.FloatingChildBiome; import art.arcane.iris.builtin.floating.FloatingChildBiome;
import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.IrisData;
@@ -28,16 +30,15 @@ import art.arcane.iris.engine.object.terrain.carving.CaveProfiles;
import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; import art.arcane.iris.engine.object.noise.IrisGeneratorStyle;
import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
import art.arcane.iris.engine.object.prefab.IrisObjectScale; import art.arcane.iris.engine.object.prefab.IrisObjectScale;
import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry; import art.arcane.iris.engine.object.terrain.carving.CaveProfileSampler;
import art.arcane.iris.engine.object.terrain.carving.CarvingBands;
import art.arcane.iris.engine.object.terrain.carving.CarvingResolver;
import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfileSampler;
import art.arcane.iris.engine.object.value.IRare; import art.arcane.iris.engine.object.value.IRare;
import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.util.project.noise.CNG; import art.arcane.iris.util.project.noise.CNG;
import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import java.util.List;
/** /**
* A {@link FloatingChildBiome} made ready for one engine: the noise its styles build (each from the world seed it is first * A {@link FloatingChildBiome} made ready for one engine: the noise its styles build (each from the world seed it is first
* asked with), the edge taper profile, the biome it targets, the carving profile sampler and the objects it hosts. The * asked with), the edge taper profile, the biome it targets, the carving profile sampler and the objects it hosts. The
@@ -62,7 +63,7 @@ public final class ResolvedFloatingChild implements IRare {
private final AtomicCache<CNG> bottomCache = new AtomicCache<>(); private final AtomicCache<CNG> bottomCache = new AtomicCache<>();
private final AtomicCache<CNG> wallWarpCache = new AtomicCache<>(); private final AtomicCache<CNG> wallWarpCache = new AtomicCache<>();
private final AtomicCache<CNG> carveCache = new AtomicCache<>(); private final AtomicCache<CNG> carveCache = new AtomicCache<>();
private final AtomicCache<IrisCaveProfileSampler> carvingProfileSamplerCache = new AtomicCache<>(true); private final AtomicCache<CaveProfileSampler> carvingProfileSamplerCache = new AtomicCache<>(true);
private final AtomicCache<IrisObjectScale> shrinkScaleCache = new AtomicCache<>(); private final AtomicCache<IrisObjectScale> shrinkScaleCache = new AtomicCache<>();
public ResolvedFloatingChild(FloatingChildBiome settings) { public ResolvedFloatingChild(FloatingChildBiome settings) {
@@ -132,7 +133,7 @@ public final class ResolvedFloatingChild implements IRare {
return carveCache.aquire(() -> carveStyle.create(new RNG(baseSeed ^ 0xCA5EC1EE5EL), data)); return carveCache.aquire(() -> carveStyle.create(new RNG(baseSeed ^ 0xCA5EC1EE5EL), data));
} }
public IrisCaveProfileSampler getCarvingProfileSampler(Engine engine, IrisData data) { public CaveProfileSampler getCarvingProfileSampler(Engine engine, IrisData data) {
if (!hasCarvingReference()) { if (!hasCarvingReference()) {
return null; return null;
} }
@@ -144,7 +145,7 @@ public final class ResolvedFloatingChild implements IRare {
return null; return null;
} }
return new IrisCaveProfileSampler(engine, profile); return new CaveProfileSampler(data.getPackResources().noise(), engine.getSeedManager().getCarve(), profile);
}); });
} }
@@ -158,9 +159,10 @@ public final class ResolvedFloatingChild implements IRare {
return null; return null;
} }
ResolvedCarvingEntry entry = CarvingBands.of(engine).index().get(carving); CarvingEntry entry = dimensionCarvingEntry(carving, engine);
if (entry != null) { if (entry != null) {
return CarvingResolver.resolveEntryBiome(engine, entry); String biomeKey = entry.biome().trim();
return biomeKey.isEmpty() || data.getBiomeLoader() == null ? null : data.getBiomeLoader().load(biomeKey);
} }
if (data.getBiomeLoader() == null) { if (data.getBiomeLoader() == null) {
@@ -170,6 +172,17 @@ public final class ResolvedFloatingChild implements IRare {
return data.getBiomeLoader().load(carving); return data.getBiomeLoader().load(carving);
} }
/** The dimension's carving entry with this id (the last of several with one id); null when it declares none. */
private static CarvingEntry dimensionCarvingEntry(String id, Engine engine) {
CarvingEntry found = null;
for (CarvingEntry entry : engine.getDimension().getModuleSettings().find(CarvingSettings.class).map(CarvingSettings::entries).orElse(List.of())) {
if (entry != null && !entry.id().isBlank() && entry.id().trim().equals(id)) {
found = entry;
}
}
return found;
}
public KList<IrisObjectPlacement> resolveTopObjects(IrisBiome target) { public KList<IrisObjectPlacement> resolveTopObjects(IrisBiome target) {
KList<IrisObjectPlacement> surfaceObjects = (settings.inheritObjects() && target != null) ? target.getSurfaceObjects() : new KList<>(); KList<IrisObjectPlacement> surfaceObjects = (settings.inheritObjects() && target != null) ? target.getSurfaceObjects() : new KList<>();
return resolveTopObjectsFromSurface(surfaceObjects); return resolveTopObjectsFromSurface(surfaceObjects);
@@ -184,8 +184,6 @@ public class IrisDimension extends IrisRegistrant {
@MaxNumber(256) @MaxNumber(256)
@Desc("Minimum air gap in blocks between the lower terrain surface and the upper terrain surface.") @Desc("Minimum air gap in blocks between the lower terrain surface and the upper terrain surface.")
private int upperDimensionGap = 32; private int upperDimensionGap = 32;
@Desc("When true, cave carving will cut through the upper dimension terrain. When false, the upper terrain is a solid untouched mass.")
private boolean upperDimensionCarving = false;
@Desc("When true, objects from the mantle (structures, trees, etc.) can be placed in the upper dimension terrain zone. When false, the upper terrain is protected from object placement.") @Desc("When true, objects from the mantle (structures, trees, etc.) can be placed in the upper dimension terrain zone. When false, the upper terrain is protected from object placement.")
private boolean upperDimensionObjects = false; private boolean upperDimensionObjects = false;
@Desc("When true, upper-dimension objects force-place regardless of placement restrictions (slope, underwater, clamp, collisions, carving). Normal dimension objects always place first; upper objects place second and may clip or occlude lower-dimension placements when this is enabled.") @Desc("When true, upper-dimension objects force-place regardless of placement restrictions (slope, underwater, clamp, collisions, carving). Normal dimension objects always place first; upper objects place second and may clip or occlude lower-dimension placements when this is enabled.")
@@ -238,10 +236,6 @@ public class IrisDimension extends IrisRegistrant {
@ArrayType(type = String.class, min = 1) @ArrayType(type = String.class, min = 1)
@Desc("External datapack sources owned by this dimension. Bukkit registers their resources server-wide, but Iris excludes their structure sets and definitions from generation and locate state in vanilla worlds and Iris dimensions that do not declare the same source. Editable auto-import is limited to resources supplied by the URLs declared by each Iris pack. Any registered datapack structure can be placed directly through nativeStructures without conversion. Replacing native generation requires a dimension-level structure placement with nativeSuppression set to REPLACE_SOURCE; provenance alone never disables native structures.") @Desc("External datapack sources owned by this dimension. Bukkit registers their resources server-wide, but Iris excludes their structure sets and definitions from generation and locate state in vanilla worlds and Iris dimensions that do not declare the same source. Editable auto-import is limited to resources supplied by the URLs declared by each Iris pack. Any registered datapack structure can be placed directly through nativeStructures without conversion. Replacing native generation requires a dimension-level structure placement with nativeSuppression set to REPLACE_SOURCE; provenance alone never disables native structures.")
private KList<String> datapackImports = new KList<>(); private KList<String> datapackImports = new KList<>();
@MinNumber(0)
@MaxNumber(318)
@Desc("The subterranean fluid (cave lava) layer height, in engine-local Y where 0 is the bottom of the dimension, not world Y. With the default -64..320 height, 8 means world Y -56.")
private int caveLavaHeight = 8;
@RegistryListFunction(ComponentFlagFunction.class) @RegistryListFunction(ComponentFlagFunction.class)
@ArrayType(type = String.class) @ArrayType(type = String.class)
@Desc("Mantle passes to skip in this dimension: CARVED (caves), OBJECT (objects), FLOATING_OBJECT (objects on floating islands) or JIGSAW (structures), or the id of a pack module's mantle stage, such as example:moss/veins. A name that matches nothing is warned about and ignored.") @Desc("Mantle passes to skip in this dimension: CARVED (caves), OBJECT (objects), FLOATING_OBJECT (objects on floating islands) or JIGSAW (structures), or the id of a pack module's mantle stage, such as example:moss/veins. A name that matches nothing is warned about and ignored.")