diff --git a/adapters/bukkit/plugin/src/test/gameplay/object-scaling-pack/dimensions/object-scaling-fixture.json b/adapters/bukkit/plugin/src/test/gameplay/object-scaling-pack/dimensions/object-scaling-fixture.json index 5adde3f51..885442264 100644 --- a/adapters/bukkit/plugin/src/test/gameplay/object-scaling-pack/dimensions/object-scaling-fixture.json +++ b/adapters/bukkit/plugin/src/test/gameplay/object-scaling-pack/dimensions/object-scaling-fixture.json @@ -10,6 +10,5 @@ "dimensionHeight": {"min": 0, "max": 128}, "logicalHeight": 128, "fluidHeight": 0, - "bedrock": false, - "caveProfile": {"enabled": false} + "bedrock": false } diff --git a/core/src/main/java/art/arcane/iris/generation/biome/FloatingIslandSample.java b/core/src/main/java/art/arcane/iris/generation/biome/FloatingIslandSample.java index d5c86bd85..eac92c196 100644 --- a/core/src/main/java/art/arcane/iris/generation/biome/FloatingIslandSample.java +++ b/core/src/main/java/art/arcane/iris/generation/biome/FloatingIslandSample.java @@ -18,7 +18,6 @@ package art.arcane.iris.generation.biome; -import art.arcane.iris.generation.cave.IrisCaveProfileSampler; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.runtime.Engine; @@ -419,13 +418,11 @@ public final class FloatingIslandSample { CNG wallWarp = entry.getWallWarpCng(baseSeed, data); double warpAmp = Math.max(0, entry.getWallWarpAmplitude()); double effectiveWarpAmp = effectiveWallWarpAmplitude(warpAmp, edgeFade); - IrisCaveProfileSampler carvingProfileSampler = entry.getCarvingProfileSampler(engine, data); - CNG carve = carvingProfileSampler == null && !entry.hasCarvingReference() ? entry.getCarveCng(baseSeed, data) : null; + CNG carve = entry.getCarveCng(baseSeed, data); double carveThreshold = entry.getCarveThreshold(); boolean useWarp = wallWarp != null && effectiveWarpAmp > 0; - boolean useProfileCarve = carvingProfileSampler != null; - boolean useCarve = directCarveEnabled(entry, carvingProfileSampler, carve, carveThreshold); - boolean[] lateralCarveMask = useProfileCarve || useCarve ? new boolean[thickness] : null; + boolean useCarve = directCarveEnabled(carve, carveThreshold); + boolean[] lateralCarveMask = useCarve ? new boolean[thickness] : null; boolean baseCarveInterior = lateralCarveMask != null && canCarveLaterally(edgeFade, footprintSupport); if (useWarp) { @@ -452,9 +449,7 @@ public final class FloatingIslandSample { } int solidCount = solidifyUncarvedInterior(solidMask); - if (useProfileCarve) { - solidCount = carveSolidInterior(solidMask, lateralCarveMask, botY, wx, wz, carvingProfileSampler, carveThreshold); - } else if (useCarve) { + if (useCarve) { solidCount = carveSolidInterior(solidMask, lateralCarveMask, botY, wx, wz, carve, carveThreshold); } int highestSolidIdx = highestSolidIndex(solidMask); @@ -488,8 +483,8 @@ public final class FloatingIslandSample { return amplitude * fade; } - static boolean directCarveEnabled(IrisFloatingChildBiomes entry, IrisCaveProfileSampler carvingProfileSampler, CNG carve, double carveThreshold) { - return carvingProfileSampler == null && (entry == null || !entry.hasCarvingReference()) && carve != null && carveThreshold < 1.0; + static boolean directCarveEnabled(CNG carve, double carveThreshold) { + return carve != null && carveThreshold < 1.0; } static boolean canCarveLaterally(double edgeFade, NeighborSupport support) { @@ -504,10 +499,6 @@ public final class FloatingIslandSample { }); } - static int carveSolidInterior(boolean[] solidMask, boolean[] lateralCarveMask, int botY, int wx, int wz, IrisCaveProfileSampler carve, double carveThreshold) { - return carveSolidInterior(solidMask, lateralCarveMask, botY, wx, wz, (x, y, z) -> carve.shouldCarve(x, y, z, carveThreshold)); - } - private static int carveSolidInterior(boolean[] solidMask, boolean[] lateralCarveMask, int botY, int wx, int wz, CarveSampler carve) { int firstSolid = -1; int lastSolid = -1; diff --git a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiome.java b/core/src/main/java/art/arcane/iris/generation/biome/IrisBiome.java index 782f298f3..924a4969d 100644 --- a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiome.java +++ b/core/src/main/java/art/arcane/iris/generation/biome/IrisBiome.java @@ -19,7 +19,6 @@ package art.arcane.iris.generation.biome; import art.arcane.iris.generation.cave.IrisCave; -import art.arcane.iris.generation.cave.IrisCaveProfile; import art.arcane.iris.generation.decoration.IrisDecorationPart; import art.arcane.iris.generation.decoration.IrisDecorator; import art.arcane.iris.generation.decoration.IrisDepositGenerator; @@ -161,8 +160,6 @@ public class IrisBiome extends IrisRegistrant implements Rarity { private boolean lockLayers = false; @Description("The max layers to iterate below the surface for locked layer biomes (mesa).") private int lockLayersMax = 7; - @Description("Profile-driven 3D cave configuration") - private IrisCaveProfile caveProfile = new IrisCaveProfile(); @ArrayType(type = String.class, min = 1) @RegistryListResource(IrisCave.class) @Description("Caves that carve under this biome, by their file in the pack's caves folder. As a cave biome, they carve where the cave biome is. They add to the dimension's and the region's lists.") diff --git a/core/src/main/java/art/arcane/iris/generation/biome/IrisFloatingChildBiomes.java b/core/src/main/java/art/arcane/iris/generation/biome/IrisFloatingChildBiomes.java index 55111cad3..b5dbe5499 100644 --- a/core/src/main/java/art/arcane/iris/generation/biome/IrisFloatingChildBiomes.java +++ b/core/src/main/java/art/arcane/iris/generation/biome/IrisFloatingChildBiomes.java @@ -18,12 +18,8 @@ package art.arcane.iris.generation.biome; -import art.arcane.iris.generation.cave.IrisCaveProfileSampler; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.NoiseStyle; -import art.arcane.iris.generation.terrain.IrisDimension; -import art.arcane.iris.generation.terrain.IrisDimensionCarvingEntry; -import art.arcane.iris.generation.terrain.IrisDimensionCarvingResolver; import art.arcane.iris.pack.validation.CompatPools; import art.arcane.iris.pack.value.OverrideMode; import art.arcane.iris.structure.object.IrisObjectPlacement; @@ -68,12 +64,6 @@ public class IrisFloatingChildBiomes implements Rarity { @Getter(AccessLevel.NONE) @Setter(AccessLevel.NONE) private transient volatile CachedEdgeProfile recentEdgeProfile; - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient LazyBoundedCache carvingProfileSamplers = new LazyBoundedCache<>(8); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private transient volatile CachedCarvingProfile recentCarvingProfile; private final transient AtomicCache shrinkScaleCache = new AtomicCache<>(); public CNG getFootprintCng(long baseSeed, IrisData data) { @@ -133,52 +123,6 @@ public class IrisFloatingChildBiomes implements Rarity { return style.create(baseSeed ^ 0xCA5EC1EE5EL, data); } - public IrisCaveProfileSampler getCarvingProfileSampler(Engine engine, IrisData data) { - if (!hasCarvingReference()) { - return null; - } - - CachedCarvingProfile recent = recentCarvingProfile; - if (recent != null && recent.key.matches(0L, data, engine)) { - return recent.sampler; - } - RuntimeKey key = new RuntimeKey(0L, data, engine); - IrisCaveProfileSampler sampler = carvingProfileSamplers.computeIfAbsent(key, ignored -> { - IrisBiome resolved = resolveCarvingBiome(carving, engine, data); - if (resolved == null || resolved.getCaveProfile() == null || !resolved.getCaveProfile().isEnabled()) { - return null; - } - - return new IrisCaveProfileSampler(engine, resolved.getCaveProfile()); - }); - recentCarvingProfile = new CachedCarvingProfile(key, sampler); - return sampler; - } - - public boolean hasCarvingReference() { - return carving != null && !carving.isBlank(); - } - - static IrisBiome resolveCarvingBiome(String carving, Engine engine, IrisData data) { - if (carving == null || carving.isBlank() || engine == null || data == null) { - return null; - } - - IrisDimension dimension = engine.getDimension(); - if (dimension != null && dimension.getCarvingEntryIndex() != null) { - IrisDimensionCarvingEntry entry = dimension.getCarvingEntryIndex().get(carving); - if (entry != null) { - return IrisDimensionCarvingResolver.resolveEntryBiome(engine, entry); - } - } - - if (data.getBiomeLoader() == null) { - return null; - } - - return data.getBiomeLoader().load(carving); - } - @RegistryListResource(IrisBiome.class) @Description("The target biome whose visual design (layers, palette, decorators, surface objects, derivative, and — when topShapeMode=BIOME — generator profile) drives the floating island. Leave empty to reuse the parent biome (self).") private String biome = ""; @@ -293,12 +237,9 @@ public class IrisFloatingChildBiomes implements Rarity { @Description("Optional 3D noise that swiss-cheeses the island interior by marking individual blocks as air when the noise exceeds carveThreshold. Leave null to keep the island solid. Good defaults: {\"style\":\"CELLULAR\",\"zoom\":0.3} for bubble pockets, {\"style\":\"VASCULAR\",\"zoom\":0.25} for wormy tunnels.") private IrisGeneratorStyle carveStyle = null; - @Description("Optional carving biome key or dimension carving entry id whose caveProfile drives floating-island internal air pockets. Dimension carving ids resolve first; biome keys such as carving/mushroom resolve second. When set, this overrides carveStyle while carveThreshold remains a final tuning bias.") - private String carving = ""; - @MinNumber(0) @MaxNumber(1) - @Description("Threshold (0..1) above which carveStyle noise carves air pockets. 1.0 = no direct-noise carving. 0.75 = sparse pockets. 0.55 = heavy swiss-cheese. 0.4 = shredded lattice. When carving is set, lower values add a final positive threshold bias to the referenced caveProfile.") + @Description("Threshold (0..1) above which carveStyle noise carves air pockets. 1.0 = no direct-noise carving. 0.75 = sparse pockets. 0.55 = heavy swiss-cheese. 0.4 = shredded lattice.") private double carveThreshold = 1.0; @Description("Optional water surface height above the island base, in blocks. null = no internal water. Positive = water fills any dip in the top profile up to baseY + localFluidHeight (forms lakes/ponds in concavities of the biome-top heightmap).") @@ -421,7 +362,4 @@ public class IrisFloatingChildBiomes implements Rarity { private record CachedEdgeProfile(RuntimeKey key, FloatingIslandEdgeProfile profile) { } - - private record CachedCarvingProfile(RuntimeKey key, IrisCaveProfileSampler sampler) { - } } diff --git a/core/src/main/java/art/arcane/iris/generation/cave/IrisCaveFieldModule.java b/core/src/main/java/art/arcane/iris/generation/cave/IrisCaveFieldModule.java deleted file mode 100644 index ccaf23234..000000000 --- a/core/src/main/java/art/arcane/iris/generation/cave/IrisCaveFieldModule.java +++ /dev/null @@ -1,40 +0,0 @@ -package art.arcane.iris.generation.cave; - -import art.arcane.iris.generation.noise.IrisGeneratorStyle; -import art.arcane.iris.generation.noise.NoiseStyle; -import art.arcane.iris.pack.value.IrisRange; - -import art.arcane.volmlib.util.documentation.Description; -import art.arcane.iris.pack.schema.annotation.MaxNumber; -import art.arcane.iris.pack.schema.annotation.MinNumber; -import art.arcane.iris.pack.schema.annotation.Snippet; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("cave-field-module") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Description("Represents a modular cave-density layer.") -@Data -public class IrisCaveFieldModule { - @Description("Density style used by this module.") - private IrisGeneratorStyle style = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - - @MinNumber(0) - @Description("Layer contribution multiplier.") - private double weight = 1; - - @MinNumber(-1) - @MaxNumber(1) - @Description("Threshold offset applied to this layer before blending.") - private double threshold = 0; - - @Description("Vertical bounds where this module can contribute, in engine-local Y where 0 is the bottom of the dimension, not world Y.") - private IrisRange verticalRange = new IrisRange(0, 384); - - @Description("Invert this module before weighting.") - private boolean invert = false; -} diff --git a/core/src/main/java/art/arcane/iris/generation/cave/IrisCaveProfile.java b/core/src/main/java/art/arcane/iris/generation/cave/IrisCaveProfile.java deleted file mode 100644 index bd11e5b81..000000000 --- a/core/src/main/java/art/arcane/iris/generation/cave/IrisCaveProfile.java +++ /dev/null @@ -1,154 +0,0 @@ -package art.arcane.iris.generation.cave; - -import art.arcane.iris.generation.noise.IrisGeneratorStyle; -import art.arcane.iris.generation.noise.IrisStyledRange; -import art.arcane.iris.generation.noise.NoiseStyle; -import art.arcane.iris.pack.value.IrisRange; -import art.arcane.iris.structure.object.ObjectPlaceMode; - -import art.arcane.iris.pack.schema.annotation.ArrayType; -import art.arcane.volmlib.util.documentation.Description; -import art.arcane.iris.pack.schema.annotation.MaxNumber; -import art.arcane.iris.pack.schema.annotation.MinNumber; -import art.arcane.iris.pack.schema.annotation.Snippet; -import art.arcane.volmlib.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("cave-profile") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Description("Represents a configurable 3D cave profile.") -@Data -public class IrisCaveProfile { - @Description("Enable profile-driven cave carving.") - private boolean enabled = false; - - @Description("Global vertical bounds for profile cave carving, in engine-local Y where 0 is the bottom of the dimension, not world Y.") - private IrisRange verticalRange = new IrisRange(0, 384); - - @MinNumber(0) - @MaxNumber(128) - @Description("Vertical fade range applied near cave profile min/max bounds to avoid abrupt hard-stop ceilings/floors.") - private int verticalEdgeFade = 20; - - @MinNumber(0) - @MaxNumber(1) - @Description("Strength of the vertical edge fade at cave profile min/max bounds.") - private double verticalEdgeFadeStrength = 0.18; - - @Description("Base density style for cave field generation.") - private IrisGeneratorStyle baseDensityStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - - @Description("Detail density style blended into base caves.") - private IrisGeneratorStyle detailDensityStyle = new IrisGeneratorStyle(NoiseStyle.SIMPLEX); - - @Description("Warp style used to distort cave coordinates.") - private IrisGeneratorStyle warpStyle = new IrisGeneratorStyle(NoiseStyle.FLAT); - - @MinNumber(0) - @Description("Base cave field multiplier.") - private double baseWeight = 1; - - @MinNumber(0) - @Description("Detail cave field multiplier.") - private double detailWeight = 0.35; - - @MinNumber(0) - @Description("Coordinate warp strength for cave fields.") - private double warpStrength = 0; - - @Description("Threshold range used for carve cutoff decisions.") - private IrisStyledRange densityThreshold = new IrisStyledRange(-0.2, 0.2, NoiseStyle.CELLULAR_IRIS_DOUBLE.style()); - - @MinNumber(0) - @MaxNumber(1) - @Description("Extra threshold bias subtracted from sampled threshold before carve tests.") - private double thresholdBias = 0.16; - - @MinNumber(1) - @MaxNumber(8) - @Description("Vertical sample step used while evaluating cave density.") - private int sampleStep = 1; - - @Description("Use adaptive cave density prediction so only threshold-adjacent cells fall back to full-resolution evaluation.") - private boolean adaptiveSampling = true; - - @MinNumber(2) - @MaxNumber(4) - @Description("Horizontal adaptive predictor tuning. The carver always samples the predictor grid at a fixed step of 8; values below 8 only widen the ambiguity margin slightly and do not tighten the grid.") - private int adaptiveSampleStep = 2; - - @MinNumber(0) - @MaxNumber(1) - @Description("Additional adaptive ambiguity margin used before the cave predictor falls back to exact sampling.") - private double adaptiveThresholdMargin = 0.04; - - @MinNumber(0) - @MaxNumber(64) - @Description("Minimum solid clearance below terrain surface where carving may occur.") - private int surfaceClearance = 4; - - @Description("Allow profile-driven cave carving to break through terrain surface in selected columns.") - private boolean allowSurfaceBreak = true; - - @Description("Noise style used to decide where surface-breaking cave columns are allowed.") - private IrisGeneratorStyle surfaceBreakStyle = new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.08); - - @MinNumber(-1) - @MaxNumber(1) - @Description("Minimum signed surface-break noise value required before near-surface carving is allowed.") - private double surfaceBreakNoiseThreshold = 0.62; - - @MinNumber(0) - @MaxNumber(64) - @Description("Near-surface depth window used for surface-break carve logic.") - private int surfaceBreakDepth = 18; - - @MinNumber(0) - @MaxNumber(1) - @Description("Additional threshold boost applied while carving in the surface-break depth window.") - private double surfaceBreakThresholdBoost = 0.2; - - @MinNumber(0) - @MaxNumber(64) - @Description("Minimum depth below terrain surface required for cave-only object anchor placement.") - private int objectMinDepthBelowSurface = 6; - - @ArrayType(type = IrisCaveFieldModule.class, min = 1) - @Description("Additional layered cave-density modules.") - private KList modules = new KList<>(); - - @Description("Default cave anchor mode for cave-only object placement.") - private IrisCaveAnchorMode defaultObjectAnchor = IrisCaveAnchorMode.FLOOR; - - @Description("Default placement mode for cave objects. Only applies to placements that are still on the default CENTER_HEIGHT mode; an explicit mode on the placement always wins. Stilt modes tile the object base block down to the cave floor surface. FAST_MIN_STILT is recommended for cave objects to prevent floating.") - private ObjectPlaceMode defaultObjectPlaceMode = null; - - @MinNumber(1) - @MaxNumber(8) - @Description("Vertical scan step used while searching cave anchors.") - private int anchorScanStep = 1; - - @MinNumber(1) - @MaxNumber(64) - @Description("Maximum random column retries while searching a valid cave object anchor in the chunk.") - private int anchorSearchAttempts = 6; - - @Description("Allow cave fluid placement from the dimension fluid palette below fluid level.") - private boolean allowFluid = true; - - @MinNumber(0) - @MaxNumber(64) - @Description("Minimum depth below terrain surface required before cave fluid may be placed.") - private int fluidMinDepthBelowSurface = 12; - - @Description("Require solid floor support below cave fluid to reduce unsupported fluid flows.") - private boolean fluidRequiresFloor = true; - - @Description("Allow cave lava placement based on lava height.") - private boolean allowLava = true; -} diff --git a/core/src/main/java/art/arcane/iris/generation/cave/IrisCaveProfileSampler.java b/core/src/main/java/art/arcane/iris/generation/cave/IrisCaveProfileSampler.java deleted file mode 100644 index a78b2250e..000000000 --- a/core/src/main/java/art/arcane/iris/generation/cave/IrisCaveProfileSampler.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.generation.cave; - -import art.arcane.iris.pack.value.IrisRange; -import art.arcane.iris.generation.noise.IrisStyledRange; -import art.arcane.volmlib.util.math.M; - -import art.arcane.iris.pack.loading.IrisData; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.volmlib.util.noise.CNG; -import art.arcane.volmlib.util.math.RNG; - -import java.util.ArrayList; -import java.util.List; - -public final class IrisCaveProfileSampler { - private static final double FLOATING_THRESHOLD_BIAS_SCALE = 0.2D; - - private final IrisCaveProfile profile; - private final CNG baseDensity; - private final CNG detailDensity; - private final CNG warpDensity; - private final CNG thresholdDensity; - private final double thresholdMin; - private final double thresholdMax; - private final double constantThreshold; - private final boolean thresholdHasNoise; - private final ModuleState[] modules; - private final double inverseNormalization; - private final double baseWeight; - private final double detailWeight; - private final double warpStrength; - private final boolean enabled; - private final boolean hasWarp; - private final boolean hasModules; - - public IrisCaveProfileSampler(Engine engine, IrisCaveProfile profile) { - IrisData data = engine.getData(); - this.profile = profile; - List moduleStates = new ArrayList<>(); - RNG baseRng = new RNG(engine.getSeedManager().getCarve()); - this.baseDensity = profile.getBaseDensityStyle().create(baseRng.nextParallelRNG(934_447), data); - this.detailDensity = profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), data); - this.warpDensity = profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), data); - IrisStyledRange threshold = profile.getDensityThreshold(); - thresholdMin = threshold.getMin(); - thresholdMax = threshold.getMax(); - thresholdHasNoise = thresholdMin != thresholdMax && !threshold.getStyle().isFlat(); - thresholdDensity = thresholdHasNoise ? threshold.getStyle().create(baseRng.nextParallelRNG(489_112), data) : null; - constantThreshold = thresholdMin == thresholdMax ? thresholdMin : M.lerp(thresholdMin, thresholdMax, 0.5D); - this.baseWeight = profile.getBaseWeight(); - this.detailWeight = profile.getDetailWeight(); - this.warpStrength = profile.getWarpStrength(); - this.hasWarp = warpStrength > 0D; - - double weight = Math.abs(baseWeight) + Math.abs(detailWeight); - int index = 0; - for (IrisCaveFieldModule module : profile.getModules()) { - CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), data); - ModuleState state = new ModuleState(module, moduleDensity); - moduleStates.add(state); - weight += Math.abs(state.weight); - index++; - } - - this.modules = moduleStates.toArray(new ModuleState[0]); - double normalization = weight <= 0 ? 1D : weight; - this.inverseNormalization = 1D / normalization; - this.hasModules = modules.length > 0; - this.enabled = profile.isEnabled() && baseDensity != null && detailDensity != null && (!hasWarp || warpDensity != null); - } - - public boolean shouldCarve(int x, int y, int z, double floatingCarveThreshold) { - if (!enabled) { - return false; - } - - double threshold = (thresholdHasNoise ? thresholdDensity.fitDouble(thresholdMin, thresholdMax, x, z) - : constantThreshold) - profile.getThresholdBias(); - threshold += floatingThresholdBias(floatingCarveThreshold); - return sampleDensity(x, y, z) <= threshold; - } - - double sampleDensity(int x, int y, int z) { - if (hasWarp) { - return sampleDensityWarped(x, y, z); - } - - return sampleDensityUnwarped(x, y, z); - } - - private double sampleDensityUnwarped(int x, int y, int z) { - double density = baseDensity.noiseFastSigned3D(x, y, z) * baseWeight; - density += detailDensity.noiseFastSigned3D(x, y, z) * detailWeight; - if (hasModules) { - for (ModuleState module : modules) { - if (!module.isActive(y)) { - continue; - } - - density += module.sample(x, y, z); - } - } - - return density * inverseNormalization; - } - - private double sampleDensityWarped(int x, int y, int z) { - double warpA = warpDensity.noiseFastSigned3D(x, y, z); - double warpB = warpDensity.noiseFastSigned3D(x + 31.37D, y - 17.21D, z + 23.91D); - double warpedX = x + (warpA * warpStrength); - double warpedY = y + (warpB * warpStrength); - double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); - double density = baseDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * baseWeight; - density += detailDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * detailWeight; - if (hasModules) { - for (ModuleState module : modules) { - if (!module.isActive(y)) { - continue; - } - - density += module.sample(warpedX, warpedY, warpedZ); - } - } - - return density * inverseNormalization; - } - - private double floatingThresholdBias(double floatingCarveThreshold) { - double clamped = Math.max(0D, Math.min(1D, floatingCarveThreshold)); - return (1D - clamped) * FLOATING_THRESHOLD_BIAS_SCALE; - } - - private static final class ModuleState { - private final CNG density; - private final int minY; - private final int maxY; - private final double weight; - private final double threshold; - private final boolean invert; - - private ModuleState(IrisCaveFieldModule module, CNG density) { - IrisRange range = module.getVerticalRange(); - this.density = density; - this.minY = (int) Math.floor(range.getMin()); - this.maxY = (int) Math.ceil(range.getMax()); - this.weight = module.getWeight(); - this.threshold = module.getThreshold(); - this.invert = module.isInvert(); - } - - private boolean isActive(int y) { - return density != null && y >= minY && y <= maxY; - } - - private double sample(double x, double y, double z) { - double sampled = density.noiseFastSigned3D(x, y, z); - return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight; - } - } -} diff --git a/core/src/main/java/art/arcane/iris/generation/cave/field/AquiferPockets.java b/core/src/main/java/art/arcane/iris/generation/cave/field/AquiferPockets.java new file mode 100644 index 000000000..ad9309d54 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/cave/field/AquiferPockets.java @@ -0,0 +1,48 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.cave.field; + +/** + * Where a cave holds pockets of the dimension's fluid: a smooth noise read above a cutoff that rises towards the + * fluid height, so pockets fill the deepest parts of a cave first. The noise is stretched to twice its horizontal + * size vertically, the way the caves this replaces read theirs. + */ +public final class AquiferPockets { + /** The spacing of the pockets' noise horizontally, in blocks: the SIMPLEX style at zoom 1. */ + private static final double POCKET_SPACING_BLOCKS = 52.6D; + private static final double POCKET_VERTICAL_SPACING_BLOCKS = POCKET_SPACING_BLOCKS * 2D; + private static final double CUTOFF_AT_FLUID_HEIGHT = 0.35D; + private static final double CUTOFF_RISE_PER_DEPTH_SPAN = 0.2D; + private static final double DEPTH_SPAN_BLOCKS = 48D; + private static final double MOST_DEPTH_SPANS = 1.5D; + private static final String NOISE_NAME = "aquifer.pockets"; + + private final Field3 pockets; + + public AquiferPockets(NoiseFactory noise, long seed) { + this.pockets = new CaveNoise(noise, seed).named(NOISE_NAME).smooth(POCKET_SPACING_BLOCKS, POCKET_VERTICAL_SPACING_BLOCKS); + } + + /** Whether the block at height {@code y} below fluid height {@code fluidHeight} lies in a pocket of fluid. */ + public boolean holdsFluidAt(int x, int y, int z, int fluidHeight) { + double depthSpans = Math.max(0D, Math.min(MOST_DEPTH_SPANS, (fluidHeight - y) / DEPTH_SPAN_BLOCKS)); + double cutoff = CUTOFF_AT_FLUID_HEIGHT + (depthSpans * CUTOFF_RISE_PER_DEPTH_SPAN); + return pockets.at(x, y, z) > cutoff; + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/cave/field/CaveCarver.java b/core/src/main/java/art/arcane/iris/generation/cave/field/CaveCarver.java index 38f1e1423..e48caefbc 100644 --- a/core/src/main/java/art/arcane/iris/generation/cave/field/CaveCarver.java +++ b/core/src/main/java/art/arcane/iris/generation/cave/field/CaveCarver.java @@ -103,8 +103,12 @@ public final class CaveCarver { * @param sealed columns whose surface the cave must not cut through, even if it opens to the surface * @param topLimitY the highest height the cave may carve in each column, where something else caps it, such as the * ceiling of a cave pool; the cave closes under the cap like it does under the rock it keeps. Null for no caps + * @param depthRange which heights the cave carves at */ - public record ChunkColumns(int[] surfaceY, double[] weight, boolean[] sealed, int[] topLimitY) { + public record ChunkColumns(int[] surfaceY, double[] weight, boolean[] sealed, int[] topLimitY, DepthRange depthRange) { + public ChunkColumns(int[] surfaceY, double[] weight, boolean[] sealed, int[] topLimitY) { + this(surfaceY, weight, sealed, topLimitY, DepthRange.OWN); + } } private record PartShape(CavePart part, LatticeShape shape) { @@ -145,10 +149,11 @@ public final class CaveCarver { Columns columns = Columns.of(chunk.weight()); fillBlocks(fade, originX, originZ, columns.fadeBlocks()); fillBlocks(ceilingFade, originX, originZ, columns.ceilingFadeBlocks()); - boolean depthVaries = depthMin.varies() || depthMax.varies(); + boolean wholeDimension = chunk.depthRange() == DepthRange.WHOLE_DIMENSION; + boolean depthVaries = !wholeDimension && (depthMin.varies() || depthMax.varies()); int constantClearance = surfaceClearanceAt(originX, originZ); - int constantDepthMinY = depthMinYAt(originX, originZ); - int constantDepthMaxY = depthMaxYAt(originX, originZ); + int constantDepthMinY = wholeDimension ? ROCK_KEPT_ABOVE_BOTTOM_BLOCKS : depthMinYAt(originX, originZ); + int constantDepthMaxY = wholeDimension ? worldHeight - 1 : depthMaxYAt(originX, originZ); for (int column = 0; column < CaveLimits.CHUNK_COLUMNS; column++) { double x = originX + (column >> 4); double z = originZ + (column & 15); diff --git a/core/src/main/java/art/arcane/iris/generation/cave/field/DepthRange.java b/core/src/main/java/art/arcane/iris/generation/cave/field/DepthRange.java new file mode 100644 index 000000000..f5b79e7fd --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/cave/field/DepthRange.java @@ -0,0 +1,27 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.cave.field; + +/** Which heights a cave carves at, before a {@link HeightBand} cuts them off. */ +public enum DepthRange { + /** The depth range the cave writes, or the whole dimension where it writes none. */ + OWN, + /** The whole dimension, whatever the cave writes: for carving the terrain of an upper dimension. */ + WHOLE_DIMENSION +} diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/CaveCarveScratch.java b/core/src/main/java/art/arcane/iris/generation/mantle/CaveCarveScratch.java deleted file mode 100644 index ba0e5fd64..000000000 --- a/core/src/main/java/art/arcane/iris/generation/mantle/CaveCarveScratch.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.generation.mantle; - -import art.arcane.volmlib.util.matter.Matter; -import art.arcane.volmlib.util.matter.MatterCavern; -import art.arcane.volmlib.util.matter.MatterSlice; - -import java.util.Arrays; - -final class CaveCarveScratch { - final int[] columnMaxY = new int[256]; - final int[] fluidMaxY = new int[256]; - final int[] surfaceBreakFloorY = new int[256]; - final boolean[] surfaceBreakColumn = new boolean[256]; - final boolean[] surfaceCeilingColumn = new boolean[256]; - final double[] columnThreshold = new double[256]; - final double[] passThreshold = new double[256]; - final double[] fullWeights = new double[256]; - final double[] clampedColumnWeights = new double[256]; - final int[] activeColumnIndices = new int[256]; - final int[] activeColumnTopY = new int[256]; - final int[] planeColumnIndices = new int[256]; - final double[] planeThresholdLimit = new double[256]; - final boolean[] planeCarve = new boolean[256]; - final double[] adaptivePlaneDensity = new double[81]; - final CaveDensityGrid.Column[] densityColumns = new CaveDensityGrid.Column[16]; - double[] verticalDensityLower = new double[9]; - double[] verticalDensityUpper = new double[9]; - int verticalDensityLowerY = Integer.MIN_VALUE; - int verticalDensityUpperY = Integer.MIN_VALUE; - int verticalDensityX; - int verticalDensityZ; - final double[] adaptivePlanePrediction = new double[256]; - final double[] adaptivePlaneAmbiguity = new double[256]; - final int[] adaptivePlaneSampleBounds = new int[4]; - final int[] adaptiveCellX = new int[256]; - final int[] adaptiveCellZ = new int[256]; - final int[] adaptiveRow0 = new int[256]; - final int[] adaptiveRow1 = new int[256]; - final double[] adaptiveTx = new double[256]; - final double[] adaptiveTz = new double[256]; - final boolean[] warpCacheSet = new boolean[256]; - final int[] warpCacheX = new int[256]; - final int[] warpCacheY = new int[256]; - final int[] warpCacheZ = new int[256]; - final double[] warpCacheA = new double[256]; - final double[] warpCacheB = new double[256]; - final int[] tileIndices = new int[4]; - final int[] tileLocalX = new int[4]; - final int[] tileLocalZ = new int[4]; - final int[] tileTopY = new int[4]; - final long[] rowCarveBits = new long[4]; - final long[] cellPassBits = new long[4]; - final CaveDensityLattice cellLattice = new CaveDensityLattice(); - final double[] cellThresholdMin = new double[4]; - final double[] cellThresholdMax = new double[4]; - final double[] cellThresholdMaxBoost = new double[4]; - final int[] cellBreakFloorMin = new int[4]; - final int[] cellCeilingFadeStart = new int[4]; - final int[] cellTopY = new int[4]; - final int[] cellMinTopY = new int[4]; - final boolean[] cellProtected = new boolean[4]; - final int[] columnProtectStartY = new int[256]; - final int[] columnProtectEndY = new int[256]; - int[] rowActiveCount = new int[0]; - long solidCells; - long openCells; - long mixedCells; - long exactRows; - CaveFieldModuleState[] activeModules = new CaveFieldModuleState[0]; - double[] activeModuleRemainingMin = new double[0]; - double[] activeModuleRemainingMax = new double[0]; - int activeModulesY = Integer.MIN_VALUE; - int activeModuleCount; - double[] verticalEdgeFade = new double[0]; - double[] surfaceClosureThreshold = new double[0]; - MatterCavern[] matterByY = new MatterCavern[0]; - Matter[] sectionMatter = new Matter[0]; - MatterSlice[] sectionSlices = new MatterSlice[0]; - int adaptiveGeometryStep = -1; - int adaptiveGeometryAxisCells = -1; - boolean fullWeightsInitialized; - - void releaseReferences() { - Arrays.fill(sectionMatter, null); - Arrays.fill(sectionSlices, null); - Arrays.fill(densityColumns, null); - cellLattice.releaseReferences(); - } -} diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/CaveCellKernel.java b/core/src/main/java/art/arcane/iris/generation/mantle/CaveCellKernel.java deleted file mode 100644 index 6eb42c753..000000000 --- a/core/src/main/java/art/arcane/iris/generation/mantle/CaveCellKernel.java +++ /dev/null @@ -1,33 +0,0 @@ -package art.arcane.iris.generation.mantle; - -final class CaveCellKernel { - static final int NONE = 0; - static final int ALL = 1; - static final int MIXED = 2; - private static final double GUARD_ULPS = 32D; - private static final double MAXIMUM_MAGNITUDE = 0x1p500; - - private CaveCellKernel() { - } - - static int decide(double d00, double d01, double d10, double d11, double thresholdLow, double thresholdHigh) { - double low = Math.min(Math.min(d00, d01), Math.min(d10, d11)); - double high = Math.max(Math.max(d00, d01), Math.max(d10, d11)); - double magnitude = Math.max(Math.abs(low), Math.abs(high)); - if (!(magnitude < MAXIMUM_MAGNITUDE)) { - return MIXED; - } - double guard = Math.ulp(magnitude) * GUARD_ULPS; - if (high + guard <= thresholdLow) { - return ALL; - } - if (low - guard > thresholdHigh) { - return NONE; - } - return MIXED; - } - - static double threshold(double localThreshold, double normalizationFactor, double inverseNormalization) { - return (localThreshold * normalizationFactor) * inverseNormalization; - } -} diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/CaveCellSink.java b/core/src/main/java/art/arcane/iris/generation/mantle/CaveCellSink.java new file mode 100644 index 000000000..613bfee94 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/mantle/CaveCellSink.java @@ -0,0 +1,27 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.mantle; + +import art.arcane.volmlib.util.matter.MatterCavern; + +/** Takes the carved blocks of a chunk, by their place in it and their height from the dimension's bottom. */ +@FunctionalInterface +interface CaveCellSink { + void set(int localX, int y, int localZ, MatterCavern cell); +} diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/CaveDensityGrid.java b/core/src/main/java/art/arcane/iris/generation/mantle/CaveDensityGrid.java deleted file mode 100644 index eb49c899c..000000000 --- a/core/src/main/java/art/arcane/iris/generation/mantle/CaveDensityGrid.java +++ /dev/null @@ -1,110 +0,0 @@ -package art.arcane.iris.generation.mantle; - -import art.arcane.iris.generation.cache.ConcurrentClockCache; - -import java.lang.invoke.MethodHandles; -import java.lang.invoke.VarHandle; -import java.util.Arrays; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReferenceArray; - -/** - * Shares the adaptive cave planes' 8-block density lattice between neighbouring chunks. Every lattice column on a - * chunk edge is sampled by two chunks and every corner by four, with identical coordinates and carver noise, so a - * value computed once is reused bit for bit. Racing writers store the same value. - */ -final class CaveDensityGrid { - static final int LATTICE_SHIFT = 3; - private static final int SEGMENT_SHIFT = 5; - private static final int SEGMENT_SIZE = 1 << SEGMENT_SHIFT; - private static final long COORDINATE_MASK = 0xFFFFFFL; - private static final VarHandle VALUES = MethodHandles.arrayElementVarHandle(double[].class); - private static final AtomicInteger OWNERS = new AtomicInteger(); - - private final ConcurrentClockCache columns; - private final ConcurrentClockCache warpColumns; - private final ConcurrentHashMap owners = new ConcurrentHashMap<>(); - - CaveDensityGrid(int capacity) { - columns = new ConcurrentClockCache<>(capacity); - warpColumns = new ConcurrentClockCache<>(Math.max(1, capacity >> 2)); - } - - Owner owner(Object fieldKey) { - return owners.computeIfAbsent(fieldKey, ignored -> new Owner(OWNERS.getAndIncrement())); - } - - Column column(Owner owner, int height, int latticeX, int latticeZ) { - return column(columns, owner, height, latticeX, latticeZ); - } - - Column warpColumn(Owner owner, int height, int latticeX, int latticeZ) { - return column(warpColumns, owner, height, latticeX, latticeZ); - } - - void clear() { - columns.clear(); - warpColumns.clear(); - owners.clear(); - } - - private static Column column(ConcurrentClockCache cache, Owner owner, int height, int latticeX, int latticeZ) { - long key = (long) (owner.id & 0xFFFF) << 48 | (latticeX & COORDINATE_MASK) << 24 | (latticeZ & COORDINATE_MASK); - Column cached = cache.get(key); - if (cached == null) { - cached = cache.putIfAbsent(key, new Column(owner, latticeX, latticeZ, height)); - } - return cached.matches(owner, latticeX, latticeZ) ? cached : null; - } - - static final class Owner { - private final int id; - - private Owner(int id) { - this.id = id; - } - } - - static final class Column { - private final Owner owner; - private final int latticeX; - private final int latticeZ; - private final AtomicReferenceArray segments; - - private Column(Owner owner, int latticeX, int latticeZ, int height) { - this.owner = owner; - this.latticeX = latticeX; - this.latticeZ = latticeZ; - segments = new AtomicReferenceArray<>(Math.ceilDiv(Math.max(1, height), SEGMENT_SIZE)); - } - - boolean matches(Owner owner, int latticeX, int latticeZ) { - return this.owner == owner && this.latticeX == latticeX && this.latticeZ == latticeZ; - } - - double get(int y) { - int segment = y >> SEGMENT_SHIFT; - if (segment >= segments.length()) { - return Double.NaN; - } - double[] values = segments.getAcquire(segment); - return values == null ? Double.NaN : (double) VALUES.getOpaque(values, y & (SEGMENT_SIZE - 1)); - } - - void set(int y, double value) { - int segment = y >> SEGMENT_SHIFT; - if (segment >= segments.length()) { - return; - } - double[] values = segments.getAcquire(segment); - if (values == null) { - double[] created = new double[SEGMENT_SIZE]; - Arrays.fill(created, Double.NaN); - double[] published = segments.compareAndExchange(segment, null, created); - values = published == null ? created : published; - } - VALUES.setOpaque(values, y & (SEGMENT_SIZE - 1), value); - } - } -} diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/CaveDensityLattice.java b/core/src/main/java/art/arcane/iris/generation/mantle/CaveDensityLattice.java deleted file mode 100644 index 10aadb38d..000000000 --- a/core/src/main/java/art/arcane/iris/generation/mantle/CaveDensityLattice.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.generation.mantle; - -import java.util.Arrays; - -final class CaveDensityLattice { - static final int CORNERS = 9; - - final CaveDensityGrid.Column[] densityColumns = new CaveDensityGrid.Column[CORNERS]; - final CaveDensityGrid.Column[] warpColumns = new CaveDensityGrid.Column[CORNERS]; - private double[] values = new double[0]; - private byte[] rowCells = new byte[0]; - private short[] rowCorners = new short[0]; - private int minimumY; - private int rows; - - void reset(int minimumY, int rows) { - this.minimumY = minimumY; - this.rows = rows; - if (rowCells.length < rows) { - rowCells = new byte[rows]; - rowCorners = new short[rows]; - } - if (values.length < rows * CORNERS) { - values = new double[rows * CORNERS]; - } - Arrays.fill(rowCells, 0, rows, (byte) 0); - Arrays.fill(rowCorners, 0, rows, (short) 0); - } - - void markRow(int y, int cells, int corners) { - int row = y - minimumY; - rowCells[row] = (byte) cells; - rowCorners[row] = (short) corners; - } - - int cells(int y) { - return rowCells[y - minimumY]; - } - - boolean needs(int corner, int y) { - return (rowCorners[y - minimumY] & (1 << corner)) != 0; - } - - double density(int corner, int y) { - return values[corner * rows + (y - minimumY)]; - } - - void store(int corner, int y, double density) { - values[corner * rows + (y - minimumY)] = density; - } - - void releaseReferences() { - Arrays.fill(densityColumns, null); - Arrays.fill(warpColumns, null); - } -} diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/CaveFieldKey.java b/core/src/main/java/art/arcane/iris/generation/mantle/CaveFieldKey.java deleted file mode 100644 index 7278e09db..000000000 --- a/core/src/main/java/art/arcane/iris/generation/mantle/CaveFieldKey.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.generation.mantle; - -import art.arcane.volmlib.util.noise.program.NoiseProgram; -import art.arcane.volmlib.util.noise.program.PrimitiveKind; - -record CaveFieldKey(long signature, long probe, NoiseProgram identity) { - private static final double[][] PROBE_POINTS = { - {0.5D, 3.25D, -7.75D}, - {-1031.125D, 77.5D, 2049.875D}, - {16D, 255D, -16D}, - {123_456.375D, -40.25D, -98_765.625D} - }; - - static CaveFieldKey of(NoiseProgram program) { - if (!shareable(program)) { - return new CaveFieldKey(program.structuralSignature(), 0L, program); - } - long probe = 0xCBF29CE484222325L; - for (double[] point : PROBE_POINTS) { - probe = (probe ^ Double.doubleToRawLongBits(program.sampleSigned3D(point[0], point[1], point[2]))) * 0x100000001B3L; - } - return new CaveFieldKey(program.structuralSignature(), probe, null); - } - - private static boolean shareable(NoiseProgram program) { - for (int node = 0; node < program.nodeCount(); node++) { - if (program.nodeOpaque(node) || program.nodeKernel(node).kind() == PrimitiveKind.GENERIC) { - return false; - } - } - return true; - } -} diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/CaveFieldModuleState.java b/core/src/main/java/art/arcane/iris/generation/mantle/CaveFieldModuleState.java deleted file mode 100644 index c963f2af2..000000000 --- a/core/src/main/java/art/arcane/iris/generation/mantle/CaveFieldModuleState.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.generation.mantle; - -import art.arcane.iris.generation.cave.IrisCaveFieldModule; -import art.arcane.iris.pack.value.IrisRange; -import art.arcane.volmlib.util.noise.program.NoiseProgram; - -final class CaveFieldModuleState { - final NoiseProgram density; - final int minY; - final int maxY; - final double weight; - final double threshold; - final boolean invert; - final double minContribution; - final double maxContribution; - - CaveFieldModuleState(IrisCaveFieldModule module, NoiseProgram density) { - IrisRange range = module.getVerticalRange(); - this.density = density; - this.minY = (int) Math.floor(range.getMin()); - this.maxY = (int) Math.ceil(range.getMax()); - this.weight = module.getWeight(); - this.threshold = module.getThreshold(); - this.invert = module.isInvert(); - double rawMin = invert ? threshold - 1D : -1D - threshold; - double rawMax = invert ? threshold + 1D : 1D - threshold; - this.minContribution = rawMin * weight; - this.maxContribution = rawMax * weight; - } - - double sample(double x, int y, double z) { - double sampled = density.sampleSigned3D(x, y, z); - return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight; - } - - double sample(double x, double y, double z) { - double sampled = density.sampleSigned3D(x, y, z); - return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight; - } -} diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/CaveLatticeBatch.java b/core/src/main/java/art/arcane/iris/generation/mantle/CaveLatticeBatch.java deleted file mode 100644 index 0b7a77023..000000000 --- a/core/src/main/java/art/arcane/iris/generation/mantle/CaveLatticeBatch.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.generation.mantle; - -import art.arcane.volmlib.util.noise.program.NoiseScratch; - -final class CaveLatticeBatch { - private static final ThreadLocal CURRENT = ThreadLocal.withInitial(CaveLatticeBatch::new); - - final NoiseScratch noise = new NoiseScratch(); - final int[] cornerStart = new int[CaveDensityLattice.CORNERS + 1]; - final int[] snapStart = new int[CaveDensityLattice.CORNERS + 1]; - int[] y = new int[0]; - int[] snapY = new int[0]; - boolean[] snapMissing = new boolean[0]; - double[] warpA = new double[0]; - double[] warpB = new double[0]; - double[] warpedX = new double[0]; - double[] warpedY = new double[0]; - double[] warpedZ = new double[0]; - double[] density = new double[0]; - double[] values = new double[0]; - double[] pointX = new double[0]; - double[] pointY = new double[0]; - double[] pointZ = new double[0]; - int[] pointIndex = new int[0]; - private CaveLatticeBatch nested; - private boolean active; - - static CaveLatticeBatch acquire() { - CaveLatticeBatch batch = CURRENT.get(); - while (batch.active) { - if (batch.nested == null) { - batch.nested = new CaveLatticeBatch(); - } - batch = batch.nested; - } - batch.active = true; - return batch; - } - - void release() { - active = false; - } - - void ensure(int size) { - if (y.length >= size) { - return; - } - y = new int[size]; - snapY = new int[size]; - snapMissing = new boolean[size]; - warpA = new double[size]; - warpB = new double[size]; - warpedX = new double[size]; - warpedY = new double[size]; - warpedZ = new double[size]; - density = new double[size]; - values = new double[size * 2]; - pointX = new double[size * 2]; - pointY = new double[size * 2]; - pointZ = new double[size * 2]; - pointIndex = new int[size * 2]; - } -} diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/CaveListing.java b/core/src/main/java/art/arcane/iris/generation/mantle/CaveListing.java new file mode 100644 index 000000000..8582a1419 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/mantle/CaveListing.java @@ -0,0 +1,43 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.mantle; + +import art.arcane.iris.generation.cave.field.HeightBand; + +import java.util.List; + +/** + * The caves that carve in one chunk, in the order they were listed: the first cave listed owns a block that several carve. + * + * @param caves each listed cave with how much each column lists it + * @param opensToSurface whether any of the caves cuts through the surface + */ +record CaveListing(List caves, boolean opensToSurface) { + boolean isEmpty() { + return caves.isEmpty(); + } + + /** + * @param cave the cave + * @param weight how much each column of the chunk lists the cave, from 0 to 1, indexed as {@code (localX << 4) | localZ} + * @param band the heights the cave is limited to, from the dimension's bottom; unlimited unless a carving band lists it + */ + record ListedColumns(ListedCave cave, double[] weight, HeightBand band) { + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/CaveTerrain.java b/core/src/main/java/art/arcane/iris/generation/mantle/CaveTerrain.java new file mode 100644 index 000000000..01a6faea8 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/mantle/CaveTerrain.java @@ -0,0 +1,53 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.mantle; + +import art.arcane.iris.generation.biome.IrisBiome; +import art.arcane.iris.generation.terrain.IrisRegion; + +import java.util.List; + +/** What listed cave carving reads of the world around a chunk. */ +interface CaveTerrain { + /** The region, surface biome and cave biome that decide which caves carve at the column. */ + CavePlace placeAt(int worldX, int worldZ); + + /** + * The cave biomes that dimension carving entries put at each column of the chunk, one band of world heights at a + * time. Caves a band's biome lists carve only inside that band. + */ + List bandsOf(int chunkX, int chunkZ); + + /** + * @param region the region of the column + * @param surfaceBiome the biome at the surface of the column + * @param caveBiome the cave biome the column's caves belong to: the surface biome where the cave is too shallow to + * have its own, as {@code caveMinDepthBelowSurface} says + */ + record CavePlace(IrisRegion region, IrisBiome surfaceBiome, IrisBiome caveBiome) { + } + + /** + * @param lowestWorldY lowest world height of the band + * @param highestWorldY highest world height of the band, included + * @param biomeByColumn the cave biome in each column of the chunk indexed as {@code (localX << 4) | localZ}; null where the entry gives none + */ + record CaveBand(int lowestWorldY, int highestWorldY, IrisBiome[] biomeByColumn) { + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/CaveWorld.java b/core/src/main/java/art/arcane/iris/generation/mantle/CaveWorld.java new file mode 100644 index 000000000..50ee369ac --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/mantle/CaveWorld.java @@ -0,0 +1,32 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.mantle; + +/** + * What caves know of the world they carve. Heights count from the dimension's bottom, except + * {@code minHeight}, the world height of that bottom. + * + * @param minHeight world Y of the dimension's lowest block + * @param height the dimension's height in blocks + * @param carveSeed the seed caves carve with + * @param fluidHeight the height the dimension's fluid fills up to + * @param caveLavaHeight the height below which caves hold lava + */ +record CaveWorld(int minHeight, int height, long carveSeed, int fluidHeight, int caveLavaHeight) { +} diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/EngineCaveTerrain.java b/core/src/main/java/art/arcane/iris/generation/mantle/EngineCaveTerrain.java new file mode 100644 index 000000000..331f08e69 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/mantle/EngineCaveTerrain.java @@ -0,0 +1,147 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.mantle; + +import art.arcane.iris.generation.biome.IrisBiome; +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.generation.runtime.IrisComplex; +import art.arcane.iris.generation.terrain.IrisDimensionCarvingEntry; +import art.arcane.iris.generation.terrain.IrisDimensionCarvingResolver; +import art.arcane.iris.generation.terrain.IrisRegion; +import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; + +import java.util.ArrayList; +import java.util.List; +import java.util.TreeSet; + +/** The terrain an engine generates, as listed cave carving reads it: the streams of one {@link IrisComplex}. */ +final class EngineCaveTerrain implements CaveTerrain { + private static final int CHUNK_AREA = 256; + /** 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 final Engine engine; + private final IrisComplex complex; + private final IrisDimensionCarvingResolver.State resolverState; + + EngineCaveTerrain(Engine engine, IrisComplex complex, IrisDimensionCarvingResolver.State resolverState) { + this.engine = engine; + this.complex = complex; + this.resolverState = resolverState; + } + + @Override + public CavePlace placeAt(int worldX, int worldZ) { + double surfaceHeight = complex.getNaturalHeightStream().getDouble(worldX, worldZ); + IrisRegion region = complex.getRegionStream().get(worldX, worldZ); + IrisBiome surfaceBiome = complex.getNaturalTrueBiomeStream().get(worldX, worldZ); + IrisBiome caveBiome = complex.getCaveBiomeStream().get(worldX, worldZ); + return new CavePlace(region, surfaceBiome, caveBiomeOf(worldX, worldZ, surfaceHeight, surfaceBiome, caveBiome)); + } + + /** + * The cave biome of a column: the one a carving entry puts at the height caves are read at, else the cave biome the + * world places there, unless it asks to lie deeper than the cave is, in which case the surface biome stands in. + */ + private IrisBiome caveBiomeOf(int worldX, int worldZ, double surfaceHeight, IrisBiome surfaceBiome, IrisBiome worldCaveBiome) { + int sampleY = Math.max(1, (int) Math.round(surfaceHeight) - CAVE_SAMPLE_DEPTH_BELOW_SURFACE_BLOCKS); + int worldY = sampleY + engine.getWorld().minHeight(); + IrisBiome carvingBiome = carvingBiomeAt(worldX, worldY, worldZ); + if (carvingBiome != null) { + return carvingBiome; + } + if (worldCaveBiome == null || surfaceBiome == null) { + return worldCaveBiome; + } + int depthBelowSurface = (int) surfaceHeight - sampleY; + boolean tooShallow = depthBelowSurface <= 0 || depthBelowSurface < Math.max(0, worldCaveBiome.getCaveMinDepthBelowSurface()); + return tooShallow ? surfaceBiome : worldCaveBiome; + } + + private IrisBiome carvingBiomeAt(int worldX, int worldY, int worldZ) { + IrisDimensionCarvingEntry root = IrisDimensionCarvingResolver.resolveRootEntry(engine, worldY, resolverState); + if (root == null) { + return null; + } + IrisDimensionCarvingEntry resolved = IrisDimensionCarvingResolver.resolveFromRoot(engine, root, worldX, worldY, worldZ, resolverState); + return IrisDimensionCarvingResolver.resolveEntryBiome(engine, resolved, resolverState); + } + + @Override + public List bandsOf(int chunkX, int chunkZ) { + List entries = engine.getDimension().getCarving(); + List bands = new ArrayList<>(); + if (entries == null || entries.isEmpty()) { + return bands; + } + TreeSet boundaries = boundariesOf(entries); + for (IrisDimensionCarvingEntry entry : entries) { + if (entry != null && entry.isEnabled()) { + addBandsOf(entry, boundaries, chunkX, chunkZ, bands); + } + } + return bands; + } + + private TreeSet boundariesOf(List entries) { + int minimumY = engine.getWorld().minHeight(); + int maximumY = engine.getWorld().maxHeight(); + TreeSet boundaries = new TreeSet<>(); + boundaries.add(minimumY); + boundaries.add(maximumY); + for (IrisDimensionCarvingEntry candidate : entries) { + if (candidate != null && candidate.getWorldYRange() != null) { + boundaries.add(Math.max(minimumY, Math.min(maximumY, (int) Math.ceil(candidate.getWorldYRange().getMin())))); + boundaries.add(Math.max(minimumY, Math.min(maximumY, (int) Math.floor(candidate.getWorldYRange().getMax()) + 1))); + } + } + return boundaries; + } + + private void addBandsOf(IrisDimensionCarvingEntry entry, TreeSet boundaries, int chunkX, int chunkZ, List bands) { + if (IrisDimensionCarvingResolver.resolveEntryBiome(engine, entry, resolverState) == null) { + return; + } + Integer previous = null; + for (int boundary : boundaries) { + boolean bandStartsInEntry = previous != null && boundary > previous + && (entry.getWorldYRange() == null || entry.getWorldYRange().contains(previous)); + if (bandStartsInEntry) { + addBand(entry, previous, boundary - 1, chunkX, chunkZ, bands); + } + previous = boundary; + } + } + + private void addBand(IrisDimensionCarvingEntry entry, int lowestWorldY, int highestWorldY, int chunkX, int chunkZ, List bands) { + int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX); + int baseZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); + IrisBiome[] biomeByColumn = new IrisBiome[CHUNK_AREA]; + boolean any = false; + for (int column = 0; column < CHUNK_AREA; column++) { + IrisDimensionCarvingEntry resolved = IrisDimensionCarvingResolver.resolveFromRoot( + engine, entry, baseX + (column >> 4), lowestWorldY, baseZ + (column & 15), resolverState); + biomeByColumn[column] = IrisDimensionCarvingResolver.resolveEntryBiome(engine, resolved, resolverState); + any |= biomeByColumn[column] != null; + } + if (any) { + bands.add(new CaveBand(lowestWorldY, highestWorldY, biomeByColumn)); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/IrisCaveCarver3D.java b/core/src/main/java/art/arcane/iris/generation/mantle/IrisCaveCarver3D.java deleted file mode 100644 index bf8868823..000000000 --- a/core/src/main/java/art/arcane/iris/generation/mantle/IrisCaveCarver3D.java +++ /dev/null @@ -1,3711 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.generation.mantle; - -import art.arcane.iris.pack.loading.IrisData; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.generation.runtime.GenerationCounter; -import art.arcane.iris.generation.cave.IrisCaveFieldModule; -import art.arcane.iris.generation.cave.IrisCaveProfile; -import art.arcane.iris.pack.value.IrisRange; -import art.arcane.iris.generation.noise.IrisGeneratorStyle; -import art.arcane.iris.generation.noise.IrisStyledRange; -import art.arcane.volmlib.util.noise.CNG; -import art.arcane.volmlib.util.noise.program.NoiseProgram; -import art.arcane.volmlib.util.noise.program.NoiseScratch; -import art.arcane.volmlib.util.mantle.runtime.MantleChunk; -import art.arcane.volmlib.util.math.M; -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.MatterCavern; -import art.arcane.volmlib.util.matter.MatterSlice; -import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.ForkJoinWorkerThread; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.LongAdder; - -public class IrisCaveCarver3D { - private static final byte LIQUID_AIR = 0; - private static final byte LIQUID_FLUID = 1; - private static final byte LIQUID_LAVA = 2; - private static final byte LIQUID_FORCED_AIR = 3; - private static final int ADAPTIVE_MIN_PLANE_COLUMNS = 16; - private static final int ADAPTIVE_DEEP_SAMPLE_STEP = 8; - private static final double ADAPTIVE_LOCAL_RANGE_SCALE = 0.125D; - private static final double ADAPTIVE_DEEP_MARGIN_BOOST = 0.015D; - private static final int SURFACE_CEILING_FADE_DEPTH = 12; - private static final double SURFACE_CEILING_SOLID_EPSILON = 0.000001D; - - private static final byte DENSITY_CARVE = 1; - private static final byte DENSITY_FLUID = 2; - private static final int MINIMUM_PARALLEL_DENSITY_CELLS = 16_384; - private static final int MAXIMUM_DENSITY_WORKERS = 4; - private static final int[] LATTICE_TILE_OFFSETS = {0, 1, 16, 17}; - private static final int STANDALONE_DENSITY_GRID_COLUMNS = 1024; - private static final int[] CELL_CORNER_MASKS = {0b000011011, 0b000110110, 0b011011000, 0b110110000}; - private static final long[] CELL_Z_MASKS = {0x00FF00FF00FF00FFL, 0xFF00FF00FF00FF00L}; - private static final LongAdder SOLID_CELLS = new LongAdder(); - private static final LongAdder OPEN_CELLS = new LongAdder(); - private static final LongAdder MIXED_CELLS = new LongAdder(); - private static final LongAdder EXACT_ROWS = new LongAdder(); - private static final double WARP_B_OFFSET_X = 31.37D; - private static final double WARP_B_OFFSET_Y = 17.21D; - private static final double WARP_B_OFFSET_Z = 23.91D; - - private final Engine engine; - private final IrisData data; - private final IrisCaveProfile profile; - private final NoiseProgram baseDensity; - private final NoiseProgram detailDensity; - private final NoiseProgram warpDensity; - private final CNG surfaceBreakDensity; - private final RNG thresholdRng; - private final CaveFieldModuleState[] modules; - private final double inverseNormalization; - private final MatterCavern carveAir; - private final MatterCavern carveFluid; - private final MatterCavern carveLava; - private final MatterCavern carveForcedAir; - private final double normalizationFactor; - private final double baseWeight; - private final double detailWeight; - private final double detailMinContribution; - private final double detailMaxContribution; - private final double warpStrength; - private final boolean hasWarp; - private final boolean hasModules; - private final int warpResolution; - private final boolean allowFluid; - private final boolean fluidRequiresFloor; - private final int fluidMinDepthBelowSurface; - private final int fluidHeight; - private final int aquiferCeilingY; - private final boolean parallelDensity; - private final int verticalDensityStep; - private final int worldMinimumY; - private final int densityMaximumY; - private final ThreadLocal carving = ThreadLocal.withInitial(() -> false); - private final ThreadLocal scratchCache = ThreadLocal.withInitial(CaveCarveScratch::new); - private final CaveDensityGrid densityGrid; - private final CaveDensityGrid.Owner densityOwner; - private final CaveDensityGrid.Owner warpOwner; - - public IrisCaveCarver3D(Engine engine, IrisCaveProfile profile) { - this(engine, profile, new CaveDensityGrid(STANDALONE_DENSITY_GRID_COLUMNS)); - } - - IrisCaveCarver3D(Engine engine, IrisCaveProfile profile, CaveDensityGrid densityGrid) { - this.engine = engine; - this.densityGrid = densityGrid; - this.data = engine.getData(); - this.profile = profile; - this.carveAir = new MatterCavern(true, "", LIQUID_AIR); - this.carveFluid = new MatterCavern(true, "", LIQUID_FLUID); - this.carveLava = new MatterCavern(true, "", LIQUID_LAVA); - this.carveForcedAir = new MatterCavern(true, "", LIQUID_FORCED_AIR); - List moduleStates = new ArrayList<>(); - - RNG baseRng = new RNG(engine.getSeedManager().getCarve()); - this.baseDensity = NoiseProgram.compileSigned3D(profile.getBaseDensityStyle().create(baseRng.nextParallelRNG(934_447), data)); - this.detailDensity = NoiseProgram.compileSigned3D(profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), data)); - this.warpDensity = NoiseProgram.compileSigned3D(profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), data)); - this.surfaceBreakDensity = profile.getSurfaceBreakStyle().create(baseRng.nextParallelRNG(341_219), data); - this.thresholdRng = baseRng.nextParallelRNG(489_112); - this.baseWeight = profile.getBaseWeight(); - this.detailWeight = profile.getDetailWeight(); - this.warpStrength = profile.getWarpStrength(); - this.hasWarp = this.warpStrength > 0D; - this.warpResolution = 2; - this.allowFluid = profile.isAllowFluid(); - this.fluidRequiresFloor = profile.isFluidRequiresFloor(); - this.fluidMinDepthBelowSurface = Math.max(0, profile.getFluidMinDepthBelowSurface()); - this.fluidHeight = engine.getDimension().getFluidHeight(); - this.aquiferCeilingY = engine.getHeight() - 1; - - double weight = Math.abs(baseWeight) + Math.abs(detailWeight); - int index = 0; - for (IrisCaveFieldModule module : profile.getModules()) { - CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), data); - CaveFieldModuleState state = new CaveFieldModuleState(module, NoiseProgram.compileSigned3D(moduleDensity)); - moduleStates.add(state); - weight += Math.abs(state.weight); - index++; - } - - this.modules = moduleStates.toArray(new CaveFieldModuleState[0]); - double normalization = weight <= 0 ? 1 : weight; - normalizationFactor = normalization; - inverseNormalization = 1D / normalization; - hasModules = modules.length > 0; - detailMinContribution = -detailWeight; - detailMaxContribution = detailWeight; - parallelDensity = fixedDensityStyles(profile); - verticalDensityStep = parallelDensity ? Math.max(1, engine.getDimension().getCaveDensitySamplingStep()) : 1; - worldMinimumY = engine.getWorld().minHeight(); - densityMaximumY = engine.getWorld().getHeight() - 1; - CaveFieldKey warpKey = CaveFieldKey.of(warpDensity); - warpOwner = densityGrid.owner(new WarpFieldKey(warpKey)); - densityOwner = densityGrid.owner(new DensityFieldKey(hasWarp, warpKey, Double.doubleToRawLongBits(warpStrength), - CaveFieldKey.of(baseDensity), Double.doubleToRawLongBits(baseWeight), CaveFieldKey.of(detailDensity), - Double.doubleToRawLongBits(detailWeight), Double.doubleToRawLongBits(inverseNormalization), - moduleFieldKeys(modules))); - } - - private static List moduleFieldKeys(CaveFieldModuleState[] modules) { - List keys = new ArrayList<>(modules.length); - for (CaveFieldModuleState module : modules) { - keys.add(new ModuleFieldKey(CaveFieldKey.of(module.density), module.minY, module.maxY, - Double.doubleToRawLongBits(module.weight), Double.doubleToRawLongBits(module.threshold), module.invert)); - } - return List.copyOf(keys); - } - - public static CellCounters cellCounters() { - return new CellCounters(SOLID_CELLS.sum(), OPEN_CELLS.sum(), MIXED_CELLS.sum(), EXACT_ROWS.sum()); - } - - 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( - MantleWriter writer, - 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 chunkZ, - double[] columnWeights, - double minWeight, - double thresholdPenalty, - IrisRange worldYRange - ) { - return carve(writer, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, worldYRange, null); - } - - public int carve( - MantleWriter writer, - int chunkX, - int chunkZ, - double[] columnWeights, - double minWeight, - double thresholdPenalty, - IrisRange worldYRange, - int[] precomputedSurfaceHeights - ) { - 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(); - int carved = carve(writer, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, - worldYRange, precomputedSurfaceHeights, null, null, overrideVerticalRange, fluidSupportPlan); - fluidSupportPlan.resolve(writer.acquireChunk(chunkX, chunkZ)); - return carved; - } - - int carve( - MantleWriter writer, - int chunkX, - int chunkZ, - double[] columnWeights, - double minWeight, - double thresholdPenalty, - IrisRange worldYRange, - int[] precomputedSurfaceHeights, - long[] surfaceFluidBoundaries, - int[] columnCeilings, - IrisRange overrideVerticalRange, - CaveFluidSupportPlan fluidSupportPlan - ) { - PrecisionStopwatch applyStopwatch = PrecisionStopwatch.start(); - boolean nested = carving.get(); - CaveCarveScratch previousScratch = scratchCache.get(); - if (nested) { - scratchCache.set(new CaveCarveScratch()); - } - carving.set(true); - try { - CaveCarveScratch scratch = scratchCache.get(); - if (columnWeights == null || columnWeights.length < 256) { - if (!scratch.fullWeightsInitialized) { - Arrays.fill(scratch.fullWeights, 1D); - scratch.fullWeightsInitialized = true; - } - columnWeights = scratch.fullWeights; - } - - double resolvedMinWeight = Math.max(0D, Math.min(1D, minWeight)); - double resolvedThresholdPenalty = Math.max(0D, thresholdPenalty); - int worldHeight = writer.getMantle().getWorldHeight(); - IrisRange effectiveVerticalRange = overrideVerticalRange != null ? overrideVerticalRange : profile.getVerticalRange(); - int minY = Math.max(0, (int) Math.floor(effectiveVerticalRange.getMin())); - int maxY = Math.min(worldHeight - 1, (int) Math.ceil(effectiveVerticalRange.getMax())); - if (worldYRange != null) { - int worldMinHeight = engine.getWorld().minHeight(); - int rangeMinY = (int) Math.floor(worldYRange.getMin() - worldMinHeight); - int rangeMaxY = (int) Math.ceil(worldYRange.getMax() - worldMinHeight); - minY = Math.max(minY, rangeMinY); - maxY = Math.min(maxY, rangeMaxY); - } - int sampleStep = Math.max(1, profile.getSampleStep()); - boolean exactSampling = sampleStep <= 2; - boolean adaptiveSampling = exactSampling && profile.isAdaptiveSampling(); - int adaptiveSampleStep = Math.max(2, profile.getAdaptiveSampleStep()); - double adaptiveThresholdMargin = Math.max(0D, profile.getAdaptiveThresholdMargin()); - int surfaceClearance = Math.max(0, profile.getSurfaceClearance()); - int surfaceBreakDepth = Math.max(0, profile.getSurfaceBreakDepth()); - double surfaceBreakNoiseThreshold = profile.getSurfaceBreakNoiseThreshold(); - double surfaceBreakThresholdBoost = Math.max(0, profile.getSurfaceBreakThresholdBoost()); - boolean allowSurfaceBreak = profile.isAllowSurfaceBreak(); - if (maxY < minY) { - return 0; - } - - MantleChunk chunk = writer.acquireChunk(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); - - // IrisStyledRange.get() resolves its CNG per call, which costs a cache-key allocation, - // a capturing lambda and a shared LRU touch. The CNG is constant for (thresholdRng, data), - // so resolve it once here and replicate the min==max / isFlat short circuits verbatim. - IrisStyledRange densityThreshold = profile.getDensityThreshold(); - double thresholdMin = densityThreshold.getMin(); - double thresholdMax = densityThreshold.getMax(); - double thresholdBias = profile.getThresholdBias(); - CNG thresholdDensity = null; - double constantThreshold = 0D; - if (thresholdMin == thresholdMax) { - constantThreshold = thresholdMin; - } else if (densityThreshold.getStyle().isFlat()) { - constantThreshold = M.lerp(thresholdMin, thresholdMax, 0.5); - } else { - thresholdDensity = densityThreshold.getStyle().create(thresholdRng, data); - } - - 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); - clampedWeights[index] = clampColumnWeight(columnWeights[index]); - if (clampedWeights[index] <= resolvedMinWeight) { - columnMaxY[index] = minY - 1; - continue; - } - int columnSurfaceY; - if (precomputedSurfaceHeights != null && precomputedSurfaceHeights.length > index) { - columnSurfaceY = precomputedSurfaceHeights[index]; - } else { - columnSurfaceY = Engine.hostHeight(engine, x, z, true); - } - 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; - boolean masked = columnCeilings != null && columnCeilings[index] < columnTopY; - - columnMaxY[index] = masked ? columnCeilings[index] : columnTopY; - fluidMaxY[index] = allowFluid - ? Math.min(fluidHeight, columnSurfaceY - fluidMinDepthBelowSurface) - : Integer.MIN_VALUE; - surfaceBreakFloorY[index] = Math.max(minY, columnSurfaceY - surfaceBreakDepth); - surfaceBreakColumn[index] = breakColumn && !masked; - surfaceCeilingColumn[index] = masked || !breakColumn && unclampedClearanceTopY <= maxY; - columnThreshold[index] = (thresholdDensity == null - ? constantThreshold - : thresholdDensity.fitDouble(thresholdMin, thresholdMax, x, z)) - thresholdBias; - } - } - - int carved; - if (exactSampling) { - if (adaptiveSampling) { - carved = carvePassAdaptive( - chunk, - x0, - z0, - minY, - maxY, - adaptiveSampleStep, - adaptiveThresholdMargin, - surfaceBreakThresholdBoost, - columnMaxY, - fluidMaxY, - surfaceFluidBoundaries, - surfaceBreakFloorY, - surfaceBreakColumn, - columnThreshold, - clampedWeights, - verticalEdgeFade, - matterByY, - fluidRequiresFloor ? fluidSupportPlan : null, - resolvedMinWeight, - resolvedThresholdPenalty, - 0D, - false - ); - } else { - carved = carvePassExact( - chunk, - x0, - z0, - minY, - maxY, - surfaceBreakThresholdBoost, - columnMaxY, - fluidMaxY, - surfaceFluidBoundaries, - surfaceBreakFloorY, - surfaceBreakColumn, - columnThreshold, - clampedWeights, - verticalEdgeFade, - matterByY, - fluidRequiresFloor ? fluidSupportPlan : null, - resolvedMinWeight, - resolvedThresholdPenalty, - 0D, - false - ); - } - } else { - int latticeStep = sampleStep; - carved = carvePassLattice( - chunk, - x0, - z0, - minY, - maxY, - latticeStep, - surfaceBreakThresholdBoost, - columnMaxY, - fluidMaxY, - surfaceFluidBoundaries, - 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, - surfaceFluidBoundaries, - surfaceBreakFloorY, - surfaceBreakColumn, - columnThreshold, - clampedWeights, - verticalEdgeFade, - matterByY, - fluidRequiresFloor ? fluidSupportPlan : null, - resolvedMinWeight, - resolvedThresholdPenalty, - 0D, - false - ); - } - } - - return carved; - } finally { - scratchCache.get().releaseReferences(); - carving.set(nested); - if (nested) { - scratchCache.set(previousScratch); - } - engine.getMetrics().getCarveApply().put(applyStopwatch.getMilliseconds()); - } - } - - private static boolean fixedDensityStyles(IrisCaveProfile profile) { - if (!fixedStyle(profile.getBaseDensityStyle()) || !fixedStyle(profile.getDetailDensityStyle()) - || !fixedStyle(profile.getWarpStyle()) || !fixedStyle(profile.getSurfaceBreakStyle()) - || !fixedStyle(profile.getDensityThreshold().getStyle())) { - return false; - } - for (IrisCaveFieldModule module : profile.getModules()) { - if (!fixedStyle(module.getStyle())) { - return false; - } - } - return true; - } - - private static boolean fixedStyle(IrisGeneratorStyle style) { - for (IrisGeneratorStyle current = style; current != null; current = current.getFracture()) { - if (current.getExpression() != null) { - return false; - } - } - return true; - } - - private byte[] classifyPassParallel(DensityPass pass) { - int height = pass.maximumY() - pass.minimumY() + 1; - if (!parallelDensity || height < 64 - || (long) height * pass.columnCount() < MINIMUM_PARALLEL_DENSITY_CELLS - || !(Thread.currentThread() instanceof ForkJoinWorkerThread worker)) { - return null; - } - ForkJoinPool pool = worker.getPool(); - int workers = Math.min(MAXIMUM_DENSITY_WORKERS, pool.getParallelism()); - if (workers < 2) { - return null; - } - byte[] classified = new byte[Math.multiplyExact(height, 256)]; - int rows = Math.ceilDiv(height, workers); - ArrayList tasks = new ArrayList<>(workers); - for (int index = 0; index < workers; index++) { - int minimumY = pass.minimumY() + index * rows; - int maximumY = Math.min(pass.maximumY(), minimumY + rows - 1); - if (minimumY <= maximumY) { - tasks.add(pass.cellKernel() - ? () -> classifyCellRows(pass, minimumY, maximumY, classified) - : () -> classifyRows(pass, minimumY, maximumY, classified)); - } - } - runDensityTasks(tasks, pool); - return classified; - } - - private void classifyRows(DensityPass pass, int minimumY, int maximumY, byte[] classified) { - CaveCarveScratch scratch = new CaveCarveScratch(); - for (int y = minimumY; y <= maximumY; y++) { - int count = 0; - for (int index = 0; index < pass.columnCount(); index++) { - int column = pass.columns()[index]; - if (pass.columnTops()[index] < y - || SurfaceFluidBoundaryPlan.protects(pass.fluidBoundaries(), column, y)) { - continue; - } - double threshold = pass.thresholds()[column]; - if (pass.surfaceBreakColumns()[column] && y >= pass.surfaceBreakFloors()[column]) { - threshold += pass.surfaceBreakBoost(); - } - threshold -= pass.verticalFade()[y - pass.minimumY()]; - threshold = applySurfaceCeilingFade(pass.sourceScratch(), threshold, column, y, pass.minimumY()); - scratch.planeColumnIndices[count] = column; - scratch.planeThresholdLimit[count++] = threshold * normalizationFactor; - } - if (count == 0) { - continue; - } - if (pass.adaptiveStep() == 0) { - classifyDensityPlane(scratch, pass.x(), pass.z(), y, scratch.planeColumnIndices, - scratch.planeThresholdLimit, count, scratch.planeCarve); - } else { - classifyDensityPlaneAdaptive(scratch, pass.x(), pass.z(), y, scratch.planeColumnIndices, - scratch.planeThresholdLimit, count, scratch.planeCarve, - pass.adaptiveStep(), pass.adaptiveMargin()); - } - int offset = (y - pass.minimumY()) * 256; - for (int index = 0; index < count; index++) { - if (!scratch.planeCarve[index]) { - continue; - } - int column = scratch.planeColumnIndices[index]; - double threshold = scratch.planeThresholdLimit[index] * inverseNormalization; - MatterCavern matter = resolveMatter(scratch, pass.matterByY()[y - pass.minimumY()], - pass.x() + PowerOfTwoCoordinates.unpackLocal16X(column), y, pass.z() + (column & 15), - column, pass.fluidTops(), threshold); - classified[offset + column] = matter == carveFluid - ? DENSITY_CARVE | DENSITY_FLUID : DENSITY_CARVE; - } - } - } - - private double[] sampleLatticeParallel( - int x, int z, int minimumY, int maximumY, int step, double[] thresholds, int[] tops - ) { - int rows = (maximumY - minimumY) / step + 1; - if (!parallelDensity || rows < 64 - || !(Thread.currentThread() instanceof ForkJoinWorkerThread worker)) { - return null; - } - ForkJoinPool pool = worker.getPool(); - int workers = Math.min(MAXIMUM_DENSITY_WORKERS, pool.getParallelism()); - if (workers < 2) { - return null; - } - int[] tileTops = new int[64]; - int samples = 0; - for (int tile = 0; tile < 64; tile++) { - int column = (tile >> 3) * 32 + (tile & 7) * 2; - int top = Integer.MIN_VALUE; - for (int offset : LATTICE_TILE_OFFSETS) { - if (!Double.isNaN(thresholds[column + offset])) { - top = Math.max(top, tops[column + offset]); - } - } - tileTops[tile] = top; - if (top >= minimumY) { - samples += (top - minimumY) / step + 1; - } - } - if (samples < 4096) { - return null; - } - double[] densities = new double[Math.multiplyExact(rows, 64)]; - LatticePass pass = new LatticePass(x, z, minimumY, step, rows, tileTops); - int tilesPerWorker = Math.ceilDiv(64, workers); - ArrayList tasks = new ArrayList<>(workers); - for (int index = 0; index < workers; index++) { - int firstTile = index * tilesPerWorker; - int lastTile = Math.min(64, firstTile + tilesPerWorker); - tasks.add(() -> sampleLatticeTiles(pass, firstTile, lastTile, densities)); - } - runDensityTasks(tasks, pool); - return densities; - } - - private void sampleLatticeTiles(LatticePass pass, int firstTile, int lastTile, double[] densities) { - CaveCarveScratch scratch = new CaveCarveScratch(); - for (int tile = firstTile; tile < lastTile; tile++) { - int blockX = pass.x() + (tile >> 3) * 2; - int blockZ = pass.z() + (tile & 7) * 2; - int offset = tile * pass.rows(); - for (int y = pass.minimumY(); y <= pass.tileTops()[tile]; y += pass.step()) { - densities[offset++] = sampleDensityOptimized(scratch, blockX, y, blockZ); - } - } - } - - private static void copyClassifiedPlane(byte[] classified, int row, int[] columns, int count, boolean[] result) { - int offset = row * 256; - for (int index = 0; index < count; index++) { - result[index] = (classified[offset + columns[index]] & DENSITY_CARVE) != 0; - } - } - - static void runDensityTasks(List work, ForkJoinPool pool) { - ArrayList tasks = new ArrayList<>(work.size()); - for (Runnable runnable : work) { - tasks.add(new DensityTask(runnable)); - } - Throwable failure = null; - for (int index = 1; index < tasks.size(); index++) { - try { - pool.execute(tasks.get(index)); - } catch (RuntimeException | Error rejected) { - failure = rejected; - break; - } - } - for (DensityTask task : tasks) { - task.run(); - } - boolean interrupted = Thread.interrupted(); - for (DensityTask task : tasks) { - boolean complete = false; - boolean managed = true; - while (!complete) { - try { - if (managed) { - ForkJoinPool.managedBlock(task); - } else { - task.complete.await(); - } - complete = true; - } catch (InterruptedException interruption) { - interrupted = true; - managed = false; - } catch (RejectedExecutionException unavailable) { - managed = false; - } catch (RuntimeException | Error blockingFailure) { - if (failure == null) { - failure = blockingFailure; - } else if (failure != blockingFailure) { - failure.addSuppressed(blockingFailure); - } - managed = false; - } - } - if (task.failure != null) { - if (failure == null) { - failure = task.failure; - } else if (failure != task.failure) { - failure.addSuppressed(task.failure); - } - } - } - interrupted |= Thread.interrupted(); - if (interrupted) { - Thread.currentThread().interrupt(); - InterruptedException interruption = new InterruptedException("Cave density classification interrupted."); - if (failure == null) { - failure = new IllegalStateException(interruption); - } else { - failure.addSuppressed(interruption); - } - } - if (failure instanceof Error error) { - throw error; - } - if (failure instanceof RuntimeException runtimeFailure) { - throw runtimeFailure; - } - } - - private record LatticePass(int x, int z, int minimumY, int step, int rows, int[] tileTops) { - } - - private record DensityPass( - int x, int z, int minimumY, int maximumY, - int[] columns, int[] columnTops, int columnCount, double[] thresholds, - long[] fluidBoundaries, boolean[] surfaceBreakColumns, int[] surfaceBreakFloors, - double surfaceBreakBoost, double[] verticalFade, CaveCarveScratch sourceScratch, - int adaptiveStep, double adaptiveMargin, int[] fluidTops, MatterCavern[] matterByY, boolean cellKernel - ) { - } - - public record CellCounters(long solidCells, long openCells, long mixedCells, long exactRows) { - public long decided() { - return solidCells + openCells; - } - - public long evaluated() { - return mixedCells; - } - - public String machineLine() { - return "IRIS_GENPROBE_CARVE_CELLS solid=" + solidCells + " open=" + openCells + " mixed=" + mixedCells - + " exact_rows=" + exactRows; - } - } - - private static final class DensityTask implements Runnable, ForkJoinPool.ManagedBlocker { - private final Runnable work; - private final AtomicBoolean claimed = new AtomicBoolean(); - private final CountDownLatch complete = new CountDownLatch(1); - private Throwable failure; - - private DensityTask(Runnable work) { - this.work = work; - } - - @Override - public boolean isReleasable() { - return complete.getCount() == 0; - } - - @Override - public boolean block() throws InterruptedException { - complete.await(); - return true; - } - - @Override - public void run() { - if (!claimed.compareAndSet(false, true)) { - return; - } - try { - work.run(); - } catch (RuntimeException | Error failed) { - failure = failed; - } finally { - complete.countDown(); - } - } - } - - private int carvePassExact( - MantleChunk chunk, - int x0, - int z0, - int minY, - int maxY, - double surfaceBreakThresholdBoost, - int[] columnMaxY, - int[] fluidMaxY, - long[] surfaceFluidBoundaries, - int[] surfaceBreakFloorY, - boolean[] surfaceBreakColumn, - double[] columnThreshold, - double[] clampedWeights, - double[] verticalEdgeFade, - MatterCavern[] matterByY, - CaveFluidSupportPlan fluidSupportPlan, - double minWeight, - double thresholdPenalty, - double thresholdBoost, - boolean skipExistingCarved - ) { - int carved = 0; - CaveCarveScratch scratch = scratchCache.get(); - double[] passThreshold = scratch.passThreshold; - int[] activeColumnIndices = scratch.activeColumnIndices; - int[] activeColumnTopY = scratch.activeColumnTopY; - int activeColumnCount = 0; - int activeMaxY = Integer.MIN_VALUE; - - for (int index = 0; index < 256; index++) { - double columnWeight = clampedWeights[index]; - if (columnWeight <= minWeight || columnMaxY[index] < minY) { - passThreshold[index] = Double.NaN; - continue; - } - - passThreshold[index] = columnThreshold[index] + thresholdBoost - ((1D - columnWeight) * thresholdPenalty); - activeColumnIndices[activeColumnCount] = index; - activeColumnTopY[activeColumnCount] = columnMaxY[index]; - activeMaxY = Math.max(activeMaxY, columnMaxY[index]); - activeColumnCount++; - } - - if (activeColumnCount == 0) { - return 0; - } - - int[] planeColumnIndices = scratch.planeColumnIndices; - double[] planeThresholdLimit = scratch.planeThresholdLimit; - boolean[] planeCarve = scratch.planeCarve; - int minSection = PowerOfTwoCoordinates.floorDivPow2(minY, 4); - int passMaxY = Math.min(maxY, activeMaxY); - int maxSection = PowerOfTwoCoordinates.floorDivPow2(passMaxY, 4); - - byte[] classified = skipExistingCarved ? null : classifyPassParallel(new DensityPass( - x0, z0, minY, passMaxY, activeColumnIndices, activeColumnTopY, activeColumnCount, - passThreshold, surfaceFluidBoundaries, surfaceBreakColumn, surfaceBreakFloorY, - surfaceBreakThresholdBoost, verticalEdgeFade, scratch, 0, 0D, fluidMaxY, matterByY, false)); - - for (int sectionIndex = minSection; sectionIndex <= maxSection; sectionIndex++) { - int sectionMinY = Math.max(minY, PowerOfTwoCoordinates.chunkToBlock(sectionIndex)); - int sectionMaxY = Math.min(passMaxY, PowerOfTwoCoordinates.chunkToBlock(sectionIndex) + 15); - MatterSlice cavernSlice = resolveCavernSlice(scratch, chunk, sectionIndex); - - for (int y = sectionMinY; y <= sectionMaxY; y++) { - int planeCount = 0; - for (int activeIndex = 0; activeIndex < activeColumnCount; activeIndex++) { - if (activeColumnTopY[activeIndex] < y) { - continue; - } - - int columnIndex = activeColumnIndices[activeIndex]; - if (SurfaceFluidBoundaryPlan.protects(surfaceFluidBoundaries, columnIndex, y)) { - continue; - } - planeColumnIndices[planeCount] = columnIndex; - double localThreshold = passThreshold[columnIndex]; - if (surfaceBreakColumn[columnIndex] && y >= surfaceBreakFloorY[columnIndex]) { - localThreshold += surfaceBreakThresholdBoost; - } - localThreshold -= verticalEdgeFade[y - minY]; - localThreshold = applySurfaceCeilingFade(scratch, localThreshold, columnIndex, y, minY); - planeThresholdLimit[planeCount] = localThreshold * normalizationFactor; - planeCount++; - } - - if (planeCount == 0) { - continue; - } - - if (classified == null) { - classifyDensityPlane(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); - } else { - copyClassifiedPlane(classified, y - minY, planeColumnIndices, planeCount, planeCarve); - } - int fadeIndex = y - minY; - int localY = y & 15; - MatterCavern verticalMatter = matterByY[fadeIndex]; - - if (skipExistingCarved) { - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - if (!planeCarve[planeIndex]) { - continue; - } - - int columnIndex = planeColumnIndices[planeIndex]; - int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int localZ = columnIndex & 15; - if (cavernSlice.get(localX, localY, localZ) != null) { - continue; - } - - double localThreshold = planeThresholdLimit[planeIndex] * inverseNormalization; - MatterCavern matter = resolveMatter(scratch, verticalMatter, x0 + localX, y, z0 + localZ, - columnIndex, fluidMaxY, localThreshold); - writeCavern(cavernSlice, localX, y, localZ, matter, fluidSupportPlan); - carved++; - } - continue; - } - - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - if (!planeCarve[planeIndex]) { - continue; - } - - int columnIndex = planeColumnIndices[planeIndex]; - int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int localZ = columnIndex & 15; - double localThreshold = planeThresholdLimit[planeIndex] * inverseNormalization; - MatterCavern matter = classified == null - ? resolveMatter(scratch, verticalMatter, x0 + localX, y, z0 + localZ, - columnIndex, fluidMaxY, localThreshold) - : (classified[fadeIndex * 256 + columnIndex] & DENSITY_FLUID) != 0 - ? carveFluid : verticalMatter; - writeCavern(cavernSlice, localX, y, localZ, matter, fluidSupportPlan); - carved++; - } - } - } - - return carved; - } - - private int carvePassAdaptive( - MantleChunk chunk, - int x0, - int z0, - int minY, - int maxY, - int adaptiveSampleStep, - double adaptiveThresholdMargin, - double surfaceBreakThresholdBoost, - int[] columnMaxY, - int[] fluidMaxY, - long[] surfaceFluidBoundaries, - int[] surfaceBreakFloorY, - boolean[] surfaceBreakColumn, - double[] columnThreshold, - double[] clampedWeights, - double[] verticalEdgeFade, - MatterCavern[] matterByY, - CaveFluidSupportPlan fluidSupportPlan, - double minWeight, - double thresholdPenalty, - double thresholdBoost, - boolean skipExistingCarved - ) { - int carved = 0; - CaveCarveScratch scratch = scratchCache.get(); - double[] passThreshold = scratch.passThreshold; - int[] activeColumnIndices = scratch.activeColumnIndices; - int[] activeColumnTopY = scratch.activeColumnTopY; - int activeColumnCount = 0; - int activeMaxY = Integer.MIN_VALUE; - - for (int index = 0; index < 256; index++) { - double columnWeight = clampedWeights[index]; - if (columnWeight <= minWeight || columnMaxY[index] < minY) { - passThreshold[index] = Double.NaN; - continue; - } - - passThreshold[index] = columnThreshold[index] + thresholdBoost - ((1D - columnWeight) * thresholdPenalty); - activeColumnIndices[activeColumnCount] = index; - activeColumnTopY[activeColumnCount] = columnMaxY[index]; - activeMaxY = Math.max(activeMaxY, columnMaxY[index]); - activeColumnCount++; - } - - if (activeColumnCount == 0) { - return 0; - } - - int[] planeColumnIndices = scratch.planeColumnIndices; - double[] planeThresholdLimit = scratch.planeThresholdLimit; - boolean[] planeCarve = scratch.planeCarve; - int minSection = PowerOfTwoCoordinates.floorDivPow2(minY, 4); - int passMaxY = Math.min(maxY, activeMaxY); - int maxSection = PowerOfTwoCoordinates.floorDivPow2(passMaxY, 4); - int effectiveAdaptiveSampleStep = Math.max(adaptiveSampleStep, ADAPTIVE_DEEP_SAMPLE_STEP); - double effectiveAdaptiveThresholdMargin = resolveAdaptivePlaneThresholdMargin( - adaptiveThresholdMargin, - adaptiveSampleStep, - effectiveAdaptiveSampleStep - ); - boolean cellKernel = !skipExistingCarved && usesCellKernel(effectiveAdaptiveSampleStep); - if (cellKernel) { - prepareCellPlan(scratch, x0, z0, minY, passMaxY, activeColumnIndices, activeColumnCount, - surfaceFluidBoundaries, surfaceBreakThresholdBoost); - } - - byte[] classified = skipExistingCarved ? null : classifyPassParallel(new DensityPass( - x0, z0, minY, passMaxY, activeColumnIndices, activeColumnTopY, activeColumnCount, - passThreshold, surfaceFluidBoundaries, surfaceBreakColumn, surfaceBreakFloorY, - surfaceBreakThresholdBoost, verticalEdgeFade, scratch, effectiveAdaptiveSampleStep, effectiveAdaptiveThresholdMargin, - fluidMaxY, matterByY, cellKernel)); - - if (cellKernel) { - if (classified == null) { - fillCellLattice(scratch, x0, z0, minY, passMaxY); - } - return emitCellPass(chunk, scratch, classified, x0, z0, minY, passMaxY, minSection, maxSection, - activeColumnIndices, activeColumnTopY, activeColumnCount, surfaceFluidBoundaries, - surfaceBreakThresholdBoost, verticalEdgeFade, fluidMaxY, matterByY, fluidSupportPlan); - } - - for (int sectionIndex = minSection; sectionIndex <= maxSection; sectionIndex++) { - int sectionMinY = Math.max(minY, PowerOfTwoCoordinates.chunkToBlock(sectionIndex)); - int sectionMaxY = Math.min(passMaxY, PowerOfTwoCoordinates.chunkToBlock(sectionIndex) + 15); - MatterSlice cavernSlice = resolveCavernSlice(scratch, chunk, sectionIndex); - - for (int y = sectionMinY; y <= sectionMaxY; y++) { - int planeCount = 0; - for (int activeIndex = 0; activeIndex < activeColumnCount; activeIndex++) { - if (activeColumnTopY[activeIndex] < y) { - continue; - } - - int columnIndex = activeColumnIndices[activeIndex]; - if (SurfaceFluidBoundaryPlan.protects(surfaceFluidBoundaries, columnIndex, y)) { - continue; - } - planeColumnIndices[planeCount] = columnIndex; - double localThreshold = passThreshold[columnIndex]; - if (surfaceBreakColumn[columnIndex] && y >= surfaceBreakFloorY[columnIndex]) { - localThreshold += surfaceBreakThresholdBoost; - } - localThreshold -= verticalEdgeFade[y - minY]; - localThreshold = applySurfaceCeilingFade(scratch, localThreshold, columnIndex, y, minY); - planeThresholdLimit[planeCount] = localThreshold * normalizationFactor; - planeCount++; - } - - if (planeCount == 0) { - continue; - } - - if (classified == null) { - classifyDensityPlaneAdaptive( - scratch, - x0, - z0, - y, - planeColumnIndices, - planeThresholdLimit, - planeCount, - planeCarve, - effectiveAdaptiveSampleStep, - effectiveAdaptiveThresholdMargin - ); - } else { - copyClassifiedPlane(classified, y - minY, planeColumnIndices, planeCount, planeCarve); - } - int fadeIndex = y - minY; - int localY = y & 15; - MatterCavern verticalMatter = matterByY[fadeIndex]; - - if (skipExistingCarved) { - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - if (!planeCarve[planeIndex]) { - continue; - } - - int columnIndex = planeColumnIndices[planeIndex]; - int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int localZ = columnIndex & 15; - if (cavernSlice.get(localX, localY, localZ) != null) { - continue; - } - - double localThreshold = planeThresholdLimit[planeIndex] * inverseNormalization; - MatterCavern matter = resolveMatter(scratch, verticalMatter, x0 + localX, y, z0 + localZ, - columnIndex, fluidMaxY, localThreshold); - writeCavern(cavernSlice, localX, y, localZ, matter, fluidSupportPlan); - carved++; - } - continue; - } - - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - if (!planeCarve[planeIndex]) { - continue; - } - - int columnIndex = planeColumnIndices[planeIndex]; - int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int localZ = columnIndex & 15; - double localThreshold = planeThresholdLimit[planeIndex] * inverseNormalization; - MatterCavern matter = classified == null - ? resolveMatter(scratch, verticalMatter, x0 + localX, y, z0 + localZ, - columnIndex, fluidMaxY, localThreshold) - : (classified[fadeIndex * 256 + columnIndex] & DENSITY_FLUID) != 0 - ? carveFluid : verticalMatter; - writeCavern(cavernSlice, localX, y, localZ, matter, fluidSupportPlan); - carved++; - } - } - } - - return carved; - } - - private double resolveAdaptivePlaneThresholdMargin( - double adaptiveThresholdMargin, - int adaptiveSampleStep, - int effectiveAdaptiveSampleStep - ) { - if (effectiveAdaptiveSampleStep <= adaptiveSampleStep) { - return adaptiveThresholdMargin; - } - - return adaptiveThresholdMargin + ((effectiveAdaptiveSampleStep - adaptiveSampleStep) * ADAPTIVE_DEEP_MARGIN_BOOST); - } - - private boolean usesCellKernel(int effectiveAdaptiveSampleStep) { - return effectiveAdaptiveSampleStep == ADAPTIVE_DEEP_SAMPLE_STEP - && verticalDensityStep == 1 - && parallelDensity - && (hasWarp || !hasModules); - } - - private void prepareCellPlan( - CaveCarveScratch plan, - int x0, - int z0, - int minY, - int passMaxY, - int[] activeColumnIndices, - int activeColumnCount, - long[] surfaceFluidBoundaries, - double surfaceBreakThresholdBoost - ) { - int rows = passMaxY - minY + 1; - if (plan.rowActiveCount.length < rows + 1) { - plan.rowActiveCount = new int[rows + 1]; - } - int[] rowActiveCount = plan.rowActiveCount; - Arrays.fill(rowActiveCount, 0, rows + 1, 0); - Arrays.fill(plan.cellPassBits, 0L); - Arrays.fill(plan.cellThresholdMin, Double.POSITIVE_INFINITY); - Arrays.fill(plan.cellThresholdMax, Double.NEGATIVE_INFINITY); - Arrays.fill(plan.cellThresholdMaxBoost, Double.NEGATIVE_INFINITY); - Arrays.fill(plan.cellBreakFloorMin, Integer.MAX_VALUE); - Arrays.fill(plan.cellCeilingFadeStart, Integer.MAX_VALUE); - Arrays.fill(plan.cellTopY, Integer.MIN_VALUE); - Arrays.fill(plan.cellMinTopY, Integer.MAX_VALUE); - Arrays.fill(plan.cellProtected, false); - prepareAdaptiveGeometry(plan, ADAPTIVE_DEEP_SAMPLE_STEP, 2, 3); - double[] passThreshold = plan.passThreshold; - for (int activeIndex = 0; activeIndex < activeColumnCount; activeIndex++) { - int column = activeColumnIndices[activeIndex]; - int cell = ((column >> 7) << 1) | ((column >> 3) & 1); - int top = plan.columnMaxY[column]; - double threshold = passThreshold[column]; - plan.cellPassBits[column >> 6] |= 1L << column; - plan.cellThresholdMin[cell] = Math.min(plan.cellThresholdMin[cell], threshold); - plan.cellThresholdMax[cell] = Math.max(plan.cellThresholdMax[cell], threshold); - if (plan.surfaceBreakColumn[column]) { - plan.cellThresholdMaxBoost[cell] = Math.max(plan.cellThresholdMaxBoost[cell], threshold + surfaceBreakThresholdBoost); - plan.cellBreakFloorMin[cell] = Math.min(plan.cellBreakFloorMin[cell], plan.surfaceBreakFloorY[column]); - } else { - plan.cellThresholdMaxBoost[cell] = Math.max(plan.cellThresholdMaxBoost[cell], threshold); - } - if (plan.surfaceCeilingColumn[column]) { - plan.cellCeilingFadeStart[cell] = Math.min(plan.cellCeilingFadeStart[cell], top - SURFACE_CEILING_FADE_DEPTH + 1); - } - plan.cellTopY[cell] = Math.max(plan.cellTopY[cell], top); - plan.cellMinTopY[cell] = Math.min(plan.cellMinTopY[cell], top); - int protectStart = SurfaceFluidBoundaryPlan.NO_BOUNDARY; - int protectEnd = Integer.MIN_VALUE; - if (surfaceFluidBoundaries != null) { - long boundary = surfaceFluidBoundaries[column]; - protectStart = SurfaceFluidBoundaryPlan.startY(boundary); - protectEnd = SurfaceFluidBoundaryPlan.endY(boundary); - } - plan.columnProtectStartY[column] = protectStart; - plan.columnProtectEndY[column] = protectEnd; - rowActiveCount[0]++; - rowActiveCount[top - minY + 1]--; - int protectedFrom = Math.max(protectStart, minY); - int protectedTo = Math.min(protectEnd, top); - if (protectedFrom <= protectedTo) { - rowActiveCount[protectedFrom - minY]--; - rowActiveCount[protectedTo - minY + 1]++; - plan.cellProtected[cell] = true; - } - } - for (int row = 1; row < rows; row++) { - rowActiveCount[row] += rowActiveCount[row - 1]; - } - int usedCorners = 0; - for (int cell = 0; cell < 4; cell++) { - if (plan.cellTopY[cell] >= minY) { - usedCorners |= CELL_CORNER_MASKS[cell]; - } - } - prepareCellLattice(plan, x0 >> CaveDensityGrid.LATTICE_SHIFT, z0 >> CaveDensityGrid.LATTICE_SHIFT, minY, passMaxY, - usedCorners); - } - - private void prepareCellLattice(CaveCarveScratch plan, int latticeX, int latticeZ, int minY, int passMaxY, int usedCorners) { - CaveDensityLattice lattice = plan.cellLattice; - lattice.reset(minY, passMaxY - minY + 1); - for (int corner = 0; corner < CaveDensityLattice.CORNERS; corner++) { - boolean used = (usedCorners & (1 << corner)) != 0; - int cornerX = latticeX + (corner / 3); - int cornerZ = latticeZ + (corner % 3); - lattice.densityColumns[corner] = used ? densityGrid.column(densityOwner, densityMaximumY + 1, cornerX, cornerZ) : null; - lattice.warpColumns[corner] = used && hasWarp - ? densityGrid.warpColumn(warpOwner, densityMaximumY + 2, cornerX, cornerZ) : null; - } - for (int y = minY; y <= passMaxY; y++) { - if (plan.rowActiveCount[y - minY] < ADAPTIVE_MIN_PLANE_COLUMNS) { - continue; - } - int cells = 0; - int corners = 0; - for (int cell = 0; cell < 4; cell++) { - if (isCellActive(plan, cell, y)) { - cells |= 1 << cell; - corners |= CELL_CORNER_MASKS[cell]; - } - } - lattice.markRow(y, cells, corners); - } - } - - private void fillCellLattice(CaveCarveScratch plan, int x0, int z0, int fromY, int toY) { - CaveLatticeBatch batch = CaveLatticeBatch.acquire(); - try { - fillCellLattice(batch, plan.cellLattice, x0, z0, fromY, toY); - } finally { - batch.release(); - } - } - - private void fillCellLattice(CaveLatticeBatch batch, CaveDensityLattice lattice, int x0, int z0, int fromY, int toY) { - batch.ensure((toY - fromY + 1) * CaveDensityLattice.CORNERS); - int[] latticeY = batch.y; - int[] cornerStart = batch.cornerStart; - long reads = 0L; - int count = 0; - for (int corner = 0; corner < CaveDensityLattice.CORNERS; corner++) { - cornerStart[corner] = count; - CaveDensityGrid.Column column = lattice.densityColumns[corner]; - for (int y = fromY; y <= toY; y++) { - if (!lattice.needs(corner, y)) { - continue; - } - reads++; - double cached = column == null ? Double.NaN : column.get(y); - if (Double.isNaN(cached)) { - latticeY[count++] = y; - } else { - lattice.store(corner, y, cached); - } - } - } - cornerStart[CaveDensityLattice.CORNERS] = count; - if (count > 0) { - sampleLatticePoints(batch, lattice, x0, z0, count); - double[] density = batch.density; - for (int corner = 0; corner < CaveDensityLattice.CORNERS; corner++) { - CaveDensityGrid.Column column = lattice.densityColumns[corner]; - for (int index = cornerStart[corner]; index < cornerStart[corner + 1]; index++) { - lattice.store(corner, latticeY[index], density[index]); - if (column != null) { - column.set(latticeY[index], density[index]); - } - } - } - } - if (GenerationCounter.ENABLED) { - GenerationCounter.CAVE_LATTICE_READS.add(reads); - GenerationCounter.CAVE_LATTICE_SAMPLES.add(count); - } - } - - private void sampleLatticePoints(CaveLatticeBatch batch, CaveDensityLattice lattice, int x0, int z0, int count) { - double[] xs = batch.warpedX; - double[] ys = batch.warpedY; - double[] zs = batch.warpedZ; - if (hasWarp) { - resolveLatticeWarp(batch, lattice, x0, z0); - } else { - int[] latticeY = batch.y; - int[] cornerStart = batch.cornerStart; - for (int corner = 0; corner < CaveDensityLattice.CORNERS; corner++) { - double x = x0 + (corner / 3) * ADAPTIVE_DEEP_SAMPLE_STEP; - double z = z0 + (corner % 3) * ADAPTIVE_DEEP_SAMPLE_STEP; - for (int index = cornerStart[corner]; index < cornerStart[corner + 1]; index++) { - xs[index] = x; - ys[index] = latticeY[index]; - zs[index] = z; - } - } - } - NoiseScratch noise = batch.noise; - double[] density = batch.density; - double[] values = batch.values; - baseDensity.fillPoints3D(noise, xs, ys, zs, count, values); - for (int index = 0; index < count; index++) { - density[index] = values[index] * baseWeight; - } - detailDensity.fillPoints3D(noise, xs, ys, zs, count, values); - for (int index = 0; index < count; index++) { - density[index] += values[index] * detailWeight; - } - if (hasWarp) { - for (CaveFieldModuleState module : modules) { - addLatticeModule(batch, module, count); - } - } - for (int index = 0; index < count; index++) { - density[index] = density[index] * inverseNormalization; - } - } - - private void addLatticeModule(CaveLatticeBatch batch, CaveFieldModuleState module, int count) { - NoiseScratch noise = batch.noise; - int[] latticeY = batch.y; - double[] xs = batch.warpedX; - double[] ys = batch.warpedY; - double[] zs = batch.warpedZ; - double[] density = batch.density; - double[] values = batch.values; - int[] band = batch.pointIndex; - int inBand = 0; - for (int index = 0; index < count; index++) { - int y = latticeY[index]; - if (y >= module.minY && y <= module.maxY) { - band[inBand++] = index; - } - } - if (inBand == 0) { - return; - } - if (inBand == count) { - module.density.fillPoints3D(noise, xs, ys, zs, count, values); - for (int index = 0; index < count; index++) { - double moduleDensity = values[index] - module.threshold; - if (module.invert) { - moduleDensity = -moduleDensity; - } - density[index] += moduleDensity * module.weight; - } - return; - } - double[] bandX = batch.pointX; - double[] bandY = batch.pointY; - double[] bandZ = batch.pointZ; - for (int slot = 0; slot < inBand; slot++) { - int index = band[slot]; - bandX[slot] = xs[index]; - bandY[slot] = ys[index]; - bandZ[slot] = zs[index]; - } - module.density.fillPoints3D(noise, bandX, bandY, bandZ, inBand, values); - for (int slot = 0; slot < inBand; slot++) { - double moduleDensity = values[slot] - module.threshold; - if (module.invert) { - moduleDensity = -moduleDensity; - } - density[band[slot]] += moduleDensity * module.weight; - } - } - - private void resolveLatticeWarp(CaveLatticeBatch batch, CaveDensityLattice lattice, int x0, int z0) { - int[] latticeY = batch.y; - int[] cornerStart = batch.cornerStart; - int[] snapStart = batch.snapStart; - int[] snapY = batch.snapY; - boolean[] snapMissing = batch.snapMissing; - double[] warpA = batch.warpA; - double[] warpB = batch.warpB; - int snapCount = 0; - int pending = 0; - long computed = 0L; - for (int corner = 0; corner < CaveDensityLattice.CORNERS; corner++) { - int first = snapCount; - snapStart[corner] = first; - for (int index = cornerStart[corner]; index < cornerStart[corner + 1]; index++) { - int snap = snapWarp(latticeY[index]); - if (snapCount == first || snapY[snapCount - 1] != snap) { - snapY[snapCount++] = snap; - } - } - if (snapCount == first) { - continue; - } - int x = x0 + (corner / 3) * ADAPTIVE_DEEP_SAMPLE_STEP; - int z = z0 + (corner % 3) * ADAPTIVE_DEEP_SAMPLE_STEP; - CaveDensityGrid.Column warpColumn = lattice.warpColumns[corner]; - int runStart = -1; - for (int snapIndex = first; snapIndex <= snapCount; snapIndex++) { - boolean missing = false; - if (snapIndex < snapCount) { - int snap = snapY[snapIndex]; - double cachedA = warpColumn == null ? Double.NaN : warpColumn.get(snap); - double cachedB = warpColumn == null ? Double.NaN : warpColumn.get(snap + 1); - missing = Double.isNaN(cachedA) || Double.isNaN(cachedB); - snapMissing[snapIndex] = missing; - warpA[snapIndex] = cachedA; - warpB[snapIndex] = cachedB; - } - if (runStart >= 0 && (!missing || snapY[snapIndex] != snapY[snapIndex - 1] + warpResolution)) { - pending = queueLatticeWarpRun(batch, x, z, runStart, snapIndex, pending); - computed += snapIndex - runStart; - runStart = -1; - } - if (missing && runStart < 0) { - runStart = snapIndex; - } - } - } - snapStart[CaveDensityLattice.CORNERS] = snapCount; - if (pending > 0) { - evaluateLatticeWarpPoints(batch, lattice, pending); - } - if (GenerationCounter.ENABLED) { - GenerationCounter.CAVE_WARP_SAMPLES.add(computed); - } - double[] warpedX = batch.warpedX; - double[] warpedY = batch.warpedY; - double[] warpedZ = batch.warpedZ; - for (int corner = 0; corner < CaveDensityLattice.CORNERS; corner++) { - int x = x0 + (corner / 3) * ADAPTIVE_DEEP_SAMPLE_STEP; - int z = z0 + (corner % 3) * ADAPTIVE_DEEP_SAMPLE_STEP; - int snapIndex = snapStart[corner]; - for (int index = cornerStart[corner]; index < cornerStart[corner + 1]; index++) { - int y = latticeY[index]; - int snap = snapWarp(y); - while (snapY[snapIndex] != snap) { - snapIndex++; - } - double a = warpA[snapIndex]; - double b = warpB[snapIndex]; - warpedX[index] = x + (a * warpStrength); - warpedY[index] = y + (b * warpStrength); - warpedZ[index] = z + ((a - b) * 0.5D * warpStrength); - } - } - } - - private int queueLatticeWarpRun(CaveLatticeBatch batch, int x, int z, int from, int to, int pending) { - int[] snapY = batch.snapY; - double[] pointX = batch.pointX; - double[] pointY = batch.pointY; - double[] pointZ = batch.pointZ; - int[] target = batch.pointIndex; - int length = to - from; - int queued = pending; - if (length == 1) { - pointX[queued] = x; - pointY[queued] = snapY[from]; - pointZ[queued] = z; - target[queued++] = from << 1; - } else { - double[] column = batch.values; - warpDensity.fillColumn3D(batch.noise, x, z, snapY[from], warpResolution, length, column); - System.arraycopy(column, 0, batch.warpA, from, length); - } - for (int snapIndex = from; snapIndex < to; snapIndex++) { - pointX[queued] = x + WARP_B_OFFSET_X; - pointY[queued] = snapY[snapIndex] - WARP_B_OFFSET_Y; - pointZ[queued] = z + WARP_B_OFFSET_Z; - target[queued++] = (snapIndex << 1) | 1; - } - return queued; - } - - private void evaluateLatticeWarpPoints(CaveLatticeBatch batch, CaveDensityLattice lattice, int pending) { - double[] values = batch.values; - warpDensity.fillPoints3D(batch.noise, batch.pointX, batch.pointY, batch.pointZ, pending, values); - int[] target = batch.pointIndex; - double[] warpA = batch.warpA; - double[] warpB = batch.warpB; - for (int slot = 0; slot < pending; slot++) { - int code = target[slot]; - if ((code & 1) == 0) { - warpA[code >> 1] = values[slot]; - } else { - warpB[code >> 1] = values[slot]; - } - } - int[] snapStart = batch.snapStart; - int[] snapY = batch.snapY; - boolean[] snapMissing = batch.snapMissing; - for (int corner = 0; corner < CaveDensityLattice.CORNERS; corner++) { - CaveDensityGrid.Column warpColumn = lattice.warpColumns[corner]; - if (warpColumn == null) { - continue; - } - for (int snapIndex = snapStart[corner]; snapIndex < snapStart[corner + 1]; snapIndex++) { - if (snapMissing[snapIndex]) { - warpColumn.set(snapY[snapIndex], warpA[snapIndex]); - warpColumn.set(snapY[snapIndex] + 1, warpB[snapIndex]); - } - } - } - } - - private int emitCellPass( - MantleChunk chunk, - CaveCarveScratch scratch, - byte[] classified, - int x0, - int z0, - int minY, - int passMaxY, - int minSection, - int maxSection, - int[] activeColumnIndices, - int[] activeColumnTopY, - int activeColumnCount, - long[] surfaceFluidBoundaries, - double surfaceBreakThresholdBoost, - double[] verticalEdgeFade, - int[] fluidMaxY, - MatterCavern[] matterByY, - CaveFluidSupportPlan fluidSupportPlan - ) { - int carved = 0; - long[] rowBits = scratch.rowCarveBits; - for (int sectionIndex = minSection; sectionIndex <= maxSection; sectionIndex++) { - int sectionMinY = Math.max(minY, PowerOfTwoCoordinates.chunkToBlock(sectionIndex)); - int sectionMaxY = Math.min(passMaxY, PowerOfTwoCoordinates.chunkToBlock(sectionIndex) + 15); - MatterSlice cavernSlice = resolveCavernSlice(scratch, chunk, sectionIndex); - for (int y = sectionMinY; y <= sectionMaxY; y++) { - int fadeIndex = y - minY; - if (scratch.rowActiveCount[fadeIndex] == 0) { - continue; - } - MatterCavern verticalMatter = matterByY[fadeIndex]; - if (classified != null) { - carved += emitClassifiedRow(cavernSlice, classified, fadeIndex, y, verticalMatter, fluidSupportPlan); - continue; - } - classifyAdaptiveRow(scratch, scratch, x0, z0, y, minY, activeColumnIndices, activeColumnTopY, - activeColumnCount, surfaceFluidBoundaries, surfaceBreakThresholdBoost, verticalEdgeFade, rowBits); - for (int word = 0; word < 4; word++) { - long bits = rowBits[word]; - while (bits != 0L) { - int column = (word << 6) | Long.numberOfTrailingZeros(bits); - bits &= bits - 1L; - int localX = PowerOfTwoCoordinates.unpackLocal16X(column); - int localZ = column & 15; - MatterCavern matter = verticalMatter; - if (verticalMatter != carveLava && y <= fluidMaxY[column]) { - matter = resolveMatter(scratch, verticalMatter, x0 + localX, y, z0 + localZ, column, fluidMaxY, - cellThreshold(scratch, column, y, minY, surfaceBreakThresholdBoost, verticalEdgeFade)); - } - writeCavern(cavernSlice, localX, y, localZ, matter, fluidSupportPlan); - carved++; - } - } - } - } - flushCellCounters(scratch); - return carved; - } - - private int emitClassifiedRow(MatterSlice cavernSlice, byte[] classified, int fadeIndex, int y, - MatterCavern verticalMatter, CaveFluidSupportPlan fluidSupportPlan) { - int carved = 0; - int offset = fadeIndex * 256; - for (int column = 0; column < 256; column++) { - byte flags = classified[offset + column]; - if ((flags & DENSITY_CARVE) == 0) { - continue; - } - MatterCavern matter = (flags & DENSITY_FLUID) != 0 ? carveFluid : verticalMatter; - writeCavern(cavernSlice, PowerOfTwoCoordinates.unpackLocal16X(column), y, column & 15, matter, fluidSupportPlan); - carved++; - } - return carved; - } - - private void classifyCellRows(DensityPass pass, int minimumY, int maximumY, byte[] classified) { - CaveCarveScratch scratch = new CaveCarveScratch(); - CaveCarveScratch plan = pass.sourceScratch(); - fillCellLattice(plan, pass.x(), pass.z(), minimumY, maximumY); - long[] rowBits = scratch.rowCarveBits; - for (int y = minimumY; y <= maximumY; y++) { - int fadeIndex = y - pass.minimumY(); - if (plan.rowActiveCount[fadeIndex] == 0) { - continue; - } - classifyAdaptiveRow(scratch, plan, pass.x(), pass.z(), y, pass.minimumY(), pass.columns(), pass.columnTops(), - pass.columnCount(), pass.fluidBoundaries(), pass.surfaceBreakBoost(), pass.verticalFade(), rowBits); - MatterCavern verticalMatter = pass.matterByY()[fadeIndex]; - int offset = fadeIndex * 256; - for (int word = 0; word < 4; word++) { - long bits = rowBits[word]; - while (bits != 0L) { - int column = (word << 6) | Long.numberOfTrailingZeros(bits); - bits &= bits - 1L; - MatterCavern matter = verticalMatter; - if (verticalMatter != carveLava && y <= pass.fluidTops()[column]) { - matter = resolveMatter(scratch, verticalMatter, pass.x() + PowerOfTwoCoordinates.unpackLocal16X(column), - y, pass.z() + (column & 15), column, pass.fluidTops(), - cellThreshold(plan, column, y, pass.minimumY(), pass.surfaceBreakBoost(), pass.verticalFade())); - } - classified[offset + column] = matter == carveFluid ? DENSITY_CARVE | DENSITY_FLUID : DENSITY_CARVE; - } - } - } - flushCellCounters(scratch); - } - - private void classifyAdaptiveRow( - CaveCarveScratch scratch, - CaveCarveScratch plan, - int x0, - int z0, - int y, - int minY, - int[] activeColumnIndices, - int[] activeColumnTopY, - int activeColumnCount, - long[] surfaceFluidBoundaries, - double surfaceBreakThresholdBoost, - double[] verticalEdgeFade, - long[] rowBits - ) { - Arrays.fill(rowBits, 0L); - if (plan.rowActiveCount[y - minY] >= ADAPTIVE_MIN_PLANE_COLUMNS) { - classifyCellRow(scratch, plan, y, minY, surfaceBreakThresholdBoost, verticalEdgeFade, rowBits); - return; - } - int[] planeColumnIndices = scratch.planeColumnIndices; - double[] planeThresholdLimit = scratch.planeThresholdLimit; - boolean[] planeCarve = scratch.planeCarve; - int planeCount = 0; - for (int activeIndex = 0; activeIndex < activeColumnCount; activeIndex++) { - if (activeColumnTopY[activeIndex] < y) { - continue; - } - int columnIndex = activeColumnIndices[activeIndex]; - if (SurfaceFluidBoundaryPlan.protects(surfaceFluidBoundaries, columnIndex, y)) { - continue; - } - planeColumnIndices[planeCount] = columnIndex; - planeThresholdLimit[planeCount] = cellLocalThreshold(plan, columnIndex, y, minY, surfaceBreakThresholdBoost, - verticalEdgeFade) * normalizationFactor; - planeCount++; - } - classifyDensityPlane(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - if (planeCarve[planeIndex]) { - int columnIndex = planeColumnIndices[planeIndex]; - rowBits[columnIndex >> 6] |= 1L << columnIndex; - } - } - scratch.exactRows++; - } - - private void classifyCellRow( - CaveCarveScratch scratch, - CaveCarveScratch plan, - int y, - int minY, - double surfaceBreakThresholdBoost, - double[] verticalEdgeFade, - long[] rowBits - ) { - CaveDensityLattice lattice = plan.cellLattice; - int activeCells = lattice.cells(y); - if (activeCells == 0) { - return; - } - int fadeIndex = y - minY; - double fade = verticalEdgeFade[fadeIndex]; - double closure = plan.surfaceClosureThreshold[fadeIndex]; - for (int cell = 0; cell < 4; cell++) { - if ((activeCells & (1 << cell)) == 0) { - continue; - } - int corner = ((cell >> 1) * 3) + (cell & 1); - double d00 = lattice.density(corner, y); - double d01 = lattice.density(corner + 1, y); - double d10 = lattice.density(corner + 3, y); - double d11 = lattice.density(corner + 4, y); - double low = plan.cellThresholdMin[cell] - fade; - if (y >= plan.cellCeilingFadeStart[cell]) { - low = Math.min(low, closure); - } - double high = (y >= plan.cellBreakFloorMin[cell] ? plan.cellThresholdMaxBoost[cell] : plan.cellThresholdMax[cell]) - fade; - int decision = CaveCellKernel.decide(d00, d01, d10, d11, - CaveCellKernel.threshold(low, normalizationFactor, inverseNormalization), - CaveCellKernel.threshold(high, normalizationFactor, inverseNormalization)); - boolean uniform = !plan.cellProtected[cell] && y <= plan.cellMinTopY[cell]; - if (decision == CaveCellKernel.NONE) { - scratch.solidCells++; - } else if (decision == CaveCellKernel.ALL) { - scratch.openCells++; - if (uniform) { - int word = (cell >> 1) << 1; - long mask = CELL_Z_MASKS[cell & 1]; - rowBits[word] |= plan.cellPassBits[word] & mask; - rowBits[word + 1] |= plan.cellPassBits[word + 1] & mask; - } else { - markActiveCellColumns(plan, cell, y, rowBits); - } - } else { - scratch.mixedCells++; - if (uniform && y < plan.cellCeilingFadeStart[cell] && y < plan.cellBreakFloorMin[cell]) { - classifyPlainMixedCell(plan, cell, fade, d00, d01, d10, d11, rowBits); - } else { - classifyMixedCell(plan, cell, y, minY, surfaceBreakThresholdBoost, verticalEdgeFade, d00, d01, d10, d11, rowBits); - } - } - } - } - - private void classifyMixedCell( - CaveCarveScratch plan, - int cell, - int y, - int minY, - double surfaceBreakThresholdBoost, - double[] verticalEdgeFade, - double d00, - double d01, - double d10, - double d11, - long[] rowBits - ) { - double[] adaptiveTx = plan.adaptiveTx; - double[] adaptiveTz = plan.adaptiveTz; - int firstLocalX = (cell >> 1) << 3; - int firstLocalZ = (cell & 1) << 3; - for (int localX = firstLocalX; localX < firstLocalX + ADAPTIVE_DEEP_SAMPLE_STEP; localX++) { - int rowColumn = PowerOfTwoCoordinates.packLocal16(localX, firstLocalZ); - double tx = adaptiveTx[rowColumn]; - double dx0 = d00 + ((d10 - d00) * tx); - double dx1 = d01 + ((d11 - d01) * tx); - double slope = dx1 - dx0; - for (int column = rowColumn; column < rowColumn + ADAPTIVE_DEEP_SAMPLE_STEP; column++) { - if (!isCellColumnActive(plan, column, y)) { - continue; - } - double predictedDensity = dx0 + (slope * adaptiveTz[column]); - if (predictedDensity <= cellThreshold(plan, column, y, minY, surfaceBreakThresholdBoost, verticalEdgeFade)) { - rowBits[column >> 6] |= 1L << column; - } - } - } - } - - private void classifyPlainMixedCell( - CaveCarveScratch plan, - int cell, - double fade, - double d00, - double d01, - double d10, - double d11, - long[] rowBits - ) { - double[] passThreshold = plan.passThreshold; - double[] adaptiveTx = plan.adaptiveTx; - double[] adaptiveTz = plan.adaptiveTz; - int firstLocalX = (cell >> 1) << 3; - int firstLocalZ = (cell & 1) << 3; - for (int localX = firstLocalX; localX < firstLocalX + ADAPTIVE_DEEP_SAMPLE_STEP; localX++) { - int rowColumn = PowerOfTwoCoordinates.packLocal16(localX, firstLocalZ); - double tx = adaptiveTx[rowColumn]; - double dx0 = d00 + ((d10 - d00) * tx); - double dx1 = d01 + ((d11 - d01) * tx); - double slope = dx1 - dx0; - long bits = 0L; - for (int offset = 0; offset < ADAPTIVE_DEEP_SAMPLE_STEP; offset++) { - int column = rowColumn + offset; - double predictedDensity = dx0 + (slope * adaptiveTz[column]); - if (predictedDensity <= CaveCellKernel.threshold(passThreshold[column] - fade, normalizationFactor, - inverseNormalization)) { - bits |= 1L << offset; - } - } - rowBits[rowColumn >> 6] |= bits << (rowColumn & 63); - } - } - - private static void markActiveCellColumns(CaveCarveScratch plan, int cell, int y, long[] rowBits) { - int firstLocalX = (cell >> 1) << 3; - int firstLocalZ = (cell & 1) << 3; - for (int localX = firstLocalX; localX < firstLocalX + ADAPTIVE_DEEP_SAMPLE_STEP; localX++) { - int rowColumn = PowerOfTwoCoordinates.packLocal16(localX, firstLocalZ); - for (int column = rowColumn; column < rowColumn + ADAPTIVE_DEEP_SAMPLE_STEP; column++) { - if (isCellColumnActive(plan, column, y)) { - rowBits[column >> 6] |= 1L << column; - } - } - } - } - - private static boolean isCellActive(CaveCarveScratch plan, int cell, int y) { - if (y > plan.cellTopY[cell]) { - return false; - } - if (!plan.cellProtected[cell]) { - return true; - } - int firstLocalX = (cell >> 1) << 3; - int firstLocalZ = (cell & 1) << 3; - for (int localX = firstLocalX; localX < firstLocalX + ADAPTIVE_DEEP_SAMPLE_STEP; localX++) { - int rowColumn = PowerOfTwoCoordinates.packLocal16(localX, firstLocalZ); - for (int column = rowColumn; column < rowColumn + ADAPTIVE_DEEP_SAMPLE_STEP; column++) { - if (isCellColumnActive(plan, column, y)) { - return true; - } - } - } - return false; - } - - private static boolean isCellColumnActive(CaveCarveScratch plan, int column, int y) { - return (plan.cellPassBits[column >> 6] & (1L << column)) != 0L - && plan.columnMaxY[column] >= y - && (y < plan.columnProtectStartY[column] || y > plan.columnProtectEndY[column]); - } - - private double cellThreshold(CaveCarveScratch plan, int column, int y, int minY, double surfaceBreakThresholdBoost, - double[] verticalEdgeFade) { - return CaveCellKernel.threshold(cellLocalThreshold(plan, column, y, minY, surfaceBreakThresholdBoost, verticalEdgeFade), - normalizationFactor, inverseNormalization); - } - - private double cellLocalThreshold(CaveCarveScratch plan, int column, int y, int minY, double surfaceBreakThresholdBoost, - double[] verticalEdgeFade) { - double localThreshold = plan.passThreshold[column]; - if (plan.surfaceBreakColumn[column] && y >= plan.surfaceBreakFloorY[column]) { - localThreshold += surfaceBreakThresholdBoost; - } - localThreshold -= verticalEdgeFade[y - minY]; - return applySurfaceCeilingFade(plan, localThreshold, column, y, minY); - } - - private static void flushCellCounters(CaveCarveScratch scratch) { - if (scratch.solidCells != 0L) { - SOLID_CELLS.add(scratch.solidCells); - scratch.solidCells = 0L; - } - if (scratch.openCells != 0L) { - OPEN_CELLS.add(scratch.openCells); - scratch.openCells = 0L; - } - if (scratch.mixedCells != 0L) { - MIXED_CELLS.add(scratch.mixedCells); - scratch.mixedCells = 0L; - } - if (scratch.exactRows != 0L) { - EXACT_ROWS.add(scratch.exactRows); - scratch.exactRows = 0L; - } - } - - private int carvePassLattice( - MantleChunk chunk, - int x0, - int z0, - int minY, - int maxY, - int latticeStep, - double surfaceBreakThresholdBoost, - int[] columnMaxY, - int[] fluidMaxY, - long[] surfaceFluidBoundaries, - int[] surfaceBreakFloorY, - boolean[] surfaceBreakColumn, - double[] columnThreshold, - double[] clampedWeights, - double[] verticalEdgeFade, - MatterCavern[] matterByY, - CaveFluidSupportPlan fluidSupportPlan, - double minWeight, - double thresholdPenalty, - double thresholdBoost, - boolean skipExistingCarved - ) { - int carved = 0; - CaveCarveScratch scratch = scratchCache.get(); - double[] passThreshold = scratch.passThreshold; - int[] tileIndices = scratch.tileIndices; - int[] tileLocalX = scratch.tileLocalX; - int[] tileLocalZ = scratch.tileLocalZ; - int[] tileTopY = scratch.tileTopY; - - for (int index = 0; index < 256; index++) { - double columnWeight = clampedWeights[index]; - if (columnWeight <= minWeight || columnMaxY[index] < minY) { - passThreshold[index] = Double.NaN; - continue; - } - passThreshold[index] = columnThreshold[index] + thresholdBoost - ((1D - columnWeight) * thresholdPenalty); - } - - double[] latticeDensity = sampleLatticeParallel(x0, z0, minY, maxY, latticeStep, passThreshold, columnMaxY); - int latticeRows = (maxY - minY) / latticeStep + 1; - - for (int lx = 0; lx < 16; lx += 2) { - int x = x0 + lx; - int lx1 = lx + 1; - for (int lz = 0; lz < 16; lz += 2) { - int z = z0 + lz; - int lz1 = lz + 1; - int activeColumns = 0; - - int index00 = PowerOfTwoCoordinates.packLocal16(lx, lz); - if (!Double.isNaN(passThreshold[index00])) { - tileIndices[activeColumns] = index00; - tileLocalX[activeColumns] = lx; - tileLocalZ[activeColumns] = lz; - tileTopY[activeColumns] = columnMaxY[index00]; - activeColumns++; - } - - int index01 = PowerOfTwoCoordinates.packLocal16(lx, lz1); - if (!Double.isNaN(passThreshold[index01])) { - tileIndices[activeColumns] = index01; - tileLocalX[activeColumns] = lx; - tileLocalZ[activeColumns] = lz1; - tileTopY[activeColumns] = columnMaxY[index01]; - activeColumns++; - } - - int index10 = PowerOfTwoCoordinates.packLocal16(lx1, lz); - if (!Double.isNaN(passThreshold[index10])) { - tileIndices[activeColumns] = index10; - tileLocalX[activeColumns] = lx1; - tileLocalZ[activeColumns] = lz; - tileTopY[activeColumns] = columnMaxY[index10]; - activeColumns++; - } - - int index11 = PowerOfTwoCoordinates.packLocal16(lx1, lz1); - if (!Double.isNaN(passThreshold[index11])) { - tileIndices[activeColumns] = index11; - tileLocalX[activeColumns] = lx1; - tileLocalZ[activeColumns] = lz1; - tileTopY[activeColumns] = columnMaxY[index11]; - activeColumns++; - } - - if (activeColumns == 0) { - continue; - } - - int tileMaxY = minY; - for (int columnIndex = 0; columnIndex < activeColumns; columnIndex++) { - if (tileTopY[columnIndex] > tileMaxY) { - tileMaxY = tileTopY[columnIndex]; - } - } - if (tileMaxY < minY) { - continue; - } - - for (int y = minY; y <= tileMaxY; y += latticeStep) { - double density = latticeDensity == null - ? sampleDensityOptimized(scratch, x, y, z) - : latticeDensity[((lx >> 1) * 8 + (lz >> 1)) * latticeRows + (y - minY) / latticeStep]; - int stampMaxY = Math.min(maxY, y + 1); - for (int yy = y; yy <= stampMaxY; yy++) { - MatterCavern verticalMatter = matterByY[yy - minY]; - MatterSlice cavernSlice = resolveCavernSlice(scratch, chunk, PowerOfTwoCoordinates.floorDivPow2(yy, 4)); - int localY = yy & 15; - int fadeIndex = yy - minY; - for (int columnIndex = 0; columnIndex < activeColumns; columnIndex++) { - if (yy > tileTopY[columnIndex]) { - continue; - } - - int index = tileIndices[columnIndex]; - if (SurfaceFluidBoundaryPlan.protects(surfaceFluidBoundaries, index, yy)) { - continue; - } - double localThreshold = passThreshold[index]; - if (surfaceBreakColumn[index] && yy >= surfaceBreakFloorY[index]) { - localThreshold += surfaceBreakThresholdBoost; - } - localThreshold -= verticalEdgeFade[fadeIndex]; - localThreshold = applySurfaceCeilingFade(scratch, localThreshold, index, yy, minY); - if (density > localThreshold) { - continue; - } - - int localX = tileLocalX[columnIndex]; - int localZ = tileLocalZ[columnIndex]; - int worldX = x0 + localX; - int worldZ = z0 + localZ; - MatterCavern matter = resolveMatter(scratch, verticalMatter, worldX, yy, worldZ, - index, fluidMaxY, localThreshold); - if (skipExistingCarved) { - if (cavernSlice.get(localX, localY, localZ) == null) { - writeCavern(cavernSlice, localX, yy, localZ, matter, fluidSupportPlan); - carved++; - } - continue; - } - - writeCavern(cavernSlice, localX, yy, localZ, matter, fluidSupportPlan); - carved++; - } - } - } - } - } - - return carved; - } - - private int carvePassFallback( - MantleChunk chunk, - int x0, - int z0, - int minY, - int maxY, - int sampleStep, - double surfaceBreakThresholdBoost, - int[] columnMaxY, - int[] fluidMaxY, - long[] surfaceFluidBoundaries, - int[] surfaceBreakFloorY, - boolean[] surfaceBreakColumn, - double[] columnThreshold, - double[] clampedWeights, - double[] verticalEdgeFade, - MatterCavern[] matterByY, - CaveFluidSupportPlan fluidSupportPlan, - double minWeight, - double thresholdPenalty, - double thresholdBoost, - boolean skipExistingCarved - ) { - int carved = 0; - CaveCarveScratch scratch = scratchCache.get(); - - for (int lx = 0; lx < 16; lx++) { - int x = x0 + lx; - for (int lz = 0; lz < 16; lz++) { - int z = z0 + lz; - int index = PowerOfTwoCoordinates.packLocal16(lx, lz); - double columnWeight = clampedWeights[index]; - if (columnWeight <= minWeight) { - continue; - } - - int columnTopY = columnMaxY[index]; - if (columnTopY < minY) { - continue; - } - - boolean breakColumn = surfaceBreakColumn[index]; - int breakFloorY = surfaceBreakFloorY[index]; - double threshold = columnThreshold[index] + thresholdBoost - ((1D - columnWeight) * thresholdPenalty); - - for (int y = minY; y <= columnTopY; y += sampleStep) { - double density = sampleDensityOptimized(scratch, x, y, z); - int carveMaxY = Math.min(columnTopY, y + sampleStep - 1); - for (int yy = y; yy <= carveMaxY; yy++) { - if (SurfaceFluidBoundaryPlan.protects(surfaceFluidBoundaries, index, yy)) { - continue; - } - double localThreshold = threshold; - if (breakColumn && yy >= breakFloorY) { - localThreshold += surfaceBreakThresholdBoost; - } - localThreshold -= verticalEdgeFade[yy - minY]; - localThreshold = applySurfaceCeilingFade(scratch, localThreshold, index, yy, minY); - if (density > localThreshold) { - continue; - } - MatterCavern verticalMatter = matterByY[yy - minY]; - MatterCavern matter = resolveMatter(scratch, verticalMatter, x, yy, z, - index, fluidMaxY, localThreshold); - MatterSlice cavernSlice = resolveCavernSlice(scratch, chunk, PowerOfTwoCoordinates.floorDivPow2(yy, 4)); - int localY = yy & 15; - if (skipExistingCarved) { - if (cavernSlice.get(lx, localY, lz) == null) { - writeCavern(cavernSlice, lx, yy, lz, matter, fluidSupportPlan); - carved++; - } - continue; - } - - writeCavern(cavernSlice, lx, yy, lz, matter, fluidSupportPlan); - carved++; - } - } - } - } - - return carved; - } - - private boolean hasFallbackCandidates(int[] columnMaxY, double[] clampedWeights, int minY, double minWeight) { - for (int index = 0; index < 256; index++) { - if (clampedWeights[index] <= minWeight) { - continue; - } - - if (columnMaxY[index] >= minY) { - return true; - } - } - - return false; - } - - private double sampleDensityOptimized(int x, int y, int z) { - if (!hasWarp && !hasModules) { - return sampleDensityNoWarpNoModules(x, y, z); - } - - return sampleDensityOptimized(scratchCache.get(), x, y, z); - } - - private double sampleDensityOptimized(CaveCarveScratch scratch, int x, int y, int z) { - if (!hasWarp) { - if (!hasModules) { - return sampleDensityNoWarpNoModules(x, y, z); - } - - return sampleDensityNoWarpModules(scratch, x, y, z); - } - - if (!hasModules) { - return sampleDensityWarpOnly(scratch, x, y, z); - } - - return sampleDensityWarpModules(scratch, x, y, z); - } - - private void classifyDensityPlane(CaveCarveScratch scratch, int x0, int z0, int y, int[] planeColumnIndices, double[] planeThresholdLimit, int planeCount, boolean[] planeCarve) { - if (!hasWarp) { - if (!hasModules) { - classifyDensityPlaneNoWarpNoModules(x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); - return; - } - - classifyDensityPlaneNoWarpModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); - return; - } - - if (!hasModules) { - classifyDensityPlaneWarpOnly(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); - return; - } - - classifyDensityPlaneWarpModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); - } - - private void classifyDensityPlaneAdaptive( - CaveCarveScratch scratch, - int x0, - int z0, - int y, - int[] planeColumnIndices, - double[] planeThresholdLimit, - int planeCount, - boolean[] planeCarve, - int adaptiveSampleStep, - double adaptiveThresholdMargin - ) { - if (adaptiveSampleStep <= 1 || planeCount < ADAPTIVE_MIN_PLANE_COLUMNS) { - classifyDensityPlane(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); - return; - } - - if (verticalDensityStep > 1 && adaptiveSampleStep == ADAPTIVE_DEEP_SAMPLE_STEP) { - prepareVerticalDensityPlane(scratch, x0, z0, y); - classifyDeepAdaptivePlaneFromSamples(scratch, planeColumnIndices, planeThresholdLimit, - planeCount, planeCarve, ADAPTIVE_DEEP_SAMPLE_STEP, scratch.adaptivePlaneDensity, 2, 3); - return; - } - - if (!hasWarp) { - if (!hasModules) { - classifyDensityPlaneAdaptiveNoWarpNoModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); - return; - } - - classifyDensityPlaneAdaptiveNoWarpModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); - return; - } - - if (!hasModules) { - classifyDensityPlaneAdaptiveWarpOnly(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); - return; - } - - classifyDensityPlaneAdaptiveWarpModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); - } - - private void prepareVerticalDensityPlane(CaveCarveScratch scratch, int x0, int z0, int y) { - int lower = (int) (Math.floorDiv((long) y + worldMinimumY, verticalDensityStep) - * verticalDensityStep - worldMinimumY); - int upper = Math.min(densityMaximumY, lower + verticalDensityStep); - lower = Math.max(0, lower); - for (CaveFieldModuleState module : modules) { - if (y < module.minY) { - upper = Math.min(upper, module.minY - 1); - } else if (y > module.maxY) { - lower = Math.max(lower, module.maxY + 1); - } else { - lower = Math.max(lower, module.minY); - upper = Math.min(upper, module.maxY); - } - } - if (scratch.verticalDensityX != x0 || scratch.verticalDensityZ != z0) { - scratch.verticalDensityX = x0; - scratch.verticalDensityZ = z0; - scratch.verticalDensityLowerY = Integer.MIN_VALUE; - scratch.verticalDensityUpperY = Integer.MIN_VALUE; - } - if (scratch.verticalDensityUpperY == lower) { - double[] previousLower = scratch.verticalDensityLower; - scratch.verticalDensityLower = scratch.verticalDensityUpper; - scratch.verticalDensityUpper = previousLower; - scratch.verticalDensityUpperY = scratch.verticalDensityLowerY; - scratch.verticalDensityLowerY = lower; - } - if (scratch.verticalDensityLowerY != lower) { - scratch.verticalDensityLowerY = Integer.MIN_VALUE; - sampleVerticalDensityPlane(scratch, x0, z0, lower, scratch.verticalDensityLower); - scratch.verticalDensityLowerY = lower; - } - if (y == lower) { - System.arraycopy(scratch.verticalDensityLower, 0, scratch.adaptivePlaneDensity, 0, 9); - return; - } - if (scratch.verticalDensityUpperY != upper) { - scratch.verticalDensityUpperY = Integer.MIN_VALUE; - sampleVerticalDensityPlane(scratch, x0, z0, upper, scratch.verticalDensityUpper); - scratch.verticalDensityUpperY = upper; - } - double fraction = (y - lower) / (double) (upper - lower); - for (int index = 0; index < 9; index++) { - double lowerDensity = scratch.verticalDensityLower[index]; - scratch.adaptivePlaneDensity[index] = lowerDensity - + (scratch.verticalDensityUpper[index] - lowerDensity) * fraction; - } - } - - private void sampleVerticalDensityPlane(CaveCarveScratch scratch, int x0, int z0, int y, double[] samples) { - for (int x = 0; x < 3; x++) { - for (int z = 0; z < 3; z++) { - samples[x * 3 + z] = sampleDensityOptimized(scratch, - x0 + x * ADAPTIVE_DEEP_SAMPLE_STEP, y, z0 + z * ADAPTIVE_DEEP_SAMPLE_STEP); - } - } - } - - private void classifyDensityPlaneNoWarpNoModules(int x0, int z0, int y, int[] planeColumnIndices, double[] planeThresholdLimit, int planeCount, boolean[] planeCarve) { - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - int columnIndex = planeColumnIndices[planeIndex]; - int x = x0 + PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int z = z0 + (columnIndex & 15); - planeCarve[planeIndex] = classifyDensityPointNoWarpNoModules(x, y, z, planeThresholdLimit[planeIndex]); - } - } - - private void classifyDensityPlaneNoWarpModules(CaveCarveScratch scratch, int x0, int z0, int y, int[] planeColumnIndices, double[] planeThresholdLimit, int planeCount, boolean[] planeCarve) { - int activeModuleCount = prepareActiveModules(scratch, y); - if (activeModuleCount == 0) { - classifyDensityPlaneNoWarpNoModules(x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); - return; - } - - CaveFieldModuleState[] localModules = scratch.activeModules; - double[] remainingMin = scratch.activeModuleRemainingMin; - double[] remainingMax = scratch.activeModuleRemainingMax; - - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - int columnIndex = planeColumnIndices[planeIndex]; - int x = x0 + PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int z = z0 + (columnIndex & 15); - planeCarve[planeIndex] = classifyDensityPointNoWarpModules( - x, - y, - z, - planeThresholdLimit[planeIndex], - localModules, - activeModuleCount, - remainingMin, - remainingMax - ); - } - } - - private void classifyDensityPlaneWarpOnly(CaveCarveScratch scratch, int x0, int z0, int y, int[] planeColumnIndices, double[] planeThresholdLimit, int planeCount, boolean[] planeCarve) { - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - int columnIndex = planeColumnIndices[planeIndex]; - int x = x0 + PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int z = z0 + (columnIndex & 15); - planeCarve[planeIndex] = classifyDensityPointWarpOnly(scratch, x, y, z, planeThresholdLimit[planeIndex]); - } - } - - private void classifyDensityPlaneWarpModules(CaveCarveScratch scratch, int x0, int z0, int y, int[] planeColumnIndices, double[] planeThresholdLimit, int planeCount, boolean[] planeCarve) { - int activeModuleCount = prepareActiveModules(scratch, y); - if (activeModuleCount == 0) { - classifyDensityPlaneWarpOnly(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); - return; - } - - CaveFieldModuleState[] localModules = scratch.activeModules; - double[] remainingMin = scratch.activeModuleRemainingMin; - double[] remainingMax = scratch.activeModuleRemainingMax; - - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - int columnIndex = planeColumnIndices[planeIndex]; - int x = x0 + PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int z = z0 + (columnIndex & 15); - planeCarve[planeIndex] = classifyDensityPointWarpModules( - scratch, - x, - y, - z, - planeThresholdLimit[planeIndex], - localModules, - activeModuleCount, - remainingMin, - remainingMax - ); - } - } - - private void classifyDensityPlaneAdaptiveNoWarpNoModules( - CaveCarveScratch scratch, - int x0, - int z0, - int y, - int[] planeColumnIndices, - double[] planeThresholdLimit, - int planeCount, - boolean[] planeCarve, - int adaptiveSampleStep, - double adaptiveThresholdMargin - ) { - double[] adaptivePlaneDensity = scratch.adaptivePlaneDensity; - int axisCells = (16 + adaptiveSampleStep - 1) / adaptiveSampleStep; - int axisSamples = axisCells + 1; - int[] adaptivePlaneSampleBounds = scratch.adaptivePlaneSampleBounds; - prepareAdaptivePlaneSampleBounds(scratch, planeColumnIndices, planeCount, adaptiveSampleStep, adaptivePlaneSampleBounds, axisCells); - for (int sampleXIndex = adaptivePlaneSampleBounds[0]; sampleXIndex <= adaptivePlaneSampleBounds[1]; sampleXIndex++) { - int sampleLocalX = Math.min(sampleXIndex * adaptiveSampleStep, 16); - int x = x0 + sampleLocalX; - int rowOffset = sampleXIndex * axisSamples; - for (int sampleZIndex = adaptivePlaneSampleBounds[2]; sampleZIndex <= adaptivePlaneSampleBounds[3]; sampleZIndex++) { - int sampleLocalZ = Math.min(sampleZIndex * adaptiveSampleStep, 16); - adaptivePlaneDensity[rowOffset + sampleZIndex] = latticeDensity(scratch, x, y, z0 + sampleLocalZ); - } - } - - classifyAdaptivePlaneColumnsNoWarpNoModules( - scratch, - x0, - z0, - y, - planeColumnIndices, - planeThresholdLimit, - planeCount, - planeCarve, - adaptiveSampleStep, - adaptiveThresholdMargin, - adaptivePlaneDensity, - axisCells, - axisSamples - ); - } - - private void classifyDensityPlaneAdaptiveNoWarpModules( - CaveCarveScratch scratch, - int x0, - int z0, - int y, - int[] planeColumnIndices, - double[] planeThresholdLimit, - int planeCount, - boolean[] planeCarve, - int adaptiveSampleStep, - double adaptiveThresholdMargin - ) { - int activeModuleCount = prepareActiveModules(scratch, y); - if (activeModuleCount == 0) { - classifyDensityPlaneAdaptiveNoWarpNoModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); - return; - } - - CaveFieldModuleState[] localModules = scratch.activeModules; - double[] remainingMin = scratch.activeModuleRemainingMin; - double[] remainingMax = scratch.activeModuleRemainingMax; - double[] adaptivePlaneDensity = scratch.adaptivePlaneDensity; - int axisCells = (16 + adaptiveSampleStep - 1) / adaptiveSampleStep; - int axisSamples = axisCells + 1; - int[] adaptivePlaneSampleBounds = scratch.adaptivePlaneSampleBounds; - prepareAdaptivePlaneSampleBounds(scratch, planeColumnIndices, planeCount, adaptiveSampleStep, adaptivePlaneSampleBounds, axisCells); - for (int sampleXIndex = adaptivePlaneSampleBounds[0]; sampleXIndex <= adaptivePlaneSampleBounds[1]; sampleXIndex++) { - int sampleLocalX = Math.min(sampleXIndex * adaptiveSampleStep, 16); - int x = x0 + sampleLocalX; - int rowOffset = sampleXIndex * axisSamples; - for (int sampleZIndex = adaptivePlaneSampleBounds[2]; sampleZIndex <= adaptivePlaneSampleBounds[3]; sampleZIndex++) { - int sampleLocalZ = Math.min(sampleZIndex * adaptiveSampleStep, 16); - adaptivePlaneDensity[rowOffset + sampleZIndex] = latticeDensity(scratch, x, y, z0 + sampleLocalZ); - } - } - - classifyAdaptivePlaneColumnsNoWarpModules( - scratch, - x0, - z0, - y, - planeColumnIndices, - planeThresholdLimit, - planeCount, - planeCarve, - adaptiveSampleStep, - adaptiveThresholdMargin, - adaptivePlaneDensity, - axisCells, - axisSamples, - localModules, - activeModuleCount, - remainingMin, - remainingMax - ); - } - - private void classifyDensityPlaneAdaptiveWarpOnly( - CaveCarveScratch scratch, - int x0, - int z0, - int y, - int[] planeColumnIndices, - double[] planeThresholdLimit, - int planeCount, - boolean[] planeCarve, - int adaptiveSampleStep, - double adaptiveThresholdMargin - ) { - double[] adaptivePlaneDensity = scratch.adaptivePlaneDensity; - int axisCells = (16 + adaptiveSampleStep - 1) / adaptiveSampleStep; - int axisSamples = axisCells + 1; - int[] adaptivePlaneSampleBounds = scratch.adaptivePlaneSampleBounds; - prepareAdaptivePlaneSampleBounds(scratch, planeColumnIndices, planeCount, adaptiveSampleStep, adaptivePlaneSampleBounds, axisCells); - for (int sampleXIndex = adaptivePlaneSampleBounds[0]; sampleXIndex <= adaptivePlaneSampleBounds[1]; sampleXIndex++) { - int sampleLocalX = Math.min(sampleXIndex * adaptiveSampleStep, 16); - int x = x0 + sampleLocalX; - int rowOffset = sampleXIndex * axisSamples; - for (int sampleZIndex = adaptivePlaneSampleBounds[2]; sampleZIndex <= adaptivePlaneSampleBounds[3]; sampleZIndex++) { - int sampleLocalZ = Math.min(sampleZIndex * adaptiveSampleStep, 16); - adaptivePlaneDensity[rowOffset + sampleZIndex] = latticeDensity(scratch, x, y, z0 + sampleLocalZ); - } - } - - classifyAdaptivePlaneColumnsWarpOnly( - scratch, - x0, - z0, - y, - planeColumnIndices, - planeThresholdLimit, - planeCount, - planeCarve, - adaptiveSampleStep, - adaptiveThresholdMargin, - adaptivePlaneDensity, - axisCells, - axisSamples - ); - } - - private void classifyDensityPlaneAdaptiveWarpModules( - CaveCarveScratch scratch, - int x0, - int z0, - int y, - int[] planeColumnIndices, - double[] planeThresholdLimit, - int planeCount, - boolean[] planeCarve, - int adaptiveSampleStep, - double adaptiveThresholdMargin - ) { - int activeModuleCount = prepareActiveModules(scratch, y); - if (activeModuleCount == 0) { - classifyDensityPlaneAdaptiveWarpOnly(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); - return; - } - - CaveFieldModuleState[] localModules = scratch.activeModules; - double[] remainingMin = scratch.activeModuleRemainingMin; - double[] remainingMax = scratch.activeModuleRemainingMax; - double[] adaptivePlaneDensity = scratch.adaptivePlaneDensity; - int axisCells = (16 + adaptiveSampleStep - 1) / adaptiveSampleStep; - int axisSamples = axisCells + 1; - int[] adaptivePlaneSampleBounds = scratch.adaptivePlaneSampleBounds; - prepareAdaptivePlaneSampleBounds(scratch, planeColumnIndices, planeCount, adaptiveSampleStep, adaptivePlaneSampleBounds, axisCells); - for (int sampleXIndex = adaptivePlaneSampleBounds[0]; sampleXIndex <= adaptivePlaneSampleBounds[1]; sampleXIndex++) { - int sampleLocalX = Math.min(sampleXIndex * adaptiveSampleStep, 16); - int x = x0 + sampleLocalX; - int rowOffset = sampleXIndex * axisSamples; - for (int sampleZIndex = adaptivePlaneSampleBounds[2]; sampleZIndex <= adaptivePlaneSampleBounds[3]; sampleZIndex++) { - int sampleLocalZ = Math.min(sampleZIndex * adaptiveSampleStep, 16); - adaptivePlaneDensity[rowOffset + sampleZIndex] = latticeDensity(scratch, x, y, z0 + sampleLocalZ); - } - } - - classifyAdaptivePlaneColumnsWarpModulesSampled( - scratch, - x0, - z0, - y, - planeColumnIndices, - planeThresholdLimit, - planeCount, - planeCarve, - adaptiveSampleStep, - adaptiveThresholdMargin, - adaptivePlaneDensity, - axisCells, - axisSamples, - localModules, - activeModuleCount, - remainingMin, - remainingMax - ); - } - - private void classifyAdaptivePlaneColumnsNoWarpNoModules( - CaveCarveScratch scratch, - int x0, - int z0, - int y, - int[] planeColumnIndices, - double[] planeThresholdLimit, - int planeCount, - boolean[] planeCarve, - int adaptiveSampleStep, - double adaptiveThresholdMargin, - double[] adaptivePlaneDensity, - int axisCells, - int axisSamples - ) { - double[] adaptivePlanePrediction = scratch.adaptivePlanePrediction; - double[] adaptivePlaneAmbiguity = scratch.adaptivePlaneAmbiguity; - prepareAdaptivePlaneColumns( - scratch, - planeColumnIndices, - planeCount, - adaptiveSampleStep, - adaptiveThresholdMargin, - adaptivePlaneDensity, - axisCells, - axisSamples, - adaptivePlanePrediction, - adaptivePlaneAmbiguity - ); - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - int columnIndex = planeColumnIndices[planeIndex]; - int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int localZ = columnIndex & 15; - double threshold = planeThresholdLimit[planeIndex] * inverseNormalization; - double predictedDensity = adaptivePlanePrediction[planeIndex]; - double ambiguityMargin = adaptivePlaneAmbiguity[planeIndex]; - if (isAdaptivePlaneSampleAligned(localX, localZ, adaptiveSampleStep)) { - planeCarve[planeIndex] = predictedDensity <= threshold; - continue; - } - if (predictedDensity <= threshold - ambiguityMargin) { - planeCarve[planeIndex] = true; - continue; - } - if (predictedDensity > threshold + ambiguityMargin) { - planeCarve[planeIndex] = false; - continue; - } - if (adaptiveSampleStep >= ADAPTIVE_DEEP_SAMPLE_STEP) { - planeCarve[planeIndex] = predictedDensity <= threshold; - continue; - } - - planeCarve[planeIndex] = classifyDensityPointNoWarpNoModules(x0 + localX, y, z0 + localZ, planeThresholdLimit[planeIndex]); - } - } - - private void classifyAdaptivePlaneColumnsNoWarpModules( - CaveCarveScratch scratch, - int x0, - int z0, - int y, - int[] planeColumnIndices, - double[] planeThresholdLimit, - int planeCount, - boolean[] planeCarve, - int adaptiveSampleStep, - double adaptiveThresholdMargin, - double[] adaptivePlaneDensity, - int axisCells, - int axisSamples, - CaveFieldModuleState[] localModules, - int activeModuleCount, - double[] remainingMin, - double[] remainingMax - ) { - double[] adaptivePlanePrediction = scratch.adaptivePlanePrediction; - double[] adaptivePlaneAmbiguity = scratch.adaptivePlaneAmbiguity; - prepareAdaptivePlaneColumns( - scratch, - planeColumnIndices, - planeCount, - adaptiveSampleStep, - adaptiveThresholdMargin, - adaptivePlaneDensity, - axisCells, - axisSamples, - adaptivePlanePrediction, - adaptivePlaneAmbiguity - ); - double minRemaining = remainingMin[0] * inverseNormalization; - double maxRemaining = remainingMax[0] * inverseNormalization; - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - int columnIndex = planeColumnIndices[planeIndex]; - int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int localZ = columnIndex & 15; - double threshold = planeThresholdLimit[planeIndex] * inverseNormalization; - double predictedDensity = adaptivePlanePrediction[planeIndex]; - double ambiguityMargin = adaptivePlaneAmbiguity[planeIndex]; - if (isAdaptivePlaneSampleAligned(localX, localZ, adaptiveSampleStep)) { - planeCarve[planeIndex] = classifyDensityPointNoWarpModulesFromExactDensity( - x0 + localX, - y, - z0 + localZ, - threshold, - predictedDensity, - localModules, - activeModuleCount, - remainingMin, - remainingMax - ); - continue; - } - if ((predictedDensity + maxRemaining) <= threshold - ambiguityMargin) { - planeCarve[planeIndex] = true; - continue; - } - if ((predictedDensity + minRemaining) > threshold + ambiguityMargin) { - planeCarve[planeIndex] = false; - continue; - } - if (adaptiveSampleStep >= ADAPTIVE_DEEP_SAMPLE_STEP) { - planeCarve[planeIndex] = predictedDensity <= threshold; - continue; - } - - planeCarve[planeIndex] = classifyDensityPointNoWarpModules( - x0 + localX, - y, - z0 + localZ, - planeThresholdLimit[planeIndex], - localModules, - activeModuleCount, - remainingMin, - remainingMax - ); - } - } - - private void classifyDeepAdaptivePlaneFromSamples( - CaveCarveScratch scratch, - int[] planeColumnIndices, - double[] planeThresholdLimit, - int planeCount, - boolean[] planeCarve, - int adaptiveSampleStep, - double[] adaptivePlaneDensity, - int axisCells, - int axisSamples - ) { - prepareAdaptiveGeometry(scratch, adaptiveSampleStep, axisCells, axisSamples); - int[] adaptiveCellZ = scratch.adaptiveCellZ; - int[] adaptiveRow0 = scratch.adaptiveRow0; - int[] adaptiveRow1 = scratch.adaptiveRow1; - double[] adaptiveTx = scratch.adaptiveTx; - double[] adaptiveTz = scratch.adaptiveTz; - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - int columnIndex = planeColumnIndices[planeIndex]; - int cellZ = adaptiveCellZ[columnIndex]; - int row0 = adaptiveRow0[columnIndex]; - int row1 = adaptiveRow1[columnIndex]; - double tx = adaptiveTx[columnIndex]; - double tz = adaptiveTz[columnIndex]; - double d00 = adaptivePlaneDensity[row0 + cellZ]; - double d01 = adaptivePlaneDensity[row0 + cellZ + 1]; - double d10 = adaptivePlaneDensity[row1 + cellZ]; - double d11 = adaptivePlaneDensity[row1 + cellZ + 1]; - double dx0 = d00 + ((d10 - d00) * tx); - double dx1 = d01 + ((d11 - d01) * tx); - double predictedDensity = dx0 + ((dx1 - dx0) * tz); - planeCarve[planeIndex] = predictedDensity <= planeThresholdLimit[planeIndex] * inverseNormalization; - } - } - - private void classifyAdaptivePlaneColumnsWarpOnly( - CaveCarveScratch scratch, - int x0, - int z0, - int y, - int[] planeColumnIndices, - double[] planeThresholdLimit, - int planeCount, - boolean[] planeCarve, - int adaptiveSampleStep, - double adaptiveThresholdMargin, - double[] adaptivePlaneDensity, - int axisCells, - int axisSamples - ) { - double[] adaptivePlanePrediction = scratch.adaptivePlanePrediction; - double[] adaptivePlaneAmbiguity = scratch.adaptivePlaneAmbiguity; - prepareAdaptivePlaneColumns( - scratch, - planeColumnIndices, - planeCount, - adaptiveSampleStep, - adaptiveThresholdMargin, - adaptivePlaneDensity, - axisCells, - axisSamples, - adaptivePlanePrediction, - adaptivePlaneAmbiguity - ); - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - int columnIndex = planeColumnIndices[planeIndex]; - int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int localZ = columnIndex & 15; - double threshold = planeThresholdLimit[planeIndex] * inverseNormalization; - double predictedDensity = adaptivePlanePrediction[planeIndex]; - double ambiguityMargin = adaptivePlaneAmbiguity[planeIndex]; - if (isAdaptivePlaneSampleAligned(localX, localZ, adaptiveSampleStep)) { - planeCarve[planeIndex] = predictedDensity <= threshold; - continue; - } - if (predictedDensity <= threshold - ambiguityMargin) { - planeCarve[planeIndex] = true; - continue; - } - if (predictedDensity > threshold + ambiguityMargin) { - planeCarve[planeIndex] = false; - continue; - } - if (adaptiveSampleStep >= ADAPTIVE_DEEP_SAMPLE_STEP) { - planeCarve[planeIndex] = predictedDensity <= threshold; - continue; - } - - planeCarve[planeIndex] = classifyDensityPointWarpOnly(scratch, x0 + localX, y, z0 + localZ, planeThresholdLimit[planeIndex]); - } - } - - private void classifyAdaptivePlaneColumnsWarpModules( - CaveCarveScratch scratch, - int x0, - int z0, - int y, - int[] planeColumnIndices, - double[] planeThresholdLimit, - int planeCount, - boolean[] planeCarve, - int adaptiveSampleStep, - double adaptiveThresholdMargin, - double[] adaptivePlaneDensity, - int axisCells, - int axisSamples, - CaveFieldModuleState[] localModules, - int activeModuleCount, - double[] remainingMin, - double[] remainingMax - ) { - double[] adaptivePlanePrediction = scratch.adaptivePlanePrediction; - double[] adaptivePlaneAmbiguity = scratch.adaptivePlaneAmbiguity; - prepareAdaptivePlaneColumns( - scratch, - planeColumnIndices, - planeCount, - adaptiveSampleStep, - adaptiveThresholdMargin, - adaptivePlaneDensity, - axisCells, - axisSamples, - adaptivePlanePrediction, - adaptivePlaneAmbiguity - ); - double minRemaining = remainingMin[0] * inverseNormalization; - double maxRemaining = remainingMax[0] * inverseNormalization; - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - int columnIndex = planeColumnIndices[planeIndex]; - int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int localZ = columnIndex & 15; - double threshold = planeThresholdLimit[planeIndex] * inverseNormalization; - double predictedDensity = adaptivePlanePrediction[planeIndex]; - double ambiguityMargin = adaptivePlaneAmbiguity[planeIndex]; - if (isAdaptivePlaneSampleAligned(localX, localZ, adaptiveSampleStep)) { - planeCarve[planeIndex] = classifyDensityPointWarpModulesFromExactDensity( - scratch, - x0 + localX, - y, - z0 + localZ, - threshold, - predictedDensity, - localModules, - activeModuleCount, - remainingMin, - remainingMax - ); - continue; - } - if ((predictedDensity + maxRemaining) <= threshold - ambiguityMargin) { - planeCarve[planeIndex] = true; - continue; - } - if ((predictedDensity + minRemaining) > threshold + ambiguityMargin) { - planeCarve[planeIndex] = false; - continue; - } - - planeCarve[planeIndex] = classifyDensityPointWarpModules( - scratch, - x0 + localX, - y, - z0 + localZ, - planeThresholdLimit[planeIndex], - localModules, - activeModuleCount, - remainingMin, - remainingMax - ); - } - } - - private void classifyAdaptivePlaneColumnsWarpModulesSampled( - CaveCarveScratch scratch, - int x0, - int z0, - int y, - int[] planeColumnIndices, - double[] planeThresholdLimit, - int planeCount, - boolean[] planeCarve, - int adaptiveSampleStep, - double adaptiveThresholdMargin, - double[] adaptivePlaneDensity, - int axisCells, - int axisSamples, - CaveFieldModuleState[] localModules, - int activeModuleCount, - double[] remainingMin, - double[] remainingMax - ) { - if (adaptiveSampleStep >= ADAPTIVE_DEEP_SAMPLE_STEP) { - classifyDeepAdaptivePlaneFromSamples( - scratch, - planeColumnIndices, - planeThresholdLimit, - planeCount, - planeCarve, - adaptiveSampleStep, - adaptivePlaneDensity, - axisCells, - axisSamples - ); - return; - } - - double[] adaptivePlanePrediction = scratch.adaptivePlanePrediction; - double[] adaptivePlaneAmbiguity = scratch.adaptivePlaneAmbiguity; - prepareAdaptivePlaneColumns( - scratch, - planeColumnIndices, - planeCount, - adaptiveSampleStep, - adaptiveThresholdMargin, - adaptivePlaneDensity, - axisCells, - axisSamples, - adaptivePlanePrediction, - adaptivePlaneAmbiguity - ); - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - int columnIndex = planeColumnIndices[planeIndex]; - int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int localZ = columnIndex & 15; - double threshold = planeThresholdLimit[planeIndex] * inverseNormalization; - double predictedDensity = adaptivePlanePrediction[planeIndex]; - double ambiguityMargin = adaptivePlaneAmbiguity[planeIndex]; - if (isAdaptivePlaneSampleAligned(localX, localZ, adaptiveSampleStep)) { - planeCarve[planeIndex] = predictedDensity <= threshold; - continue; - } - if (predictedDensity <= threshold - ambiguityMargin) { - planeCarve[planeIndex] = true; - continue; - } - if (predictedDensity > threshold + ambiguityMargin) { - planeCarve[planeIndex] = false; - continue; - } - if (adaptiveSampleStep >= ADAPTIVE_DEEP_SAMPLE_STEP) { - planeCarve[planeIndex] = predictedDensity <= threshold; - continue; - } - - planeCarve[planeIndex] = classifyDensityPointWarpModules( - scratch, - x0 + localX, - y, - z0 + localZ, - planeThresholdLimit[planeIndex], - localModules, - activeModuleCount, - remainingMin, - remainingMax - ); - } - } - - private boolean classifyDensityPointNoWarpNoModules(int x, int y, int z, double thresholdLimit) { - double density = baseDensity.sampleSigned3D(x, y, z) * baseWeight; - if ((density + detailMinContribution) > thresholdLimit) { - return false; - } - if ((density + detailMaxContribution) <= thresholdLimit) { - return true; - } - - density += detailDensity.sampleSigned3D(x, y, z) * detailWeight; - return density <= thresholdLimit; - } - - private boolean classifyDensityPointNoWarpModules( - int x, - int y, - int z, - double thresholdLimit, - CaveFieldModuleState[] localModules, - int activeModuleCount, - double[] remainingMin, - double[] remainingMax - ) { - if (activeModuleCount == 0) { - return classifyDensityPointNoWarpNoModules(x, y, z, thresholdLimit); - } - - double density = baseDensity.sampleSigned3D(x, y, z) * baseWeight; - if ((density + detailMinContribution + remainingMin[0]) > thresholdLimit) { - return false; - } - if ((density + detailMaxContribution + remainingMax[0]) <= thresholdLimit) { - return true; - } - - density += detailDensity.sampleSigned3D(x, y, z) * detailWeight; - if ((density + remainingMin[0]) > thresholdLimit) { - return false; - } - if ((density + remainingMax[0]) <= thresholdLimit) { - return true; - } - - for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { - density += localModules[moduleIndex].sample(x, y, z); - if ((density + remainingMin[moduleIndex + 1]) > thresholdLimit) { - return false; - } - if ((density + remainingMax[moduleIndex + 1]) <= thresholdLimit) { - return true; - } - } - - return density <= thresholdLimit; - } - - private int snapWarp(int c) { - int g = warpResolution; - if (g <= 1) { - return c; - } - if ((g & (g - 1)) == 0) { - return c & -g; - } - return Math.floorDiv(c, g) * g; - } - - private boolean classifyDensityPointWarpOnly(CaveCarveScratch scratch, int x, int y, int z, double thresholdLimit) { - int sx = snapWarp(x); - int sy = snapWarp(y); - int sz = snapWarp(z); - int warpSlot = prepareWarpSample(scratch, sx, sy, sz); - double warpA = scratch.warpCacheA[warpSlot]; - double warpB = scratch.warpCacheB[warpSlot]; - double warpedX = x + (warpA * warpStrength); - double warpedY = y + (warpB * warpStrength); - double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); - double density = baseDensity.sampleSigned3D(warpedX, warpedY, warpedZ) * baseWeight; - if ((density + detailMinContribution) > thresholdLimit) { - return false; - } - if ((density + detailMaxContribution) <= thresholdLimit) { - return true; - } - - density += detailDensity.sampleSigned3D(warpedX, warpedY, warpedZ) * detailWeight; - return density <= thresholdLimit; - } - - private boolean classifyDensityPointWarpModules( - CaveCarveScratch scratch, - int x, - int y, - int z, - double thresholdLimit, - CaveFieldModuleState[] localModules, - int activeModuleCount, - double[] remainingMin, - double[] remainingMax - ) { - if (activeModuleCount == 0) { - return classifyDensityPointWarpOnly(scratch, x, y, z, thresholdLimit); - } - - int sx = snapWarp(x); - int sy = snapWarp(y); - int sz = snapWarp(z); - int warpSlot = prepareWarpSample(scratch, sx, sy, sz); - double warpA = scratch.warpCacheA[warpSlot]; - double warpB = scratch.warpCacheB[warpSlot]; - double warpedX = x + (warpA * warpStrength); - double warpedY = y + (warpB * warpStrength); - double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); - double density = baseDensity.sampleSigned3D(warpedX, warpedY, warpedZ) * baseWeight; - if ((density + detailMinContribution + remainingMin[0]) > thresholdLimit) { - return false; - } - if ((density + detailMaxContribution + remainingMax[0]) <= thresholdLimit) { - return true; - } - - density += detailDensity.sampleSigned3D(warpedX, warpedY, warpedZ) * detailWeight; - if ((density + remainingMin[0]) > thresholdLimit) { - return false; - } - if ((density + remainingMax[0]) <= thresholdLimit) { - return true; - } - - for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { - density += localModules[moduleIndex].sample(warpedX, warpedY, warpedZ); - if ((density + remainingMin[moduleIndex + 1]) > thresholdLimit) { - return false; - } - if ((density + remainingMax[moduleIndex + 1]) <= thresholdLimit) { - return true; - } - } - - return density <= thresholdLimit; - } - - private boolean classifyDensityPointNoWarpModulesFromExactDensity( - int x, - int y, - int z, - double threshold, - double density, - CaveFieldModuleState[] localModules, - int activeModuleCount, - double[] remainingMin, - double[] remainingMax - ) { - if (activeModuleCount == 0) { - return density <= threshold; - } - - double minRemaining = remainingMin[0] * inverseNormalization; - double maxRemaining = remainingMax[0] * inverseNormalization; - if ((density + minRemaining) > threshold) { - return false; - } - if ((density + maxRemaining) <= threshold) { - return true; - } - - for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { - density += localModules[moduleIndex].sample(x, y, z) * inverseNormalization; - if ((density + (remainingMin[moduleIndex + 1] * inverseNormalization)) > threshold) { - return false; - } - if ((density + (remainingMax[moduleIndex + 1] * inverseNormalization)) <= threshold) { - return true; - } - } - - return density <= threshold; - } - - private boolean classifyDensityPointWarpModulesFromExactDensity( - CaveCarveScratch scratch, - int x, - int y, - int z, - double threshold, - double density, - CaveFieldModuleState[] localModules, - int activeModuleCount, - double[] remainingMin, - double[] remainingMax - ) { - if (activeModuleCount == 0) { - return density <= threshold; - } - - double minRemaining = remainingMin[0] * inverseNormalization; - double maxRemaining = remainingMax[0] * inverseNormalization; - if ((density + minRemaining) > threshold) { - return false; - } - if ((density + maxRemaining) <= threshold) { - return true; - } - - int sx = snapWarp(x); - int sy = snapWarp(y); - int sz = snapWarp(z); - int warpSlot = prepareWarpSample(scratch, sx, sy, sz); - double warpA = scratch.warpCacheA[warpSlot]; - double warpB = scratch.warpCacheB[warpSlot]; - double warpedX = x + (warpA * warpStrength); - double warpedY = y + (warpB * warpStrength); - double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); - for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { - density += localModules[moduleIndex].sample(warpedX, warpedY, warpedZ) * inverseNormalization; - if ((density + (remainingMin[moduleIndex + 1] * inverseNormalization)) > threshold) { - return false; - } - if ((density + (remainingMax[moduleIndex + 1] * inverseNormalization)) <= threshold) { - return true; - } - } - - return density <= threshold; - } - - private boolean isAdaptivePlaneSampleAligned(int localX, int localZ, int adaptiveSampleStep) { - if ((adaptiveSampleStep & (adaptiveSampleStep - 1)) == 0) { - int mask = adaptiveSampleStep - 1; - return (localX & mask) == 0 && (localZ & mask) == 0; - } - return localX % adaptiveSampleStep == 0 && localZ % adaptiveSampleStep == 0; - } - - private void prepareAdaptivePlaneSampleBounds( - CaveCarveScratch scratch, - int[] planeColumnIndices, - int planeCount, - int adaptiveSampleStep, - int[] adaptivePlaneSampleBounds, - int axisCells - ) { - prepareAdaptiveGeometry(scratch, adaptiveSampleStep, axisCells, axisCells + 1); - int[] adaptiveCellX = scratch.adaptiveCellX; - int[] adaptiveCellZ = scratch.adaptiveCellZ; - int minSampleX = axisCells; - int maxSampleX = 0; - int minSampleZ = axisCells; - int maxSampleZ = 0; - - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - int columnIndex = planeColumnIndices[planeIndex]; - int sampleX = adaptiveCellX[columnIndex]; - int sampleZ = adaptiveCellZ[columnIndex]; - if (sampleX < minSampleX) { - minSampleX = sampleX; - } - if (sampleX + 1 > maxSampleX) { - maxSampleX = sampleX + 1; - } - if (sampleZ < minSampleZ) { - minSampleZ = sampleZ; - } - if (sampleZ + 1 > maxSampleZ) { - maxSampleZ = sampleZ + 1; - } - } - - adaptivePlaneSampleBounds[0] = minSampleX; - adaptivePlaneSampleBounds[1] = maxSampleX; - adaptivePlaneSampleBounds[2] = minSampleZ; - adaptivePlaneSampleBounds[3] = maxSampleZ; - } - - private void prepareAdaptivePlaneColumns( - CaveCarveScratch scratch, - int[] planeColumnIndices, - int planeCount, - int adaptiveSampleStep, - double adaptiveThresholdMargin, - double[] adaptivePlaneDensity, - int axisCells, - int axisSamples, - double[] adaptivePlanePrediction, - double[] adaptivePlaneAmbiguity - ) { - prepareAdaptiveGeometry(scratch, adaptiveSampleStep, axisCells, axisSamples); - int[] adaptiveCellZ = scratch.adaptiveCellZ; - int[] adaptiveRow0 = scratch.adaptiveRow0; - int[] adaptiveRow1 = scratch.adaptiveRow1; - double[] adaptiveTx = scratch.adaptiveTx; - double[] adaptiveTz = scratch.adaptiveTz; - for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { - int columnIndex = planeColumnIndices[planeIndex]; - int cellZ = adaptiveCellZ[columnIndex]; - int row0 = adaptiveRow0[columnIndex]; - int row1 = adaptiveRow1[columnIndex]; - double tx = adaptiveTx[columnIndex]; - double tz = adaptiveTz[columnIndex]; - double d00 = adaptivePlaneDensity[row0 + cellZ]; - double d01 = adaptivePlaneDensity[row0 + cellZ + 1]; - double d10 = adaptivePlaneDensity[row1 + cellZ]; - double d11 = adaptivePlaneDensity[row1 + cellZ + 1]; - double dx0 = d00 + ((d10 - d00) * tx); - double dx1 = d01 + ((d11 - d01) * tx); - adaptivePlanePrediction[planeIndex] = dx0 + ((dx1 - dx0) * tz); - double minDensity = Math.min(Math.min(d00, d01), Math.min(d10, d11)); - double maxDensity = Math.max(Math.max(d00, d01), Math.max(d10, d11)); - adaptivePlaneAmbiguity[planeIndex] = adaptiveThresholdMargin + ((maxDensity - minDensity) * ADAPTIVE_LOCAL_RANGE_SCALE); - } - } - - private void prepareAdaptiveGeometry(CaveCarveScratch scratch, int adaptiveSampleStep, int axisCells, int axisSamples) { - if (scratch.adaptiveGeometryStep == adaptiveSampleStep && scratch.adaptiveGeometryAxisCells == axisCells) { - return; - } - - for (int columnIndex = 0; columnIndex < 256; columnIndex++) { - int localX = columnIndex >> 4; - int localZ = columnIndex & 15; - int cellX = Math.min(localX / adaptiveSampleStep, axisCells - 1); - int cellZ = Math.min(localZ / adaptiveSampleStep, axisCells - 1); - int x0 = cellX * adaptiveSampleStep; - int z0 = cellZ * adaptiveSampleStep; - int x1 = Math.min(x0 + adaptiveSampleStep, 16); - int z1 = Math.min(z0 + adaptiveSampleStep, 16); - scratch.adaptiveCellX[columnIndex] = cellX; - scratch.adaptiveCellZ[columnIndex] = cellZ; - scratch.adaptiveRow0[columnIndex] = cellX * axisSamples; - scratch.adaptiveRow1[columnIndex] = (cellX + 1) * axisSamples; - scratch.adaptiveTx[columnIndex] = x1 == x0 ? 0D : (localX - x0) / (double) (x1 - x0); - scratch.adaptiveTz[columnIndex] = z1 == z0 ? 0D : (localZ - z0) / (double) (z1 - z0); - } - - scratch.adaptiveGeometryStep = adaptiveSampleStep; - scratch.adaptiveGeometryAxisCells = axisCells; - } - - private double latticeDensity(CaveCarveScratch scratch, int x, int y, int z) { - int latticeMask = (1 << CaveDensityGrid.LATTICE_SHIFT) - 1; - if (((x | z) & latticeMask) != 0) { - return samplePlaneDensity(scratch, x, y, z); - } - int latticeX = x >> CaveDensityGrid.LATTICE_SHIFT; - int latticeZ = z >> CaveDensityGrid.LATTICE_SHIFT; - int slot = ((latticeX & 3) << 2) | (latticeZ & 3); - CaveDensityGrid.Column column = parallelDensity ? scratch.densityColumns[slot] : null; - if (column == null || !column.matches(densityOwner, latticeX, latticeZ)) { - column = densityGrid.column(densityOwner, densityMaximumY + 1, latticeX, latticeZ); - if (parallelDensity) { - scratch.densityColumns[slot] = column; - } - } - if (column == null) { - return samplePlaneDensity(scratch, x, y, z); - } - double cached = column.get(y); - if (!Double.isNaN(cached)) { - return cached; - } - double density = samplePlaneDensity(scratch, x, y, z); - column.set(y, density); - return density; - } - - private double samplePlaneDensity(CaveCarveScratch scratch, int x, int y, int z) { - if (!hasWarp) { - return sampleDensityNoWarpNoModules(x, y, z); - } - int activeModuleCount = hasModules ? prepareActiveModules(scratch, y) : 0; - if (activeModuleCount == 0) { - return sampleDensityWarpOnly(scratch, x, y, z); - } - return sampleDensityWarpModules(scratch, x, y, z, scratch.activeModules, activeModuleCount); - } - - private double sampleDensityNoWarpNoModules(int x, int y, int z) { - double density = baseDensity.sampleSigned3D(x, y, z) * baseWeight; - density += detailDensity.sampleSigned3D(x, y, z) * detailWeight; - return density * inverseNormalization; - } - - private double sampleDensityNoWarpModules(CaveCarveScratch scratch, int x, int y, int z) { - int activeModuleCount = prepareActiveModules(scratch, y); - if (activeModuleCount == 0) { - return sampleDensityNoWarpNoModules(x, y, z); - } - - CaveFieldModuleState[] localModules = scratch.activeModules; - double density = baseDensity.sampleSigned3D(x, y, z) * baseWeight; - density += detailDensity.sampleSigned3D(x, y, z) * detailWeight; - for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { - CaveFieldModuleState module = localModules[moduleIndex]; - double moduleDensity = module.density.sampleSigned3D(x, y, z) - module.threshold; - if (module.invert) { - moduleDensity = -moduleDensity; - } - - density += moduleDensity * module.weight; - } - - return density * inverseNormalization; - } - - private double sampleDensityWarpOnly(CaveCarveScratch scratch, int x, int y, int z) { - int sx = snapWarp(x); - int sy = snapWarp(y); - int sz = snapWarp(z); - int warpSlot = prepareWarpSample(scratch, sx, sy, sz); - double warpA = scratch.warpCacheA[warpSlot]; - double warpB = scratch.warpCacheB[warpSlot]; - double warpedX = x + (warpA * warpStrength); - double warpedY = y + (warpB * warpStrength); - double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); - double density = baseDensity.sampleSigned3D(warpedX, warpedY, warpedZ) * baseWeight; - density += detailDensity.sampleSigned3D(warpedX, warpedY, warpedZ) * detailWeight; - return density * inverseNormalization; - } - - private double sampleDensityWarpModules(CaveCarveScratch scratch, int x, int y, int z) { - int activeModuleCount = prepareActiveModules(scratch, y); - if (activeModuleCount == 0) { - return sampleDensityWarpOnly(scratch, x, y, z); - } - - CaveFieldModuleState[] localModules = scratch.activeModules; - return sampleDensityWarpModules(scratch, x, y, z, localModules, activeModuleCount); - } - - private double sampleDensityWarpModules(CaveCarveScratch scratch, int x, int y, int z, CaveFieldModuleState[] localModules, int activeModuleCount) { - int sx = snapWarp(x); - int sy = snapWarp(y); - int sz = snapWarp(z); - int warpSlot = prepareWarpSample(scratch, sx, sy, sz); - double warpA = scratch.warpCacheA[warpSlot]; - double warpB = scratch.warpCacheB[warpSlot]; - double warpedX = x + (warpA * warpStrength); - double warpedY = y + (warpB * warpStrength); - double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); - double density = baseDensity.sampleSigned3D(warpedX, warpedY, warpedZ) * baseWeight; - density += detailDensity.sampleSigned3D(warpedX, warpedY, warpedZ) * detailWeight; - for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { - CaveFieldModuleState module = localModules[moduleIndex]; - double moduleDensity = module.density.sampleSigned3D(warpedX, warpedY, warpedZ) - module.threshold; - if (module.invert) { - moduleDensity = -moduleDensity; - } - - density += moduleDensity * module.weight; - } - - return density * inverseNormalization; - } - - private int prepareWarpSample(CaveCarveScratch scratch, int sx, int sy, int sz) { - int slot = mixWarpKey(sx, sy, sz) & (scratch.warpCacheX.length - 1); - if (scratch.warpCacheSet[slot] - && scratch.warpCacheX[slot] == sx - && scratch.warpCacheY[slot] == sy - && scratch.warpCacheZ[slot] == sz) { - return slot; - } - - scratch.warpCacheSet[slot] = true; - scratch.warpCacheX[slot] = sx; - scratch.warpCacheY[slot] = sy; - scratch.warpCacheZ[slot] = sz; - scratch.warpCacheA[slot] = warpDensity.sampleSigned3D(sx, sy, sz); - scratch.warpCacheB[slot] = warpDensity.sampleSigned3D(sx + 31.37D, sy - 17.21D, sz + 23.91D); - return slot; - } - - private static int mixWarpKey(int sx, int sy, int sz) { - int hash = sx * 73428767; - hash ^= sy * 91227153; - hash ^= sz * 43828939; - hash ^= hash >>> 16; - return hash; - } - - private int prepareActiveModules(CaveCarveScratch scratch, int y) { - CaveFieldModuleState[] configuredModules = modules; - int configuredCount = configuredModules.length; - if (configuredCount == 0) { - return 0; - } - - // Pure function of (y, modules). modules is final and the scratch is per carver per thread, - // so the band selection and the remaining-contribution prefix sums only change when y does. - if (scratch.activeModulesY == y) { - return scratch.activeModuleCount; - } - - if (scratch.activeModules.length < configuredCount) { - scratch.activeModules = new CaveFieldModuleState[configuredCount]; - } - - int activeCount = 0; - for (int moduleIndex = 0; moduleIndex < configuredCount; moduleIndex++) { - CaveFieldModuleState module = configuredModules[moduleIndex]; - if (y < module.minY || y > module.maxY) { - continue; - } - - scratch.activeModules[activeCount] = module; - activeCount++; - } - - if (scratch.activeModuleRemainingMin.length < activeCount + 1) { - scratch.activeModuleRemainingMin = new double[activeCount + 1]; - scratch.activeModuleRemainingMax = new double[activeCount + 1]; - } - - scratch.activeModuleRemainingMin[activeCount] = 0D; - scratch.activeModuleRemainingMax[activeCount] = 0D; - for (int moduleIndex = activeCount - 1; moduleIndex >= 0; moduleIndex--) { - CaveFieldModuleState module = scratch.activeModules[moduleIndex]; - scratch.activeModuleRemainingMin[moduleIndex] = scratch.activeModuleRemainingMin[moduleIndex + 1] + module.minContribution; - scratch.activeModuleRemainingMax[moduleIndex] = scratch.activeModuleRemainingMax[moduleIndex + 1] + module.maxContribution; - } - - scratch.activeModulesY = y; - scratch.activeModuleCount = activeCount; - return activeCount; - } - - private MatterSlice resolveCavernSlice(CaveCarveScratch scratch, MantleChunk chunk, int sectionIndex) { - @SuppressWarnings("unchecked") - MatterSlice cachedSlice = (MatterSlice) scratch.sectionSlices[sectionIndex]; - if (cachedSlice != null) { - return cachedSlice; - } - - Matter sectionMatter = scratch.sectionMatter[sectionIndex]; - if (sectionMatter == null) { - sectionMatter = chunk.getOrCreate(sectionIndex); - scratch.sectionMatter[sectionIndex] = sectionMatter; - } - - MatterSlice resolvedSlice = sectionMatter.slice(MatterCavern.class); - scratch.sectionSlices[sectionIndex] = resolvedSlice; - return resolvedSlice; - } - - private MatterCavern[] prepareMatterByYTable(CaveCarveScratch scratch, int minY, int maxY) { - int size = Math.max(0, maxY - minY + 1); - if (scratch.matterByY.length < size) { - scratch.matterByY = new MatterCavern[size]; - } - - MatterCavern[] matterByY = scratch.matterByY; - boolean allowLava = profile.isAllowLava(); - int lavaHeight = engine.getDimension().getCaveLavaHeight(); - - for (int y = minY; y <= maxY; y++) { - int offset = y - minY; - if (allowLava && y <= lavaHeight) { - matterByY[offset] = carveLava; - continue; - } - if (!allowLava && y <= lavaHeight) { - matterByY[offset] = carveForcedAir; - continue; - } - - matterByY[offset] = carveAir; - } - - return matterByY; - } - - private MatterCavern resolveMatter(CaveCarveScratch scratch, MatterCavern verticalMatter, int x, int y, int z, - int columnIndex, int[] fluidMaxY, double localThreshold) { - if (verticalMatter != carveLava - && y <= fluidMaxY[columnIndex] - && isAquiferCandidate(scratch, x, y, z, localThreshold)) { - return carveFluid; - } - return verticalMatter; - } - - private boolean isAquiferCandidate(CaveCarveScratch scratch, int x, int y, int z, double localThreshold) { - double depthFactor = Math.max(0D, Math.min(1.5D, (fluidHeight - y) / 48D)); - double cutoff = 0.35D + (depthFactor * 0.2D); - if (detailDensity.sampleSigned3D(x, y * 0.5D, z) <= cutoff) { - return false; - } - return !fluidRequiresFloor || hasAquiferCupSupport(scratch, x, y, z, localThreshold); - } - - private boolean isAquiferCandidate(int x, int y, int z, double localThreshold) { - return isAquiferCandidate(scratchCache.get(), x, y, z, localThreshold); - } - - private boolean hasAquiferCupSupport(CaveCarveScratch scratch, int x, int y, int z, double threshold) { - int floorY = Math.max(0, y - 1); - int deepFloorY = Math.max(0, y - 2); - int aboveY = Math.min(aquiferCeilingY, y + 1); - if (!isDensitySolid(scratch, x, floorY, z, threshold)) { - return false; - } - if (!isDensitySolid(scratch, x, deepFloorY, z, threshold - 0.05D)) { - return false; - } - - int support = 0; - int misses = 0; - if (isDensitySolid(scratch, x + 1, y, z, threshold)) { - support++; - } else { - misses++; - } - if (isDensitySolid(scratch, x - 1, y, z, threshold)) { - support++; - } else if (++misses >= 2) { - return false; - } - if (isDensitySolid(scratch, x, y, z + 1, threshold)) { - support++; - } else if (++misses >= 2) { - return false; - } - if (isDensitySolid(scratch, x, y, z - 1, threshold)) { - support++; - if (support >= 4) { - return true; - } - } else if (++misses >= 2) { - return false; - } - if (isDensitySolid(scratch, x, aboveY, z, threshold)) { - support++; - } - return support >= 4; - } - - private boolean isDensitySolid(CaveCarveScratch scratch, int x, int y, int z, double threshold) { - return sampleDensityOptimized(scratch, x, y, z) > threshold; - } - - private void writeCavern(MatterSlice cavernSlice, int localX, int y, int localZ, - MatterCavern matter, CaveFluidSupportPlan fluidSupportPlan) { - cavernSlice.set(localX, y & 15, localZ, matter); - if (fluidSupportPlan != null && matter == carveFluid) { - fluidSupportPlan.add(localX, y, localZ, carveFluid, carveAir); - } - } - - private void prepareSectionCaches(CaveCarveScratch scratch, int minY, int maxY) { - int minSection = Math.max(0, PowerOfTwoCoordinates.floorDivPow2(minY, 4)); - int maxSection = Math.max(minSection, PowerOfTwoCoordinates.floorDivPow2(maxY, 4)); - int requiredSections = maxSection + 1; - if (scratch.sectionMatter.length < requiredSections) { - scratch.sectionMatter = new Matter[requiredSections]; - scratch.sectionSlices = new MatterSlice[requiredSections]; - return; - } - - for (int section = minSection; section <= maxSection; section++) { - scratch.sectionMatter[section] = null; - scratch.sectionSlices[section] = null; - } - } - - private double clampColumnWeight(double weight) { - if (Double.isNaN(weight) || Double.isInfinite(weight)) { - return 0D; - } - - if (weight <= 0D) { - return 0D; - } - - if (weight >= 1D) { - return 1D; - } - - return weight; - } - - private double applySurfaceCeilingFade( - CaveCarveScratch scratch, - double threshold, - int columnIndex, - int y, - int minY - ) { - if (!scratch.surfaceCeilingColumn[columnIndex]) { - return threshold; - } - - int ceilingDistance = scratch.columnMaxY[columnIndex] - y; - if (ceilingDistance < 0 || ceilingDistance >= SURFACE_CEILING_FADE_DEPTH) { - return threshold; - } - - double closureThreshold = scratch.surfaceClosureThreshold[y - minY]; - if (threshold <= closureThreshold) { - return threshold; - } - - double progress = ceilingDistance / (double) SURFACE_CEILING_FADE_DEPTH; - double smooth = progress * progress * (3D - (2D * progress)); - return closureThreshold + ((threshold - closureThreshold) * smooth); - } - - private void prepareSurfaceClosureThresholdTable(CaveCarveScratch scratch, int minY, int maxY) { - int size = Math.max(0, maxY - minY + 1); - if (scratch.surfaceClosureThreshold.length < size) { - scratch.surfaceClosureThreshold = new double[size]; - } - - double baseMinimum = -Math.abs(baseWeight) - Math.abs(detailWeight); - for (int y = minY; y <= maxY; y++) { - double minimumDensity = baseMinimum; - for (CaveFieldModuleState module : modules) { - if (y < module.minY || y > module.maxY) { - continue; - } - minimumDensity += Math.min(module.minContribution, module.maxContribution); - } - scratch.surfaceClosureThreshold[y - minY] = - (minimumDensity * inverseNormalization) - SURFACE_CEILING_SOLID_EPSILON; - } - } - - private double[] prepareVerticalEdgeFadeTable(CaveCarveScratch scratch, int minY, int maxY) { - int size = Math.max(0, maxY - minY + 1); - if (scratch.verticalEdgeFade.length < size) { - scratch.verticalEdgeFade = new double[size]; - } - - double[] verticalEdgeFade = scratch.verticalEdgeFade; - int fadeRange = Math.max(0, profile.getVerticalEdgeFade()); - double fadeStrength = Math.max(0D, profile.getVerticalEdgeFadeStrength()); - if (size <= 0 || fadeRange <= 0 || maxY <= minY || fadeStrength <= 0D) { - Arrays.fill(verticalEdgeFade, 0, size, 0D); - return verticalEdgeFade; - } - - for (int y = minY; y <= maxY; y++) { - int floorDistance = y - minY; - int ceilingDistance = maxY - y; - int edgeDistance = Math.min(floorDistance, ceilingDistance); - int offsetIndex = y - minY; - if (edgeDistance >= fadeRange) { - verticalEdgeFade[offsetIndex] = 0D; - continue; - } - - double t = Math.max(0D, Math.min(1D, edgeDistance / (double) fadeRange)); - double smooth = t * t * (3D - (2D * t)); - verticalEdgeFade[offsetIndex] = (1D - smooth) * fadeStrength; - } - - return verticalEdgeFade; - } - - private record WarpFieldKey(CaveFieldKey field) { - } - - private record ModuleFieldKey(CaveFieldKey field, int minY, int maxY, long weight, long threshold, boolean invert) { - } - - private record DensityFieldKey(boolean warp, CaveFieldKey warpField, long warpStrength, CaveFieldKey base, long baseWeight, - CaveFieldKey detail, long detailWeight, long inverseNormalization, - List modules) { - } -} diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/ListedCave.java b/core/src/main/java/art/arcane/iris/generation/mantle/ListedCave.java new file mode 100644 index 000000000..220927ca2 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/mantle/ListedCave.java @@ -0,0 +1,109 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.mantle; + +import art.arcane.iris.generation.cave.IrisCave; +import art.arcane.iris.generation.cave.field.AquiferPockets; +import art.arcane.iris.generation.cave.field.CaveCarver; +import art.arcane.iris.generation.cave.field.NoiseFactory; +import art.arcane.volmlib.util.matter.MatterCavern; + +import java.util.Arrays; + +/** + * One cave of a pack ready to carve one world: its carver, and the cells it writes into the mantle, which hold the + * cave's biome. Cells say what fills a carved block: air, fluid from the dimension's palette, lava, or air that no + * hydrology may fill. + */ +final class ListedCave { + private static final byte LIQUID_AIR = 0; + private static final byte LIQUID_FLUID = 1; + private static final byte LIQUID_LAVA = 2; + private static final byte LIQUID_FORCED_AIR = 3; + + private final String key; + private final IrisCave cave; + private final CaveWorld world; + private final CaveCarver carver; + private final AquiferPockets aquiferPockets; + private final MatterCavern air; + private final MatterCavern fluid; + private final MatterCavern lava; + private final MatterCavern forcedAir; + + /** + * @param biomeKey the cave biome that paints the cave's walls, or empty to leave them to the cave biome of the place + */ + ListedCave(String key, IrisCave cave, String biomeKey, CaveWorld world, NoiseFactory noise) { + long seed = CaveCarver.seedOf(world.carveSeed(), key); + this.key = key; + this.cave = cave; + this.world = world; + this.carver = new CaveCarver(cave, noise, seed, world.minHeight(), world.height()); + this.aquiferPockets = new AquiferPockets(noise, seed); + this.air = new MatterCavern(true, biomeKey, LIQUID_AIR); + this.fluid = new MatterCavern(true, biomeKey, LIQUID_FLUID); + this.lava = new MatterCavern(true, biomeKey, LIQUID_LAVA); + this.forcedAir = new MatterCavern(true, biomeKey, LIQUID_FORCED_AIR); + } + + String key() { + return key; + } + + CaveCarver carver() { + return carver; + } + + MatterCavern air() { + return air; + } + + MatterCavern fluid() { + return fluid; + } + + boolean fluidNeedsFloor() { + return cave.fluidRequiresFloor(); + } + + /** Fills {@code fluidTopY} with the highest height at which the cave may hold fluid in each column, below the surface. */ + void fillFluidTops(int[] surfaceY, int[] fluidTopY) { + if (!cave.allowFluid()) { + Arrays.fill(fluidTopY, Integer.MIN_VALUE); + return; + } + int minDepth = cave.fluidMinDepthBelowSurface(); + for (int column = 0; column < fluidTopY.length; column++) { + fluidTopY[column] = Math.min(world.fluidHeight(), surfaceY[column] - minDepth); + } + } + + /** What fills the carved block at height {@code y}, which lies at most {@code fluidTopY} up where the cave may hold fluid. */ + MatterCavern cellAt(int worldX, int y, int worldZ, int fluidTopY) { + boolean belowLavaHeight = y <= world.caveLavaHeight(); + if (belowLavaHeight && cave.allowLava()) { + return lava; + } + if (y <= fluidTopY && aquiferPockets.holdsFluidAt(worldX, y, worldZ, world.fluidHeight())) { + return fluid; + } + return belowLavaHeight ? forcedAir : air; + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/ListedCaveCarving.java b/core/src/main/java/art/arcane/iris/generation/mantle/ListedCaveCarving.java new file mode 100644 index 000000000..2b3a25b09 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/mantle/ListedCaveCarving.java @@ -0,0 +1,347 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.mantle; + +import art.arcane.iris.generation.biome.IrisBiome; +import art.arcane.iris.generation.cave.IrisCave; +import art.arcane.iris.generation.cave.field.CaveCarver.ChunkColumns; +import art.arcane.iris.generation.cave.field.ChunkLattice; +import art.arcane.iris.generation.cave.field.DepthRange; +import art.arcane.iris.generation.cave.field.HeightBand; +import art.arcane.iris.generation.cave.field.NoiseFactory; +import art.arcane.iris.generation.mantle.CaveListing.ListedColumns; +import art.arcane.iris.generation.mantle.CaveTerrain.CaveBand; +import art.arcane.iris.generation.mantle.CaveTerrain.CavePlace; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; +import art.arcane.volmlib.util.matter.MatterCavern; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import java.util.function.Predicate; + +/** + * Plans one chunk's caves for {@link MantleCarvingComponent}: every cave the dimension, the regions and the biomes around + * the chunk list under {@code caves}, and the caves of the cave biomes that carving bands put at some heights. The lists + * of a column add up, and a cave narrows to nothing over a few blocks where the columns that list it end. One per + * world, keeping a carver per cave. + * + *

A block that several caves carve takes its fluid and biome from the first of them in list order: the dimension's + * caves, then the region's, the surface biome's and the cave biome's, then the carving bands'. Caves are carved last to + * first, so the first listed writes last. + */ +final class ListedCaveCarving { + private static final int CHUNK_SIZE = 16; + private static final int CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE; + /** Which caves a column lists is read every fourth block, one ring beyond the chunk, and smoothed between the readings. */ + private static final int LISTING_STEP_BLOCKS = ChunkLattice.CELL_BLOCKS; + private static final int LISTINGS_PER_AXIS = ChunkLattice.CELLS_PER_CHUNK_AXIS + 3; + private static final int LISTINGS = LISTINGS_PER_AXIS * LISTINGS_PER_AXIS; + private static final int WEIGHTS_PER_AXIS = ChunkLattice.CELLS_PER_CHUNK_AXIS + 1; + private static final int LISTINGS_PER_WEIGHT = 9; + private static final double[] LISTED_EVERYWHERE = filled(1D); + + /** What listed cave carving reports to the pack's author. */ + interface Problems { + void missingCave(String caveKey); + + void missingCaveBiome(String caveKey, String biomeKey); + } + + private final List dimensionCaves; + private final boolean onlyDimensionLists; + private final CaveWorld world; + private final NoiseFactory noise; + private final Function caveOf; + private final Predicate biomeExists; + private final Problems problems; + private final Map> caves = new ConcurrentHashMap<>(); + + /** + * @param dimensionCaves the caves the dimension lists + * @param onlyDimensionLists whether no region or biome lists a cave, which spares reading the biomes around each chunk + * @param caveOf the cave a key names in the pack, or null + * @param biomeExists whether the pack has the biome a key names + */ + ListedCaveCarving(List dimensionCaves, boolean onlyDimensionLists, CaveWorld world, NoiseFactory noise, + Function caveOf, Predicate biomeExists, Problems problems) { + this.dimensionCaves = List.copyOf(dimensionCaves); + this.onlyDimensionLists = onlyDimensionLists; + this.world = world; + this.noise = noise; + this.caveOf = caveOf; + this.biomeExists = biomeExists; + this.problems = problems; + } + + /** The caves that carve in the chunk at chunk coordinates {@code chunkX}, {@code chunkZ}, with how much each column lists them. */ + CaveListing list(CaveTerrain terrain, int chunkX, int chunkZ) { + int originX = PowerOfTwoCoordinates.chunkToBlock(chunkX); + int originZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); + List listed = new ArrayList<>(); + boolean opensToSurface = false; + for (Map.Entry entry : columnCaves(terrain, originX, originZ).entrySet()) { + ListedCave cave = caveOf(entry.getKey()); + if (cave == null) { + continue; + } + opensToSurface |= cave.carver().opensToSurface(); + listed.add(new ListedColumns(cave, entry.getValue(), HeightBand.UNLIMITED)); + } + for (ListedColumns inBand : bandCaves(terrain.bandsOf(chunkX, chunkZ))) { + opensToSurface |= inBand.cave().carver().opensToSurface(); + listed.add(inBand); + } + return new CaveListing(List.copyOf(listed), opensToSurface); + } + + /** Carves the listed caves of the chunk into {@code sink}, under the surface and the fluids and ceilings that surround it. */ + void carve(CaveListing listing, int chunkX, int chunkZ, ChunkSurface surface, CaveCellSink sink, CaveFluidSupportPlan fluidSupport) { + boolean[] sealed = sealedColumns(surface.fluidBoundaries()); + for (int index = listing.caves().size() - 1; index >= 0; index--) { + ListedColumns listed = listing.caves().get(index); + ChunkColumns columns = new ChunkColumns(surface.surfaceY(), listed.weight(), sealed, surface.ceilings(), DepthRange.OWN); + carveCave(listed.cave(), columns, listed.band(), surface, chunkX, chunkZ, sink, fluidSupport); + } + } + + /** + * Carves the listed caves into the terrain of an upper dimension, which hangs from the top of the world down to + * {@code lowestUpperY}: through all heights of the dimension instead of the ones each cave writes, closed under the + * top of the world. + */ + void carveBeneathUpperTerrain(CaveListing listing, int chunkX, int chunkZ, int lowestUpperY, CaveCellSink sink, CaveFluidSupportPlan fluidSupport) { + int[] worldTop = new int[CHUNK_AREA]; + Arrays.fill(worldTop, world.height() - 1); + boolean[] sealed = new boolean[CHUNK_AREA]; + Arrays.fill(sealed, true); + ChunkSurface surface = new ChunkSurface(worldTop, null, null); + for (int index = listing.caves().size() - 1; index >= 0; index--) { + ListedColumns listed = listing.caves().get(index); + HeightBand band = new HeightBand(Math.max(listed.band().lowestY(), lowestUpperY), Math.min(listed.band().highestY(), world.height() - 1)); + if (band.lowestY() > band.highestY()) { + continue; + } + ChunkColumns columns = new ChunkColumns(worldTop, listed.weight(), sealed, null, DepthRange.WHOLE_DIMENSION); + carveCave(listed.cave(), columns, band, surface, chunkX, chunkZ, sink, fluidSupport); + } + } + + private void carveCave(ListedCave cave, ChunkColumns columns, HeightBand band, ChunkSurface surface, int chunkX, int chunkZ, + CaveCellSink sink, CaveFluidSupportPlan fluidSupport) { + int originX = PowerOfTwoCoordinates.chunkToBlock(chunkX); + int originZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); + int[] fluidTopY = new int[CHUNK_AREA]; + cave.fillFluidTops(surface.surfaceY(), fluidTopY); + MatterCavern fluid = cave.fluid(); + cave.carver().carve(originX, originZ, columns, band, (localX, y, localZ) -> { + int column = PowerOfTwoCoordinates.packLocal16(localX, localZ); + if (SurfaceFluidBoundaryPlan.protects(surface.fluidBoundaries(), column, y)) { + return; + } + MatterCavern cell = cave.cellAt(originX + localX, y, originZ + localZ, fluidTopY[column]); + sink.set(localX, y, localZ, cell); + if (cell == fluid && cave.fluidNeedsFloor()) { + fluidSupport.add(localX, y, localZ, fluid, cave.air()); + } + }); + } + + /** Columns whose surface lies under or next to a fluid, where no cave may open the surface. */ + private static boolean[] sealedColumns(long[] fluidBoundaries) { + boolean[] sealed = new boolean[CHUNK_AREA]; + if (fluidBoundaries == null) { + return sealed; + } + for (int column = 0; column < CHUNK_AREA; column++) { + sealed[column] = SurfaceFluidBoundaryPlan.startY(fluidBoundaries[column]) != SurfaceFluidBoundaryPlan.NO_BOUNDARY; + } + return sealed; + } + + /** + * The caves any column of the chunk lists, in the order they were first listed, each with how much every column + * lists it: 1 well inside the columns that do, 0 well outside, in between across their border. + */ + private Map columnCaves(CaveTerrain terrain, int originX, int originZ) { + Map weights = new LinkedHashMap<>(); + if (onlyDimensionLists) { + dimensionCaves.stream().filter(ListedCaveCarving::isKey).forEach(key -> weights.put(key, LISTED_EVERYWHERE)); + return weights; + } + Map listedAt = new LinkedHashMap<>(); + for (int listingX = 0; listingX < LISTINGS_PER_AXIS; listingX++) { + int worldX = originX + ((listingX - 1) * LISTING_STEP_BLOCKS); + for (int listingZ = 0; listingZ < LISTINGS_PER_AXIS; listingZ++) { + int worldZ = originZ + ((listingZ - 1) * LISTING_STEP_BLOCKS); + int listing = (listingX * LISTINGS_PER_AXIS) + listingZ; + for (String key : listingAt(terrain.placeAt(worldX, worldZ))) { + listedAt.computeIfAbsent(key, absent -> new boolean[LISTINGS])[listing] = true; + } + } + } + listedAt.forEach((key, listed) -> weights.put(key, columnWeights(listed))); + return weights; + } + + /** Every cave the dimension, the region, the surface biome and the cave biome of a column list between them, once each. */ + private List listingAt(CavePlace place) { + List listed = new ArrayList<>(dimensionCaves); + addListed(listed, place.region() == null ? null : place.region().getCaves()); + addListed(listed, place.surfaceBiome() == null ? null : place.surfaceBiome().getCaves()); + addListed(listed, place.caveBiome() == null ? null : place.caveBiome().getCaves()); + return listed.stream().filter(ListedCaveCarving::isKey).distinct().toList(); + } + + private static void addListed(List listed, KList keys) { + if (keys != null) { + listed.addAll(keys); + } + } + + private static boolean isKey(String key) { + return key != null && !key.isBlank(); + } + + private List bandCaves(List bands) { + List listed = new ArrayList<>(); + for (CaveBand band : bands) { + HeightBand heights = new HeightBand(band.lowestWorldY() - world.minHeight(), band.highestWorldY() - world.minHeight()); + for (Map.Entry entry : bandWeights(band).entrySet()) { + ListedCave cave = caveOf(entry.getKey()); + if (cave != null) { + listed.add(new ListedColumns(cave, entry.getValue(), heights)); + } + } + } + return listed; + } + + private static Map bandWeights(CaveBand band) { + Map weights = new LinkedHashMap<>(); + for (int column = 0; column < CHUNK_AREA; column++) { + IrisBiome biome = band.biomeByColumn()[column]; + if (biome == null || biome.getCaves() == null) { + continue; + } + for (String key : biome.getCaves()) { + if (isKey(key)) { + weights.computeIfAbsent(key, absent -> new double[CHUNK_AREA])[column] = 1D; + } + } + } + return weights; + } + + private static double[] columnWeights(boolean[] listedAt) { + if (isAllTrue(listedAt)) { + return LISTED_EVERYWHERE; + } + double[] latticeWeight = new double[WEIGHTS_PER_AXIS * WEIGHTS_PER_AXIS]; + for (int weightX = 0; weightX < WEIGHTS_PER_AXIS; weightX++) { + for (int weightZ = 0; weightZ < WEIGHTS_PER_AXIS; weightZ++) { + latticeWeight[(weightX * WEIGHTS_PER_AXIS) + weightZ] = listingsAround(listedAt, weightX, weightZ) / (double) LISTINGS_PER_WEIGHT; + } + } + double[] columnWeight = new double[CHUNK_AREA]; + for (int localX = 0; localX < CHUNK_SIZE; localX++) { + int weightX = localX / LISTING_STEP_BLOCKS; + double shareX = (localX % LISTING_STEP_BLOCKS) / (double) LISTING_STEP_BLOCKS; + for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { + int weightZ = localZ / LISTING_STEP_BLOCKS; + double shareZ = (localZ % LISTING_STEP_BLOCKS) / (double) LISTING_STEP_BLOCKS; + double west = between(latticeWeight[(weightX * WEIGHTS_PER_AXIS) + weightZ], latticeWeight[(weightX * WEIGHTS_PER_AXIS) + weightZ + 1], shareZ); + double east = between(latticeWeight[((weightX + 1) * WEIGHTS_PER_AXIS) + weightZ], latticeWeight[((weightX + 1) * WEIGHTS_PER_AXIS) + weightZ + 1], shareZ); + columnWeight[PowerOfTwoCoordinates.packLocal16(localX, localZ)] = between(west, east, shareX); + } + } + return columnWeight; + } + + /** How many of the nine readings on and around a lattice point list the cave. The point's own reading is one ring in. */ + private static int listingsAround(boolean[] listedAt, int weightX, int weightZ) { + int count = 0; + for (int listingX = weightX; listingX <= weightX + 2; listingX++) { + for (int listingZ = weightZ; listingZ <= weightZ + 2; listingZ++) { + if (listedAt[(listingX * LISTINGS_PER_AXIS) + listingZ]) { + count++; + } + } + } + return count; + } + + private static double between(double from, double to, double share) { + return from + ((to - from) * share); + } + + private static boolean isAllTrue(boolean[] values) { + for (boolean value : values) { + if (!value) { + return false; + } + } + return true; + } + + private static double[] filled(double value) { + double[] values = new double[CHUNK_AREA]; + Arrays.fill(values, value); + return values; + } + + /** The cave with this key, ready to carve; null when the pack has no such cave, which is reported once. */ + private ListedCave caveOf(String key) { + return caves.computeIfAbsent(key, this::loadCave).orElse(null); + } + + private Optional loadCave(String key) { + IrisCave cave = caveOf.apply(key); + if (cave == null) { + problems.missingCave(key); + return Optional.empty(); + } + return Optional.of(new ListedCave(key, cave, wallBiomeKey(key, cave), world, noise)); + } + + private String wallBiomeKey(String caveKey, IrisCave cave) { + String biomeKey = cave.biome(); + if (biomeKey.isBlank() || biomeExists.test(biomeKey)) { + return biomeKey; + } + problems.missingCaveBiome(caveKey, biomeKey); + return ""; + } + + /** + * What a chunk's carving is held back by. + * + * @param surfaceY the height of the surface in each column, indexed as {@code (localX << 4) | localZ} + * @param fluidBoundaries per column, the heights over which a surface fluid keeps the carving out; null for none + * @param ceilings per column, the highest height caves may carve at, where hydrology keeps cave pools below it; null for none + */ + record ChunkSurface(int[] surfaceY, long[] fluidBoundaries, int[] ceilings) { + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/MantleCarvingComponent.java b/core/src/main/java/art/arcane/iris/generation/mantle/MantleCarvingComponent.java index 7250cfbb8..f17994995 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/MantleCarvingComponent.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/MantleCarvingComponent.java @@ -18,85 +18,77 @@ package art.arcane.iris.generation.mantle; -import art.arcane.iris.generation.runtime.IrisComplex; -import art.arcane.iris.generation.subterrain.SubterrainPlanner; -import art.arcane.iris.generation.subterrain.SubterrainRasterizer; -import art.arcane.volmlib.util.matter.MatterCavern; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.generation.runtime.UpperDimensionContext; import art.arcane.iris.generation.biome.IrisBiome; -import art.arcane.iris.generation.cave.IrisCaveProfile; -import art.arcane.iris.generation.terrain.IrisDimensionCarvingEntry; -import art.arcane.iris.generation.terrain.IrisDimensionCarvingResolver; -import art.arcane.iris.generation.terrain.IrisRegion; -import art.arcane.iris.pack.value.IrisRange; -import art.arcane.volmlib.nativelib.terrain.NativeBlockState; import art.arcane.iris.generation.block.B; +import art.arcane.iris.generation.cave.field.CngNoiseFactory; import art.arcane.iris.generation.context.ChunkContext; -import art.arcane.volmlib.util.stream.ProceduralStream; +import art.arcane.iris.generation.mantle.ListedCaveCarving.ChunkSurface; +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.generation.runtime.IrisComplex; +import art.arcane.iris.generation.runtime.UpperDimensionContext; import art.arcane.iris.generation.stream.BakedDoubleStream; import art.arcane.iris.generation.stream.BakedStream; import art.arcane.iris.generation.stream.ChunkFillableDoubleStream2D; -import art.arcane.iris.generation.simd.SimdSupport; -import art.arcane.volmlib.util.documentation.ChunkCoordinates; +import art.arcane.iris.generation.subterrain.SubterrainPlanner; +import art.arcane.iris.generation.subterrain.SubterrainRasterizer; +import art.arcane.iris.generation.terrain.IrisDimension; +import art.arcane.iris.generation.terrain.IrisDimensionCarvingResolver; +import art.arcane.iris.generation.terrain.IrisRegion; +import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.volmlib.nativelib.terrain.NativeBlockState; import art.arcane.volmlib.util.mantle.flag.ReservedFlag; +import art.arcane.volmlib.util.mantle.runtime.MantleChunk; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; +import art.arcane.volmlib.util.matter.Matter; +import art.arcane.volmlib.util.matter.MatterCavern; import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; +import art.arcane.volmlib.util.stream.ProceduralStream; -import java.util.TreeSet; -import java.util.ArrayList; import java.util.Arrays; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; @ComponentFlag(ReservedFlag.CARVED) public class MantleCarvingComponent extends IrisMantleComponent { private static final int CHUNK_SIZE = 16; private static final int CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE; - private static final int BLEND_RADIUS = 3; - private static final int FIELD_SIZE = CHUNK_SIZE + (BLEND_RADIUS * 2); - private static final double MIN_WEIGHT = 0.08D; - private static final double THRESHOLD_PENALTY = 0.24D; - private static final int MAX_POOLED_WEIGHT_BUFFERS = 64; - /** Lattice columns kept for neighbouring chunks: about 3 KB each on land, roughly 50 MB when full. */ - private static final int DENSITY_GRID_COLUMNS = 16_384; - private static final int KERNEL_WIDTH = (BLEND_RADIUS * 2) + 1; - private static final int KERNEL_SIZE = KERNEL_WIDTH * KERNEL_WIDTH; - private static final int[] KERNEL_DX = new int[KERNEL_SIZE]; - private static final int[] KERNEL_DZ = new int[KERNEL_SIZE]; - private static final double[] KERNEL_WEIGHT = new double[KERNEL_SIZE]; + /** Columns read beyond the chunk to find where surface fluids reach, which no cave may open under. */ + private static final int FLUID_BOUNDARY_PADDING = 3; + private static final int FIELD_SIZE = CHUNK_SIZE + (FLUID_BOUNDARY_PADDING * 2); + /** Loose rock is swept this far below the surface where a cave opens to it. */ + private static final int LOOSE_ROCK_SWEEP_DEPTH_BLOCKS = 16; + /** An upper dimension's terrain needs this much room under the top of the world to be carved. */ + private static final int MINIMUM_UPPER_TERRAIN_THICKNESS_BLOCKS = 2; private static final int NEIGHBOURS = 9; private static final int[] NEIGHBOUR_DX = new int[NEIGHBOURS]; private static final int[] NEIGHBOUR_DZ = new int[NEIGHBOURS]; private static final long[][] NEIGHBOUR_COLUMNS = new long[NEIGHBOURS][4]; private static final int[] FIELD_NEIGHBOUR = new int[FIELD_SIZE * FIELD_SIZE]; private static final int[] FIELD_COLUMN = new int[FIELD_SIZE * FIELD_SIZE]; - private static final ThreadLocal BLEND_SCRATCH = ThreadLocal.withInitial(BlendScratch::new); + private static final ThreadLocal CHUNK_SCRATCH = ThreadLocal.withInitial(ChunkScratch::new); + private static final ListedCaveCarving.Problems CAVE_PROBLEMS = new ListedCaveCarving.Problems() { + @Override + public void missingCave(String caveKey) { + IrisLogging.warnOnce("missing-cave:" + caveKey, "Cave '%s' is listed under caves but the pack has no readable caves/%s.json", caveKey, caveKey); + } - private final Object profileCarverLock = new Object(); - private final CaveDensityGrid densityGrid = new CaveDensityGrid(DENSITY_GRID_COLUMNS); - private volatile Map profileCarvers = new IdentityHashMap<>(); + @Override + public void missingCaveBiome(String caveKey, String biomeKey) { + IrisLogging.warnOnce("missing-cave-biome:" + caveKey + ":" + biomeKey, "Cave '%s' names the biome '%s', which the pack does not have", caveKey, biomeKey); + } + }; + + private final Object caveCarvingLock = new Object(); + private volatile ListedCaveCarving caveCarving; static { - int kernelIndex = 0; - for (int offsetX = -BLEND_RADIUS; offsetX <= BLEND_RADIUS; offsetX++) { - for (int offsetZ = -BLEND_RADIUS; offsetZ <= BLEND_RADIUS; offsetZ++) { - KERNEL_DX[kernelIndex] = offsetX; - KERNEL_DZ[kernelIndex] = offsetZ; - int edgeDistance = Math.max(Math.abs(offsetX), Math.abs(offsetZ)); - KERNEL_WEIGHT[kernelIndex] = (BLEND_RADIUS + 1D) - edgeDistance; - kernelIndex++; - } - } for (int neighbour = 0; neighbour < NEIGHBOURS; neighbour++) { NEIGHBOUR_DX[neighbour] = (neighbour / 3) - 1; NEIGHBOUR_DZ[neighbour] = (neighbour % 3) - 1; } for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) { - int offsetX = fieldX - BLEND_RADIUS; + int offsetX = fieldX - FLUID_BOUNDARY_PADDING; for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) { - int offsetZ = fieldZ - BLEND_RADIUS; + int offsetZ = fieldZ - FLUID_BOUNDARY_PADDING; int neighbour = ((Math.floorDiv(offsetX, CHUNK_SIZE) + 1) * 3) + Math.floorDiv(offsetZ, CHUNK_SIZE) + 1; int column = ((offsetZ & (CHUNK_SIZE - 1)) << 4) | (offsetX & (CHUNK_SIZE - 1)); int fieldIndex = (fieldX * FIELD_SIZE) + fieldZ; @@ -119,12 +111,10 @@ public class MantleCarvingComponent extends IrisMantleComponent { @Override public void hotload() { super.hotload(); - // Hotload swaps in fresh IrisCaveProfile instances (identity keys), so retained - // entries would strand a full carver set pinning the closed IrisData per reload. - // Carvers rebuild deterministically from the carve seed, so output is unchanged. - synchronized (profileCarverLock) { - profileCarvers = new IdentityHashMap<>(); - densityGrid.clear(); + // Carvers hold the pack's caves and the closed IrisData of the previous load. They rebuild + // deterministically from the carve seed, so output is unchanged. + synchronized (caveCarvingLock) { + caveCarving = null; } } @@ -134,10 +124,10 @@ public class MantleCarvingComponent extends IrisMantleComponent { if (!complex.allowsMantleChunkWrite(x, z)) { return; } - BlendScratch previous = BLEND_SCRATCH.get(); - BlendScratch scratch = previous.inUse ? new BlendScratch() : previous; + ChunkScratch previous = CHUNK_SCRATCH.get(); + ChunkScratch scratch = previous.inUse ? new ChunkScratch() : previous; if (scratch != previous) { - BLEND_SCRATCH.set(scratch); + CHUNK_SCRATCH.set(scratch); } scratch.inUse = true; try { @@ -145,52 +135,59 @@ public class MantleCarvingComponent extends IrisMantleComponent { } finally { scratch.release(); if (scratch != previous) { - BLEND_SCRATCH.set(previous); + CHUNK_SCRATCH.set(previous); } } } - private void generateLayer(MantleWriter writer, int x, int z, ChunkContext context, BlendScratch blendScratch) { + private void generateLayer(MantleWriter writer, int x, int z, ChunkContext context, ChunkScratch scratch) { IrisComplex complex = context.getComplex(); - IrisDimensionCarvingResolver.State resolverState = blendScratch.resolverState; - int[] chunkSurfaceHeights = prepareChunkSurfaceHeights(x, z, context, blendScratch.chunkSurfaceHeights); + Engine engine = getEngineMantle().getEngine(); + int[] chunkSurfaceHeights = prepareChunkSurfaceHeights(x, z, context, scratch.chunkSurfaceHeights); + int[] caveCeilings = CaveCeilingMask.fill(x, z, complex.getHydrologyRuntime()::raster, + scratch.caveCeilingField, scratch.caveCeilings) ? scratch.caveCeilings : null; + ListedCaveCarving carving = caveCarving(); PrecisionStopwatch resolveStopwatch = PrecisionStopwatch.start(); - List weightedProfiles = resolveWeightedProfiles(x, z, complex, resolverState); - getEngineMantle().getEngine().getMetrics().getCarveResolve().put(resolveStopwatch.getMilliseconds()); - long[] surfaceFluidBoundaries = blendScratch.surfaceFluidBoundaries; + CaveListing listing = carving.list(new EngineCaveTerrain(engine, complex, scratch.resolverState), x, z); + engine.getMetrics().getCarveResolve().put(resolveStopwatch.getMilliseconds()); + carveListing(carving, listing, writer, x, z, complex, chunkSurfaceHeights, caveCeilings, scratch); + rasterizeSubterrain(writer, x, z, complex, caveCeilings); + } + + private void carveListing(ListedCaveCarving carving, CaveListing listing, MantleWriter writer, int x, int z, IrisComplex complex, + int[] chunkSurfaceHeights, int[] caveCeilings, ChunkScratch scratch) { + MantleChunk chunk = listing.isEmpty() ? null : writer.acquireChunk(x, z); + if (chunk == null) { + return; + } + PrecisionStopwatch applyStopwatch = PrecisionStopwatch.start(); + long[] surfaceFluidBoundaries = fillSurfaceFluidBoundaries(complex, x, z, chunkSurfaceHeights, scratch); + CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan(); + CaveCellSink sink = new MantleCaveCellSink(chunk, writer.getMantle().getWorldHeight()); + carving.carve(listing, x, z, new ChunkSurface(chunkSurfaceHeights, surfaceFluidBoundaries, caveCeilings), sink, fluidSupportPlan); + UpperDimensionContext upperContext = getEngineMantle().getEngine().getUpperContext(); + if (upperContext != null && getDimension().isUpperDimensionCarving()) { + carveUpperTerrain(upperContext, carving, listing, sink, x, z, fluidSupportPlan); + } + fluidSupportPlan.resolve(chunk); + int sweepDepth = listing.opensToSurface() ? LOOSE_ROCK_SWEEP_DEPTH_BLOCKS : 0; + CarveOrphanSweep.sweepChunk(chunk, chunkSurfaceHeights, sweepDepth, writer.getMantle().getWorldHeight() - 1, + surfaceFluidBoundaries, caveCeilings); + getEngineMantle().getEngine().getMetrics().getCarveApply().put(applyStopwatch.getMilliseconds()); + } + + private long[] fillSurfaceFluidBoundaries(IrisComplex complex, int x, int z, int[] chunkSurfaceHeights, ChunkScratch scratch) { + prefillFluidBoundaryField(complex, x, z, scratch); SurfaceFluidBoundaryPlan.fill( chunkSurfaceHeights, - blendScratch.fieldSurfaceHeights, - blendScratch.fieldHasFluid, - blendScratch.fieldFluidHeights, + scratch.fieldSurfaceHeights, + scratch.fieldHasFluid, + scratch.fieldFluidHeights, FIELD_SIZE, - BLEND_RADIUS, - surfaceFluidBoundaries + FLUID_BOUNDARY_PADDING, + scratch.surfaceFluidBoundaries ); - int[] caveCeilings = CaveCeilingMask.fill(x, z, complex.getHydrologyRuntime()::raster, - blendScratch.caveCeilingField, blendScratch.caveCeilings) ? blendScratch.caveCeilings : null; - CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan(); - for (WeightedProfile weightedProfile : weightedProfiles) { - carveProfile(weightedProfile, writer, x, z, chunkSurfaceHeights, surfaceFluidBoundaries, caveCeilings, fluidSupportPlan); - } - - UpperDimensionContext upperCtx = getEngineMantle().getEngine().getUpperContext(); - if (upperCtx != null && getDimension().isUpperDimensionCarving()) { - carveUpperTerrain(upperCtx, weightedProfiles, writer, x, z, fluidSupportPlan); - } - fluidSupportPlan.resolve(writer.acquireChunk(x, z)); - - if (!weightedProfiles.isEmpty()) { - CarveOrphanSweep.sweepChunk( - writer.acquireChunk(x, z), - chunkSurfaceHeights, - maxSurfaceBreakDepth(weightedProfiles), - writer.getMantle().getWorldHeight() - 1, - surfaceFluidBoundaries, - caveCeilings - ); - } - rasterizeSubterrain(writer, x, z, complex, caveCeilings); + return scratch.surfaceFluidBoundaries; } private void rasterizeSubterrain(MantleWriter writer, int chunkX, int chunkZ, IrisComplex complex, int[] caveCeilings) { @@ -223,366 +220,74 @@ public class MantleCarvingComponent extends IrisMantleComponent { }); } - private static int maxSurfaceBreakDepth(List weightedProfiles) { - int maxDepth = 0; - for (WeightedProfile weightedProfile : weightedProfiles) { - maxDepth = Math.max(maxDepth, Math.max(0, weightedProfile.profile.getSurfaceBreakDepth())); - } - return maxDepth; - } - - @ChunkCoordinates - private void carveProfile(WeightedProfile weightedProfile, MantleWriter writer, int cx, int cz, - int[] chunkSurfaceHeights, long[] surfaceFluidBoundaries, int[] caveCeilings, - CaveFluidSupportPlan fluidSupportPlan) { - IrisCaveCarver3D carver = getCarver(weightedProfile.profile); - carver.carve(writer, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY, - weightedProfile.worldYRange, chunkSurfaceHeights, surfaceFluidBoundaries, caveCeilings, null, fluidSupportPlan); - } - - private void carveUpperTerrain(UpperDimensionContext upperCtx, List normalProfiles, - MantleWriter writer, int cx, int cz, - CaveFluidSupportPlan fluidSupportPlan) { + private void carveUpperTerrain(UpperDimensionContext upperContext, ListedCaveCarving carving, CaveListing listing, CaveCellSink sink, + int cx, int cz, CaveFluidSupportPlan fluidSupportPlan) { int chunkHeight = getEngineMantle().getEngine().getHeight(); - int worldMinHeight = getEngineMantle().getEngine().getWorld().minHeight(); int baseX = PowerOfTwoCoordinates.chunkToBlock(cx); int baseZ = PowerOfTwoCoordinates.chunkToBlock(cz); - - int minUpperSurfaceY = chunkHeight; + int lowestUpperSurfaceY = chunkHeight; for (int localX = 0; localX < CHUNK_SIZE; localX++) { - int worldX = baseX + localX; for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { - int worldZ = baseZ + localZ; - int upperY = upperCtx.getEffectiveSurfaceY(worldX, worldZ); - if (upperY < minUpperSurfaceY) { - minUpperSurfaceY = upperY; - } + lowestUpperSurfaceY = Math.min(lowestUpperSurfaceY, upperContext.getEffectiveSurfaceY(baseX + localX, baseZ + localZ)); } } - - if (minUpperSurfaceY >= chunkHeight - 2) { + if (lowestUpperSurfaceY >= chunkHeight - MINIMUM_UPPER_TERRAIN_THICKNESS_BLOCKS) { return; } + carving.carveBeneathUpperTerrain(listing, cx, cz, lowestUpperSurfaceY, sink, fluidSupportPlan); + } - IrisRange upperYRange = new IrisRange( - minUpperSurfaceY + worldMinHeight, - chunkHeight - 1 + worldMinHeight - ); - IrisRange fullVerticalRange = new IrisRange(0, chunkHeight); - - int[] ceilingSurfaceHeights = new int[CHUNK_AREA]; - Arrays.fill(ceilingSurfaceHeights, chunkHeight - 1); - - for (WeightedProfile weightedProfile : normalProfiles) { - IrisRange constrainedRange; - if (weightedProfile.worldYRange != null) { - double min = Math.max(weightedProfile.worldYRange.getMin(), upperYRange.getMin()); - double max = Math.min(weightedProfile.worldYRange.getMax(), upperYRange.getMax()); - if (min >= max) { - continue; - } - constrainedRange = new IrisRange(min, max); - } else { - constrainedRange = upperYRange; + private ListedCaveCarving caveCarving() { + ListedCaveCarving carving = caveCarving; + if (carving != null) { + return carving; + } + synchronized (caveCarvingLock) { + if (caveCarving == null) { + caveCarving = createCaveCarving(); } - IrisCaveCarver3D carver = getCarver(weightedProfile.profile); - carver.carve(writer, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY, - constrainedRange, ceilingSurfaceHeights, null, null, fullVerticalRange, fluidSupportPlan); + return caveCarving; } } - private List resolveWeightedProfiles(int chunkX, int chunkZ, IrisComplex complex, IrisDimensionCarvingResolver.State resolverState) { - BlendScratch blendScratch = BLEND_SCRATCH.get(); - IrisCaveProfile[] profileField = blendScratch.profileField; - Map columnProfileWeights = blendScratch.columnProfileWeights; - List profileOrder = blendScratch.profileOrder; - IrisCaveProfile[] kernelProfiles = blendScratch.kernelProfiles; - double[] kernelProfileWeights = blendScratch.kernelProfileWeights; - columnProfileWeights.clear(); - profileOrder.clear(); - blendScratch.nextWeightBuffer = 0; - fillProfileField(profileField, chunkX, chunkZ, complex, resolverState, blendScratch); - - for (int localX = 0; localX < CHUNK_SIZE; localX++) { - for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { - int profileCount = 0; - int centerX = localX + BLEND_RADIUS; - int centerZ = localZ + BLEND_RADIUS; - double totalKernelWeight = 0D; - - for (int kernelIndex = 0; kernelIndex < KERNEL_SIZE; kernelIndex++) { - int sampleX = centerX + KERNEL_DX[kernelIndex]; - int sampleZ = centerZ + KERNEL_DZ[kernelIndex]; - IrisCaveProfile profile = profileField[(sampleX * FIELD_SIZE) + sampleZ]; - if (!isProfileEnabled(profile)) { - continue; - } - - double kernelWeight = KERNEL_WEIGHT[kernelIndex]; - int existingIndex = findProfileIndex(kernelProfiles, profileCount, profile); - if (existingIndex >= 0) { - kernelProfileWeights[existingIndex] += kernelWeight; - } else { - kernelProfiles[profileCount] = profile; - kernelProfileWeights[profileCount] = kernelWeight; - profileCount++; - } - totalKernelWeight += kernelWeight; - } - - if (totalKernelWeight <= 0D || profileCount == 0) { - continue; - } - - int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); - for (int profileIndex = 0; profileIndex < profileCount; profileIndex++) { - IrisCaveProfile profile = kernelProfiles[profileIndex]; - double kernelWeight = kernelProfileWeights[profileIndex]; - kernelProfiles[profileIndex] = null; - kernelProfileWeights[profileIndex] = 0D; - - double columnWeight = clampWeight(kernelWeight / totalKernelWeight); - if (columnWeight < MIN_WEIGHT) { - continue; - } - - double[] weights = columnProfileWeights.get(profile); - if (weights == null) { - weights = blendScratch.acquireWeights(); - columnProfileWeights.put(profile, weights); - profileOrder.add(profile); - } - weights[columnIndex] = columnWeight; - } - } - } - - List columnWeightedProfiles = new ArrayList<>(); - for (IrisCaveProfile profile : profileOrder) { - double[] weights = columnProfileWeights.get(profile); - if (weights == null) { - continue; - } - - // averageWeight ranks and orders carve passes, so it must be bit-identical across - // installations: kernels.sum reassociates FP addition under the vector kernel, - // making profile order depend on a JVM flag. max() is order-independent and safe. - double maxWeight = SimdSupport.kernels().max(weights, weights.length); - - if (maxWeight < MIN_WEIGHT) { - continue; - } - - double averageWeight = computeAverageWeight(weights); - columnWeightedProfiles.add(new WeightedProfile(profile, weights, averageWeight, null, columnWeightedProfiles.size())); - } - - columnWeightedProfiles.sort(MantleCarvingComponent::compareByCarveOrder); - List resolvedProfiles = resolveDimensionCarvingProfiles(chunkX, chunkZ, resolverState, blendScratch); - resolvedProfiles.addAll(columnWeightedProfiles); - return resolvedProfiles; - } - - private List resolveDimensionCarvingProfiles(int chunkX, int chunkZ, IrisDimensionCarvingResolver.State resolverState, BlendScratch blendScratch) { - List weightedProfiles = new ArrayList<>(); - List entries = getDimension().getCarving(); - if (entries == null || entries.isEmpty()) { - return weightedProfiles; - } - + private ListedCaveCarving createCaveCarving() { Engine engine = getEngineMantle().getEngine(); - int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX); - int baseZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); - - for (IrisDimensionCarvingEntry entry : entries) { - if (entry == null || !entry.isEnabled()) { - continue; - } - - IrisBiome rootBiome = IrisDimensionCarvingResolver.resolveEntryBiome(engine, entry, resolverState); - if (rootBiome == null) { - continue; - } - - TreeSet boundaries = new TreeSet<>(); - int minimumY = engine.getWorld().minHeight(); - int maximumY = engine.getWorld().maxHeight(); - boundaries.add(minimumY); - boundaries.add(maximumY); - for (IrisDimensionCarvingEntry candidate : entries) { - if (candidate != null && candidate.getWorldYRange() != null) { - boundaries.add(Math.max(minimumY, Math.min(maximumY, (int) Math.ceil(candidate.getWorldYRange().getMin())))); - boundaries.add(Math.max(minimumY, Math.min(maximumY, (int) Math.floor(candidate.getWorldYRange().getMax()) + 1))); - } - } - Integer previous = null; - for (int boundary : boundaries) { - if (previous != null && boundary > previous - && (entry.getWorldYRange() == null || entry.getWorldYRange().contains(previous))) { - Map rootProfileColumnWeights = new IdentityHashMap<>(); - List rootProfileOrder = new ArrayList<>(); - for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { - IrisDimensionCarvingEntry resolvedEntry = IrisDimensionCarvingResolver.resolveFromRoot( - engine, entry, baseX + (columnIndex >> 4), previous, baseZ + (columnIndex & 15), resolverState); - IrisBiome resolvedBiome = IrisDimensionCarvingResolver.resolveEntryBiome(engine, resolvedEntry, resolverState); - IrisCaveProfile profile = resolvedBiome == null ? null : resolvedBiome.getCaveProfile(); - if (!isProfileEnabled(profile)) { - continue; - } - double[] columnWeights = rootProfileColumnWeights.get(profile); - if (columnWeights == null) { - columnWeights = blendScratch.acquireWeights(); - rootProfileColumnWeights.put(profile, columnWeights); - rootProfileOrder.add(profile); - } - columnWeights[columnIndex] = 1D; - } - IrisRange worldYRange = new IrisRange(previous, boundary - 1); - for (IrisCaveProfile profile : rootProfileOrder) { - weightedProfiles.add(new WeightedProfile(profile, rootProfileColumnWeights.get(profile), -1D, worldYRange, weightedProfiles.size())); - } - } - previous = boundary; - } - } - - return weightedProfiles; + IrisDimension dimension = getDimension(); + IrisData data = engine.getData(); + CaveWorld world = new CaveWorld(engine.getWorld().minHeight(), engine.getHeight(), engine.getSeedManager().getCarve(), + dimension.getFluidHeight(), dimension.getCaveLavaHeight()); + return new ListedCaveCarving(dimension.getCaves(), onlyDimensionListsCaves(dimension, data), world, new CngNoiseFactory(data), + key -> data.getCaveLoader().load(key), key -> data.getBiomeLoader().load(key) != null, CAVE_PROBLEMS); } - private void fillProfileField(IrisCaveProfile[] profileField, int chunkX, int chunkZ, IrisComplex complex, IrisDimensionCarvingResolver.State resolverState, BlendScratch blendScratch) { - int startX = PowerOfTwoCoordinates.chunkToBlock(chunkX) - BLEND_RADIUS; - int startZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ) - BLEND_RADIUS; - prefillProfileFieldSamples(chunkX, chunkZ, startX, startZ, complex, blendScratch); - - for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) { - int worldX = startX + fieldX; - for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) { - int worldZ = startZ + fieldZ; - int fieldIndex = (fieldX * FIELD_SIZE) + fieldZ; - profileField[fieldIndex] = resolveColumnProfile( - worldX, - worldZ, - blendScratch.fieldSurfaceHeights[fieldIndex], - blendScratch.fieldRegions[fieldIndex], - blendScratch.fieldSurfaceBiomes[fieldIndex], - blendScratch.fieldCaveBiomes[fieldIndex], - resolverState - ); + /** Whether no region and no biome the dimension reaches lists a cave, so every column lists what the dimension lists. */ + private static boolean onlyDimensionListsCaves(IrisDimension dimension, IrisData data) { + for (IrisRegion region : dimension.getAllRegions(() -> data)) { + if (region != null && !region.getCaves().isEmpty()) { + return false; } } + for (IrisBiome biome : dimension.getReachableBiomes(() -> data)) { + if (biome != null && !biome.getCaves().isEmpty()) { + return false; + } + } + return true; } - private int findProfileIndex(IrisCaveProfile[] profiles, int size, IrisCaveProfile profile) { - for (int index = 0; index < size; index++) { - if (profiles[index] == profile) { - return index; - } - } - - return -1; - } - - private IrisCaveProfile resolveColumnProfile( - int worldX, - int worldZ, - double surfaceHeight, - IrisRegion region, - IrisBiome surfaceBiome, - IrisBiome caveBiome, - IrisDimensionCarvingResolver.State resolverState - ) { - IrisCaveProfile resolved = null; - IrisCaveProfile dimensionProfile = getDimension().getCaveProfile(); - if (isProfileEnabled(dimensionProfile)) { - resolved = dimensionProfile; - } - - if (region != null) { - IrisCaveProfile regionProfile = region.getCaveProfile(); - if (isProfileEnabled(regionProfile)) { - resolved = regionProfile; - } - } - - if (surfaceBiome != null) { - IrisCaveProfile surfaceProfile = surfaceBiome.getCaveProfile(); - if (isProfileEnabled(surfaceProfile)) { - resolved = surfaceProfile; - } - } - - int roundedSurfaceY = (int) Math.round(surfaceHeight); - int sampleY = Math.max(1, roundedSurfaceY - 56); - int worldY = sampleY + getEngineMantle().getEngine().getWorld().minHeight(); - IrisDimensionCarvingEntry rootCarvingEntry = IrisDimensionCarvingResolver.resolveRootEntry(getEngineMantle().getEngine(), worldY, resolverState); - IrisBiome resolvedCarvingBiome = null; - if (rootCarvingEntry != null) { - IrisDimensionCarvingEntry resolvedCarvingEntry = IrisDimensionCarvingResolver.resolveFromRoot(getEngineMantle().getEngine(), rootCarvingEntry, worldX, worldY, worldZ, resolverState); - resolvedCarvingBiome = IrisDimensionCarvingResolver.resolveEntryBiome(getEngineMantle().getEngine(), 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, caveBiome.getCaveMinDepthBelowSurface()); - if (depthBelowSurface < minDepth) { - effectiveCaveBiome = surfaceBiome; - } - } - } - } - - IrisCaveProfile caveProfile = effectiveCaveBiome.getCaveProfile(); - if (isProfileEnabled(caveProfile)) { - resolved = caveProfile; - } - } - - return resolved; - } - - private void prefillProfileFieldSamples(int chunkX, int chunkZ, int startX, int startZ, IrisComplex complex, BlendScratch blendScratch) { - fillFieldHeights(complex.getNaturalHeightStream(), chunkX, chunkZ, startX, startZ, blendScratch); + private void prefillFluidBoundaryField(IrisComplex complex, int chunkX, int chunkZ, ChunkScratch scratch) { + int startX = PowerOfTwoCoordinates.chunkToBlock(chunkX) - FLUID_BOUNDARY_PADDING; + int startZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ) - FLUID_BOUNDARY_PADDING; + fillFieldHeights(complex.getNaturalHeightStream(), chunkX, chunkZ, startX, startZ, scratch); double fluidHeight = complex.getFluidHeight(); - Arrays.fill(blendScratch.fieldFluidHeights, fluidHeight); - fillFieldFluidPresence(complex.getFluidStream(), chunkX, chunkZ, startX, startZ, Math.round(fluidHeight), blendScratch); - fillFieldObjects(complex.getRegionStream(), chunkX, chunkZ, startX, startZ, blendScratch.fieldRegions, blendScratch.neighbourObjects); - fillFieldObjects(complex.getNaturalTrueBiomeStream(), chunkX, chunkZ, startX, startZ, blendScratch.fieldSurfaceBiomes, blendScratch.neighbourObjects); - fillFieldObjects(complex.getCaveBiomeStream(), chunkX, chunkZ, startX, startZ, blendScratch.fieldCaveBiomes, blendScratch.neighbourObjects); + Arrays.fill(scratch.fieldFluidHeights, fluidHeight); + fillFieldFluidPresence(complex.getFluidStream(), chunkX, chunkZ, startX, startZ, Math.round(fluidHeight), scratch); } - @SuppressWarnings("unchecked") - private void fillFieldObjects(ProceduralStream stream, int chunkX, int chunkZ, int startX, int startZ, T[] target, Object[][] neighbourObjects) { - if (stream instanceof BakedStream baked) { - for (int neighbour = 0; neighbour < NEIGHBOURS; neighbour++) { - baked.fillColumns(chunkX + NEIGHBOUR_DX[neighbour], chunkZ + NEIGHBOUR_DZ[neighbour], - NEIGHBOUR_COLUMNS[neighbour], neighbourObjects[neighbour]); - } - for (int fieldIndex = 0; fieldIndex < target.length; fieldIndex++) { - target[fieldIndex] = (T) neighbourObjects[FIELD_NEIGHBOUR[fieldIndex]][FIELD_COLUMN[fieldIndex]]; - } - return; - } - 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.get(worldX, startZ + fieldZ); - } - } - } - - private void fillFieldHeights(ProceduralStream stream, int chunkX, int chunkZ, int startX, int startZ, BlendScratch blendScratch) { - double[] target = blendScratch.fieldSurfaceHeights; + private void fillFieldHeights(ProceduralStream stream, int chunkX, int chunkZ, int startX, int startZ, ChunkScratch scratch) { + double[] target = scratch.fieldSurfaceHeights; if (stream instanceof BakedDoubleStream baked) { - double[][] neighbourHeights = blendScratch.neighbourHeights; + double[][] neighbourHeights = scratch.neighbourHeights; for (int neighbour = 0; neighbour < NEIGHBOURS; neighbour++) { baked.fillColumns(chunkX + NEIGHBOUR_DX[neighbour], chunkZ + NEIGHBOUR_DZ[neighbour], NEIGHBOUR_COLUMNS[neighbour], neighbourHeights[neighbour]); @@ -601,11 +306,11 @@ public class MantleCarvingComponent extends IrisMantleComponent { } private void fillFieldFluidPresence(ProceduralStream stream, int chunkX, int chunkZ, int startX, int startZ, - long roundedFluidHeight, BlendScratch blendScratch) { - double[] surfaceHeights = blendScratch.fieldSurfaceHeights; - boolean[] target = blendScratch.fieldHasFluid; + long roundedFluidHeight, ChunkScratch scratch) { + double[] surfaceHeights = scratch.fieldSurfaceHeights; + boolean[] target = scratch.fieldHasFluid; if (stream instanceof BakedStream baked) { - long[][] submerged = blendScratch.neighbourSubmerged; + long[][] submerged = scratch.neighbourSubmerged; for (long[] columns : submerged) { Arrays.fill(columns, 0L); } @@ -615,7 +320,7 @@ public class MantleCarvingComponent extends IrisMantleComponent { submerged[FIELD_NEIGHBOUR[fieldIndex]][column >>> 6] |= 1L << (column & 63); } } - Object[][] neighbourObjects = blendScratch.neighbourObjects; + Object[][] neighbourObjects = scratch.neighbourObjects; for (int neighbour = 0; neighbour < NEIGHBOURS; neighbour++) { long[] columns = submerged[neighbour]; if ((columns[0] | columns[1] | columns[2] | columns[3]) != 0L) { @@ -639,30 +344,6 @@ public class MantleCarvingComponent extends IrisMantleComponent { } } - private IrisCaveCarver3D getCarver(IrisCaveProfile profile) { - IrisCaveCarver3D carver = profileCarvers.get(profile); - if (carver != null) { - return carver; - } - - IrisCaveCarver3D createdCarver = new IrisCaveCarver3D(getEngineMantle().getEngine(), profile, densityGrid); - synchronized (profileCarverLock) { - IrisCaveCarver3D published = profileCarvers.get(profile); - if (published != null) { - return published; - } - - Map updated = new IdentityHashMap<>(profileCarvers); - updated.put(profile, createdCarver); - profileCarvers = updated; - return createdCarver; - } - } - - private boolean isProfileEnabled(IrisCaveProfile profile) { - return profile != null && profile.isEnabled(); - } - protected int computeRadius() { return 1; } @@ -679,7 +360,7 @@ public class MantleCarvingComponent extends IrisMantleComponent { ProceduralStream naturalHeight = context.getComplex().getNaturalHeightStream(); double[] cachedChunkHeights = null; if (naturalHeight instanceof ChunkFillableDoubleStream2D cachedHeightStream) { - cachedChunkHeights = BLEND_SCRATCH.get().chunkSurfaceHeightSamples; + cachedChunkHeights = CHUNK_SCRATCH.get().chunkSurfaceHeightSamples; cachedHeightStream.fillChunkDoubles(baseX, baseZ, cachedChunkHeights); } for (int localX = 0; localX < CHUNK_SIZE; localX++) { @@ -697,68 +378,11 @@ public class MantleCarvingComponent extends IrisMantleComponent { return surfaceHeights; } - private static int compareByCarveOrder(WeightedProfile a, WeightedProfile b) { - int weightOrder = Double.compare(a.averageWeight, b.averageWeight); - if (weightOrder != 0) { - return weightOrder; - } - return Integer.compare(a.sequence, b.sequence); - } - - private static double computeAverageWeight(double[] weights) { - if (weights == null || weights.length == 0) { - return 0D; - } - double sum = 0D; - for (double weight : weights) { - sum += weight; - } - return sum / CHUNK_AREA; - } - - private static double clampWeight(double value) { - if (Double.isNaN(value) || Double.isInfinite(value)) { - return 0D; - } - if (value <= 0D) { - return 0D; - } - if (value >= 1D) { - return 1D; - } - return value; - } - - private static final class WeightedProfile { - private final IrisCaveProfile profile; - private final double[] columnWeights; - private final double averageWeight; - private final IrisRange worldYRange; - private final int sequence; - - private WeightedProfile(IrisCaveProfile profile, double[] columnWeights, double averageWeight, IrisRange worldYRange, int sequence) { - this.profile = profile; - this.columnWeights = columnWeights; - this.averageWeight = averageWeight; - this.worldYRange = worldYRange; - this.sequence = sequence; - } - } - - private static final class BlendScratch { - private final IrisCaveProfile[] profileField = new IrisCaveProfile[FIELD_SIZE * FIELD_SIZE]; - private final IrisCaveProfile[] kernelProfiles = new IrisCaveProfile[KERNEL_SIZE]; - private final double[] kernelProfileWeights = new double[KERNEL_SIZE]; - private final IdentityHashMap columnProfileWeights = new IdentityHashMap<>(); - private final List weightBuffers = new ArrayList<>(); - private final List profileOrder = new ArrayList<>(); + private static final class ChunkScratch { private final double[] fieldSurfaceHeights = new double[FIELD_SIZE * FIELD_SIZE]; private final double[] fieldFluidHeights = new double[FIELD_SIZE * FIELD_SIZE]; private final boolean[] fieldHasFluid = new boolean[FIELD_SIZE * FIELD_SIZE]; private final long[] surfaceFluidBoundaries = new long[CHUNK_AREA]; - 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 double[] chunkSurfaceHeightSamples = new double[CHUNK_AREA]; private final int[] caveCeilingField = new int[CaveCeilingMask.FIELD * CaveCeilingMask.FIELD]; @@ -767,35 +391,12 @@ public class MantleCarvingComponent extends IrisMantleComponent { private final Object[][] neighbourObjects = new Object[NEIGHBOURS][CHUNK_AREA]; private final long[][] neighbourSubmerged = new long[NEIGHBOURS][4]; private final IrisDimensionCarvingResolver.State resolverState = new IrisDimensionCarvingResolver.State(); - private int nextWeightBuffer; private boolean inUse; - private double[] acquireWeights() { - if (nextWeightBuffer < weightBuffers.size()) { - double[] weights = weightBuffers.get(nextWeightBuffer++); - Arrays.fill(weights, 0D); - return weights; - } - double[] weights = new double[CHUNK_AREA]; - if (weightBuffers.size() < MAX_POOLED_WEIGHT_BUFFERS) { - weightBuffers.add(weights); - nextWeightBuffer++; - } - return weights; - } - private void release() { - Arrays.fill(profileField, null); - Arrays.fill(kernelProfiles, null); - Arrays.fill(fieldRegions, null); - Arrays.fill(fieldSurfaceBiomes, null); - Arrays.fill(fieldCaveBiomes, null); for (Object[] objects : neighbourObjects) { Arrays.fill(objects, null); } - columnProfileWeights.clear(); - profileOrder.clear(); - nextWeightBuffer = 0; inUse = false; } } diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/MantleCaveCellSink.java b/core/src/main/java/art/arcane/iris/generation/mantle/MantleCaveCellSink.java new file mode 100644 index 000000000..11e38bfa7 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/mantle/MantleCaveCellSink.java @@ -0,0 +1,54 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.mantle; + +import art.arcane.volmlib.util.mantle.runtime.MantleChunk; +import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; +import art.arcane.volmlib.util.matter.Matter; +import art.arcane.volmlib.util.matter.MatterCavern; +import art.arcane.volmlib.util.matter.MatterSlice; + +/** Writes the carved blocks of one chunk into the cavern slices of its mantle sections, keeping the slice of each section it has used. */ +final class MantleCaveCellSink implements CaveCellSink { + private static final int SECTION_HEIGHT_SHIFT = 4; + private static final int SECTION_HEIGHT_MASK = (1 << SECTION_HEIGHT_SHIFT) - 1; + + private final MantleChunk chunk; + private final MatterSlice[] slices; + + @SuppressWarnings("unchecked") + MantleCaveCellSink(MantleChunk chunk, int worldHeight) { + this.chunk = chunk; + this.slices = new MatterSlice[PowerOfTwoCoordinates.ceilDivPow2(worldHeight, SECTION_HEIGHT_SHIFT)]; + } + + @Override + public void set(int localX, int y, int localZ, MatterCavern cell) { + sliceOf(y >> SECTION_HEIGHT_SHIFT).set(localX, y & SECTION_HEIGHT_MASK, localZ, cell); + } + + private MatterSlice sliceOf(int section) { + MatterSlice slice = slices[section]; + if (slice == null) { + slice = chunk.getOrCreate(section).slice(MatterCavern.class); + slices[section] = slice; + } + return slice; + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java b/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java index ac53f6af3..03bf50912 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java @@ -33,7 +33,6 @@ import art.arcane.iris.structure.object.IObjectPlacer; import art.arcane.iris.structure.object.IrisAxisRotationClamp; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.cave.IrisCaveAnchorMode; -import art.arcane.iris.generation.cave.IrisCaveProfile; import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.iris.structure.object.IrisObject; import art.arcane.iris.structure.object.IrisObjectPlacement; @@ -72,7 +71,6 @@ import art.arcane.iris.generation.block.DataProvider; import java.util.Locale; import java.util.Map; import java.util.Set; -import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.concurrent.ConcurrentHashMap; @@ -82,6 +80,11 @@ import java.util.function.BiConsumer; @ComponentFlag(ReservedFlag.OBJECT) public class MantleObjectComponent extends IrisMantleComponent { + /** The anchor a cave object takes when its placement names none. */ + private static final IrisCaveAnchorMode DEFAULT_CAVE_ANCHOR = IrisCaveAnchorMode.FLOOR; + private static final int CAVE_ANCHOR_SCAN_STEP_BLOCKS = 1; + private static final int CAVE_ANCHOR_SEARCH_ATTEMPTS = 6; + private static final int CAVE_OBJECT_MIN_DEPTH_BELOW_SURFACE_BLOCKS = 6; private static final long CAVE_REJECT_LOG_THROTTLE_MS = 5000L; private static final int BEDROCK_CLEARANCE = 6; static final byte LIQUID_FORCED_AIR = 3; @@ -473,8 +476,6 @@ public class MantleObjectComponent extends IrisMantleComponent { int rejected = 0; int nullObjects = 0; int errors = 0; - IrisCaveProfile biomeCaveProfile = resolveCaveProfile(caveBiome.getCaveProfile(), region.getCaveProfile()); - IrisCaveProfile regionCaveProfile = resolveCaveProfile(region.getCaveProfile(), caveBiome.getCaveProfile()); CaveAnchorCache caveAnchorCache = new CaveAnchorCache(); for (IrisObjectPlacement i : surfaceBiome.getSurfaceObjects()) { @@ -521,7 +522,7 @@ public class MantleObjectComponent extends IrisMantleComponent { if (chance) { biomeCaveTriggered++; try { - ObjectPlacementResult result = placeCaveObject(writer, rng, x, z, i, biomeCaveProfile, complex, traceRegen, x, z, "biome-cave", caveBiome.getLoadKey(), caveAnchorCache); + ObjectPlacementResult result = placeCaveObject(writer, rng, x, z, i, complex, traceRegen, x, z, "biome-cave", caveBiome.getLoadKey(), caveAnchorCache); attempts += result.attempts(); placed += result.placed(); rejected += result.rejected(); @@ -578,7 +579,7 @@ public class MantleObjectComponent extends IrisMantleComponent { if (chance) { regionCaveTriggered++; try { - ObjectPlacementResult result = placeCaveObject(writer, rng, x, z, i, regionCaveProfile, complex, traceRegen, x, z, "region-cave", null, caveAnchorCache); + ObjectPlacementResult result = placeCaveObject(writer, rng, x, z, i, complex, traceRegen, x, z, "region-cave", null, caveAnchorCache); attempts += result.attempts(); placed += result.placed(); rejected += result.rejected(); @@ -610,13 +611,10 @@ public class MantleObjectComponent extends IrisMantleComponent { @ChunkCoordinates private void placeProceduralObjects(ObjectPassPlacer writer, RNG rng, int x, int z, IrisBiome surfaceBiome, IrisBiome caveBiome, IrisRegion region, IrisComplex complex) { - IrisCaveProfile surfaceCaveProfile = resolveCaveProfile(surfaceBiome.getCaveProfile(), region.getCaveProfile()); - IrisCaveProfile regionCaveProfile = resolveCaveProfile(region.getCaveProfile(), caveBiome == null ? null : caveBiome.getCaveProfile()); - placeProceduralFrom(writer, rng, x, z, surfaceBiome.getProceduralObjects(), surfaceBiome.getName(), surfaceCaveProfile, surfaceBiome.getLoadKey()); - placeProceduralFrom(writer, rng, x, z, region.getProceduralObjects(), region.getName(), regionCaveProfile, null); + placeProceduralFrom(writer, rng, x, z, surfaceBiome.getProceduralObjects(), surfaceBiome.getName(), surfaceBiome.getLoadKey()); + placeProceduralFrom(writer, rng, x, z, region.getProceduralObjects(), region.getName(), null); if (caveBiome != null && caveBiome != surfaceBiome) { - IrisCaveProfile caveProfile = resolveCaveProfile(caveBiome.getCaveProfile(), region.getCaveProfile()); - placeProceduralFrom(writer, rng, x, z, caveBiome.getProceduralObjects(), caveBiome.getName(), caveProfile, caveBiome.getLoadKey()); + placeProceduralFrom(writer, rng, x, z, caveBiome.getProceduralObjects(), caveBiome.getName(), caveBiome.getLoadKey()); } if (complex.getSubterrainPlanner() != null && !complex.getSubterrainPlanner().isEmpty()) { Set placed = new HashSet<>(); @@ -630,8 +628,7 @@ public class MantleObjectComponent extends IrisMantleComponent { } IrisBiome featureBiome = getData().getBiomeLoader().load(plan.biome()); if (featureBiome != null) { - placeProceduralFrom(writer, rng, x, z, featureBiome.getProceduralObjects(), featureBiome.getName(), - resolveCaveProfile(featureBiome.getCaveProfile(), region.getCaveProfile()), featureBiome.getLoadKey()); + placeProceduralFrom(writer, rng, x, z, featureBiome.getProceduralObjects(), featureBiome.getName(), featureBiome.getLoadKey()); } } } @@ -645,7 +642,6 @@ public class MantleObjectComponent extends IrisMantleComponent { int z, IrisProceduralObjects proceduralObjects, String scope, - IrisCaveProfile caveProfile, String expectedCaveBiomeKey ) { if (proceduralObjects == null || proceduralObjects.isEmpty()) { @@ -672,13 +668,13 @@ public class MantleObjectComponent extends IrisMantleComponent { IrisObjectPlacement placement = p.asPlacement(); boolean carving = placement.getCarvingSupport() == CarvingMode.CARVING_ONLY; - IrisCaveAnchorMode anchorMode = resolveAnchorMode(placement, caveProfile); + IrisCaveAnchorMode anchorMode = resolveAnchorMode(placement); if (placement.getMode() == ObjectPlaceMode.CEILING_HANG) { anchorMode = IrisCaveAnchorMode.CEILING; } - int anchorScanStep = resolveAnchorScanStep(caveProfile); - int minDepthBelowSurface = resolveObjectMinDepthBelowSurface(caveProfile); - int anchorSearchAttempts = resolveAnchorSearchAttempts(caveProfile); + int anchorScanStep = CAVE_ANCHOR_SCAN_STEP_BLOCKS; + int minDepthBelowSurface = CAVE_OBJECT_MIN_DEPTH_BELOW_SURFACE_BLOCKS; + int anchorSearchAttempts = CAVE_ANCHOR_SEARCH_ATTEMPTS; IObjectPlacer basePlacer = p.isPlausible() ? new DecayControlPlacer(writer) : writer; IObjectPlacer placer = golden ? new GoldenDebugObjectPlacer(basePlacer, scope + "/" + p.getName()) : basePlacer; int density = Math.max(1, p.getDensity()); @@ -745,7 +741,7 @@ public class MantleObjectComponent extends IrisMantleComponent { + " zz=" + zz + " caveFloorY=" + caveFloorY); } - IrisObjectPlacement effectivePlacement = resolveCavePlacement(placement, variant, caveProfile); + IrisObjectPlacement effectivePlacement = resolveEffectivePlacement(placement, variant); ContainedPlacementResult contained = placeContainedCaveObject( placer, variant, @@ -1078,7 +1074,6 @@ public class MantleObjectComponent extends IrisMantleComponent { int chunkX, int chunkZ, IrisObjectPlacement objectPlacement, - IrisCaveProfile caveProfile, IrisComplex complex, boolean traceRegen, int metricChunkX, @@ -1095,13 +1090,13 @@ public class MantleObjectComponent extends IrisMantleComponent { int minX = chunkX << 4; int minZ = chunkZ << 4; int density = objectPlacement.getDensity(rng, minX, minZ, getData()); - IrisCaveAnchorMode anchorMode = resolveAnchorMode(objectPlacement, caveProfile); + IrisCaveAnchorMode anchorMode = resolveAnchorMode(objectPlacement); if (objectPlacement.getMode() == ObjectPlaceMode.CEILING_HANG) { anchorMode = IrisCaveAnchorMode.CEILING; } - int anchorScanStep = resolveAnchorScanStep(caveProfile); - int objectMinDepthBelowSurface = resolveObjectMinDepthBelowSurface(caveProfile); - int anchorSearchAttempts = resolveAnchorSearchAttempts(caveProfile); + int anchorScanStep = CAVE_ANCHOR_SCAN_STEP_BLOCKS; + int objectMinDepthBelowSurface = CAVE_OBJECT_MIN_DEPTH_BELOW_SURFACE_BLOCKS; + int anchorSearchAttempts = CAVE_ANCHOR_SEARCH_ATTEMPTS; for (int i = 0; i < density; i++) { attempts++; @@ -1174,7 +1169,7 @@ public class MantleObjectComponent extends IrisMantleComponent { int z = anchor.z(); int id = rng.i(0, Integer.MAX_VALUE); - IrisObjectPlacement effectivePlacement = resolveCavePlacement(objectPlacement, object, caveProfile); + IrisObjectPlacement effectivePlacement = resolveEffectivePlacement(objectPlacement, object); try { int continuation = writer.beginObjectPlacement(effectivePlacement.waterRule()); @@ -1513,26 +1508,6 @@ public class MantleObjectComponent extends IrisMantleComponent { return effectivePlacement; } - private IrisObjectPlacement resolveCavePlacement(IrisObjectPlacement objectPlacement, IrisObject object, IrisCaveProfile caveProfile) { - IrisObjectPlacement resolvedPlacement = resolveEffectivePlacement(objectPlacement, object); - if (resolvedPlacement.getMode() != ObjectPlaceMode.CENTER_HEIGHT || caveProfile == null) { - return resolvedPlacement; - } - - ObjectPlaceMode profileMode = caveProfile.getDefaultObjectPlaceMode(); - if (profileMode == null) { - return resolvedPlacement; - } - - String loadKey = object.getLoadKey(); - if (loadKey == null || loadKey.isBlank()) { - resolvedPlacement = resolvedPlacement.toPlacement(); - } else { - resolvedPlacement = resolvedPlacement.toPlacement(loadKey); - } - resolvedPlacement.setMode(profileMode); - return resolvedPlacement; - } static int proceduralFloorY(IObjectPlacer placer, int x, int scannedY, int z) { int floorY = scannedY; @@ -1633,63 +1608,12 @@ public class MantleObjectComponent extends IrisMantleComponent { }; } - private IrisCaveProfile resolveCaveProfile(IrisCaveProfile preferred, IrisCaveProfile secondary) { - IrisCaveProfile dimensionProfile = getDimension().getCaveProfile(); - if (preferred != null && preferred.isEnabled()) { - return preferred; - } - - if (secondary != null && secondary.isEnabled()) { - return secondary; - } - - if (dimensionProfile != null) { - return dimensionProfile; - } - - return new IrisCaveProfile(); - } - - private IrisCaveAnchorMode resolveAnchorMode(IrisObjectPlacement objectPlacement, IrisCaveProfile caveProfile) { + private IrisCaveAnchorMode resolveAnchorMode(IrisObjectPlacement objectPlacement) { IrisCaveAnchorMode placementMode = objectPlacement.getCaveAnchorMode(); - if (placementMode != null && !placementMode.equals(IrisCaveAnchorMode.PROFILE_DEFAULT)) { - return placementMode; + if (placementMode == null || placementMode == IrisCaveAnchorMode.PROFILE_DEFAULT) { + return DEFAULT_CAVE_ANCHOR; } - - if (caveProfile == null) { - return IrisCaveAnchorMode.FLOOR; - } - - IrisCaveAnchorMode profileMode = caveProfile.getDefaultObjectAnchor(); - if (profileMode == null || profileMode.equals(IrisCaveAnchorMode.PROFILE_DEFAULT)) { - return IrisCaveAnchorMode.FLOOR; - } - - return profileMode; - } - - private int resolveAnchorScanStep(IrisCaveProfile caveProfile) { - if (caveProfile == null) { - return 1; - } - - return Math.max(1, caveProfile.getAnchorScanStep()); - } - - private int resolveObjectMinDepthBelowSurface(IrisCaveProfile caveProfile) { - if (caveProfile == null) { - return 6; - } - - return Math.max(0, caveProfile.getObjectMinDepthBelowSurface()); - } - - private int resolveAnchorSearchAttempts(IrisCaveProfile caveProfile) { - if (caveProfile == null) { - return 6; - } - - return Math.max(1, caveProfile.getAnchorSearchAttempts()); + return placementMode; } private boolean isRegenTraceThread() { @@ -1912,14 +1836,12 @@ public class MantleObjectComponent extends IrisMantleComponent { private final DataProvider dataProvider; private final KSet warnedLargeObjects; private final Map extents; - private final Set caveVacuumModes; private ReachScan(IrisDimension dimension, DataProvider dataProvider, KSet warnedLargeObjects) { this.dimension = dimension; this.dataProvider = dataProvider; this.warnedLargeObjects = warnedLargeObjects; this.extents = new HashMap<>(); - this.caveVacuumModes = caveVacuumModes(dimension, dataProvider); } private PlacementReach dimension() { @@ -2038,17 +1960,7 @@ public class MantleObjectComponent extends IrisMantleComponent { } private KList profiles(IrisObjectPlacement placement) { - KList profiles = new KList<>(PlacementReach.profile(placement)); - if (placement.getMode() != ObjectPlaceMode.CENTER_HEIGHT - || placement.getCarvingSupport() == CarvingMode.SURFACE_ONLY) { - return profiles; - } - for (ObjectPlaceMode mode : caveVacuumModes) { - IrisObjectPlacement cave = placement.toPlacement(placement.getPlace().toArray(new String[0])); - cave.setMode(mode); - profiles.add(PlacementReach.profile(cave)); - } - return profiles; + return new KList<>(PlacementReach.profile(placement)); } private PlacementReach.Extent extent(String objectKey) { @@ -2060,32 +1972,6 @@ public class MantleObjectComponent extends IrisMantleComponent { extents.put(objectKey, extent); return extent; } - - private static Set caveVacuumModes(IrisDimension dimension, DataProvider dataProvider) { - Set modes = EnumSet.noneOf(ObjectPlaceMode.class); - addCaveVacuumMode(modes, dimension.getCaveProfile()); - for (IrisRegion region : dimension.getAllRegions(dataProvider)) { - if (region != null) { - addCaveVacuumMode(modes, region.getCaveProfile()); - } - } - for (IrisBiome biome : dimension.getReachableBiomes(dataProvider)) { - if (biome != null) { - addCaveVacuumMode(modes, biome.getCaveProfile()); - } - } - return modes; - } - - private static void addCaveVacuumMode(Set modes, IrisCaveProfile profile) { - if (profile == null) { - return; - } - ObjectPlaceMode mode = profile.getDefaultObjectPlaceMode(); - if (mode != null && IrisObjectVacuum.isVacuumMode(mode)) { - modes.add(mode); - } - } } @FunctionalInterface diff --git a/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimension.java b/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimension.java index 60fc8b20d..9f5dc0331 100644 --- a/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimension.java +++ b/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimension.java @@ -25,7 +25,6 @@ import art.arcane.iris.generation.biome.IrisCustomBiomeAliasResolver; import art.arcane.iris.generation.biome.IrisFloatingChildBiomes; import art.arcane.iris.generation.biome.IrisSurfaceLayerFallback; import art.arcane.iris.generation.cave.IrisCave; -import art.arcane.iris.generation.cave.IrisCaveProfile; import art.arcane.iris.generation.decoration.IrisDepositGenerator; import art.arcane.iris.generation.decoration.IrisDepositVariant; import art.arcane.iris.generation.decoration.IrisOreGenerator; @@ -230,8 +229,6 @@ public class IrisDimension extends IrisRegistrant { @ArrayType(type = IrisSubterrainFeature.class, min = 1) @Description("Deterministic bounded underground features with owned geometry, biome, fluids and room formations.") private KList subterrainFeatures = new KList<>(); - @Description("Profile-driven 3D cave configuration") - private IrisCaveProfile caveProfile = new IrisCaveProfile(); @ArrayType(type = String.class, min = 1) @RegistryListResource(IrisCave.class) @Description("Caves that carve everywhere in this dimension, by their file in the pack's caves folder. The lists of the dimension, region and biomes of a place add up: every cave any of them lists carves there.") @@ -315,11 +312,6 @@ public class IrisDimension extends IrisRegistrant { @IntegerOptions({4, 8, 16, 32}) @Description("Biome height-bound sampling interval in blocks: 4, 8, 16, or 32. 4 retains the original biome blending. Larger intervals interpolate the configured generator bounds between shared anchors, smoothing small biome-height features. Generator interpolation styles and radii remain active at the anchors. Set before creating a world.") private int biomeBoundsSamplingStep = 4; - @MinNumber(1) - @MaxNumber(8) - @IntegerOptions({1, 2, 4, 8}) - @Description("Vertical cave density sampling interval in blocks: 1, 2, 4, or 8. Larger intervals interpolate density while retaining cave module bounds, surface protection, and fluid rules. Changes cave geometry. Set before creating a world.") - private int caveDensitySamplingStep = 1; @MinNumber(0) @MaxNumber(360) @Description("You can rotate the input coordinates by an angle. This can make terrain appear more natural (less sharp corners and lines). This literally rotates the entire dimension by an angle. Hint: Try 12 degrees or something not on a 90 or 45 degree angle.") @@ -731,7 +723,6 @@ public class IrisDimension extends IrisRegistrant { } Set visited = new HashSet<>(); - Map carvingEntryIndex = getCarvingEntryIndex(); while (!pending.isEmpty()) { String biomeKey = pending.removeFirst(); if (!visited.add(biomeKey)) { @@ -763,10 +754,6 @@ public class IrisDimension extends IrisRegistrant { for (IrisFloatingChildBiomes floatingChild : floatingChildren) { if (floatingChild != null) { addReachableBiomeKey(pending, floatingChild.getBiome()); - String carvingReference = floatingChild.getCarving(); - IrisDimensionCarvingEntry carvingEntry = carvingEntryIndex.get(carvingReference); - addReachableBiomeKey(pending, - carvingEntry == null ? carvingReference : carvingEntry.getBiome()); } } } diff --git a/core/src/main/java/art/arcane/iris/generation/terrain/IrisRegion.java b/core/src/main/java/art/arcane/iris/generation/terrain/IrisRegion.java index e12f0d636..b7f36adb4 100644 --- a/core/src/main/java/art/arcane/iris/generation/terrain/IrisRegion.java +++ b/core/src/main/java/art/arcane/iris/generation/terrain/IrisRegion.java @@ -20,7 +20,6 @@ package art.arcane.iris.generation.terrain; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.cave.IrisCave; -import art.arcane.iris.generation.cave.IrisCaveProfile; import art.arcane.iris.generation.decoration.IrisDepositGenerator; import art.arcane.iris.generation.decoration.IrisDepositVariant; import art.arcane.iris.generation.decoration.IrisOreGenerator; @@ -144,8 +143,6 @@ public class IrisRegion extends IrisRegistrant implements Rarity { @MinNumber(0.0001) @Description("How large cave biomes are in this region") private double caveBiomeZoom = 1; - @Description("Profile-driven 3D cave configuration") - private IrisCaveProfile caveProfile = new IrisCaveProfile(); @ArrayType(type = String.class, min = 1) @RegistryListResource(IrisCave.class) @Description("Caves that carve in this region, by their file in the pack's caves folder. They add to the dimension's and the biomes' lists.") diff --git a/core/src/main/java/art/arcane/iris/pack/PackCaveProfileValidator.java b/core/src/main/java/art/arcane/iris/pack/PackCaveProfileValidator.java deleted file mode 100644 index 1cd2d427d..000000000 --- a/core/src/main/java/art/arcane/iris/pack/PackCaveProfileValidator.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.pack; - -import art.arcane.volmlib.util.json.JSONObject; - -import java.io.File; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; - -final class PackCaveProfileValidator { - private static final String CAVE_PROFILE_SNIPPET_FOLDER = "snippet/cave-profile"; - private static final List LEGACY_FIELDS = List.of( - new LegacyField("allowWater", "allowFluid"), - new LegacyField("waterMinDepthBelowSurface", "fluidMinDepthBelowSurface"), - new LegacyField("waterRequiresFloor", "fluidRequiresFloor") - ); - - private PackCaveProfileValidator() { - } - - static List validateLegacyFields(File packFolder) { - List blockingErrors = new ArrayList<>(); - if (packFolder == null || !packFolder.isDirectory()) { - return blockingErrors; - } - - for (String folderName : PackValidator.STRUCTURE_HOST_FOLDERS) { - File resourceFolder = new File(packFolder, folderName); - if (!resourceFolder.isDirectory()) { - continue; - } - List resourceFiles = PackValidationIo.listJsonRecursive(resourceFolder); - resourceFiles.sort(Comparator.comparing(File::getPath)); - String resourceType = PackStructurePlacementValidator.structureHostType(folderName); - for (File resourceFile : resourceFiles) { - JSONObject resource = PackValidationIo.readJson(resourceFile); - if (resource == null) { - continue; - } - JSONObject caveProfile = resource.optJSONObject("caveProfile"); - if (caveProfile == null) { - continue; - } - String resourceKey = PackValidationIo.deriveKey(resourceFolder, resourceFile); - validateFields(resourceType + " '" + resourceKey + "' caveProfile.", "caveProfile.", caveProfile, - blockingErrors); - } - } - - File snippetFolder = new File(packFolder, CAVE_PROFILE_SNIPPET_FOLDER); - if (!snippetFolder.isDirectory()) { - return blockingErrors; - } - List snippetFiles = PackValidationIo.listJsonRecursive(snippetFolder); - snippetFiles.sort(Comparator.comparing(File::getPath)); - for (File snippetFile : snippetFiles) { - JSONObject caveProfile = PackValidationIo.readJson(snippetFile); - if (caveProfile == null) { - continue; - } - String snippetKey = PackValidationIo.deriveKey(snippetFolder, snippetFile); - validateFields("Cave-profile snippet '" + snippetKey + "' ", "", caveProfile, blockingErrors); - } - return blockingErrors; - } - - private static void validateFields(String location, String replacementPrefix, JSONObject caveProfile, - List blockingErrors) { - for (LegacyField field : LEGACY_FIELDS) { - if (caveProfile.has(field.oldName())) { - blockingErrors.add(location + field.oldName() + " was removed; use " + replacementPrefix - + field.newName() - + ". Cave aquifers use the dimension fluidPalette, which defaults to water."); - } - } - } - - private record LegacyField(String oldName, String newName) { - } -} diff --git a/core/src/main/java/art/arcane/iris/pack/PackDimensionValidator.java b/core/src/main/java/art/arcane/iris/pack/PackDimensionValidator.java index 27de49967..c5ce563b7 100644 --- a/core/src/main/java/art/arcane/iris/pack/PackDimensionValidator.java +++ b/core/src/main/java/art/arcane/iris/pack/PackDimensionValidator.java @@ -63,7 +63,6 @@ final class PackDimensionValidator { validateDimensionHeights(packFolder, dimensionKey, dimJson, blockingErrors); validateBorrowedDimensionType(dimensionKey, dimJson, borrowedDimensionTypesSupported(), blockingErrors); validateSamplingStep(dimensionKey, dimJson, "terrainSamplingStep", 1, blockingErrors); - validateSamplingStep(dimensionKey, dimJson, "caveDensitySamplingStep", 1, blockingErrors); validateSamplingStep(dimensionKey, dimJson, "biomeBoundsSamplingStep", 4, blockingErrors); validateWorldBoundary(dimensionKey, dimJson, blockingErrors); validateStaticObjects(packFolder, dimensionKey, dimJson, blockingErrors); diff --git a/core/src/main/java/art/arcane/iris/pack/PackStyledRangeDefaultValidator.java b/core/src/main/java/art/arcane/iris/pack/PackStyledRangeDefaultValidator.java index 9b903585c..e75f0fa92 100644 --- a/core/src/main/java/art/arcane/iris/pack/PackStyledRangeDefaultValidator.java +++ b/core/src/main/java/art/arcane/iris/pack/PackStyledRangeDefaultValidator.java @@ -33,7 +33,7 @@ import java.util.Locale; * Catches the shared IrisStyledRange class default (min 16, max 32) leaking into pack content. * The POJO cannot distinguish an empty object from an explicit 16/32 after Gson runs, so the raw * JSON is the only place this mistake is still visible: an objects[].densityStyle of {} places - * 16-32 objects per chunk, and a caveProfile.densityThreshold of {} hollows the whole cave range. + * 16-32 objects per chunk. */ final class PackStyledRangeDefaultValidator { private static final String STYLE_RANGE_SNIPPET_FOLDER = "snippet/style-range/"; @@ -73,7 +73,6 @@ final class PackStyledRangeDefaultValidator { } validateObjectPlacements(packFolder, type, key, json, errors, warnings); - validateCaveProfileThreshold(packFolder, type, key, json.optJSONObject("caveProfile"), errors, warnings); } } return new Validation(errors, warnings); @@ -97,18 +96,6 @@ final class PackStyledRangeDefaultValidator { } } - private static void validateCaveProfileThreshold(File packFolder, String type, String key, JSONObject caveProfile, - List errors, List warnings) { - if (caveProfile == null || !caveProfile.has("densityThreshold") || caveProfile.isNull("densityThreshold")) { - return; - } - checkRange(packFolder, caveProfile.opt("densityThreshold"), - type + " '" + key + "' caveProfile.densityThreshold", - "a carve threshold of 16-32, hollowing the entire vertical range", - "remove densityThreshold to keep the cave profile default", - errors, warnings); - } - private static void checkRange(File packFolder, Object raw, String path, String consequence, String removal, List errors, List warnings) { JSONObject range = null; diff --git a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/IslandCompiler.java b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/IslandCompiler.java index 951e586a8..5ffad1f32 100644 --- a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/IslandCompiler.java +++ b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/IslandCompiler.java @@ -183,7 +183,7 @@ final class IslandCompiler { if (child.getWallWarpStyle() != null && child.getWallWarpAmplitude() > 0.0) { features.add("wall warp"); } - if (child.hasCarvingReference() || (child.getCarveStyle() != null && child.getCarveThreshold() < 1.0)) { + if (child.getCarveStyle() != null && child.getCarveThreshold() < 1.0) { features.add("interior carving"); } if (child.getLocalFluidHeight() != null && child.getLocalFluidHeight() > 0) { diff --git a/core/src/test/java/art/arcane/iris/generation/biome/FloatingIslandBoundarySamplerTest.java b/core/src/test/java/art/arcane/iris/generation/biome/FloatingIslandBoundarySamplerTest.java index 2faffebcb..1bf5ec812 100644 --- a/core/src/test/java/art/arcane/iris/generation/biome/FloatingIslandBoundarySamplerTest.java +++ b/core/src/test/java/art/arcane/iris/generation/biome/FloatingIslandBoundarySamplerTest.java @@ -577,8 +577,6 @@ public class FloatingIslandBoundarySamplerTest { when(entry.getMaxAbsoluteY()).thenReturn(null); when(entry.getWallWarpCng(anyLong(), same(data))).thenReturn(null); when(entry.getWallWarpAmplitude()).thenReturn(0.0D); - when(entry.getCarvingProfileSampler(engine, data)).thenReturn(null); - when(entry.hasCarvingReference()).thenReturn(false); when(entry.getCarveCng(anyLong(), same(data))).thenReturn(constant); when(entry.getCarveThreshold()).thenReturn(0.5D); when(engine.getWorld()).thenReturn(world); @@ -657,8 +655,6 @@ public class FloatingIslandBoundarySamplerTest { when(entry.getMaxAbsoluteY()).thenReturn(null); when(entry.getWallWarpCng(anyLong(), same(data))).thenReturn(null); when(entry.getWallWarpAmplitude()).thenReturn(0.0D); - when(entry.getCarvingProfileSampler(engine, data)).thenReturn(null); - when(entry.hasCarvingReference()).thenReturn(false); when(entry.getCarveCng(anyLong(), same(data))).thenReturn(null); when(entry.getCarveThreshold()).thenReturn(1.0D); } diff --git a/core/src/test/java/art/arcane/iris/generation/biome/FloatingIslandSampleBottomYTest.java b/core/src/test/java/art/arcane/iris/generation/biome/FloatingIslandSampleBottomYTest.java index af8c7909e..babade939 100644 --- a/core/src/test/java/art/arcane/iris/generation/biome/FloatingIslandSampleBottomYTest.java +++ b/core/src/test/java/art/arcane/iris/generation/biome/FloatingIslandSampleBottomYTest.java @@ -324,12 +324,12 @@ public class FloatingIslandSampleBottomYTest { } @Test - public void directCarveEnabled_respectsCarvingReferenceOverride() { - IrisFloatingChildBiomes entry = new IrisFloatingChildBiomes(); - entry.setCarving("carving/mushroom"); + public void directCarveEnabled_needsACarveNoiseAndAThresholdBelowOne() { CNG carve = new CNG(new RNG(9)); - assertFalse(FloatingIslandSample.directCarveEnabled(entry, null, carve, 0.5)); + assertTrue(FloatingIslandSample.directCarveEnabled(carve, 0.5)); + assertFalse(FloatingIslandSample.directCarveEnabled(carve, 1.0)); + assertFalse(FloatingIslandSample.directCarveEnabled(null, 0.5)); } @Test diff --git a/core/src/test/java/art/arcane/iris/generation/biome/IrisFloatingChildBiomesCarvingResolutionTest.java b/core/src/test/java/art/arcane/iris/generation/biome/IrisFloatingChildBiomesCarvingResolutionTest.java deleted file mode 100644 index 6b3d78443..000000000 --- a/core/src/test/java/art/arcane/iris/generation/biome/IrisFloatingChildBiomesCarvingResolutionTest.java +++ /dev/null @@ -1,89 +0,0 @@ -package art.arcane.iris.generation.biome; - -import art.arcane.iris.generation.terrain.IrisDimension; -import art.arcane.iris.generation.terrain.IrisDimensionCarvingEntry; - -import art.arcane.iris.pack.loading.IrisData; -import art.arcane.iris.pack.loading.ResourceLoader; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.testsupport.BukkitTestServer; -import art.arcane.volmlib.util.collection.KList; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.assertSame; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - -public class IrisFloatingChildBiomesCarvingResolutionTest { - @BeforeClass - public static void setupBukkit() { - BukkitTestServer.install(); - } - - @Test - public void resolveCarvingBiome_loadsBiomeKeyWhenEntryIdMissing() { - IrisBiome biome = mock(IrisBiome.class); - Fixture fixture = createFixture(Map.of(), Map.of("carving/mushroom", biome)); - - IrisBiome resolved = IrisFloatingChildBiomes.resolveCarvingBiome("carving/mushroom", fixture.engine, fixture.data); - - assertSame(biome, resolved); - } - - @Test - public void resolveCarvingBiome_prefersDimensionCarvingEntryId() { - IrisBiome entryBiome = mock(IrisBiome.class); - IrisBiome sameKeyBiome = mock(IrisBiome.class); - IrisDimensionCarvingEntry entry = new IrisDimensionCarvingEntry(); - entry.setId("global-deepdark-band"); - entry.setBiome("carving/standard-deepdark"); - - Map entries = new HashMap<>(); - entries.put("global-deepdark-band", entry); - - Map biomes = new HashMap<>(); - biomes.put("carving/standard-deepdark", entryBiome); - biomes.put("global-deepdark-band", sameKeyBiome); - - Fixture fixture = createFixture(entries, biomes); - - IrisBiome resolved = IrisFloatingChildBiomes.resolveCarvingBiome("global-deepdark-band", fixture.engine, fixture.data); - - assertSame(entryBiome, resolved); - } - - private Fixture createFixture(Map entries, Map biomes) { - @SuppressWarnings("unchecked") - ResourceLoader biomeLoader = mock(ResourceLoader.class); - for (Map.Entry biome : biomes.entrySet()) { - doReturn(biome.getValue()).when(biomeLoader).load(biome.getKey()); - } - - IrisData data = mock(IrisData.class); - doReturn(biomeLoader).when(data).getBiomeLoader(); - - IrisDimension dimension = mock(IrisDimension.class); - doReturn(entries).when(dimension).getCarvingEntryIndex(); - doReturn(new KList<>(entries.values())).when(dimension).getCarving(); - - Engine engine = mock(Engine.class); - doReturn(data).when(engine).getData(); - doReturn(dimension).when(engine).getDimension(); - - return new Fixture(engine, data); - } - - private static final class Fixture { - private final Engine engine; - private final IrisData data; - - private Fixture(Engine engine, IrisData data) { - this.engine = engine; - this.data = data; - } - } -} diff --git a/core/src/test/java/art/arcane/iris/generation/cave/IrisCaveProfileSamplerTest.java b/core/src/test/java/art/arcane/iris/generation/cave/IrisCaveProfileSamplerTest.java deleted file mode 100644 index 3eeac84a4..000000000 --- a/core/src/test/java/art/arcane/iris/generation/cave/IrisCaveProfileSamplerTest.java +++ /dev/null @@ -1,117 +0,0 @@ -package art.arcane.iris.generation.cave; - -import art.arcane.iris.generation.noise.IrisGeneratorStyle; -import art.arcane.iris.generation.noise.NoiseStyle; -import art.arcane.iris.generation.noise.IrisStyledRange; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.generation.runtime.SeedManager; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.M; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.noise.CNG; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyDouble; -import static org.mockito.ArgumentMatchers.isNull; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class IrisCaveProfileSamplerTest { - @Test - public void resolvesThresholdNoiseOnceWhilePreservingCoordinateDecisions() { - IrisGeneratorStyle style = mock(IrisGeneratorStyle.class); - CNG thresholdNoise = mock(CNG.class); - when(style.create(any(), isNull())).thenReturn(thresholdNoise); - when(thresholdNoise.fitDouble(anyDouble(), anyDouble(), anyDouble(), anyDouble())) - .thenAnswer(invocation -> (double) invocation.getArgument(2) * 0.003D - + (double) invocation.getArgument(3) * 0.005D); - IrisCaveProfile profile = profile(new IrisStyledRange().setMin(-0.4D).setMax(0.7D).setStyle(style)); - IrisCaveProfileSampler sampler = new IrisCaveProfileSampler(engine(), profile); - for (int x = -19; x <= 19; x++) { - for (int y = -3; y <= 11; y++) { - int z = -x; - double density = density(x, y, z); - double threshold = x * 0.003D + z * 0.005D - profile.getThresholdBias(); - threshold += (1D - 0.75D) * 0.2D; - assertEquals(density <= threshold, sampler.shouldCarve(x, y, z, 0.75D)); - } - } - verify(style, times(1)).create(any(), isNull()); - verify(thresholdNoise, times(585)).fitDouble(anyDouble(), anyDouble(), anyDouble(), anyDouble()); - } - - @Test - public void realSeededThresholdMatchesStyledRangeAtSignedCoordinates() { - IrisStyledRange range = new IrisStyledRange().setMin(-0.4D).setMax(0.7D) - .setStyle(new IrisGeneratorStyle(NoiseStyle.SIMPLEX)); - IrisCaveProfile profile = profile(range); - IrisCaveProfileSampler sampler = new IrisCaveProfileSampler(engine(), profile); - RNG thresholdRng = new RNG(47L).nextParallelRNG(489_112); - int[] coordinates = {-1009, -33, -1, 0, 17, 513}; - double[] floatingThresholds = {-0.5D, 0D, 0.25D, 0.75D, 1D, 1.5D}; - for (int x : coordinates) { - for (int z : coordinates) { - for (int y = -60; y <= 60; y += 3) { - for (double floatingThreshold : floatingThresholds) { - double threshold = range.get(thresholdRng, x, z, null) - profile.getThresholdBias(); - threshold += (1D - Math.max(0D, Math.min(1D, floatingThreshold))) * 0.2D; - assertEquals("x=" + x + " y=" + y + " z=" + z + " floating=" + floatingThreshold, - density(x, y, z) <= threshold, sampler.shouldCarve(x, y, z, floatingThreshold)); - } - } - } - } - } - - @Test - public void constantAndFlatThresholdsNeverResolveNoise() { - for (boolean equalBounds : new boolean[]{false, true}) { - IrisGeneratorStyle style = mock(IrisGeneratorStyle.class); - when(style.isFlat()).thenReturn(true); - IrisStyledRange range = new IrisStyledRange().setMin(-0.4D) - .setMax(equalBounds ? -0.4D : 0.7D).setStyle(style); - IrisCaveProfile profile = profile(range); - IrisCaveProfileSampler sampler = new IrisCaveProfileSampler(engine(), profile); - double threshold = (equalBounds ? -0.4D : M.lerp(-0.4D, 0.7D, 0.5D)) - profile.getThresholdBias(); - for (int y = -60; y <= 60; y++) { - assertEquals(density(-17, y, 31) <= threshold, sampler.shouldCarve(-17, y, 31, 1D)); - } - verify(style, never()).create(any(), any()); - } - } - - private Engine engine() { - Engine engine = mock(Engine.class); - SeedManager seeds = mock(SeedManager.class); - when(seeds.getCarve()).thenReturn(47L); - when(engine.getSeedManager()).thenReturn(seeds); - return engine; - } - - private IrisCaveProfile profile(IrisStyledRange threshold) { - CNG densityNoise = mock(CNG.class); - when(densityNoise.noiseFastSigned3D(anyDouble(), anyDouble(), anyDouble())).thenAnswer(invocation -> - density(invocation.getArgument(0), invocation.getArgument(1), invocation.getArgument(2))); - IrisGeneratorStyle densityStyle = mock(IrisGeneratorStyle.class); - when(densityStyle.create(any(), isNull())).thenReturn(densityNoise); - IrisCaveProfile profile = mock(IrisCaveProfile.class); - when(profile.getBaseDensityStyle()).thenReturn(densityStyle); - when(profile.getDetailDensityStyle()).thenReturn(densityStyle); - when(profile.getWarpStyle()).thenReturn(densityStyle); - when(profile.getDensityThreshold()).thenReturn(threshold); - when(profile.getThresholdBias()).thenReturn(0.03D); - when(profile.getBaseWeight()).thenReturn(1D); - when(profile.getModules()).thenReturn(new KList<>()); - when(profile.isEnabled()).thenReturn(true); - return profile; - } - - private double density(double x, double y, double z) { - return x * 0.003D + y * 0.01D + z * 0.005D; - } -} diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/CaveCellKernelTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/CaveCellKernelTest.java deleted file mode 100644 index 4df05e6af..000000000 --- a/core/src/test/java/art/arcane/iris/generation/mantle/CaveCellKernelTest.java +++ /dev/null @@ -1,106 +0,0 @@ -package art.arcane.iris.generation.mantle; - -import org.junit.Test; - -import java.util.SplittableRandom; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class CaveCellKernelTest { - private static final int TRIALS = 200_000; - - @Test - public void decidedCellsAgreeWithEveryInterpolatedColumn() { - SplittableRandom random = new SplittableRandom(91_337L); - long decided = 0L; - for (int trial = 0; trial < TRIALS; trial++) { - double scale = Math.scalb(1D, random.nextInt(-30, 4)); - double base = (random.nextDouble() * 2D - 1D) * scale; - double spread = random.nextInt(4) == 0 ? 0D : random.nextDouble() * scale * Math.scalb(1D, -random.nextInt(0, 40)); - double d00 = base + spread * (random.nextDouble() * 2D - 1D); - double d01 = random.nextInt(8) == 0 ? d00 : base + spread * (random.nextDouble() * 2D - 1D); - double d10 = base + spread * (random.nextDouble() * 2D - 1D); - double d11 = random.nextInt(8) == 0 ? d10 : base + spread * (random.nextDouble() * 2D - 1D); - double low = Math.min(Math.min(d00, d01), Math.min(d10, d11)); - double high = Math.max(Math.max(d00, d01), Math.max(d10, d11)); - int mode = random.nextInt(6); - double[] thresholds = new double[64]; - for (int column = 0; column < 64; column++) { - thresholds[column] = pickThreshold(random, low, high, mode); - } - double thresholdLow = Double.POSITIVE_INFINITY; - double thresholdHigh = Double.NEGATIVE_INFINITY; - for (double threshold : thresholds) { - thresholdLow = Math.min(thresholdLow, threshold); - thresholdHigh = Math.max(thresholdHigh, threshold); - } - int decision = CaveCellKernel.decide(d00, d01, d10, d11, thresholdLow, thresholdHigh); - if (decision == CaveCellKernel.MIXED) { - continue; - } - decided++; - for (int column = 0; column < 64; column++) { - double tx = (column >> 3) / 8D; - double tz = (column & 7) / 8D; - boolean carved = bilinear(d00, d01, d10, d11, tx, tz) <= thresholds[column]; - assertEquals("trial " + trial + " column " + column, decision == CaveCellKernel.ALL, carved); - } - } - assertTrue("decided " + decided, decided > TRIALS / 4); - } - - @Test - public void thresholdsAtTheCornerExtremesStayMixed() { - double d00 = 0.1D; - double d01 = -0.2D; - double d10 = 0.3D; - double d11 = 0.05D; - assertEquals(CaveCellKernel.MIXED, CaveCellKernel.decide(d00, d01, d10, d11, 0.3D, 0.3D)); - assertEquals(CaveCellKernel.MIXED, CaveCellKernel.decide(d00, d01, d10, d11, Math.nextUp(0.3D), 0.4D)); - assertEquals(CaveCellKernel.MIXED, CaveCellKernel.decide(d00, d01, d10, d11, -0.3D, Math.nextDown(-0.2D))); - assertEquals(CaveCellKernel.ALL, CaveCellKernel.decide(d00, d01, d10, d11, 0.3D + 1.0E-12D, 0.5D)); - assertEquals(CaveCellKernel.NONE, CaveCellKernel.decide(d00, d01, d10, d11, -0.9D, -0.2D - 1.0E-12D)); - } - - @Test - public void nonFiniteCornersAreNeverDecided() { - assertEquals(CaveCellKernel.MIXED, CaveCellKernel.decide(Double.NaN, 0D, 0D, 0D, 5D, 5D)); - assertEquals(CaveCellKernel.MIXED, CaveCellKernel.decide(0D, Double.POSITIVE_INFINITY, 0D, 0D, -5D, -5D)); - assertEquals(CaveCellKernel.MIXED, CaveCellKernel.decide(0D, 0D, Double.NEGATIVE_INFINITY, 0D, - Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY)); - assertEquals(CaveCellKernel.MIXED, CaveCellKernel.decide(0D, 0D, 0D, 0D, Double.NaN, 1D)); - } - - @Test - public void monotoneThresholdMappingPreservesBounds() { - SplittableRandom random = new SplittableRandom(7_771L); - for (int trial = 0; trial < TRIALS; trial++) { - double normalization = 0.25D + random.nextDouble() * 3D; - double inverse = 1D / normalization; - double a = (random.nextDouble() * 2D - 1D) * Math.scalb(1D, random.nextInt(-20, 3)); - double b = random.nextInt(4) == 0 ? Math.nextUp(a) : a + random.nextDouble() * Math.scalb(1D, random.nextInt(-50, 0)); - assertTrue(CaveCellKernel.threshold(a, normalization, inverse) <= CaveCellKernel.threshold(b, normalization, inverse)); - assertEquals(Double.doubleToRawLongBits((a * normalization) * inverse), - Double.doubleToRawLongBits(CaveCellKernel.threshold(a, normalization, inverse))); - } - } - - private static double pickThreshold(SplittableRandom random, double low, double high, int mode) { - double width = Math.max(high - low, Math.ulp(Math.max(Math.abs(low), Math.abs(high)))); - return switch (mode) { - case 0 -> high + Math.ulp(high) * random.nextInt(0, 64); - case 1 -> low - Math.ulp(low) * random.nextInt(0, 64); - case 2 -> high + width * random.nextDouble() * 0.5D; - case 3 -> low - width * random.nextDouble() * 0.5D; - case 4 -> high + width * (1D + random.nextDouble() * 4D); - default -> low - width * (1D + random.nextDouble() * 4D); - }; - } - - private static double bilinear(double d00, double d01, double d10, double d11, double tx, double tz) { - double dx0 = d00 + ((d10 - d00) * tx); - double dx1 = d01 + ((d11 - d01) * tx); - return dx0 + ((dx1 - dx0) * tz); - } -} diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/CaveDensityTasksTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/CaveDensityTasksTest.java deleted file mode 100644 index 8d01d106a..000000000 --- a/core/src/test/java/art/arcane/iris/generation/mantle/CaveDensityTasksTest.java +++ /dev/null @@ -1,211 +0,0 @@ -package art.arcane.iris.generation.mantle; - -import org.junit.Test; - -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.Future; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -public class CaveDensityTasksTest { - @Test - public void saturatedParentsClaimQueuedWorkWithoutHelpingOtherLocks() throws Exception { - try (ForkJoinPool pool = new ForkJoinPool(2)) { - CountDownLatch parents = new CountDownLatch(2); - AtomicInteger executions = new AtomicInteger(); - Runnable parent = () -> { - synchronized (new Object()) { - parents.countDown(); - await(parents); - IrisCaveCarver3D.runDensityTasks(List.of( - executions::incrementAndGet, executions::incrementAndGet, - executions::incrementAndGet, executions::incrementAndGet), pool); - } - }; - Future first = pool.submit(parent); - Future second = pool.submit(parent); - first.get(5, TimeUnit.SECONDS); - second.get(5, TimeUnit.SECONDS); - assertEquals(8, executions.get()); - } - } - - @Test - public void failedCallerDrainsStartedWorkerBeforeThrowing() throws Exception { - try (ForkJoinPool pool = new ForkJoinPool(2)) { - CountDownLatch started = new CountDownLatch(1); - CountDownLatch release = new CountDownLatch(1); - CountDownLatch failed = new CountDownLatch(1); - AtomicInteger completed = new AtomicInteger(); - IllegalStateException failure = new IllegalStateException("density failure"); - Future parent = pool.submit(() -> IrisCaveCarver3D.runDensityTasks(List.of(() -> { - await(started); - failed.countDown(); - throw failure; - }, () -> { - started.countDown(); - await(release); - completed.incrementAndGet(); - }), pool)); - try { - assertTrue(failed.await(5, TimeUnit.SECONDS)); - assertFalse(parent.isDone()); - } finally { - release.countDown(); - } - try { - parent.get(5, TimeUnit.SECONDS); - fail("Expected density failure"); - } catch (ExecutionException expected) { - Throwable cause = expected.getCause(); - assertTrue(cause == failure || cause.getCause() == failure); - } - assertEquals(1, completed.get()); - } - } - - @Test - public void interruptionDrainsWorkerAndRestoresInterruptStatus() throws Exception { - try (ForkJoinPool pool = new ForkJoinPool(2)) { - CountDownLatch started = new CountDownLatch(1); - CountDownLatch release = new CountDownLatch(1); - CountDownLatch awaiting = new CountDownLatch(1); - AtomicReference parentThread = new AtomicReference<>(); - AtomicInteger completed = new AtomicInteger(); - Future parent = pool.submit(() -> { - parentThread.set(Thread.currentThread()); - try { - IrisCaveCarver3D.runDensityTasks(List.of(() -> { - await(started); - awaiting.countDown(); - }, () -> { - started.countDown(); - await(release); - completed.incrementAndGet(); - }), pool); - return false; - } catch (IllegalStateException expected) { - return Thread.currentThread().isInterrupted(); - } - }); - try { - assertTrue(awaiting.await(5, TimeUnit.SECONDS)); - parentThread.get().interrupt(); - assertFalse(parent.isDone()); - } finally { - release.countDown(); - } - assertTrue(parent.get(5, TimeUnit.SECONDS)); - assertEquals(1, completed.get()); - } - } - - @Test - public void rejectedSubmissionClaimsAllWorkBeforeFailureReturns() { - ForkJoinPool pool = new ForkJoinPool(2); - pool.shutdown(); - AtomicInteger completed = new AtomicInteger(); - try { - IrisCaveCarver3D.runDensityTasks(List.of(completed::incrementAndGet, completed::incrementAndGet), pool); - fail("Expected rejected submission"); - } catch (RejectedExecutionException expected) { - assertEquals(2, completed.get()); - } - } - - @Test - public void managedDrainCompensatesWithoutRunningUnrelatedWorkOnParent() throws Exception { - try (ForkJoinPool pool = new ForkJoinPool(2, ForkJoinPool.defaultForkJoinWorkerThreadFactory, - null, false, 2, 3, 2, null, 60, TimeUnit.SECONDS)) { - CountDownLatch started = new CountDownLatch(1); - CountDownLatch awaiting = new CountDownLatch(1); - CountDownLatch release = new CountDownLatch(1); - AtomicReference owner = new AtomicReference<>(); - Object chunkFlag = new Object(); - Future parent = pool.submit(() -> { - synchronized (chunkFlag) { - owner.set(Thread.currentThread()); - IrisCaveCarver3D.runDensityTasks(List.of(() -> { - await(started); - awaiting.countDown(); - }, () -> { - started.countDown(); - await(release); - }), pool); - } - }); - try { - assertTrue(awaiting.await(5, TimeUnit.SECONDS)); - Thread other = pool.submit(Thread::currentThread).get(5, TimeUnit.SECONDS); - assertFalse(other == owner.get()); - assertFalse(parent.isDone()); - } finally { - release.countDown(); - } - parent.get(5, TimeUnit.SECONDS); - } - } - - @Test - public void unavailableCompensationStillDrainsStartedWork() throws Exception { - try (ForkJoinPool pool = new ForkJoinPool(2, ForkJoinPool.defaultForkJoinWorkerThreadFactory, - null, false, 2, 2, 2, null, 60, TimeUnit.SECONDS)) { - CountDownLatch started = new CountDownLatch(1); - CountDownLatch awaiting = new CountDownLatch(1); - CountDownLatch release = new CountDownLatch(1); - AtomicInteger completed = new AtomicInteger(); - Future parent = pool.submit(() -> IrisCaveCarver3D.runDensityTasks(List.of(() -> { - await(started); - awaiting.countDown(); - }, () -> { - started.countDown(); - await(release); - completed.incrementAndGet(); - }), pool)); - try { - assertTrue(awaiting.await(5, TimeUnit.SECONDS)); - assertFalse(parent.isDone()); - } finally { - release.countDown(); - } - parent.get(5, TimeUnit.SECONDS); - assertEquals(1, completed.get()); - } - } - - @Test - public void completedTasksStillPropagateAnExistingInterrupt() { - try (ForkJoinPool pool = new ForkJoinPool(1)) { - Thread.currentThread().interrupt(); - try { - IrisCaveCarver3D.runDensityTasks(List.of(() -> {}), pool); - fail("Expected interrupted density batch"); - } catch (IllegalStateException expected) { - assertTrue(Thread.currentThread().isInterrupted()); - } finally { - Thread.interrupted(); - } - } - } - - private static void await(CountDownLatch latch) { - try { - if (!latch.await(5, TimeUnit.SECONDS)) { - throw new AssertionError("Timed out waiting for density task"); - } - } catch (InterruptedException failure) { - Thread.currentThread().interrupt(); - throw new AssertionError(failure); - } - } -} diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DCellKernelTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DCellKernelTest.java deleted file mode 100644 index f147d7576..000000000 --- a/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DCellKernelTest.java +++ /dev/null @@ -1,414 +0,0 @@ -package art.arcane.iris.generation.mantle; - -import art.arcane.iris.generation.cave.IrisCaveFieldModule; -import art.arcane.iris.generation.cave.IrisCaveProfile; -import art.arcane.iris.generation.noise.IrisGeneratorStyle; -import art.arcane.iris.generation.noise.IrisStyledRange; -import art.arcane.iris.generation.noise.NoiseStyle; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.generation.runtime.EngineMetrics; -import art.arcane.iris.generation.runtime.SeedManager; -import art.arcane.iris.generation.terrain.IrisDimension; -import art.arcane.iris.pack.loading.IrisData; -import art.arcane.iris.pack.value.IrisRange; -import art.arcane.iris.world.IrisWorld; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.mantle.runtime.Mantle; -import art.arcane.volmlib.util.mantle.runtime.MantleChunk; -import art.arcane.volmlib.util.matter.Matter; -import art.arcane.volmlib.util.matter.MatterCavern; -import art.arcane.volmlib.util.matter.MatterSlice; -import art.arcane.volmlib.util.matter.slices.CavernMatter; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.TimeUnit; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.withSettings; - -public class IrisCaveCarver3DCellKernelTest { - private static final long CARVE_SEED = -54_777_863_784_492_918L; - private static final int WORLD_HEIGHT = 160; - private static final int CHUNK_SPAN = 4; - - @Test - public void warpModulesProfileMatchesGoldenWriteSequence() throws Exception { - assertScenario(Scenario.WARP_MODULES, 0xdf617c77d3c3cc5eL, 67798); - } - - @Test - public void warpOnlyTerrainProfileMatchesGoldenWriteSequence() throws Exception { - assertScenario(Scenario.WARP_TERRAIN, 0x7e0b63cab5bb3904L, 67036); - } - - @Test - public void styledThresholdBlendProfileMatchesGoldenWriteSequence() throws Exception { - assertScenario(Scenario.STYLED_BLEND, 0x25792d49143774faL, 30387); - } - - @Test - public void fluidBoundaryProfileMatchesGoldenWriteSequence() throws Exception { - assertScenario(Scenario.FLUID_BOUNDARY, 0xb102145856119afeL, 17584); - } - - @Test - public void noWarpModulesProfileMatchesGoldenWriteSequence() throws Exception { - assertScenario(Scenario.NO_WARP_MODULES, 0x5a83dc20c89c6398L, 47534); - } - - @Test - public void verticalStepProfileMatchesGoldenWriteSequence() throws Exception { - assertScenario(Scenario.VERTICAL_STEP, 0xac0413031ed65b61L, 48011); - } - - @Test - public void latticeProfileMatchesGoldenWriteSequence() throws Exception { - assertScenario(Scenario.LATTICE, 0xc7ffab155e6bdef9L, 72714); - } - - @Test - public void floorFluidProfilesSharingChunksMatchGoldenWriteSequence() throws Exception { - assertScenario(Scenario.FLOOR_FLUID_LAYERED, 0xb4c0fb23e071617dL, 68747); - } - - @Test - public void packStyleProfilesSharingFieldsMatchGoldenWriteSequence() throws Exception { - assertScenario(Scenario.PACK_SHARED, 0xdbe20a1ca87f9cc7L, 269035); - } - - @Test - public void cellKernelDecidesCellsWithoutColumnEvaluation() throws Exception { - IrisCaveCarver3D.CellCounters before = IrisCaveCarver3D.cellCounters(); - run(Scenario.WARP_MODULES, false); - IrisCaveCarver3D.CellCounters after = IrisCaveCarver3D.cellCounters(); - long decided = after.decided() - before.decided(); - long evaluated = after.evaluated() - before.evaluated(); - assertTrue("decided=" + decided + " evaluated=" + evaluated, decided > 0L && evaluated > 0L); - } - - private void assertScenario(Scenario scenario, long expectedHash, int expectedWrites) throws Exception { - Result serial = run(scenario, false); - Result parallel = run(scenario, true); - assertTrue(serial.carved > 0); - assertEquals(serial.hash, parallel.hash); - assertEquals(serial.writes, parallel.writes); - assertEquals(serial.carved, parallel.carved); - assertEquals(expectedHash, serial.hash); - assertEquals(expectedWrites, serial.writes); - } - - private Result run(Scenario scenario, boolean parallel) throws Exception { - if (!parallel) { - return carveArea(scenario); - } - ForkJoinPool pool = new ForkJoinPool(4); - try { - return pool.submit(() -> carveArea(scenario)).get(120, TimeUnit.SECONDS); - } finally { - pool.shutdownNow(); - } - } - - private Result carveArea(Scenario scenario) { - Engine engine = createEngine(scenario); - CaveDensityGrid grid = new CaveDensityGrid(4096); - IrisCaveProfile[] profiles = scenario.profiles(); - IrisCaveCarver3D[] carvers = new IrisCaveCarver3D[profiles.length]; - for (int index = 0; index < profiles.length; index++) { - carvers[index] = new IrisCaveCarver3D(engine, profiles[index], grid); - } - Capture capture = new Capture(); - int carved = 0; - for (int chunkX = -2; chunkX < CHUNK_SPAN - 2; chunkX++) { - for (int chunkZ = -1; chunkZ < CHUNK_SPAN - 1; chunkZ++) { - MantleWriter writer = capture.writer(chunkX, chunkZ); - CaveFluidSupportPlan supportPlan = new CaveFluidSupportPlan(); - for (int index = 0; index < carvers.length; index++) { - carved += carvers[index].carve(writer, chunkX, chunkZ, scenario.weights(index, chunkX, chunkZ), - 0.08D, 0.24D, scenario.worldYRange(), scenario.surfaceHeights(chunkX, chunkZ), - scenario.boundaries(chunkX, chunkZ), null, null, supportPlan); - } - capture.resolving = true; - supportPlan.resolve(writer.acquireChunk(chunkX, chunkZ)); - capture.finishResolve(); - } - } - return new Result(capture.hash, capture.writes, carved); - } - - private Engine createEngine(Scenario scenario) { - Engine engine = mock(Engine.class, withSettings().stubOnly()); - IrisData data = mock(IrisData.class, withSettings().stubOnly()); - IrisDimension dimension = mock(IrisDimension.class, withSettings().stubOnly()); - SeedManager seedManager = mock(SeedManager.class, withSettings().stubOnly()); - doReturn(data).when(engine).getData(); - doReturn(dimension).when(engine).getDimension(); - doReturn(seedManager).when(engine).getSeedManager(); - doReturn(CARVE_SEED).when(seedManager).getCarve(); - doReturn(new EngineMetrics(16)).when(engine).getMetrics(); - doReturn(IrisWorld.builder().minHeight(-32).maxHeight(WORLD_HEIGHT - 32).build()).when(engine).getWorld(); - doReturn(WORLD_HEIGHT).when(engine).getHeight(); - doReturn(110).when(engine).getHeight(anyInt(), anyInt()); - doReturn(24).when(dimension).getCaveLavaHeight(); - doReturn(70).when(dimension).getFluidHeight(); - doReturn(scenario == Scenario.VERTICAL_STEP ? 4 : 1).when(dimension).getCaveDensitySamplingStep(); - return engine; - } - - private static IrisCaveProfile baseProfile(boolean warp, boolean modules) { - IrisCaveProfile profile = new IrisCaveProfile(); - profile.setEnabled(true); - profile.setVerticalRange(new IrisRange(4D, 150D)); - profile.setVerticalEdgeFade(14); - profile.setVerticalEdgeFadeStrength(0.21D); - profile.setBaseDensityStyle(new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.21D)); - profile.setDetailDensityStyle(new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.43D)); - profile.setWarpStyle(new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.37D)); - profile.setSurfaceBreakStyle(new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.140625D)); - profile.setBaseWeight(1D); - profile.setDetailWeight(0.42D); - profile.setWarpStrength(warp ? 3.7D : 0D); - profile.setDensityThreshold(new IrisStyledRange(-0.18D, -0.18D, new IrisGeneratorStyle(NoiseStyle.FLAT))); - profile.setThresholdBias(0D); - profile.setSampleStep(1); - profile.setSurfaceClearance(5); - profile.setAllowSurfaceBreak(true); - profile.setSurfaceBreakNoiseThreshold(0.3D); - profile.setSurfaceBreakDepth(14); - profile.setSurfaceBreakThresholdBoost(0.21D); - profile.setAllowFluid(false); - profile.setAllowLava(true); - KList caveModules = new KList<>(); - if (modules) { - caveModules.add(new IrisCaveFieldModule(new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.33D), - 0.27D, 0.05D, new IrisRange(0D, 90D), false)); - caveModules.add(new IrisCaveFieldModule(new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.51D), - 0.19D, -0.07D, new IrisRange(40D, 150D), true)); - } - profile.setModules(caveModules); - return profile; - } - - private static IrisCaveProfile packProfile(NoiseStyle warp, double warpZoom, double warpStrength, NoiseStyle base, - double baseZoom, double threshold, IrisCaveFieldModule... modules) { - IrisCaveProfile profile = baseProfile(true, false); - profile.setWarpStyle(new IrisGeneratorStyle(warp).zoomed(warpZoom)); - profile.setWarpStrength(warpStrength); - profile.setBaseDensityStyle(new IrisGeneratorStyle(base).zoomed(baseZoom)); - profile.setDetailDensityStyle(new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.5D)); - profile.setBaseWeight(0.82D); - profile.setDetailWeight(0.15D); - profile.setDensityThreshold(new IrisStyledRange(threshold - 0.06D, threshold + 0.05D, - new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.78D))); - profile.setThresholdBias(0.12D); - profile.setSampleStep(2); - profile.setModules(new KList<>(modules)); - return profile; - } - - private static IrisCaveFieldModule packModule(NoiseStyle style, double zoom, double weight, double threshold, - double minY, double maxY, boolean invert) { - return new IrisCaveFieldModule(new IrisGeneratorStyle(style).zoomed(zoom), weight, threshold, - new IrisRange(minY, maxY), invert); - } - - private enum Scenario { - PACK_SHARED, - WARP_MODULES, - WARP_TERRAIN, - STYLED_BLEND, - FLUID_BOUNDARY, - NO_WARP_MODULES, - VERTICAL_STEP, - LATTICE, - FLOOR_FLUID_LAYERED; - - IrisCaveProfile[] profiles() { - if (this == PACK_SHARED) { - return new IrisCaveProfile[]{ - packProfile(NoiseStyle.FRACTAL_WATER, 0.44D, 3.2D, NoiseStyle.PERLIN_IRIS, 0.72D, -0.02D, - packModule(NoiseStyle.FRACTAL_FBM_SIMPLEX, 0.24D, 0.08D, 0.03D, 10D, 140D, false), - packModule(NoiseStyle.SIMPLEX_VASCULAR, 1.02D, 0.05D, 0.07D, 4D, 90D, true)), - packProfile(NoiseStyle.FRACTAL_WATER, 0.44D, 3.2D, NoiseStyle.FRACTAL_BILLOW_SIMPLEX, 0.656D, 0.01D, - packModule(NoiseStyle.CELLULAR_BILINEAR, 1.32D, 0.06D, 0.02D, 20D, 150D, false)), - packProfile(NoiseStyle.FRACTAL_WATER, 0.44D, 3.2D, NoiseStyle.PERLIN_IRIS, 0.72D, 0.04D, - packModule(NoiseStyle.FRACTAL_FBM_SIMPLEX, 0.24D, 0.08D, 0.03D, 10D, 140D, false), - packModule(NoiseStyle.SIMPLEX_VASCULAR, 1.02D, 0.05D, 0.07D, 4D, 90D, true)), - packProfile(NoiseStyle.PERLIN_IRIS, 0.35D, 2.4D, NoiseStyle.IRIS_DOUBLE, 0.68D, -0.04D, - packModule(NoiseStyle.VASCULAR_THIN, 1.28D, 0.04D, 0.05D, 8D, 120D, false)) - }; - } - if (this == FLOOR_FLUID_LAYERED) { - return new IrisCaveProfile[]{ - baseProfile(true, true).setAllowFluid(true).setFluidRequiresFloor(true).setFluidMinDepthBelowSurface(4), - baseProfile(true, false).setAllowFluid(true).setFluidRequiresFloor(true).setFluidMinDepthBelowSurface(2) - .setAllowLava(false).setDensityThreshold(new IrisStyledRange(-0.24D, -0.08D, - new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.45D))) - }; - } - return new IrisCaveProfile[]{profile()}; - } - - IrisCaveProfile profile() { - return switch (this) { - case WARP_MODULES, VERTICAL_STEP -> baseProfile(true, true); - case WARP_TERRAIN -> baseProfile(true, false); - case STYLED_BLEND -> baseProfile(false, false).setDensityThreshold(new IrisStyledRange(-0.32D, -0.04D, - new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.6D))); - case FLUID_BOUNDARY -> baseProfile(true, true).setAllowFluid(true).setFluidRequiresFloor(false) - .setFluidMinDepthBelowSurface(6).setAllowLava(false); - case NO_WARP_MODULES -> baseProfile(false, true); - case LATTICE -> baseProfile(true, true).setSampleStep(3); - case FLOOR_FLUID_LAYERED, PACK_SHARED -> baseProfile(true, true); - }; - } - - double[] weights(int layer, int chunkX, int chunkZ) { - double[] weights = new double[256]; - for (int index = 0; index < 256; index++) { - int worldX = (chunkX << 4) + (index >> 4); - int worldZ = (chunkZ << 4) + (index & 15); - double blend = 0.5D + 0.6D * Math.sin(worldX * 0.11D) * Math.cos(worldZ * 0.07D); - weights[index] = switch (this) { - case PACK_SHARED -> 0.5D + 0.6D * Math.sin(worldX * 0.13D + layer * 1.7D) * Math.cos(worldZ * 0.09D - layer); - case STYLED_BLEND, FLUID_BOUNDARY -> blend; - case FLOOR_FLUID_LAYERED -> layer == 0 ? blend : 1D - blend; - default -> 1D; - }; - } - return weights; - } - - int[] surfaceHeights(int chunkX, int chunkZ) { - int[] heights = new int[256]; - for (int index = 0; index < 256; index++) { - int worldX = (chunkX << 4) + (index >> 4); - int worldZ = (chunkZ << 4) + (index & 15); - heights[index] = this == WARP_MODULES || this == LATTICE || this == FLOOR_FLUID_LAYERED - ? 118 - : 96 + (int) Math.round(22D * Math.sin(worldX * 0.09D) + 15D * Math.cos(worldZ * 0.13D)); - } - return heights; - } - - IrisRange worldYRange() { - return this == FLUID_BOUNDARY || this == FLOOR_FLUID_LAYERED ? new IrisRange(-20D, 100D) : null; - } - - long[] boundaries(int chunkX, int chunkZ) { - long[] boundaries = new long[256]; - Arrays.fill(boundaries, SurfaceFluidBoundaryPlan.boundary(SurfaceFluidBoundaryPlan.NO_BOUNDARY, Integer.MIN_VALUE)); - if (this != FLUID_BOUNDARY && this != WARP_TERRAIN) { - return boundaries; - } - for (int index = 0; index < 256; index++) { - int worldX = (chunkX << 4) + (index >> 4); - if (Math.floorMod(worldX + chunkZ, 5) == 0) { - boundaries[index] = SurfaceFluidBoundaryPlan.boundary(60 + Math.floorMod(index, 7), 82); - } - } - return boundaries; - } - } - - private record Result(long hash, int writes, int carved) { - } - - private static final class Capture { - private final Map> chunks = new HashMap<>(); - private final IdentityHashMap identities = new IdentityHashMap<>(); - private final List resolved = new ArrayList<>(); - private long hash = 0xcbf29ce484222325L; - private int writes; - private boolean resolving; - - private MantleWriter writer(int chunkX, int chunkZ) { - MantleWriter writer = mock(MantleWriter.class, withSettings().stubOnly()); - @SuppressWarnings("unchecked") - Mantle mantle = mock(Mantle.class, withSettings().stubOnly()); - @SuppressWarnings("unchecked") - MantleChunk chunk = mock(MantleChunk.class, withSettings().stubOnly()); - long key = ((long) chunkX << 32) ^ (chunkZ & 0xffffffffL); - Map sections = chunks.computeIfAbsent(key, ignored -> new HashMap<>()); - doReturn(mantle).when(writer).getMantle(); - doReturn(WORLD_HEIGHT).when(mantle).getWorldHeight(); - doReturn(chunk).when(writer).acquireChunk(anyInt(), anyInt()); - doAnswer(invocation -> sections.get(invocation.getArgument(0, Integer.class))).when(chunk).get(anyInt()); - doAnswer(invocation -> sections.computeIfAbsent(invocation.getArgument(0, Integer.class), - sectionIndex -> createSection(chunkX, chunkZ, sectionIndex))).when(chunk).getOrCreate(anyInt()); - return writer; - } - - private Matter createSection(int chunkX, int chunkZ, int sectionIndex) { - mix(0x5EC7L); - mix(chunkX); - mix(chunkZ); - mix(sectionIndex); - Matter matter = mock(Matter.class, withSettings().stubOnly()); - MatterSlice slice = new RecordingCavernMatter(this, sectionIndex); - doReturn(slice).when(matter).slice(MatterCavern.class); - doReturn(slice).when(matter).getSlice(MatterCavern.class); - return matter; - } - - private void record(int sectionIndex, int x, int y, int z, MatterCavern value) { - writes++; - if (resolving) { - resolved.add(((long) sectionIndex << 20) | ((long) x << 16) | ((long) y << 12) | ((long) z << 8) | value.getLiquid()); - return; - } - mix(sectionIndex); - mix((x << 8) | (y << 4) | z); - mix(value == null ? -1 : value.getLiquid()); - Integer identity = identities.get(value); - if (identity == null) { - identity = identities.size(); - identities.put(value, identity); - } - mix(identity); - } - - private void finishResolve() { - resolving = false; - resolved.sort(Long::compare); - for (long entry : resolved) { - mix(entry); - } - resolved.clear(); - } - - private void mix(long value) { - hash ^= value; - hash *= 0x100000001b3L; - } - } - - private static final class RecordingCavernMatter extends CavernMatter { - private final Capture capture; - private final int sectionIndex; - - private RecordingCavernMatter(Capture capture, int sectionIndex) { - super(16, 16, 16); - this.capture = capture; - this.sectionIndex = sectionIndex; - } - - @Override - public void set(int x, int y, int z, MatterCavern value) { - super.set(x, y, z, value); - capture.record(sectionIndex, x, y, z, value); - } - } -} diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DLatticeTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DLatticeTest.java deleted file mode 100644 index 2f0d6aab3..000000000 --- a/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DLatticeTest.java +++ /dev/null @@ -1,177 +0,0 @@ -package art.arcane.iris.generation.mantle; - -import art.arcane.iris.generation.cave.IrisCaveFieldModule; -import art.arcane.iris.generation.cave.IrisCaveProfile; -import art.arcane.iris.generation.noise.IrisGeneratorStyle; -import art.arcane.iris.generation.noise.IrisStyledRange; -import art.arcane.iris.generation.noise.NoiseStyle; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.generation.runtime.EngineMetrics; -import art.arcane.iris.generation.runtime.SeedManager; -import art.arcane.iris.generation.terrain.IrisDimension; -import art.arcane.iris.pack.loading.IrisData; -import art.arcane.iris.pack.value.IrisRange; -import art.arcane.iris.world.IrisWorld; -import art.arcane.volmlib.util.collection.KList; -import org.junit.Test; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Random; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.withSettings; - -public class IrisCaveCarver3DLatticeTest { - private static final long CARVE_SEED = 7_340_119_802_557L; - private static final int WORLD_HEIGHT = 384; - - @Test - public void batchedLatticePointsMatchScalarPlaneDensityBitForBit() throws Exception { - Engine engine = createEngine(); - CaveDensityGrid grid = new CaveDensityGrid(256); - IrisCaveProfile[] profiles = { - profile(NoiseStyle.FRACTAL_WATER, 0.44D, 3.2D, NoiseStyle.PERLIN_IRIS, 0.72D, - module(NoiseStyle.FRACTAL_FBM_SIMPLEX, 0.24D, 10D, 140D, false), - module(NoiseStyle.CELLULAR_BILINEAR, 1.32D, 4D, 300D, true)), - profile(NoiseStyle.PERLIN_IRIS, 0.35D, 2.4D, NoiseStyle.IRIS_DOUBLE, 0.68D, - module(NoiseStyle.VASCULAR_THIN, 1.28D, 8D, 220D, false)), - profile(NoiseStyle.SIMPLEX, 0.5D, 0D, NoiseStyle.FRACTAL_BILLOW_SIMPLEX, 0.656D) - }; - Method sampleLatticePoints = IrisCaveCarver3D.class.getDeclaredMethod("sampleLatticePoints", - CaveLatticeBatch.class, CaveDensityLattice.class, int.class, int.class, int.class); - sampleLatticePoints.setAccessible(true); - Method samplePlaneDensity = IrisCaveCarver3D.class.getDeclaredMethod("samplePlaneDensity", - CaveCarveScratch.class, int.class, int.class, int.class); - samplePlaneDensity.setAccessible(true); - Field warpOwnerField = IrisCaveCarver3D.class.getDeclaredField("warpOwner"); - warpOwnerField.setAccessible(true); - Random random = new Random(91_337L); - for (IrisCaveProfile profile : profiles) { - IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, profile, grid); - CaveDensityGrid.Owner warpOwner = (CaveDensityGrid.Owner) warpOwnerField.get(carver); - CaveLatticeBatch batch = new CaveLatticeBatch(); - CaveDensityLattice lattice = new CaveDensityLattice(); - CaveCarveScratch reference = new CaveCarveScratch(); - for (int trial = 0; trial < 24; trial++) { - int latticeX = random.nextInt(4001) - 2000; - int latticeZ = random.nextInt(4001) - 2000; - int x0 = latticeX << CaveDensityGrid.LATTICE_SHIFT; - int z0 = latticeZ << CaveDensityGrid.LATTICE_SHIFT; - for (int corner = 0; corner < CaveDensityLattice.CORNERS; corner++) { - lattice.warpColumns[corner] = (trial + corner) % 3 == 0 ? null - : grid.warpColumn(warpOwner, WORLD_HEIGHT + 1, latticeX + corner / 3, latticeZ + corner % 3); - } - int count = selectRows(random, batch); - for (int pass = 0; pass < 2; pass++) { - sampleLatticePoints.invoke(carver, batch, lattice, x0, z0, count); - for (int corner = 0; corner < CaveDensityLattice.CORNERS; corner++) { - int x = x0 + (corner / 3) * 8; - int z = z0 + (corner % 3) * 8; - for (int index = batch.cornerStart[corner]; index < batch.cornerStart[corner + 1]; index++) { - int y = batch.y[index]; - double expected = (double) samplePlaneDensity.invoke(carver, reference, x, y, z); - assertEquals("x=" + x + " y=" + y + " z=" + z + " pass=" + pass, - Double.doubleToRawLongBits(expected), Double.doubleToRawLongBits(batch.density[index])); - } - } - } - } - } - } - - @Test - public void identicalFieldsShareGridOwnersAcrossProfiles() throws Exception { - Engine engine = createEngine(); - CaveDensityGrid grid = new CaveDensityGrid(256); - Field densityOwnerField = IrisCaveCarver3D.class.getDeclaredField("densityOwner"); - densityOwnerField.setAccessible(true); - Field warpOwnerField = IrisCaveCarver3D.class.getDeclaredField("warpOwner"); - warpOwnerField.setAccessible(true); - IrisCaveCarver3D first = new IrisCaveCarver3D(engine, profile(NoiseStyle.FRACTAL_WATER, 0.44D, 3.2D, - NoiseStyle.PERLIN_IRIS, 0.72D, module(NoiseStyle.SIMPLEX_VASCULAR, 1.02D, 4D, 90D, true)), grid); - IrisCaveCarver3D sameDensity = new IrisCaveCarver3D(engine, profile(NoiseStyle.FRACTAL_WATER, 0.44D, 3.2D, - NoiseStyle.PERLIN_IRIS, 0.72D, module(NoiseStyle.SIMPLEX_VASCULAR, 1.02D, 4D, 90D, true)) - .setDensityThreshold(new IrisStyledRange(0.2D, 0.2D, new IrisGeneratorStyle(NoiseStyle.FLAT))), grid); - IrisCaveCarver3D sameWarp = new IrisCaveCarver3D(engine, profile(NoiseStyle.FRACTAL_WATER, 0.44D, 1.7D, - NoiseStyle.FRACTAL_BILLOW_SIMPLEX, 0.656D), grid); - IrisCaveCarver3D otherWarp = new IrisCaveCarver3D(engine, profile(NoiseStyle.FRACTAL_WATER, 0.46D, 3.2D, - NoiseStyle.PERLIN_IRIS, 0.72D, module(NoiseStyle.SIMPLEX_VASCULAR, 1.02D, 4D, 90D, true)), grid); - IrisCaveCarver3D otherModule = new IrisCaveCarver3D(engine, profile(NoiseStyle.FRACTAL_WATER, 0.44D, 3.2D, - NoiseStyle.PERLIN_IRIS, 0.72D, module(NoiseStyle.SIMPLEX_VASCULAR, 1.02D, 4D, 91D, true)), grid); - assertSame(densityOwnerField.get(first), densityOwnerField.get(sameDensity)); - assertSame(warpOwnerField.get(first), warpOwnerField.get(sameDensity)); - assertSame(warpOwnerField.get(first), warpOwnerField.get(sameWarp)); - assertSame(warpOwnerField.get(first), warpOwnerField.get(otherModule)); - assertNotSame(densityOwnerField.get(first), densityOwnerField.get(sameWarp)); - assertNotSame(densityOwnerField.get(first), densityOwnerField.get(otherModule)); - assertNotSame(densityOwnerField.get(first), densityOwnerField.get(otherWarp)); - assertNotSame(warpOwnerField.get(first), warpOwnerField.get(otherWarp)); - } - - private static int selectRows(Random random, CaveLatticeBatch batch) { - batch.ensure(WORLD_HEIGHT * CaveDensityLattice.CORNERS); - int count = 0; - for (int corner = 0; corner < CaveDensityLattice.CORNERS; corner++) { - batch.cornerStart[corner] = count; - if (random.nextInt(4) == 0) { - continue; - } - int start = random.nextInt(40); - int end = start + random.nextInt(WORLD_HEIGHT - start); - for (int y = start; y <= end; y++) { - if (random.nextInt(5) != 0) { - batch.y[count++] = y; - } - } - } - batch.cornerStart[CaveDensityLattice.CORNERS] = count; - return count; - } - - private static IrisCaveProfile profile(NoiseStyle warp, double warpZoom, double warpStrength, NoiseStyle base, - double baseZoom, IrisCaveFieldModule... modules) { - IrisCaveProfile profile = new IrisCaveProfile(); - profile.setEnabled(true); - profile.setVerticalRange(new IrisRange(4D, 360D)); - profile.setWarpStyle(new IrisGeneratorStyle(warp).zoomed(warpZoom)); - profile.setWarpStrength(warpStrength); - profile.setBaseDensityStyle(new IrisGeneratorStyle(base).zoomed(baseZoom)); - profile.setDetailDensityStyle(new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.5D)); - profile.setSurfaceBreakStyle(new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.82D)); - profile.setBaseWeight(0.82D); - profile.setDetailWeight(0.15D); - profile.setDensityThreshold(new IrisStyledRange(-0.1D, 0.02D, new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.78D))); - profile.setSampleStep(2); - profile.setModules(new KList<>(modules)); - return profile; - } - - private static IrisCaveFieldModule module(NoiseStyle style, double zoom, double minY, double maxY, boolean invert) { - return new IrisCaveFieldModule(new IrisGeneratorStyle(style).zoomed(zoom), 0.07D, 0.04D, new IrisRange(minY, maxY), invert); - } - - private static Engine createEngine() { - Engine engine = mock(Engine.class, withSettings().stubOnly()); - IrisData data = mock(IrisData.class, withSettings().stubOnly()); - IrisDimension dimension = mock(IrisDimension.class, withSettings().stubOnly()); - SeedManager seedManager = mock(SeedManager.class, withSettings().stubOnly()); - doReturn(data).when(engine).getData(); - doReturn(dimension).when(engine).getDimension(); - doReturn(seedManager).when(engine).getSeedManager(); - doReturn(CARVE_SEED).when(seedManager).getCarve(); - doReturn(new EngineMetrics(16)).when(engine).getMetrics(); - doReturn(IrisWorld.builder().minHeight(-64).maxHeight(WORLD_HEIGHT - 64).build()).when(engine).getWorld(); - doReturn(WORLD_HEIGHT).when(engine).getHeight(); - doReturn(200).when(engine).getHeight(anyInt(), anyInt()); - doReturn(20).when(dimension).getCaveLavaHeight(); - doReturn(64).when(dimension).getFluidHeight(); - doReturn(1).when(dimension).getCaveDensitySamplingStep(); - return engine; - } -} diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DNearParityTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DNearParityTest.java deleted file mode 100644 index b9c2b1206..000000000 --- a/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DNearParityTest.java +++ /dev/null @@ -1,2060 +0,0 @@ -package art.arcane.iris.generation.mantle; - -import art.arcane.iris.pack.loading.IrisData; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.generation.runtime.EngineMetrics; -import art.arcane.iris.generation.runtime.SeedManager; -import art.arcane.iris.generation.cave.IrisCaveFieldModule; -import art.arcane.iris.generation.cave.IrisCaveProfile; -import art.arcane.iris.generation.hydrology.config.IrisHydrology; -import art.arcane.iris.testsupport.WaterScene; -import art.arcane.iris.generation.terrain.IrisDimension; -import art.arcane.iris.generation.noise.IrisGeneratorStyle; -import art.arcane.iris.pack.value.IrisRange; -import art.arcane.iris.generation.noise.IrisStyledRange; -import art.arcane.iris.world.IrisWorld; -import art.arcane.iris.generation.noise.NoiseStyle; -import art.arcane.volmlib.util.noise.CNG; -import art.arcane.volmlib.util.noise.program.NoiseProgram; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.mantle.runtime.Mantle; -import art.arcane.volmlib.util.mantle.runtime.MantleChunk; -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.MatterCavern; -import art.arcane.volmlib.util.matter.MatterSlice; -import art.arcane.volmlib.util.matter.slices.CavernMatter; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.atomic.AtomicReference; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.TimeUnit; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyDouble; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.withSettings; - -public class IrisCaveCarver3DNearParityTest { - private static final long CARVE_SEED = -54_777_863_784_492_918L; - private static final int SURFACE_CEILING_FADE_DEPTH = 12; - private static final double SURFACE_CEILING_SOLID_EPSILON = 0.000001D; - - private static Method sampleDensityMethod; - private static Method aquiferCandidateMethod; - private static Method aquiferCupSupportMethod; - private static Method deepAdaptivePlaneMethod; - private static Field baseDensityField; - private static Field detailDensityField; - private static Field modulesField; - private static Field moduleDensityField; - private static Field engineField; - private static Field dataField; - private static Field profileField; - private static Field surfaceBreakDensityField; - private static Field thresholdRngField; - private static Field carveAirField; - private static Field carveFluidField; - private static Field carveLavaField; - private static Field carveForcedAirField; - - @BeforeClass - public static void setupReflection() throws Exception { - sampleDensityMethod = IrisCaveCarver3D.class.getDeclaredMethod("sampleDensityOptimized", int.class, int.class, int.class); - sampleDensityMethod.setAccessible(true); - aquiferCandidateMethod = IrisCaveCarver3D.class.getDeclaredMethod("isAquiferCandidate", int.class, int.class, int.class, double.class); - aquiferCandidateMethod.setAccessible(true); - aquiferCupSupportMethod = IrisCaveCarver3D.class.getDeclaredMethod( - "hasAquiferCupSupport", CaveCarveScratch.class, int.class, int.class, int.class, double.class); - aquiferCupSupportMethod.setAccessible(true); - deepAdaptivePlaneMethod = IrisCaveCarver3D.class.getDeclaredMethod( - "classifyDeepAdaptivePlaneFromSamples", - CaveCarveScratch.class, - int[].class, - double[].class, - int.class, - boolean[].class, - int.class, - double[].class, - int.class, - int.class - ); - deepAdaptivePlaneMethod.setAccessible(true); - baseDensityField = IrisCaveCarver3D.class.getDeclaredField("baseDensity"); - baseDensityField.setAccessible(true); - detailDensityField = IrisCaveCarver3D.class.getDeclaredField("detailDensity"); - detailDensityField.setAccessible(true); - modulesField = IrisCaveCarver3D.class.getDeclaredField("modules"); - modulesField.setAccessible(true); - moduleDensityField = CaveFieldModuleState.class.getDeclaredField("density"); - moduleDensityField.setAccessible(true); - engineField = IrisCaveCarver3D.class.getDeclaredField("engine"); - engineField.setAccessible(true); - dataField = IrisCaveCarver3D.class.getDeclaredField("data"); - dataField.setAccessible(true); - profileField = IrisCaveCarver3D.class.getDeclaredField("profile"); - profileField.setAccessible(true); - surfaceBreakDensityField = IrisCaveCarver3D.class.getDeclaredField("surfaceBreakDensity"); - surfaceBreakDensityField.setAccessible(true); - thresholdRngField = IrisCaveCarver3D.class.getDeclaredField("thresholdRng"); - thresholdRngField.setAccessible(true); - carveAirField = IrisCaveCarver3D.class.getDeclaredField("carveAir"); - carveAirField.setAccessible(true); - carveFluidField = IrisCaveCarver3D.class.getDeclaredField("carveFluid"); - carveFluidField.setAccessible(true); - carveLavaField = IrisCaveCarver3D.class.getDeclaredField("carveLava"); - carveLavaField.setAccessible(true); - carveForcedAirField = IrisCaveCarver3D.class.getDeclaredField("carveForcedAir"); - carveForcedAirField.setAccessible(true); - } - - @Test - public void verticalDensityPlanesUseGlobalAnchorsAndReduceSamplesAcrossChunkEdges() throws Exception { - Engine engine = createEngine(128, 110); - IrisDimension dimension = engine.getDimension(); - doReturn(4).when(dimension).getCaveDensitySamplingStep(); - doReturn(IrisWorld.builder().minHeight(-63).maxHeight(65).build()).when(engine).getWorld(); - IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, - createProfile(false, false).setDetailWeight(0D).setAllowFluid(false)); - AtomicInteger calls = new AtomicInteger(); - Set sampledY = new HashSet<>(); - CNG density = mock(CNG.class, withSettings().stubOnly()); - doAnswer(invocation -> { - calls.incrementAndGet(); - double x = invocation.getArgument(0); - double y = invocation.getArgument(1); - double z = invocation.getArgument(2); - sampledY.add((int) y); - return x * 0.0001D + y * 0.01D + z * 0.0002D; - }).when(density).noiseFastSigned3D(anyDouble(), anyDouble(), anyDouble()); - baseDensityField.set(carver, NoiseProgram.compileSigned3D(density)); - Method prepare = IrisCaveCarver3D.class.getDeclaredMethod("prepareVerticalDensityPlane", - CaveCarveScratch.class, int.class, int.class, int.class); - prepare.setAccessible(true); - CaveCarveScratch scratch = new CaveCarveScratch(); - for (int y = 0; y < 64; y++) { - prepare.invoke(carver, scratch, -16, 32, y); - for (int x = 0; x < 3; x++) { - for (int z = 0; z < 3; z++) { - assertEquals((-16 + x * 8) * 0.0001D + y * 0.01D + (32 + z * 8) * 0.0002D, - scratch.adaptivePlaneDensity[x * 3 + z], 1.0E-14D); - } - } - } - assertEquals(153, calls.get()); - assertFalse(sampledY.contains(1)); - int interpolatedCalls = calls.get(); - doReturn(1).when(dimension).getCaveDensitySamplingStep(); - IrisCaveCarver3D scalar = new IrisCaveCarver3D(engine, - createProfile(false, false).setDetailWeight(0D).setAllowFluid(false)); - baseDensityField.set(scalar, NoiseProgram.compileSigned3D(density)); - CaveCarveScratch scalarScratch = new CaveCarveScratch(); - for (int index = 0; index < 256; index++) { - scalarScratch.planeColumnIndices[index] = index; - } - Method classify = IrisCaveCarver3D.class.getDeclaredMethod("classifyDensityPlaneAdaptive", - CaveCarveScratch.class, int.class, int.class, int.class, int[].class, double[].class, - int.class, boolean[].class, int.class, double.class); - classify.setAccessible(true); - calls.set(0); - for (int y = 0; y < 64; y++) { - classify.invoke(scalar, scalarScratch, -16, 32, y, scalarScratch.planeColumnIndices, - scalarScratch.planeThresholdLimit, 256, scalarScratch.planeCarve, 8, 0.04D); - } - assertEquals(576, calls.get()); - assertTrue(interpolatedCalls < calls.get() * 0.3D); - assertTrue(sampledY.containsAll(List.of(0, 3, 7, 63))); - CaveCarveScratch neighboring = new CaveCarveScratch(); - prepare.invoke(carver, neighboring, 0, 32, 63); - for (int z = 0; z < 3; z++) { - assertEquals(scratch.adaptivePlaneDensity[6 + z], neighboring.adaptivePlaneDensity[z], 0D); - } - prepare.invoke(carver, scratch, 48, -32, 9); - assertEquals(48 * 0.0001D + 0.09D - 32 * 0.0002D, scratch.adaptivePlaneDensity[0], 1.0E-14D); - } - - @Test - public void expressionStylesKeepTheOriginalSamplingAndCarvingBehavior() throws Exception { - CNG density = mock(CNG.class, withSettings().stubOnly()); - AtomicInteger calls = new AtomicInteger(); - doAnswer(invocation -> { - calls.incrementAndGet(); - double y = invocation.getArgument(1); - return Math.sin(y * 0.2D); - }).when(density).noiseFastSigned3D(anyDouble(), anyDouble(), anyDouble()); - IrisGeneratorStyle style = mock(IrisGeneratorStyle.class, withSettings().stubOnly()); - doReturn("density_expression").when(style).getExpression(); - doReturn(density).when(style).create(any(RNG.class), any(IrisData.class)); - IrisCaveProfile profile = createProfile(false, false).setBaseDensityStyle(style) - .setDetailWeight(0D).setAllowFluid(false) - .setDensityThreshold(new IrisStyledRange(0.15D, 0.15D, new IrisGeneratorStyle(NoiseStyle.FLAT))); - WriterCapture expected = null; - int expectedSamples = 0; - for (int step : new int[]{1, 4}) { - Engine engine = createEngine(128, 110); - IrisDimension dimension = engine.getDimension(); - doReturn(step).when(dimension).getCaveDensitySamplingStep(); - WriterCapture capture = createWriterCapture(128); - calls.set(0); - new IrisCaveCarver3D(engine, profile).carve(capture.writer, 0, 0, - fullWeights(), 0D, 0D, null, filledHeights(110)); - assertFalse(capture.carvedCells.isEmpty()); - if (expected == null) { - expected = capture; - expectedSamples = calls.get(); - } else { - assertEquals(expectedSamples, calls.get()); - assertEquals(expected.carvedCells, capture.carvedCells); - assertEquals(expected.carvedLiquids, capture.carvedLiquids); - } - } - } - - @Test - public void sparseProfilesSampleOnlyActiveColumnsAndDiscardPreviousPassColumns() { - for (int sampleStep : new int[]{1, 2, 3}) { - for (boolean adaptive : new boolean[]{false, true}) { - Engine engine = createEngine(128, 110); - AtomicInteger heightSamples = new AtomicInteger(); - doAnswer(invocation -> { - heightSamples.incrementAndGet(); - return 110; - }).when(engine).getHeight(anyInt(), anyInt(), anyBoolean()); - IrisCaveProfile profile = createProfile(false, false) - .setSampleStep(sampleStep).setAdaptiveSampling(adaptive) - .setAllowFluid(false).setAllowSurfaceBreak(false) - .setDensityThreshold(new IrisStyledRange(2D, 2D, new IrisGeneratorStyle(NoiseStyle.FLAT))); - IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, profile); - double[] weights = new double[256]; - weights[0] = 1D; - weights[255] = 1D; - WriterCapture first = createWriterCapture(128); - - carver.carve(first.writer, 0, 0, weights, 0.08D, 0.24D); - - assertEquals(2, heightSamples.get()); - assertFalse(first.carvedCells.isEmpty()); - for (String cell : first.carvedCells) { - int x = coordinate(cell, 0); - int z = coordinate(cell, 2); - assertTrue(x == 0 && z == 0 || x == 15 && z == 15); - } - - Arrays.fill(weights, 0D); - weights[(7 << 4) | 3] = 1D; - heightSamples.set(0); - WriterCapture second = createWriterCapture(128); - - carver.carve(second.writer, 0, 0, weights, 0.08D, 0.24D); - - assertEquals(1, heightSamples.get()); - assertFalse(second.carvedCells.isEmpty()); - for (String cell : second.carvedCells) { - assertEquals(7, coordinate(cell, 0)); - assertEquals(3, coordinate(cell, 2)); - } - } - } - } - - @Test - public void verticalDensityPreservesTwoBlockModuleTunnelsWithoutBleedingAcrossBands() throws Exception { - for (int step : new int[]{2, 4, 8}) { - Engine engine = createEngine(128, 110); - IrisDimension dimension = engine.getDimension(); - doReturn(step).when(dimension).getCaveDensitySamplingStep(); - IrisCaveProfile profile = createProfile(false, false).setDetailWeight(0D).setAllowFluid(false) - .setVerticalEdgeFade(0).setVerticalEdgeFadeStrength(0D).setAllowSurfaceBreak(false) - .setDensityThreshold(new IrisStyledRange(0.25D, 0.25D, new IrisGeneratorStyle(NoiseStyle.FLAT))) - .setModules(new KList<>(new IrisCaveFieldModule(new IrisGeneratorStyle(NoiseStyle.FLAT), - 1D, 0D, new IrisRange(5D, 6D), false))); - IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, profile); - CNG base = mock(CNG.class, withSettings().stubOnly()); - doReturn(1D).when(base).noiseFastSigned3D(anyDouble(), anyDouble(), anyDouble()); - baseDensityField.set(carver, NoiseProgram.compileSigned3D(base)); - CNG module = mock(CNG.class, withSettings().stubOnly()); - doReturn(-1D).when(module).noiseFastSigned3D(anyDouble(), anyDouble(), anyDouble()); - moduleDensityField.set(((CaveFieldModuleState[]) modulesField.get(carver))[0], NoiseProgram.compileSigned3D(module)); - WriterCapture capture = createWriterCapture(128); - carver.carve(capture.writer, -1, 2, fullWeights(), 0D, 0D, null, filledHeights(110)); - assertEquals(512, capture.carvedCells.size()); - for (int x = 0; x < 16; x++) { - for (int z = 0; z < 16; z++) { - assertTrue(capture.carvedCells.contains(cellKey(x, 5, z))); - assertTrue(capture.carvedCells.contains(cellKey(x, 6, z))); - assertFalse(capture.carvedCells.contains(cellKey(x, 4, z))); - assertFalse(capture.carvedCells.contains(cellKey(x, 7, z))); - } - } - } - } - - @Test - public void verticalDensityMatchesParallelDecisionsAndKeepsSurfaceFluidBarriers() throws Exception { - try (ForkJoinPool pool = new ForkJoinPool(4)) { - for (boolean warp : new boolean[]{false, true}) { - Engine engine = createEngine(128, 110); - IrisDimension dimension = engine.getDimension(); - doReturn(4).when(dimension).getCaveDensitySamplingStep(); - doReturn(IrisWorld.builder().minHeight(-63).maxHeight(65).build()).when(engine).getWorld(); - IrisCaveProfile profile = createProfile(warp, true).setFluidRequiresFloor(false) - .setDensityThreshold(new IrisStyledRange(0.15D, 0.15D, new IrisGeneratorStyle(NoiseStyle.FLAT))); - IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, profile); - long[] boundaries = new long[256]; - Arrays.fill(boundaries, SurfaceFluidBoundaryPlan.boundary( - SurfaceFluidBoundaryPlan.NO_BOUNDARY, Integer.MIN_VALUE)); - boundaries[16] = SurfaceFluidBoundaryPlan.boundary(61, 64); - WriterCapture serial = createWriterCapture(128); - WriterCapture parallel = createWriterCapture(128); - int[] heights = filledHeights(110); - int expected = carver.carve(serial.writer, -17, 19, fullWeights(), 0D, 0D, - null, heights, boundaries, null, null, new CaveFluidSupportPlan()); - int actual = pool.submit(() -> carver.carve(parallel.writer, -17, 19, fullWeights(), 0D, 0D, - null, heights, boundaries, null, null, new CaveFluidSupportPlan())).get(20, TimeUnit.SECONDS); - assertTrue(expected > 0); - assertEquals(expected, actual); - assertEquals(serial.carvedCells, parallel.carvedCells); - assertEquals(serial.carvedLiquids, parallel.carvedLiquids); - for (int y = 61; y <= 64; y++) { - assertFalse(serial.carvedCells.contains(cellKey(1, y, 0))); - } - assertTrue(countLiquid(serial, (byte) 2) > 0); - assertTrue(countLiquid(serial, (byte) 0) > 0); - assertTrue(maxY(serial.carvedCells) <= 110); - } - } - } - - @Test - public void carvingReleasesReferencesAfterSuccessAndFailure() throws Exception { - for (boolean fail : new boolean[]{false, true}) { - Engine engine = createEngine(128, 110); - IrisCaveProfile profile = createProfile(false, false).setAdaptiveSampling(true) - .setAllowFluid(false).setDetailWeight(0D) - .setDensityThreshold(new IrisStyledRange(2D, 2D, new IrisGeneratorStyle(NoiseStyle.FLAT))); - IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, profile); - WriterCapture capture = createWriterCapture(128); - if (fail) { - AtomicInteger samples = new AtomicInteger(); - CNG density = mock(CNG.class, withSettings().stubOnly()); - doAnswer(invocation -> { - if (samples.incrementAndGet() > 300) { - throw new IllegalStateException("Density sample failed"); - } - return -1D; - }).when(density).noiseFastSigned3D(anyDouble(), anyDouble(), anyDouble()); - baseDensityField.set(carver, NoiseProgram.compileSigned3D(density)); - assertThrows(IllegalStateException.class, () -> carver.carve(capture.writer, 0, 0, - fullWeights(), 0D, 0D, null, filledHeights(110))); - } else { - carver.carve(capture.writer, 0, 0, fullWeights(), 0D, 0D, null, filledHeights(110)); - assertFalse(capture.carvedCells.isEmpty()); - } - Field scratchField = IrisCaveCarver3D.class.getDeclaredField("scratchCache"); - scratchField.setAccessible(true); - ThreadLocal scratchCache = (ThreadLocal) scratchField.get(carver); - CaveCarveScratch scratch = (CaveCarveScratch) scratchCache.get(); - assertTrue(scratch.sectionMatter.length > 0); - for (Matter matter : scratch.sectionMatter) { - assertNull(matter); - } - for (MatterSlice slice : scratch.sectionSlices) { - assertNull(slice); - } - for (CaveDensityGrid.Column column : scratch.densityColumns) { - assertNull(column); - } - for (CaveDensityGrid.Column column : scratch.cellLattice.densityColumns) { - assertNull(column); - } - for (CaveDensityGrid.Column column : scratch.cellLattice.warpColumns) { - assertNull(column); - } - } - } - - @Test - public void parallelDensityPreservesExactAndAdaptiveCavernsAndLiquids() throws Exception { - try (ForkJoinPool pool = new ForkJoinPool(4)) { - for (boolean adaptive : new boolean[]{false, true}) { - for (boolean warp : new boolean[]{false, true}) { - for (boolean modules : new boolean[]{false, true}) { - Engine engine = createEngine(128, 110); - IrisCaveProfile profile = createProfile(warp, modules).setAdaptiveSampling(adaptive) - .setDensityThreshold(new IrisStyledRange(0.08D, 0.08D, new IrisGeneratorStyle(NoiseStyle.FLAT))) - .setFluidRequiresFloor(true); - IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, profile); - WriterCapture serial = createWriterCapture(128); - WriterCapture parallel = createWriterCapture(128); - int[] heights = filledHeights(110); - double[] weights = fullWeights(); - long[] boundaries = new long[256]; - Arrays.fill(boundaries, SurfaceFluidBoundaryPlan.boundary( - SurfaceFluidBoundaryPlan.NO_BOUNDARY, Integer.MIN_VALUE)); - for (int column = 0; column < 256; column += 11) { - heights[column] = 80; - weights[column] = column % 3 == 0 ? 0D : 0.6D; - boundaries[column] = SurfaceFluidBoundaryPlan.boundary(56, 64); - } - int expected = carver.carve(serial.writer, -17, 19, weights, 0.1D, 0.15D, - null, heights, boundaries, null, null, new CaveFluidSupportPlan()); - int actual = pool.submit(() -> carver.carve(parallel.writer, -17, 19, weights, 0.1D, 0.15D, - null, heights, boundaries, null, null, new CaveFluidSupportPlan())).get(20, TimeUnit.SECONDS); - assertTrue(expected > 0); - assertEquals(expected, actual); - assertEquals(serial.carvedCells, parallel.carvedCells); - assertEquals(serial.carvedLiquids, parallel.carvedLiquids); - } - } - } - } - } - - @Test - public void rejectedParallelVoxelsDoNotSampleAquifers() throws Exception { - Engine engine = createEngine(128, 110); - IrisCaveProfile profile = createProfile(false, false).setAdaptiveSampling(false) - .setBaseDensityStyle(new IrisGeneratorStyle(NoiseStyle.FLAT)) - .setDetailWeight(0D) - .setDensityThreshold(new IrisStyledRange(-2D, -2D, new IrisGeneratorStyle(NoiseStyle.FLAT))); - IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, profile); - CNG detail = mock(CNG.class, withSettings().stubOnly()); - doAnswer(invocation -> { - throw new AssertionError("Rejected voxel sampled an aquifer"); - }).when(detail).noiseFastSigned3D(anyDouble(), anyDouble(), anyDouble()); - Field detailField = IrisCaveCarver3D.class.getDeclaredField("detailDensity"); - detailField.setAccessible(true); - detailField.set(carver, NoiseProgram.compileSigned3D(detail)); - WriterCapture capture = createWriterCapture(128); - try (ForkJoinPool pool = new ForkJoinPool(4)) { - assertEquals(0, pool.submit(() -> carver.carve(capture.writer, 0, 0, fullWeights(), - 0D, 0D, null, filledHeights(110))).get(20, TimeUnit.SECONDS).intValue()); - } - assertTrue(capture.carvedCells.isEmpty()); - } - - @Test - public void parallelMaterialDecisionsPreserveLavaFluidAndForcedAir() throws Exception { - try (ForkJoinPool pool = new ForkJoinPool(4)) { - for (boolean lava : new boolean[]{false, true}) { - Engine engine = createEngine(128, 110); - IrisCaveProfile profile = createProfile(true, true).setAdaptiveSampling(true) - .setAllowLava(lava).setFluidRequiresFloor(false) - .setDensityThreshold(new IrisStyledRange(2D, 2D, new IrisGeneratorStyle(NoiseStyle.FLAT))); - IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, profile); - WriterCapture serial = createWriterCapture(128); - WriterCapture parallel = createWriterCapture(128); - int[] heights = filledHeights(110); - int expected = carver.carve(serial.writer, 7, -3, fullWeights(), 0D, 0D, null, heights); - int actual = pool.submit(() -> carver.carve(parallel.writer, 7, -3, fullWeights(), 0D, 0D, - null, heights)).get(20, TimeUnit.SECONDS); - assertEquals(expected, actual); - assertEquals(serial.carvedCells, parallel.carvedCells); - assertEquals(serial.carvedLiquids, parallel.carvedLiquids); - assertTrue(countLiquid(serial, (byte) 0) > 0); - assertTrue(countLiquid(serial, (byte) 1) > 0); - assertTrue(countLiquid(serial, lava ? (byte) 2 : (byte) 3) > 0); - } - } - } - - @Test - public void parallelLatticePreservesCavernsAndResolvedFluidSupport() throws Exception { - try (ForkJoinPool pool = new ForkJoinPool(4)) { - for (int step : new int[]{3, 5}) { - Engine engine = createEngine(384, 360); - IrisCaveProfile profile = createProfile(true, true).setSampleStep(step) - .setVerticalRange(new IrisRange(6, 350)) - .setDensityThreshold(new IrisStyledRange(0.08D, 0.08D, new IrisGeneratorStyle(NoiseStyle.FLAT))) - .setFluidRequiresFloor(true); - IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, profile); - WriterCapture serial = createWriterCapture(384); - WriterCapture parallel = createWriterCapture(384); - int[] heights = filledHeights(340); - double[] weights = fullWeights(); - for (int column = 0; column < 256; column += 7) { - heights[column] = 80; - weights[column] = column % 3 == 0 ? 0D : 0.6D; - } - int expected = carver.carve(serial.writer, 9, -7, weights, 0.1D, 0.15D, null, heights); - int actual = pool.submit(() -> carver.carve(parallel.writer, 9, -7, weights, 0.1D, 0.15D, - null, heights)).get(20, TimeUnit.SECONDS); - assertTrue(expected > 0); - assertEquals(expected, actual); - assertEquals(serial.carvedCells, parallel.carvedCells); - assertEquals(serial.carvedLiquids, parallel.carvedLiquids); - } - } - } - - @Test - public void expressionsInDensityFracturesDisableParallelClassification() throws Exception { - Method fixedStyles = IrisCaveCarver3D.class.getDeclaredMethod("fixedDensityStyles", IrisCaveProfile.class); - fixedStyles.setAccessible(true); - IrisCaveProfile profile = createProfile(true, true); - assertEquals(true, fixedStyles.invoke(null, profile)); - profile.getWarpStyle().setFracture(new IrisGeneratorStyle(NoiseStyle.SIMPLEX).setExpression("live-height")); - assertEquals(false, fixedStyles.invoke(null, profile)); - profile = createProfile(true, true); - profile.getModules().get(0).getStyle().setExpression("live-height"); - assertEquals(false, fixedStyles.invoke(null, profile)); - } - - @Test - public void nestedCarvingPreservesOuterScratch() { - Engine engine = createEngine(128, 110); - doReturn(110).when(engine).getHeight(anyInt(), anyInt(), anyBoolean()); - IrisCaveProfile profile = createProfile(true, true).setAdaptiveSampling(false); - WriterCapture expected = createWriterCapture(128); - new IrisCaveCarver3D(engine, profile).carve(expected.writer, 2, 3); - IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, profile); - WriterCapture nested = createWriterCapture(128); - AtomicBoolean entered = new AtomicBoolean(); - doAnswer(invocation -> { - if (entered.compareAndSet(false, true)) { - carver.carve(nested.writer, -9, -11, fullWeights(), 0D, 0D, null, filledHeights(80)); - } - return 110; - }).when(engine).getHeight(anyInt(), anyInt(), anyBoolean()); - WriterCapture actual = createWriterCapture(128); - carver.carve(actual.writer, 2, 3); - assertTrue(entered.get()); - assertFalse(nested.carvedCells.isEmpty()); - assertEquals(expected.carvedCells, actual.carvedCells); - assertEquals(expected.carvedLiquids, actual.carvedLiquids); - } - - @Test - public void genericFluidContractKeepsOverworldDefaults() { - IrisCaveProfile profile = new IrisCaveProfile(); - IrisDimension dimension = new IrisDimension(); - - assertTrue(profile.isAllowFluid()); - assertEquals(12, profile.getFluidMinDepthBelowSurface()); - assertTrue(profile.isFluidRequiresFloor()); - assertEquals("water", dimension.getFluidPalette().getPalette().get(0).getBlock()); - } - - @Test - public void carvedCellDistributionStableAcrossEquivalentCarvers() { - Engine engine = createEngine(128, 92); - - IrisCaveCarver3D firstCarver = new IrisCaveCarver3D(engine, createProfile(true, true)); - WriterCapture firstCapture = createWriterCapture(128); - int firstCarved = firstCarver.carve(firstCapture.writer, 7, -3); - - IrisCaveCarver3D secondCarver = new IrisCaveCarver3D(engine, createProfile(true, true)); - WriterCapture secondCapture = createWriterCapture(128); - int secondCarved = secondCarver.carve(secondCapture.writer, 7, -3); - - assertTrue(firstCarved > 0); - assertEquals(firstCarved, secondCarved); - assertEquals(firstCapture.carvedCells, secondCapture.carvedCells); - assertEquals(firstCapture.carvedLiquids, secondCapture.carvedLiquids); - } - - @Test - public void warpCacheDoesNotCrossContaminateCarverInstancesOnSameThread() throws Exception { - Engine engine = createEngine(128, 92); - IrisCaveProfile firstProfile = createProfile(true, false); - firstProfile.setWarpStyle(new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.1875D)); - IrisCaveProfile secondProfile = createProfile(true, false); - secondProfile.setWarpStyle(new IrisGeneratorStyle(NoiseStyle.CELLULAR).zoomed(0.1875D)); - IrisCaveProfile controlProfile = createProfile(true, false); - controlProfile.setWarpStyle(new IrisGeneratorStyle(NoiseStyle.CELLULAR).zoomed(0.1875D)); - IrisCaveCarver3D firstCarver = new IrisCaveCarver3D(engine, firstProfile); - IrisCaveCarver3D secondCarver = new IrisCaveCarver3D(engine, secondProfile); - IrisCaveCarver3D controlCarver = new IrisCaveCarver3D(engine, controlProfile); - int x = 48; - int y = 64; - int z = -352; - - double firstDensity = sampleDensity(firstCarver, x, y, z); - double secondDensity = sampleDensity(secondCarver, x, y, z); - AtomicReference controlDensity = new AtomicReference<>(); - AtomicReference controlFailure = new AtomicReference<>(); - Thread controlThread = new Thread(() -> { - try { - controlDensity.set(sampleDensity(controlCarver, x, y, z)); - } catch (Throwable throwable) { - controlFailure.set(throwable); - } - }, "Iris cave warp cache control"); - controlThread.start(); - controlThread.join(); - - if (controlFailure.get() != null) { - throw new AssertionError(controlFailure.get()); - } - assertNotEquals(firstDensity, controlDensity.get(), 0D); - assertEquals(controlDensity.get(), secondDensity, 0D); - } - - @Test - public void columnCeilingsCapEveryCarvedCellOfTheirColumns() { - Engine engine = createEngine(128, 80); - IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, carveEverywhere()); - int[] ceilings = new int[256]; - Arrays.fill(ceilings, CaveCeilingMask.UNMASKED); - for (int lx = 0; lx < 8; lx++) { - for (int lz = 0; lz < 16; lz++) { - ceilings[PowerOfTwoCoordinates.packLocal16(lx, lz)] = 40; - } - } - WriterCapture masked = createWriterCapture(128); - WriterCapture open = createWriterCapture(128); - - carver.carve(masked.writer, 0, 0, fullWeights(), 0D, 0D, null, filledHeights(80), null, ceilings, null, - new CaveFluidSupportPlan()); - carver.carve(open.writer, 0, 0, fullWeights(), 0D, 0D, null, filledHeights(80), null, null, null, - new CaveFluidSupportPlan()); - - boolean maskedBelow = false; - boolean unmaskedAbove = false; - for (String cell : masked.carvedCells) { - int x = coordinate(cell, 0); - int y = coordinate(cell, 1); - if (x < 8) { - assertTrue("masked column carved above its ceiling at " + cell, y <= 40); - maskedBelow = true; - } else { - unmaskedAbove |= y > 40; - } - } - boolean openAbove = false; - for (String cell : open.carvedCells) { - openAbove |= coordinate(cell, 0) < 8 && coordinate(cell, 1) > 40; - } - assertTrue(maskedBelow); - assertTrue(unmaskedAbove); - assertTrue("without a ceiling the same columns carve above 40", openAbove); - } - - @Test - public void waterMaskKeepsCavesUnderPondFloorsAndRiverBedsAndAwayFromWaterSides() { - WaterScene scene = CaveCeilingMaskTest.scene(new IrisHydrology()); - IrisCaveCarver3D carver = new IrisCaveCarver3D(createEngine(128, 80), carveEverywhere()); - int[] field = new int[CaveCeilingMask.FIELD * CaveCeilingMask.FIELD]; - int[] ceilings = new int[256]; - int carved = 0; - int underWater = 0; - for (int chunkX = -1; chunkX <= 1; chunkX++) { - for (int chunkZ = 0; chunkZ <= 2; chunkZ++) { - boolean masked = CaveCeilingMask.fill(chunkX, chunkZ, scene::raster, field, ceilings); - WriterCapture capture = createWriterCapture(128); - carver.carve(capture.writer, chunkX, chunkZ, fullWeights(), 0D, 0D, null, filledHeights(80), null, - masked ? ceilings : null, null, new CaveFluidSupportPlan()); - for (String cell : capture.carvedCells) { - int lx = coordinate(cell, 0); - int y = coordinate(cell, 1); - int lz = coordinate(cell, 2); - int x = (chunkX << 4) + lx; - int z = (chunkZ << 4) + lz; - carved++; - assertTrue("cave above the ceiling at " + x + "," + y + "," + z, - !masked || y <= ceilings[PowerOfTwoCoordinates.packLocal16(lx, lz)]); - if (scene.water(x, z)) { - underWater++; - assertTrue("cave reaches within two blocks of the floor at " + x + "," + y + "," + z, - y <= scene.terrain(x, z) - 3); - } - for (int[] side : new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}) { - int nx = x + side[0]; - int nz = z + side[1]; - assertFalse("cave opens sideways into water at " + x + "," + y + "," + z, - scene.water(nx, nz) && y > scene.terrain(nx, nz) && y <= scene.head(nx, nz)); - } - } - } - } - assertTrue("carved cells " + carved, carved > 10_000); - assertTrue("caves still pass below the water " + underWater, underWater > 100); - } - - @Test - public void exactPathCarvesChunkEdgesAndRespectsWorldHeightClipping() { - Engine engine = createEngine(48, 46); - IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, createProfile(true, true)); - WriterCapture capture = createWriterCapture(48); - double[] columnWeights = fullWeights(); - int[] precomputedSurfaceHeights = filledHeights(46); - - int carved = carver.carve(capture.writer, 0, 0, columnWeights, 0D, 0D, new IrisRange(0D, 80D), precomputedSurfaceHeights); - - assertTrue(carved > 0); - assertTrue(hasX(capture.carvedCells, 14)); - assertTrue(hasX(capture.carvedCells, 15)); - assertTrue(hasZ(capture.carvedCells, 14)); - assertTrue(hasZ(capture.carvedCells, 15)); - assertTrue(maxY(capture.carvedCells) <= 47); - assertTrue(minY(capture.carvedCells) >= 0); - } - - @Test - public void flatSurfaceDoesNotHardClipLargeCaveCeiling() { - assertFlatSurfaceCeiling(createFluidProfile() - .setVerticalRange(new IrisRange(20D, 72D)) - .setAllowSurfaceBreak(false) - .setSurfaceClearance(5) - .setAllowFluid(false) - .setAllowLava(false) - .setAdaptiveSampling(false) - .setSampleStep(1)); - assertFlatSurfaceCeiling(createFluidProfile() - .setVerticalRange(new IrisRange(20D, 72D)) - .setAllowSurfaceBreak(false) - .setSurfaceClearance(5) - .setAllowFluid(false) - .setAllowLava(false) - .setAdaptiveSampling(true) - .setSampleStep(1)); - } - - @Test - public void exactPathMatchesNaiveReferenceWithoutWarpOrModules() throws Exception { - assertExactParity(false, false, false); - } - - @Test - public void exactPathMatchesNaiveReferenceWithWarpAndModules() throws Exception { - assertExactParity(true, true, false); - } - - @Test - public void exactPathMatchesNaiveReferenceWhenProfileCeilingExceedsTerrain() throws Exception { - Engine engine = createEngine(256, 64); - double[] columnWeights = fullWeights(); - int[] precomputedSurfaceHeights = filledHeights(64); - IrisCaveProfile optimizedProfile = createProfile(true, true) - .setVerticalRange(new IrisRange(0D, 220D)) - .setAllowSurfaceBreak(false) - .setAdaptiveSampling(false); - IrisCaveCarver3D optimizedCarver = new IrisCaveCarver3D(engine, optimizedProfile); - WriterCapture optimizedCapture = createWriterCapture(256); - int optimizedCarved = optimizedCarver.carve( - optimizedCapture.writer, 5, -1, columnWeights, 0D, 0D, null, precomputedSurfaceHeights); - - IrisCaveProfile referenceProfile = createProfile(true, true) - .setVerticalRange(new IrisRange(0D, 220D)) - .setAllowSurfaceBreak(false) - .setAdaptiveSampling(false); - IrisCaveCarver3D referenceCarver = new IrisCaveCarver3D(engine, referenceProfile); - WriterCapture referenceCapture = createWriterCapture(256); - int referenceCarved = carveNaiveExact( - referenceCarver, referenceCapture.writer, 5, -1, columnWeights, null, precomputedSurfaceHeights); - - assertEquals(referenceCarved, optimizedCarved); - assertEquals(referenceCapture.carvedCells, optimizedCapture.carvedCells); - assertEquals(referenceCapture.carvedLiquids, optimizedCapture.carvedLiquids); - } - - @Test - public void deepAdaptiveSampleClassifierMatchesLegacyDecisionTree() throws Exception { - IrisCaveProfile profile = createProfile(true, true); - IrisCaveCarver3D carver = new IrisCaveCarver3D(createEngine(128, 92), profile); - CaveCarveScratch scratch = new CaveCarveScratch(); - int adaptiveSampleStep = 8; - int axisCells = 2; - int axisSamples = 3; - int[] planeColumnIndices = new int[256]; - double[] planeThresholdLimit = new double[256]; - boolean[] planeCarve = new boolean[256]; - double[] adaptivePlaneDensity = scratch.adaptivePlaneDensity; - for (int index = 0; index < planeColumnIndices.length; index++) { - planeColumnIndices[index] = index; - planeThresholdLimit[index] = ((index % 17) - 8) * 0.11D; - planeCarve[index] = (index & 1) == 0; - } - for (int index = 0; index < axisSamples * axisSamples; index++) { - adaptivePlaneDensity[index] = ((index * 13) % 19 - 9) * 0.14D; - } - - deepAdaptivePlaneMethod.invoke( - carver, - scratch, - planeColumnIndices, - planeThresholdLimit, - planeColumnIndices.length, - planeCarve, - adaptiveSampleStep, - adaptivePlaneDensity, - axisCells, - axisSamples - ); - - double normalization = Math.abs(profile.getBaseWeight()) + Math.abs(profile.getDetailWeight()); - for (IrisCaveFieldModule module : profile.getModules()) { - normalization += Math.abs(module.getWeight()); - } - double inverseNormalization = 1D / normalization; - double adaptiveThresholdMargin = 0.19D; - for (int columnIndex = 0; columnIndex < planeColumnIndices.length; columnIndex++) { - int localX = columnIndex >> 4; - int localZ = columnIndex & 15; - int cellX = Math.min(localX / adaptiveSampleStep, axisCells - 1); - int cellZ = Math.min(localZ / adaptiveSampleStep, axisCells - 1); - int x0 = cellX * adaptiveSampleStep; - int z0 = cellZ * adaptiveSampleStep; - int x1 = Math.min(x0 + adaptiveSampleStep, 16); - int z1 = Math.min(z0 + adaptiveSampleStep, 16); - double tx = x1 == x0 ? 0D : (localX - x0) / (double) (x1 - x0); - double tz = z1 == z0 ? 0D : (localZ - z0) / (double) (z1 - z0); - int row0 = cellX * axisSamples; - int row1 = (cellX + 1) * axisSamples; - double d00 = adaptivePlaneDensity[row0 + cellZ]; - double d01 = adaptivePlaneDensity[row0 + cellZ + 1]; - double d10 = adaptivePlaneDensity[row1 + cellZ]; - double d11 = adaptivePlaneDensity[row1 + cellZ + 1]; - double dx0 = d00 + ((d10 - d00) * tx); - double dx1 = d01 + ((d11 - d01) * tx); - double predictedDensity = dx0 + ((dx1 - dx0) * tz); - double threshold = planeThresholdLimit[columnIndex] * inverseNormalization; - double minDensity = Math.min(Math.min(d00, d01), Math.min(d10, d11)); - double maxDensity = Math.max(Math.max(d00, d01), Math.max(d10, d11)); - double ambiguityMargin = adaptiveThresholdMargin + ((maxDensity - minDensity) * 0.125D); - boolean expected; - if (localX % adaptiveSampleStep == 0 && localZ % adaptiveSampleStep == 0) { - expected = predictedDensity <= threshold; - } else if (predictedDensity <= threshold - ambiguityMargin) { - expected = true; - } else if (predictedDensity > threshold + ambiguityMargin) { - expected = false; - } else { - expected = predictedDensity <= threshold; - } - assertEquals("column " + columnIndex, expected, planeCarve[columnIndex]); - } - } - - @Test - public void aquiferCupSupportStopsAsSoonAsTheResultIsKnown() throws Exception { - Engine engine = createEngine(128, 92); - IrisCaveProfile profile = createProfile(false, false) - .setBaseWeight(1D) - .setDetailWeight(0D) - .setFluidRequiresFloor(true); - IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, profile); - Map rejectedDensity = new HashMap<>(); - rejectedDensity.put("11:10:10", -1D); - rejectedDensity.put("9:10:10", -1D); - CoordinateDensityCNG rejectedNoise = new CoordinateDensityCNG(rejectedDensity); - baseDensityField.set(carver, NoiseProgram.compileSigned3D(rejectedNoise)); - - boolean rejected = (boolean) aquiferCupSupportMethod.invoke( - carver, new CaveCarveScratch(), 10, 10, 10, 0D); - - assertFalse(rejected); - assertEquals(List.of("10:9:10", "10:8:10", "11:10:10", "9:10:10"), rejectedNoise.sampledCoordinates); - - CoordinateDensityCNG acceptedNoise = new CoordinateDensityCNG(Map.of()); - baseDensityField.set(carver, NoiseProgram.compileSigned3D(acceptedNoise)); - - boolean accepted = (boolean) aquiferCupSupportMethod.invoke( - carver, new CaveCarveScratch(), 10, 10, 10, 0D); - - assertTrue(accepted); - assertEquals( - List.of("10:9:10", "10:8:10", "11:10:10", "9:10:10", "10:10:11", "10:10:9"), - acceptedNoise.sampledCoordinates - ); - } - - @Test - public void legacySampleStepTwoMatchesExactReference() throws Exception { - Engine engine = createEngine(96, 90); - double[] columnWeights = fullWeights(); - int[] precomputedSurfaceHeights = filledHeights(90); - IrisRange worldYRange = new IrisRange(0D, 88D); - - IrisCaveProfile exactProfile = createProfile(true, true).setSampleStep(1).setAdaptiveSampling(false); - IrisCaveCarver3D exactCarver = new IrisCaveCarver3D(engine, exactProfile); - WriterCapture exactCapture = createWriterCapture(96); - int exactCarved = exactCarver.carve(exactCapture.writer, 5, -1, columnWeights, 0D, 0D, worldYRange, precomputedSurfaceHeights); - - IrisCaveProfile legacyProfile = createProfile(true, true).setSampleStep(2).setAdaptiveSampling(false); - IrisCaveCarver3D legacyCarver = new IrisCaveCarver3D(engine, legacyProfile); - WriterCapture legacyCapture = createWriterCapture(96); - int legacyCarved = legacyCarver.carve(legacyCapture.writer, 5, -1, columnWeights, 0D, 0D, worldYRange, precomputedSurfaceHeights); - - assertEquals(exactCarved, legacyCarved); - assertEquals(exactCapture.carvedCells, legacyCapture.carvedCells); - assertEquals(exactCapture.carvedLiquids, legacyCapture.carvedLiquids); - } - - @Test - public void exactPathUsesExpectedLavaAndForcedAirBands() { - Engine engine = createEngine(48, 46); - double[] columnWeights = fullWeights(); - int[] precomputedSurfaceHeights = filledHeights(46); - - IrisCaveProfile lavaProfile = createProfile(false, false).setAllowLava(true).setAllowFluid(false); - IrisCaveCarver3D lavaCarver = new IrisCaveCarver3D(engine, lavaProfile); - WriterCapture lavaCapture = createWriterCapture(48); - lavaCarver.carve(lavaCapture.writer, 0, 0, columnWeights, 0D, 0D, new IrisRange(0D, 80D), precomputedSurfaceHeights); - - IrisCaveProfile forcedAirProfile = createProfile(false, false).setAllowLava(false).setAllowFluid(false); - IrisCaveCarver3D forcedAirCarver = new IrisCaveCarver3D(engine, forcedAirProfile); - WriterCapture forcedAirCapture = createWriterCapture(48); - forcedAirCarver.carve(forcedAirCapture.writer, 0, 0, columnWeights, 0D, 0D, new IrisRange(0D, 80D), precomputedSurfaceHeights); - - assertTrue(containsLiquidInRange(lavaCapture.carvedLiquids, 0, 18, (byte) 2)); - assertTrue(containsLiquidInRange(forcedAirCapture.carvedLiquids, 0, 18, (byte) 3)); - assertTrue(containsLiquidInRange(lavaCapture.carvedLiquids, 19, 47, (byte) 0)); - assertTrue(containsLiquidInRange(forcedAirCapture.carvedLiquids, 19, 47, (byte) 0)); - } - - @Test - public void fluidPrecedesForcedAirWhenLavaIsDisabled() { - Engine engine = createEngine(48, 46); - int[] surfaceHeights = filledHeights(46); - IrisCaveProfile wetProfile = createFluidProfile() - .setVerticalRange(new IrisRange(2D, 18D)) - .setAllowLava(false) - .setFluidRequiresFloor(false); - WriterCapture wetCapture = createWriterCapture(48); - new IrisCaveCarver3D(engine, wetProfile).carve( - wetCapture.writer, 0, 0, fullWeights(), 0D, 0D, null, surfaceHeights); - - IrisCaveProfile dryProfile = createFluidProfile() - .setVerticalRange(new IrisRange(2D, 18D)) - .setAllowFluid(false) - .setAllowLava(false) - .setFluidRequiresFloor(false); - WriterCapture dryCapture = createWriterCapture(48); - new IrisCaveCarver3D(engine, dryProfile).carve( - dryCapture.writer, 0, 0, fullWeights(), 0D, 0D, null, surfaceHeights); - - assertEquals(wetCapture.carvedCells, dryCapture.carvedCells); - assertTrue(containsLiquidInRange(wetCapture.carvedLiquids, 2, 18, (byte) 1)); - assertTrue(containsLiquidInRange(wetCapture.carvedLiquids, 2, 18, (byte) 3)); - assertEquals(0, countLiquid(dryCapture, (byte) 1)); - assertTrue(containsLiquidInRange(dryCapture.carvedLiquids, 2, 18, (byte) 3)); - } - - @Test - public void fluidToggleAndMinimumDepthUseEachColumnsTerrainSurface() { - Engine engine = createEngine(80, 70); - int[] surfaceHeights = splitSurfaceHeights(40, 70); - - IrisCaveProfile enabledProfile = createFluidProfile().setAllowFluid(true).setFluidMinDepthBelowSurface(10); - WriterCapture enabledCapture = createWriterCapture(80); - new IrisCaveCarver3D(engine, enabledProfile).carve( - enabledCapture.writer, 0, 0, fullWeights(), 0D, 0D, null, surfaceHeights); - - IrisCaveProfile disabledProfile = createFluidProfile().setAllowFluid(false).setFluidMinDepthBelowSurface(10); - WriterCapture disabledCapture = createWriterCapture(80); - new IrisCaveCarver3D(engine, disabledProfile).carve( - disabledCapture.writer, 0, 0, fullWeights(), 0D, 0D, null, surfaceHeights); - - assertEquals(enabledCapture.carvedCells, disabledCapture.carvedCells); - assertTrue(countLiquid(enabledCapture, (byte) 1) > 0); - assertEquals(0, countLiquid(disabledCapture, (byte) 1)); - assertFluidRespectsSplitCutoff(enabledCapture, 30, 60); - assertTrue(enabledCapture.carvedCells.contains(cellKey(0, 40, 0))); - assertTrue(enabledCapture.carvedCells.contains(cellKey(15, 70, 0))); - } - - @Test - public void dimensionFluidHeightCapsFluidIntent() { - Engine engine = createEngine(80, 70); - IrisCaveProfile profile = createFluidProfile().setFluidMinDepthBelowSurface(0); - WriterCapture capture = createWriterCapture(80); - - new IrisCaveCarver3D(engine, profile).carve( - capture.writer, 0, 0, fullWeights(), 0D, 0D, null, filledHeights(70)); - - assertTrue(countLiquid(capture, (byte) 1) > 0); - assertLiquidAtOrBelow(capture, (byte) 1, 64); - assertTrue(containsLiquidInRange(capture.carvedLiquids, 65, 70, (byte) 0)); - } - - @Test - public void surfaceFluidBoundaryProtectsReservoirWithoutFloodingDeeperCaves() { - assertSurfaceFluidBoundaryForProfile(createFluidProfile().setAdaptiveSampling(false).setSampleStep(1)); - assertSurfaceFluidBoundaryForProfile(createFluidProfile().setAdaptiveSampling(true).setSampleStep(1)); - assertSurfaceFluidBoundaryForProfile(createFluidProfile().setAdaptiveSampling(false).setSampleStep(4)); - } - - @Test - public void floorRequiredFluidResolvesAfterTheCompleteCarveMask() { - Engine engine = createEngine(80, 70); - int[] surfaceHeights = filledHeights(70); - int chunkX = -8; - int chunkZ = -1; - - IrisStyledRange cupThreshold = new IrisStyledRange(0.15D, 0.15D, new IrisGeneratorStyle(NoiseStyle.FLAT)); - IrisCaveProfile supportedProfile = createFluidProfile() - .setDensityThreshold(cupThreshold) - .setFluidMinDepthBelowSurface(0) - .setFluidRequiresFloor(true); - WriterCapture firstCapture = createWriterCapture(80); - CaveFluidSupportPlan supportPlan = new CaveFluidSupportPlan(); - new IrisCaveCarver3D(engine, supportedProfile).carve( - firstCapture.writer, chunkX, chunkZ, fullWeights(), 0D, 0D, null, surfaceHeights, null, null, null, supportPlan); - int candidateCount = countLiquid(firstCapture, (byte) 1); - supportPlan.resolve(firstCapture.writer.acquireChunk(chunkX, chunkZ)); - - IrisCaveProfile repeatedProfile = createFluidProfile() - .setDensityThreshold(cupThreshold) - .setFluidMinDepthBelowSurface(0) - .setFluidRequiresFloor(true); - WriterCapture secondCapture = createWriterCapture(80); - new IrisCaveCarver3D(engine, repeatedProfile).carve( - secondCapture.writer, chunkX, chunkZ, fullWeights(), 0D, 0D, null, surfaceHeights); - - IrisCaveProfile unrestrictedProfile = createFluidProfile() - .setDensityThreshold(cupThreshold) - .setFluidMinDepthBelowSurface(0) - .setFluidRequiresFloor(false); - WriterCapture unrestrictedCapture = createWriterCapture(80); - new IrisCaveCarver3D(engine, unrestrictedProfile).carve( - unrestrictedCapture.writer, chunkX, chunkZ, fullWeights(), 0D, 0D, null, surfaceHeights); - - assertTrue(candidateCount > 0); - assertEquals(firstCapture.carvedLiquids, secondCapture.carvedLiquids); - assertTrue(countLiquid(firstCapture, (byte) 1) > 0); - assertTrue(countLiquid(firstCapture, (byte) 1) < countLiquid(unrestrictedCapture, (byte) 1)); - assertFluidCellsHaveSolidSupport(firstCapture); - } - - @Test - public void finalFluidSupportRejectsUnknownNeighborChunkEdges() { - WriterCapture capture = createWriterCapture(80); - MantleChunk chunk = capture.writer.acquireChunk(0, 0); - MatterSlice slice = chunk.getOrCreate(3).slice(MatterCavern.class); - MatterCavern fluid = new MatterCavern(true, "", (byte) 1); - MatterCavern air = new MatterCavern(true, "", (byte) 0); - int y = 56; - int z = 8; - slice.set(0, y & 15, z, fluid); - slice.set(8, y & 15, z, fluid); - CaveFluidSupportPlan supportPlan = new CaveFluidSupportPlan(); - supportPlan.add(0, y, z, fluid, air); - supportPlan.add(8, y, z, fluid, air); - - supportPlan.resolve(chunk); - - assertEquals(Byte.valueOf((byte) 0), capture.carvedLiquids.get(cellKey(0, y, z))); - assertEquals(Byte.valueOf((byte) 1), capture.carvedLiquids.get(cellKey(8, y, z))); - } - - @Test - public void floorRequiredFluidSeesLaterProfileCarvePasses() { - Engine engine = createEngine(80, 70); - int[] surfaceHeights = filledHeights(70); - WriterCapture capture = createWriterCapture(80); - CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan(); - IrisCaveProfile fluidProfile = createFluidProfile() - .setDensityThreshold(new IrisStyledRange(0.15D, 0.15D, new IrisGeneratorStyle(NoiseStyle.FLAT))) - .setFluidRequiresFloor(true); - IrisCaveProfile airProfile = createFluidProfile().setAllowFluid(false); - - new IrisCaveCarver3D(engine, fluidProfile).carve( - capture.writer, 0, 0, fullWeights(), 0D, 0D, null, surfaceHeights, - null, null, new IrisRange(20D, 64D), fluidSupportPlan); - String fluidCell = firstCellWithLiquid(capture, (byte) 1); - assertTrue(fluidCell != null); - int fluidY = coordinate(fluidCell, 1); - new IrisCaveCarver3D(engine, airProfile).carve( - capture.writer, 0, 0, fullWeights(), 0D, 0D, null, surfaceHeights, - null, null, new IrisRange(fluidY - 1D, fluidY - 1D), fluidSupportPlan); - - assertEquals(Byte.valueOf((byte) 1), capture.carvedLiquids.get(fluidCell)); - fluidSupportPlan.resolve(capture.writer.acquireChunk(0, 0)); - assertEquals(Byte.valueOf((byte) 0), capture.carvedLiquids.get(fluidCell)); - } - - @Test - public void optimizedExactPathOutperformsNaiveReference() throws Exception { - Engine engine = createEngine(128, 92); - IrisCaveCarver3D optimizedCarver = new IrisCaveCarver3D(engine, createProfile(true, true).setAdaptiveSampling(false)); - IrisCaveCarver3D naiveCarver = new IrisCaveCarver3D(engine, createProfile(true, true).setAdaptiveSampling(false)); - double[] columnWeights = fullWeights(); - int[] precomputedSurfaceHeights = filledHeights(92); - IrisRange worldYRange = new IrisRange(0D, 96D); - AtomicLong optimizedSamples = new AtomicLong(); - AtomicLong naiveSamples = new AtomicLong(); - countSkippableSamples(optimizedCarver, optimizedSamples); - countSkippableSamples(naiveCarver, naiveSamples); - - WriterCapture optimizedCapture = createWriterCapture(128); - int optimizedCarved = optimizedCarver.carve(optimizedCapture.writer, 3, -2, columnWeights, 0D, 0D, - worldYRange, precomputedSurfaceHeights); - WriterCapture naiveCapture = createWriterCapture(128); - int naiveCarved = carveNaiveExact(naiveCarver, naiveCapture.writer, 3, -2, columnWeights, - worldYRange, precomputedSurfaceHeights); - - assertTrue(optimizedCarved > 0); - assertEquals(naiveCarved, optimizedCarved); - assertEquals(naiveCapture.carvedCells, optimizedCapture.carvedCells); - assertEquals(naiveCapture.carvedLiquids, optimizedCapture.carvedLiquids); - - long optimizedSampleCount = optimizedSamples.get(); - long naiveSampleCount = naiveSamples.get(); - assertTrue(optimizedSampleCount > 0L); - double sampleRatio = naiveSampleCount / (double) optimizedSampleCount; - assertTrue("expected at least 1.4x fewer detail and module samples but was " + sampleRatio, - sampleRatio >= 1.4D); - } - - @Test - public void adaptivePathStaysNearExactReferenceWithWarpAndModules() throws Exception { - Engine engine = createEngine(96, 90); - double[] columnWeights = fullWeights(); - int[] precomputedSurfaceHeights = filledHeights(90); - IrisRange worldYRange = new IrisRange(0D, 88D); - - IrisCaveCarver3D adaptiveCarver = new IrisCaveCarver3D(engine, createProfile(true, true).setAdaptiveSampling(true)); - WriterCapture adaptiveCapture = createWriterCapture(96); - int adaptiveCarved = adaptiveCarver.carve(adaptiveCapture.writer, 5, -1, columnWeights, 0D, 0D, worldYRange, precomputedSurfaceHeights); - - IrisCaveCarver3D exactCarver = new IrisCaveCarver3D(engine, createProfile(true, true).setAdaptiveSampling(false)); - WriterCapture exactCapture = createWriterCapture(96); - int exactCarved = exactCarver.carve(exactCapture.writer, 5, -1, columnWeights, 0D, 0D, worldYRange, precomputedSurfaceHeights); - - Set differingCells = new HashSet<>(adaptiveCapture.carvedCells); - differingCells.addAll(exactCapture.carvedCells); - Set sharedCells = new HashSet<>(adaptiveCapture.carvedCells); - sharedCells.retainAll(exactCapture.carvedCells); - differingCells.removeAll(sharedCells); - - int baselineCells = Math.max(1, exactCapture.carvedCells.size()); - double carveDeltaRatio = Math.abs(adaptiveCarved - exactCarved) / (double) baselineCells; - double differingRatio = differingCells.size() / (double) baselineCells; - assertTrue("expected carve count delta below 2.5% but was " + carveDeltaRatio, carveDeltaRatio <= 0.025D); - assertTrue("expected carved cell delta below 3.5% but was " + differingRatio, differingRatio <= 0.035D); - } - - private void assertFlatSurfaceCeiling(IrisCaveProfile profile) { - Engine engine = createEngine(96, 72); - WriterCapture capture = createWriterCapture(96); - - new IrisCaveCarver3D(engine, profile).carve( - capture.writer, 0, 0, fullWeights(), 0D, 0D, null, filledHeights(72)); - - int[] ceilingYByColumn = new int[256]; - Arrays.fill(ceilingYByColumn, Integer.MIN_VALUE); - for (String cell : capture.carvedCells) { - int localX = coordinate(cell, 0); - int y = coordinate(cell, 1); - int localZ = coordinate(cell, 2); - int columnIndex = (localX << 4) | localZ; - ceilingYByColumn[columnIndex] = Math.max(ceilingYByColumn[columnIndex], y); - } - - Map ceilingPlaneCounts = new HashMap<>(); - int largestPlane = 0; - for (int ceilingY : ceilingYByColumn) { - assertTrue(ceilingY != Integer.MIN_VALUE); - assertTrue(ceilingY <= 67); - int planeCount = ceilingPlaneCounts.merge(ceilingY, 1, Integer::sum); - largestPlane = Math.max(largestPlane, planeCount); - } - - assertTrue("expected at least three ceiling levels but found " + ceilingPlaneCounts, - ceilingPlaneCounts.size() >= 3); - assertTrue("expected no dominant ceiling plane but found " + ceilingPlaneCounts, - largestPlane < 192); - } - - @Test - public void sharedDensityLatticeReproducesIsolatedCarvesAcrossNeighbourChunks() throws Exception { - Engine engine = createEngine(96, 90); - for (boolean warp : new boolean[]{false, true}) { - for (boolean modules : new boolean[]{false, true}) { - AtomicLong sharedSamples = new AtomicLong(); - AtomicLong isolatedSamples = new AtomicLong(); - IrisCaveCarver3D shared = new IrisCaveCarver3D(engine, - createProfile(warp, modules).setAdaptiveSampling(true), new CaveDensityGrid(4096)); - baseDensityField.set(shared, NoiseProgram.compileSigned3D(new CountingCNG((NoiseProgram) baseDensityField.get(shared), sharedSamples))); - for (int chunkX = -1; chunkX <= 1; chunkX++) { - for (int chunkZ = -1; chunkZ <= 1; chunkZ++) { - WriterCapture sharedCapture = createWriterCapture(96); - int sharedCarved = shared.carve(sharedCapture.writer, chunkX, chunkZ, fullWeights(), 0D, 0D, - null, filledHeights(90)); - IrisCaveCarver3D isolated = new IrisCaveCarver3D(engine, - createProfile(warp, modules).setAdaptiveSampling(true)); - baseDensityField.set(isolated, NoiseProgram.compileSigned3D(new CountingCNG((NoiseProgram) baseDensityField.get(isolated), isolatedSamples))); - WriterCapture isolatedCapture = createWriterCapture(96); - int isolatedCarved = isolated.carve(isolatedCapture.writer, chunkX, chunkZ, fullWeights(), 0D, 0D, - null, filledHeights(90)); - assertTrue(isolatedCarved > 0); - assertEquals(isolatedCarved, sharedCarved); - assertEquals(isolatedCapture.carvedCells, sharedCapture.carvedCells); - assertEquals(isolatedCapture.carvedLiquids, sharedCapture.carvedLiquids); - } - } - assertTrue("warp=" + warp + " modules=" + modules + " shared=" + sharedSamples.get() - + " isolated=" + isolatedSamples.get(), - sharedSamples.get() < isolatedSamples.get() * 3 / 4); - } - } - } - - @Test - public void retainedLatticeColumnsPreserveRawSamplesThroughEvictionAndClear() throws Exception { - Method latticeDensity = IrisCaveCarver3D.class.getDeclaredMethod("latticeDensity", - CaveCarveScratch.class, int.class, int.class, int.class); - latticeDensity.setAccessible(true); - Method planeDensity = IrisCaveCarver3D.class.getDeclaredMethod("samplePlaneDensity", - CaveCarveScratch.class, int.class, int.class, int.class); - planeDensity.setAccessible(true); - Engine engine = createEngine(128, 110); - for (boolean warp : new boolean[]{false, true}) { - for (boolean modules : new boolean[]{false, true}) { - AtomicInteger lookups = new AtomicInteger(); - CaveDensityGrid grid = countingGrid(4, lookups); - IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, createProfile(warp, modules), grid); - CaveCarveScratch retained = new CaveCarveScratch(); - CaveCarveScratch reference = new CaveCarveScratch(); - for (int y = 0; y < 128; y++) { - if (y == 64) { - grid.clear(); - } - for (int x = -16; x <= 0; x += 8) { - for (int z = 32; z <= 48; z += 8) { - double expected = (double) planeDensity.invoke(carver, reference, x, y, z); - double actual = (double) latticeDensity.invoke(carver, retained, x, y, z); - assertEquals(Double.doubleToRawLongBits(expected), Double.doubleToRawLongBits(actual)); - } - } - assertEquals(Double.doubleToRawLongBits((double) planeDensity.invoke(carver, reference, -15, y, 33)), - Double.doubleToRawLongBits((double) latticeDensity.invoke(carver, retained, -15, y, 33))); - } - assertEquals(9, lookups.get()); - retained.releaseReferences(); - latticeDensity.invoke(carver, retained, -16, 1, 32); - assertEquals(10, lookups.get()); - double expected = (double) planeDensity.invoke(carver, reference, 16, 1, 32); - double actual = (double) latticeDensity.invoke(carver, retained, 16, 1, 32); - assertEquals(Double.doubleToRawLongBits(expected), Double.doubleToRawLongBits(actual)); - assertEquals(11, lookups.get()); - IrisCaveCarver3D reloaded = new IrisCaveCarver3D(engine, - createProfile(warp, modules).setBaseWeight(0.73D), grid); - expected = (double) planeDensity.invoke(reloaded, new CaveCarveScratch(), 16, 1, 32); - actual = (double) latticeDensity.invoke(reloaded, retained, 16, 1, 32); - assertEquals(Double.doubleToRawLongBits(expected), Double.doubleToRawLongBits(actual)); - assertEquals(12, lookups.get()); - } - } - } - - @Test - public void retainedLatticeColumnsMatchOriginalCarvesAndReduceLookups() throws Exception { - Field fixedDensity = IrisCaveCarver3D.class.getDeclaredField("parallelDensity"); - fixedDensity.setAccessible(true); - Engine engine = createEngine(128, 110); - for (boolean warp : new boolean[]{false, true}) { - for (boolean modules : new boolean[]{false, true}) { - AtomicInteger originalLookups = new AtomicInteger(); - AtomicInteger retainedLookups = new AtomicInteger(); - IrisCaveCarver3D original = new IrisCaveCarver3D(engine, - createProfile(warp, modules), countingGrid(4096, originalLookups)); - fixedDensity.set(original, false); - IrisCaveCarver3D retained = new IrisCaveCarver3D(engine, - createProfile(warp, modules), countingGrid(4096, retainedLookups)); - for (int chunkX = -1; chunkX <= 0; chunkX++) { - WriterCapture expected = createWriterCapture(128); - WriterCapture actual = createWriterCapture(128); - assertEquals(original.carve(expected.writer, chunkX, -3, fullWeights(), 0D, 0D, - null, filledHeights(110)), - retained.carve(actual.writer, chunkX, -3, fullWeights(), 0D, 0D, - null, filledHeights(110))); - assertFalse(expected.carvedCells.isEmpty()); - assertEquals(expected.carvedCells, actual.carvedCells); - assertEquals(expected.carvedLiquids, actual.carvedLiquids); - } - assertEquals(18, retainedLookups.get()); - assertTrue(originalLookups.get() > retainedLookups.get() * 50); - } - } - } - - @Test - public void expressionDensityDoesNotRetainEvictedColumns() throws Exception { - Engine engine = createEngine(128, 110); - CNG density = mock(CNG.class, withSettings().stubOnly()); - AtomicInteger samples = new AtomicInteger(); - doAnswer(invocation -> samples.incrementAndGet() * 0.125D).when(density) - .noiseFastSigned3D(anyDouble(), anyDouble(), anyDouble()); - IrisGeneratorStyle style = mock(IrisGeneratorStyle.class, withSettings().stubOnly()); - doReturn("density_expression").when(style).getExpression(); - doReturn(density).when(style).create(any(RNG.class), any(IrisData.class)); - AtomicInteger lookups = new AtomicInteger(); - CaveDensityGrid grid = countingGrid(4, lookups); - IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, - createProfile(false, false).setBaseDensityStyle(style).setDetailWeight(0D), grid); - CaveCarveScratch scratch = new CaveCarveScratch(); - Method latticeDensity = IrisCaveCarver3D.class.getDeclaredMethod("latticeDensity", - CaveCarveScratch.class, int.class, int.class, int.class); - latticeDensity.setAccessible(true); - double first = (double) latticeDensity.invoke(carver, scratch, -16, 20, 32); - grid.clear(); - double second = (double) latticeDensity.invoke(carver, scratch, -16, 20, 32); - assertNotEquals(Double.doubleToRawLongBits(first), Double.doubleToRawLongBits(second)); - assertEquals(2, samples.get()); - assertEquals(2, lookups.get()); - for (CaveDensityGrid.Column column : scratch.densityColumns) { - assertNull(column); - } - } - - @Test - public void nestedAdaptiveCarvingPreservesRetainedColumns() throws Exception { - Engine engine = createEngine(128, 110); - IrisCaveProfile profile = createProfile(true, true); - WriterCapture expected = createWriterCapture(128); - new IrisCaveCarver3D(engine, profile).carve(expected.writer, -1, 2, - fullWeights(), 0D, 0D, null, filledHeights(110)); - IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, profile); - NoiseProgram original = (NoiseProgram) baseDensityField.get(carver); - CNG density = mock(CNG.class, withSettings().stubOnly()); - AtomicBoolean entered = new AtomicBoolean(); - WriterCapture nested = createWriterCapture(128); - doAnswer(invocation -> { - if (entered.compareAndSet(false, true)) { - carver.carve(nested.writer, -9, -11, fullWeights(), 0D, 0D, null, filledHeights(80)); - } - double x = invocation.getArgument(0); - double y = invocation.getArgument(1); - double z = invocation.getArgument(2); - return original.sampleSigned3D(x, y, z); - }).when(density).noiseFastSigned3D(anyDouble(), anyDouble(), anyDouble()); - baseDensityField.set(carver, NoiseProgram.compileSigned3D(density)); - WriterCapture actual = createWriterCapture(128); - carver.carve(actual.writer, -1, 2, fullWeights(), 0D, 0D, null, filledHeights(110)); - assertTrue(entered.get()); - assertFalse(nested.carvedCells.isEmpty()); - assertEquals(expected.carvedCells, actual.carvedCells); - assertEquals(expected.carvedLiquids, actual.carvedLiquids); - } - - private CaveDensityGrid countingGrid(int capacity, AtomicInteger lookups) { - CaveDensityGrid grid = spy(new CaveDensityGrid(capacity)); - doAnswer(invocation -> { - lookups.incrementAndGet(); - return invocation.callRealMethod(); - }).when(grid).column(any(), anyInt(), anyInt(), anyInt()); - return grid; - } - - private void assertExactParity(boolean warp, boolean modules, boolean adaptiveSampling) throws Exception { - Engine engine = createEngine(96, 90); - double[] columnWeights = fullWeights(); - int[] precomputedSurfaceHeights = filledHeights(90); - IrisRange worldYRange = new IrisRange(0D, 88D); - - IrisCaveCarver3D optimizedCarver = new IrisCaveCarver3D(engine, createProfile(warp, modules).setAdaptiveSampling(adaptiveSampling)); - WriterCapture optimizedCapture = createWriterCapture(96); - int optimizedCarved = optimizedCarver.carve(optimizedCapture.writer, 5, -1, columnWeights, 0D, 0D, worldYRange, precomputedSurfaceHeights); - - IrisCaveCarver3D naiveCarver = new IrisCaveCarver3D(engine, createProfile(warp, modules).setAdaptiveSampling(false)); - WriterCapture naiveCapture = createWriterCapture(96); - int naiveCarved = carveNaiveExact(naiveCarver, naiveCapture.writer, 5, -1, columnWeights, worldYRange, precomputedSurfaceHeights); - - assertEquals(optimizedCarved, naiveCarved); - assertEquals(optimizedCapture.carvedCells, naiveCapture.carvedCells); - assertEquals(optimizedCapture.carvedLiquids, naiveCapture.carvedLiquids); - } - - private void countSkippableSamples(IrisCaveCarver3D carver, AtomicLong samples) throws Exception { - detailDensityField.set(carver, NoiseProgram.compileSigned3D(new CountingCNG((NoiseProgram) detailDensityField.get(carver), samples))); - CaveFieldModuleState[] modules = (CaveFieldModuleState[]) modulesField.get(carver); - for (CaveFieldModuleState module : modules) { - moduleDensityField.set(module, NoiseProgram.compileSigned3D(new CountingCNG((NoiseProgram) moduleDensityField.get(module), samples))); - } - } - - private double sampleDensity(IrisCaveCarver3D carver, int x, int y, int z) throws Exception { - return (double) sampleDensityMethod.invoke(carver, x, y, z); - } - - private int carveNaiveExact(IrisCaveCarver3D carver, MantleWriter writer, int chunkX, int chunkZ, double[] columnWeights, IrisRange worldYRange, int[] precomputedSurfaceHeights) throws Exception { - Engine engine = (Engine) engineField.get(carver); - IrisData data = (IrisData) dataField.get(carver); - IrisCaveProfile profile = (IrisCaveProfile) profileField.get(carver); - CNG surfaceBreakDensity = (CNG) surfaceBreakDensityField.get(carver); - RNG thresholdRng = (RNG) thresholdRngField.get(carver); - MatterCavern carveAir = (MatterCavern) carveAirField.get(carver); - MatterCavern carveFluid = (MatterCavern) carveFluidField.get(carver); - MatterCavern carveLava = (MatterCavern) carveLavaField.get(carver); - MatterCavern carveForcedAir = (MatterCavern) carveForcedAirField.get(carver); - - double[] resolvedWeights = columnWeights; - if (resolvedWeights == null || resolvedWeights.length < 256) { - resolvedWeights = fullWeights(); - } - - int worldHeight = writer.getMantle().getWorldHeight(); - int minY = Math.max(0, (int) Math.floor(profile.getVerticalRange().getMin())); - int maxY = Math.min(worldHeight - 1, (int) Math.ceil(profile.getVerticalRange().getMax())); - if (worldYRange != null) { - int worldMinHeight = engine.getWorld().minHeight(); - int rangeMinY = (int) Math.floor(worldYRange.getMin() - worldMinHeight); - int rangeMaxY = (int) Math.ceil(worldYRange.getMax() - worldMinHeight); - minY = Math.max(minY, rangeMinY); - maxY = Math.min(maxY, rangeMaxY); - } - if (maxY < minY) { - return 0; - } - - boolean allowSurfaceBreak = profile.isAllowSurfaceBreak(); - int surfaceClearance = Math.max(0, profile.getSurfaceClearance()); - int surfaceBreakDepth = Math.max(0, profile.getSurfaceBreakDepth()); - double surfaceBreakNoiseThreshold = profile.getSurfaceBreakNoiseThreshold(); - double surfaceBreakThresholdBoost = Math.max(0D, profile.getSurfaceBreakThresholdBoost()); - int[] columnTopY = new int[256]; - int[] surfaceBreakFloorY = new int[256]; - boolean[] surfaceBreakColumn = new boolean[256]; - boolean[] surfaceCeilingColumn = new boolean[256]; - int[] fluidMaxY = new int[256]; - double[] passThreshold = new double[256]; - double[] verticalEdgeFade = computeVerticalEdgeFade(profile, minY, maxY); - double[] surfaceClosureThreshold = computeSurfaceClosureThresholds(profile, minY, maxY); - MatterCavern[] matterByY = computeMatterByY(engine, profile, carveAir, carveLava, carveForcedAir, minY, maxY); - - int x0 = chunkX << 4; - int z0 = chunkZ << 4; - for (int localX = 0; localX < 16; localX++) { - int x = x0 + localX; - for (int localZ = 0; localZ < 16; localZ++) { - int z = z0 + localZ; - int columnIndex = (localX << 4) | localZ; - int columnSurfaceY; - if (precomputedSurfaceHeights != null && precomputedSurfaceHeights.length > columnIndex) { - columnSurfaceY = precomputedSurfaceHeights[columnIndex]; - } else { - columnSurfaceY = engine.getHeight(x, z); - } - - int unclampedClearanceTopY = columnSurfaceY - surfaceClearance; - int clearanceTopY = Math.min(maxY, Math.max(minY, unclampedClearanceTopY)); - boolean breakColumn = allowSurfaceBreak && signed(surfaceBreakDensity.noiseFast2D(x, z)) >= surfaceBreakNoiseThreshold; - int resolvedTopY = breakColumn ? Math.min(maxY, Math.max(minY, columnSurfaceY)) : clearanceTopY; - columnTopY[columnIndex] = resolvedTopY; - fluidMaxY[columnIndex] = profile.isAllowFluid() - ? Math.min(engine.getDimension().getFluidHeight(), columnSurfaceY - Math.max(0, profile.getFluidMinDepthBelowSurface())) - : Integer.MIN_VALUE; - surfaceBreakFloorY[columnIndex] = Math.max(minY, columnSurfaceY - surfaceBreakDepth); - surfaceBreakColumn[columnIndex] = breakColumn; - surfaceCeilingColumn[columnIndex] = !breakColumn && unclampedClearanceTopY <= maxY; - double columnWeight = clampColumnWeight(resolvedWeights[columnIndex]); - if (columnWeight <= 0D || resolvedTopY < minY) { - passThreshold[columnIndex] = Double.NaN; - continue; - } - - passThreshold[columnIndex] = profile.getDensityThreshold().get(thresholdRng, x, z, data) - profile.getThresholdBias(); - } - } - - @SuppressWarnings("unchecked") - MantleChunk chunk = writer.acquireChunk(chunkX, chunkZ); - if (chunk == null) { - return 0; - } - - int carved = 0; - for (int localX = 0; localX < 16; localX++) { - int x = x0 + localX; - for (int localZ = 0; localZ < 16; localZ++) { - int z = z0 + localZ; - int columnIndex = (localX << 4) | localZ; - if (Double.isNaN(passThreshold[columnIndex])) { - continue; - } - - int topY = columnTopY[columnIndex]; - for (int y = minY; y <= topY; y++) { - double localThreshold = passThreshold[columnIndex]; - if (surfaceBreakColumn[columnIndex] && y >= surfaceBreakFloorY[columnIndex]) { - localThreshold += surfaceBreakThresholdBoost; - } - localThreshold -= verticalEdgeFade[y - minY]; - localThreshold = applySurfaceCeilingFade( - localThreshold, - surfaceCeilingColumn[columnIndex], - topY, - y, - minY, - surfaceClosureThreshold - ); - - double density = (double) sampleDensityMethod.invoke(carver, x, y, z); - if (density > localThreshold) { - continue; - } - - Matter sectionMatter = chunk.getOrCreate(y >> 4); - MatterSlice cavernSlice = sectionMatter.slice(MatterCavern.class); - MatterCavern verticalMatter = matterByY[y - minY]; - boolean aquifer = verticalMatter == carveAir - && y <= fluidMaxY[columnIndex] - && (boolean) aquiferCandidateMethod.invoke(carver, x, y, z, localThreshold); - MatterCavern matter = aquifer ? carveFluid : verticalMatter; - cavernSlice.set(localX, y & 15, localZ, matter); - carved++; - } - } - } - - return carved; - } - - private double applySurfaceCeilingFade( - double threshold, - boolean surfaceCeilingColumn, - int columnTopY, - int y, - int minY, - double[] surfaceClosureThreshold - ) { - if (!surfaceCeilingColumn) { - return threshold; - } - - int ceilingDistance = columnTopY - y; - if (ceilingDistance < 0 || ceilingDistance >= SURFACE_CEILING_FADE_DEPTH) { - return threshold; - } - - double closureThreshold = surfaceClosureThreshold[y - minY]; - if (threshold <= closureThreshold) { - return threshold; - } - - double progress = ceilingDistance / (double) SURFACE_CEILING_FADE_DEPTH; - double smooth = progress * progress * (3D - (2D * progress)); - return closureThreshold + ((threshold - closureThreshold) * smooth); - } - - private double[] computeSurfaceClosureThresholds(IrisCaveProfile profile, int minY, int maxY) { - double normalization = Math.abs(profile.getBaseWeight()) + Math.abs(profile.getDetailWeight()); - for (IrisCaveFieldModule module : profile.getModules()) { - normalization += Math.abs(module.getWeight()); - } - if (normalization <= 0D) { - normalization = 1D; - } - - double[] thresholds = new double[Math.max(0, maxY - minY + 1)]; - double baseMinimum = -Math.abs(profile.getBaseWeight()) - Math.abs(profile.getDetailWeight()); - for (int y = minY; y <= maxY; y++) { - double minimumDensity = baseMinimum; - for (IrisCaveFieldModule module : profile.getModules()) { - IrisRange range = module.getVerticalRange(); - if (y < Math.floor(range.getMin()) || y > Math.ceil(range.getMax())) { - continue; - } - double rawMinimum = module.isInvert() - ? module.getThreshold() - 1D - : -1D - module.getThreshold(); - double rawMaximum = module.isInvert() - ? module.getThreshold() + 1D - : 1D - module.getThreshold(); - minimumDensity += Math.min(rawMinimum * module.getWeight(), rawMaximum * module.getWeight()); - } - thresholds[y - minY] = (minimumDensity / normalization) - SURFACE_CEILING_SOLID_EPSILON; - } - return thresholds; - } - - private double[] computeVerticalEdgeFade(IrisCaveProfile profile, int minY, int maxY) { - int size = Math.max(0, maxY - minY + 1); - double[] verticalEdgeFade = new double[size]; - int fadeRange = Math.max(0, profile.getVerticalEdgeFade()); - double fadeStrength = Math.max(0D, profile.getVerticalEdgeFadeStrength()); - if (size == 0 || fadeRange <= 0 || maxY <= minY || fadeStrength <= 0D) { - return verticalEdgeFade; - } - - for (int y = minY; y <= maxY; y++) { - int floorDistance = y - minY; - int ceilingDistance = maxY - y; - int edgeDistance = Math.min(floorDistance, ceilingDistance); - int offsetIndex = y - minY; - if (edgeDistance >= fadeRange) { - continue; - } - - double t = Math.max(0D, Math.min(1D, edgeDistance / (double) fadeRange)); - double smooth = t * t * (3D - (2D * t)); - verticalEdgeFade[offsetIndex] = (1D - smooth) * fadeStrength; - } - - return verticalEdgeFade; - } - - private MatterCavern[] computeMatterByY(Engine engine, IrisCaveProfile profile, MatterCavern carveAir, MatterCavern carveLava, MatterCavern carveForcedAir, int minY, int maxY) { - MatterCavern[] matterByY = new MatterCavern[Math.max(0, maxY - minY + 1)]; - boolean allowLava = profile.isAllowLava(); - int lavaHeight = engine.getDimension().getCaveLavaHeight(); - - for (int y = minY; y <= maxY; y++) { - int offset = y - minY; - if (allowLava && y <= lavaHeight) { - matterByY[offset] = carveLava; - continue; - } - if (!allowLava && y <= lavaHeight) { - matterByY[offset] = carveForcedAir; - continue; - } - - matterByY[offset] = carveAir; - } - - return matterByY; - } - - private Engine createEngine(int worldHeight, int sampledHeight) { - Engine engine = mock(Engine.class, withSettings().stubOnly()); - IrisData data = mock(IrisData.class, withSettings().stubOnly()); - IrisDimension dimension = mock(IrisDimension.class, withSettings().stubOnly()); - SeedManager seedManager = mock(SeedManager.class, withSettings().stubOnly()); - EngineMetrics metrics = new EngineMetrics(16); - IrisWorld world = IrisWorld.builder().minHeight(0).maxHeight(worldHeight).build(); - - doReturn(data).when(engine).getData(); - doReturn(dimension).when(engine).getDimension(); - doReturn(seedManager).when(engine).getSeedManager(); - doReturn(CARVE_SEED).when(seedManager).getCarve(); - doReturn(metrics).when(engine).getMetrics(); - doReturn(world).when(engine).getWorld(); - doReturn(sampledHeight).when(engine).getHeight(anyInt(), anyInt()); - - doReturn(18).when(dimension).getCaveLavaHeight(); - doReturn(64).when(dimension).getFluidHeight(); - - return engine; - } - - private IrisCaveProfile createProfile(boolean warp, boolean modules) { - IrisCaveProfile profile = new IrisCaveProfile(); - profile.setEnabled(true); - profile.setVerticalRange(new IrisRange(0D, 120D)); - profile.setVerticalEdgeFade(14); - profile.setVerticalEdgeFadeStrength(0.21D); - profile.setBaseDensityStyle(new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.109375D)); - profile.setDetailDensityStyle(new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.265625D)); - profile.setWarpStyle(new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.1875D)); - profile.setSurfaceBreakStyle(new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.140625D)); - profile.setBaseWeight(1D); - profile.setDetailWeight(0.48D); - profile.setWarpStrength(warp ? 0.37D : 0D); - profile.setDensityThreshold(new IrisStyledRange(1D, 1D, new IrisGeneratorStyle(NoiseStyle.FLAT))); - profile.setThresholdBias(0D); - profile.setSampleStep(1); - profile.setSurfaceClearance(5); - profile.setAllowSurfaceBreak(true); - profile.setSurfaceBreakNoiseThreshold(0.16D); - profile.setSurfaceBreakDepth(12); - profile.setSurfaceBreakThresholdBoost(0.17D); - profile.setAllowFluid(true); - profile.setFluidMinDepthBelowSurface(8); - profile.setFluidRequiresFloor(false); - profile.setAllowLava(true); - if (modules) { - KList caveModules = new KList<>(); - caveModules.add(new IrisCaveFieldModule( - new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.171875D), - 0.23D, - 0.04D, - new IrisRange(0D, 72D), - false - )); - caveModules.add(new IrisCaveFieldModule( - new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.296875D), - 0.17D, - -0.06D, - new IrisRange(24D, 120D), - true - )); - profile.setModules(caveModules); - } else { - profile.setModules(new KList<>()); - } - return profile; - } - - private IrisCaveProfile carveEverywhere() { - return createProfile(false, false) - .setDensityThreshold(new IrisStyledRange(4D, 4D, new IrisGeneratorStyle(NoiseStyle.FLAT))) - .setAllowFluid(false) - .setAllowLava(false); - } - - private IrisCaveProfile createFluidProfile() { - return createProfile(false, false) - .setVerticalRange(new IrisRange(20D, 70D)) - .setVerticalEdgeFade(0) - .setVerticalEdgeFadeStrength(0D) - .setDensityThreshold(new IrisStyledRange(2D, 2D, new IrisGeneratorStyle(NoiseStyle.FLAT))) - .setAdaptiveSampling(false) - .setSurfaceClearance(5) - .setAllowSurfaceBreak(true) - .setSurfaceBreakNoiseThreshold(-1D) - .setSurfaceBreakThresholdBoost(0D) - .setAllowFluid(true) - .setFluidRequiresFloor(false) - .setAllowLava(true); - } - - private void assertSurfaceFluidBoundaryForProfile(IrisCaveProfile profile) { - Engine engine = createEngine(80, 70); - int[] surfaceHeights = filledHeights(70); - surfaceHeights[0] = 60; - long[] boundaries = new long[256]; - Arrays.fill(boundaries, SurfaceFluidBoundaryPlan.boundary( - SurfaceFluidBoundaryPlan.NO_BOUNDARY, Integer.MIN_VALUE)); - boundaries[0] = SurfaceFluidBoundaryPlan.boundary(60, 64); - boundaries[16] = SurfaceFluidBoundaryPlan.boundary(61, 64); - WriterCapture capture = createWriterCapture(80); - CaveFluidSupportPlan supportPlan = new CaveFluidSupportPlan(); - - new IrisCaveCarver3D(engine, profile.setFluidMinDepthBelowSurface(0).setFluidRequiresFloor(false)).carve( - capture.writer, - 0, - 0, - fullWeights(), - 0D, - 0D, - null, - surfaceHeights, - boundaries, - null, - null, - supportPlan - ); - - assertTrue(capture.carvedCells.contains(cellKey(0, 56, 0))); - assertFalse(capture.carvedCells.contains(cellKey(0, 60, 0))); - assertTrue(capture.carvedCells.contains(cellKey(1, 60, 0))); - for (int y = 61; y <= 64; y++) { - assertFalse(capture.carvedCells.contains(cellKey(1, y, 0))); - } - assertTrue(capture.carvedCells.contains(cellKey(1, 65, 0))); - assertTrue(capture.carvedCells.contains(cellKey(2, 64, 0))); - assertTrue(countLiquid(capture, (byte) 1) > 0); - assertTrue(countLiquid(capture, (byte) 0) > 0); - } - - private WriterCapture createWriterCapture(int worldHeight) { - MantleWriter writer = mock(MantleWriter.class, withSettings().stubOnly()); - @SuppressWarnings("unchecked") - Mantle mantle = mock(Mantle.class, withSettings().stubOnly()); - @SuppressWarnings("unchecked") - MantleChunk chunk = mock(MantleChunk.class, withSettings().stubOnly()); - Map sections = new HashMap<>(); - Set carvedCells = new HashSet<>(); - Map carvedLiquids = new HashMap<>(); - WriterCapture capture = new WriterCapture(writer, carvedCells, carvedLiquids); - - doReturn(mantle).when(writer).getMantle(); - doReturn(worldHeight).when(mantle).getWorldHeight(); - doReturn(chunk).when(writer).acquireChunk(anyInt(), anyInt()); - doAnswer(invocation -> sections.get(invocation.getArgument(0, Integer.class))).when(chunk).get(anyInt()); - doAnswer(invocation -> { - int sectionIndex = invocation.getArgument(0); - Matter section = sections.get(sectionIndex); - if (section != null) { - return section; - } - - Matter created = createSection(sectionIndex, carvedCells, carvedLiquids); - sections.put(sectionIndex, created); - return created; - }).when(chunk).getOrCreate(anyInt()); - - return capture; - } - - private Matter createSection(int sectionIndex, Set carvedCells, Map carvedLiquids) { - Matter matter = mock(Matter.class, withSettings().stubOnly()); - MatterSlice slice = new CapturingCavernMatter(sectionIndex, carvedCells, carvedLiquids); - doReturn(slice).when(matter).slice(MatterCavern.class); - doReturn(slice).when(matter).getSlice(MatterCavern.class); - return matter; - } - - private double[] fullWeights() { - double[] columnWeights = new double[256]; - Arrays.fill(columnWeights, 1D); - return columnWeights; - } - - private int[] filledHeights(int height) { - int[] heights = new int[256]; - Arrays.fill(heights, height); - return heights; - } - - private int[] splitSurfaceHeights(int lowHeight, int highHeight) { - int[] heights = new int[256]; - for (int localX = 0; localX < 16; localX++) { - for (int localZ = 0; localZ < 16; localZ++) { - heights[(localX << 4) | localZ] = localX < 8 ? lowHeight : highHeight; - } - } - return heights; - } - - private void assertFluidCellsHaveSolidSupport(WriterCapture capture) { - for (Map.Entry entry : capture.carvedLiquids.entrySet()) { - if (entry.getValue() != 1) { - continue; - } - - String[] split = entry.getKey().split(":"); - int x = Integer.parseInt(split[0]); - int y = Integer.parseInt(split[1]); - int z = Integer.parseInt(split[2]); - assertFalse(capture.carvedCells.contains(cellKey(x, y - 1, z))); - assertFalse(capture.carvedCells.contains(cellKey(x, y - 2, z))); - int support = 0; - if (!capture.carvedCells.contains(cellKey(x + 1, y, z))) { - support++; - } - if (!capture.carvedCells.contains(cellKey(x - 1, y, z))) { - support++; - } - if (!capture.carvedCells.contains(cellKey(x, y, z + 1))) { - support++; - } - if (!capture.carvedCells.contains(cellKey(x, y, z - 1))) { - support++; - } - if (!capture.carvedCells.contains(cellKey(x, y + 1, z))) { - support++; - } - assertTrue(support >= 4); - } - } - - private void assertFluidRespectsSplitCutoff(WriterCapture capture, int lowCutoff, int highCutoff) { - boolean lowFluid = false; - boolean highFluid = false; - for (Map.Entry entry : capture.carvedLiquids.entrySet()) { - if (entry.getValue() != 1) { - continue; - } - int x = coordinate(entry.getKey(), 0); - int y = coordinate(entry.getKey(), 1); - if (x < 8) { - assertTrue(y <= lowCutoff); - lowFluid = true; - } else { - assertTrue(y <= highCutoff); - highFluid = true; - } - } - assertTrue(lowFluid); - assertTrue(highFluid); - } - - private void assertLiquidAtOrBelow(WriterCapture capture, byte liquid, int maxY) { - for (Map.Entry entry : capture.carvedLiquids.entrySet()) { - if (entry.getValue() == liquid) { - assertTrue(coordinate(entry.getKey(), 1) <= maxY); - } - } - } - - private int countLiquid(WriterCapture capture, byte liquid) { - int count = 0; - for (byte value : capture.carvedLiquids.values()) { - if (value == liquid) { - count++; - } - } - return count; - } - - private String firstCellWithLiquid(WriterCapture capture, byte liquid) { - for (Map.Entry entry : capture.carvedLiquids.entrySet()) { - if (entry.getValue() == liquid) { - return entry.getKey(); - } - } - return null; - } - - private int coordinate(String cell, int index) { - return Integer.parseInt(cell.split(":")[index]); - } - - private double clampColumnWeight(double weight) { - if (Double.isNaN(weight) || Double.isInfinite(weight)) { - return 0D; - } - if (weight <= 0D) { - return 0D; - } - if (weight >= 1D) { - return 1D; - } - return weight; - } - - private double signed(double value) { - return (value * 2D) - 1D; - } - - private String cellKey(int x, int y, int z) { - return x + ":" + y + ":" + z; - } - - private boolean containsLiquidInRange(Map carvedLiquids, int minY, int maxY, byte liquid) { - for (Map.Entry entry : carvedLiquids.entrySet()) { - if (entry.getValue() != liquid) { - continue; - } - - String[] split = entry.getKey().split(":"); - int y = Integer.parseInt(split[1]); - if (y >= minY && y <= maxY) { - return true; - } - } - return false; - } - - private boolean hasX(Set carvedCells, int x) { - for (String cell : carvedCells) { - String[] split = cell.split(":"); - if (Integer.parseInt(split[0]) == x) { - return true; - } - } - - return false; - } - - private boolean hasZ(Set carvedCells, int z) { - for (String cell : carvedCells) { - String[] split = cell.split(":"); - if (Integer.parseInt(split[2]) == z) { - return true; - } - } - - return false; - } - - private int maxY(Set carvedCells) { - int max = Integer.MIN_VALUE; - for (String cell : carvedCells) { - String[] split = cell.split(":"); - int y = Integer.parseInt(split[1]); - if (y > max) { - max = y; - } - } - return max; - } - - private int minY(Set carvedCells) { - int min = Integer.MAX_VALUE; - for (String cell : carvedCells) { - String[] split = cell.split(":"); - int y = Integer.parseInt(split[1]); - if (y < min) { - min = y; - } - } - return min; - } - - private static final class CountingCNG extends CNG { - private final NoiseProgram delegate; - private final AtomicLong samples; - - private CountingCNG(NoiseProgram delegate, AtomicLong samples) { - super(new RNG(41_117L)); - this.delegate = delegate; - this.samples = samples; - } - - @Override - public double noiseFastSigned3D(double x, double y, double z) { - samples.incrementAndGet(); - return delegate.sampleSigned3D(x, y, z); - } - } - - private static final class CoordinateDensityCNG extends CNG { - private final Map densityByCoordinate; - private final List sampledCoordinates = new ArrayList<>(); - - private CoordinateDensityCNG(Map densityByCoordinate) { - super(new RNG(82_991L)); - this.densityByCoordinate = densityByCoordinate; - } - - @Override - public double noiseFastSigned3D(double x, double y, double z) { - String coordinate = (int) x + ":" + (int) y + ":" + (int) z; - sampledCoordinates.add(coordinate); - return densityByCoordinate.getOrDefault(coordinate, 1D); - } - } - - private final class CapturingCavernMatter extends CavernMatter { - private final int sectionIndex; - private final Set carvedCells; - private final Map carvedLiquids; - - private CapturingCavernMatter(int sectionIndex, Set carvedCells, Map carvedLiquids) { - super(16, 16, 16); - this.sectionIndex = sectionIndex; - this.carvedCells = carvedCells; - this.carvedLiquids = carvedLiquids; - } - - @Override - public void set(int x, int y, int z, MatterCavern value) { - super.set(x, y, z, value); - String cell = cellKey(x, (sectionIndex << 4) + y, z); - carvedCells.add(cell); - carvedLiquids.put(cell, value.getLiquid()); - } - } - - private static final class WriterCapture { - private final MantleWriter writer; - private final Set carvedCells; - private final Map carvedLiquids; - - private WriterCapture(MantleWriter writer, Set carvedCells, Map carvedLiquids) { - this.writer = writer; - this.carvedCells = carvedCells; - this.carvedLiquids = carvedLiquids; - } - } -} diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/ListedCaveCarvingTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/ListedCaveCarvingTest.java new file mode 100644 index 000000000..51999625f --- /dev/null +++ b/core/src/test/java/art/arcane/iris/generation/mantle/ListedCaveCarvingTest.java @@ -0,0 +1,395 @@ +package art.arcane.iris.generation.mantle; + +import art.arcane.iris.generation.biome.IrisBiome; +import art.arcane.iris.generation.cave.IrisCave; +import art.arcane.iris.generation.cave.TestSettings; +import art.arcane.iris.generation.cave.field.CngNoiseFactory; +import art.arcane.iris.generation.mantle.CaveListing.ListedColumns; +import art.arcane.iris.generation.mantle.CaveTerrain.CaveBand; +import art.arcane.iris.generation.mantle.CaveTerrain.CavePlace; +import art.arcane.iris.generation.mantle.ListedCaveCarving.ChunkSurface; +import art.arcane.iris.generation.terrain.IrisRegion; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; +import art.arcane.volmlib.util.matter.MatterCavern; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.BiFunction; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +public class ListedCaveCarvingTest { + private static final int WORLD_HEIGHT = 256; + private static final int SURFACE_Y = 200; + private static final long CARVE_SEED = 4_711L; + private static final int FLUID_HEIGHT = 63; + private static final int LAVA_HEIGHT = 10; + private static final int POCKET_SEARCH_CHUNKS = 12; + private static final byte LIQUID_FLUID = 1; + private static final byte LIQUID_LAVA = 2; + private static final byte LIQUID_FORCED_AIR = 3; + private static final String HALLS = "{\"cavern\": {\"size\": 40, \"height\": 24, \"coverage\": 0.45}, \"surfaceClearance\": 0, \"allowFluid\": false}"; + private static final String DEEP_HALLS = "{\"cavern\": {\"size\": 40, \"height\": 24, \"coverage\": 0.45}, \"depth\": {\"min\": 80, \"max\": 140}," + + " \"fade\": 0, \"surfaceClearance\": 0, \"allowFluid\": false}"; + private static final CavePlace NOWHERE_SPECIAL = new CavePlace(new IrisRegion(), new IrisBiome(), new IrisBiome()); + + private final Map caveFiles = new HashMap<>(); + private final Set biomes = new HashSet<>(); + private final List missingCaves = new ArrayList<>(); + private final List missingBiomes = new ArrayList<>(); + + @Test + public void listsOfTheDimensionRegionSurfaceBiomeAndCaveBiomeAddUp() { + files("dimension", HALLS, "region", HALLS, "surface", HALLS, "cave", HALLS); + IrisRegion region = new IrisRegion().setCaves(new KList<>("region")); + IrisBiome surface = new IrisBiome().setCaves(new KList<>("surface")); + IrisBiome cave = new IrisBiome().setCaves(new KList<>("cave")); + + CaveListing listing = carving(List.of("dimension"), false).list(terrainEverywhere(new CavePlace(region, surface, cave)), 0, 0); + + assertEquals(List.of("dimension", "region", "surface", "cave"), keysOf(listing)); + for (ListedColumns listed : listing.caves()) { + assertTrue(Arrays.stream(listed.weight()).allMatch(weight -> weight == 1D)); + } + } + + @Test + public void aCaveListedTwiceCarvesOnce() { + files("shared", HALLS); + IrisRegion region = new IrisRegion().setCaves(new KList<>("shared")); + + CaveListing listing = carving(List.of("shared"), false).list(terrainEverywhere(new CavePlace(region, null, null)), 0, 0); + + assertEquals(List.of("shared"), keysOf(listing)); + } + + @Test + public void aPackThatOnlyListsCavesInTheDimensionNeverReadsTheTerrain() { + files("dimension", HALLS); + int[] reads = new int[1]; + CaveTerrain counting = new CaveTerrain() { + @Override + public CavePlace placeAt(int worldX, int worldZ) { + reads[0]++; + return NOWHERE_SPECIAL; + } + + @Override + public List bandsOf(int chunkX, int chunkZ) { + return List.of(); + } + }; + + CaveListing listing = carving(List.of("dimension"), true).list(counting, 5, -3); + + assertEquals(List.of("dimension"), keysOf(listing)); + assertEquals(0, reads[0]); + } + + @Test + public void aCaveBiomeListsItsCavesOnlyWhereTheCaveBiomeIsAndTapersOffAcrossItsBorder() { + files("deep", HALLS); + IrisBiome withCaves = new IrisBiome().setCaves(new KList<>("deep")); + IrisBiome plain = new IrisBiome(); + BiFunction placeAt = (x, z) -> new CavePlace(null, null, x < -8 ? withCaves : plain); + + CaveListing listing = carving(List.of(), false).list(terrain(placeAt, List.of()), -1, 0); + + assertEquals(List.of("deep"), keysOf(listing)); + double[] weight = listing.caves().getFirst().weight(); + assertEquals(1D, weight[PowerOfTwoCoordinates.packLocal16(0, 8)], 0D); + assertEquals(0D, weight[PowerOfTwoCoordinates.packLocal16(15, 8)], 0D); + for (int localX = 1; localX < 16; localX++) { + assertTrue("weight falls towards the east", weight[PowerOfTwoCoordinates.packLocal16(localX, 8)] + <= weight[PowerOfTwoCoordinates.packLocal16(localX - 1, 8)]); + } + assertTrue(weight[PowerOfTwoCoordinates.packLocal16(8, 8)] > 0D && weight[PowerOfTwoCoordinates.packLocal16(8, 8)] < 1D); + } + + @Test + public void aCaveIsMissingFromTheListingAndReportedOnce() { + files("halls", HALLS); + ListedCaveCarving carving = carving(List.of("halls", "ghost"), true); + + CaveListing first = carving.list(terrainEverywhere(NOWHERE_SPECIAL), 0, 0); + CaveListing second = carving.list(terrainEverywhere(NOWHERE_SPECIAL), 1, 0); + + assertEquals(List.of("halls"), keysOf(first)); + assertEquals(List.of("halls"), keysOf(second)); + assertEquals(List.of("ghost"), missingCaves); + } + + @Test + public void aCaveBiomeTheCavePacksDoNotHaveIsReportedAndLeftOut() { + files("grotto", "{\"cavern\": {\"size\": 40, \"height\": 24, \"coverage\": 0.45}, \"surfaceClearance\": 0, \"allowFluid\": false, \"biome\": \"nowhere\"}"); + ListedCaveCarving carving = carving(List.of("grotto"), true); + + CaveListing listing = carving.list(terrainEverywhere(NOWHERE_SPECIAL), 0, 0); + Map cells = carve(carving, listing, 0, 0, new ChunkSurface(surfaceEverywhere(), null, null)); + + assertEquals(List.of("grotto:nowhere"), missingBiomes); + assertFalse(cells.isEmpty()); + assertTrue(cells.values().stream().allMatch(cell -> cell.getCustomBiome().isEmpty())); + } + + @Test + public void aCaveCarvesOnlyInsideItsDepthRange() { + files("deep", DEEP_HALLS); + ListedCaveCarving carving = carving(List.of("deep"), true); + + Map cells = carve(carving, carving.list(terrainEverywhere(NOWHERE_SPECIAL), 3, 4), 3, 4, + new ChunkSurface(surfaceEverywhere(), null, null)); + + assertFalse(cells.isEmpty()); + assertTrue("carved between 80 and 140", cells.keySet().stream().allMatch(key -> heightOf(key) >= 80 && heightOf(key) <= 140)); + } + + @Test + public void aCarvingBandLimitsItsBiomesCavesToItsHeights() { + files("halls", HALLS); + IrisBiome bandBiome = new IrisBiome().setCaves(new KList<>("halls")); + IrisBiome[] everywhere = new IrisBiome[256]; + Arrays.fill(everywhere, bandBiome); + CaveBand band = new CaveBand(100, 120, everywhere); + ListedCaveCarving carving = carving(List.of(), true); + + CaveListing listing = carving.list(terrain((x, z) -> NOWHERE_SPECIAL, List.of(band)), 2, 2); + Map cells = carve(carving, listing, 2, 2, new ChunkSurface(surfaceEverywhere(), null, null)); + + assertEquals(List.of("halls"), keysOf(listing)); + assertFalse(cells.isEmpty()); + assertTrue("carved between 100 and 120", cells.keySet().stream().allMatch(key -> heightOf(key) >= 100 && heightOf(key) <= 120)); + } + + @Test + public void aBandIsMeasuredFromTheDimensionsBottom() { + files("halls", HALLS); + IrisBiome[] everywhere = new IrisBiome[256]; + Arrays.fill(everywhere, new IrisBiome().setCaves(new KList<>("halls"))); + CaveWorld below = new CaveWorld(-64, WORLD_HEIGHT, CARVE_SEED, FLUID_HEIGHT, LAVA_HEIGHT); + ListedCaveCarving carving = carving(List.of(), true, below); + + CaveListing listing = carving.list(terrain((x, z) -> NOWHERE_SPECIAL, List.of(new CaveBand(0, 20, everywhere))), 2, 2); + Map cells = carve(carving, listing, 2, 2, new ChunkSurface(surfaceEverywhere(), null, null)); + + assertFalse(cells.isEmpty()); + assertTrue("world 0..20 is height 64..84", cells.keySet().stream().allMatch(key -> heightOf(key) >= 64 && heightOf(key) <= 84)); + } + + @Test + public void aColumnCeilingKeepsEveryCaveUnderIt() { + files("halls", HALLS); + int ceilingY = 90; + int[] ceilings = new int[256]; + Arrays.fill(ceilings, ceilingY); + ListedCaveCarving carving = carving(List.of("halls"), true); + CaveListing listing = carving.list(terrainEverywhere(NOWHERE_SPECIAL), 2, 2); + + Map free = carve(carving, listing, 2, 2, new ChunkSurface(surfaceEverywhere(), null, null)); + Map capped = carve(carving, listing, 2, 2, new ChunkSurface(surfaceEverywhere(), null, ceilings)); + + assertTrue("without a ceiling the cave rises above " + ceilingY, free.keySet().stream().anyMatch(key -> heightOf(key) > ceilingY)); + assertFalse(capped.isEmpty()); + assertTrue("under the ceiling", capped.keySet().stream().allMatch(key -> heightOf(key) <= ceilingY)); + } + + @Test + public void aSurfaceFluidBoundaryKeepsCavesOutOfItsHeights() { + files("halls", HALLS); + long[] boundaries = new long[256]; + Arrays.fill(boundaries, SurfaceFluidBoundaryPlan.boundary(60, 90)); + ListedCaveCarving carving = carving(List.of("halls"), true); + CaveListing listing = carving.list(terrainEverywhere(NOWHERE_SPECIAL), 2, 2); + + Map free = carve(carving, listing, 2, 2, new ChunkSurface(surfaceEverywhere(), null, null)); + Map protectedCells = carve(carving, listing, 2, 2, new ChunkSurface(surfaceEverywhere(), boundaries, null)); + + assertTrue(free.keySet().stream().anyMatch(key -> heightOf(key) >= 60 && heightOf(key) <= 90)); + assertFalse(protectedCells.isEmpty()); + assertTrue(protectedCells.keySet().stream().noneMatch(key -> heightOf(key) >= 60 && heightOf(key) <= 90)); + } + + @Test + public void aBlockSeveralCavesCarveBelongsToTheFirstListed() { + files("first", "{\"cavern\": {\"size\": 40, \"height\": 24, \"coverage\": 0.5}, \"surfaceClearance\": 0, \"allowFluid\": false, \"biome\": \"one\"}", + "second", "{\"cavern\": {\"size\": 40, \"height\": 24, \"coverage\": 0.5}, \"surfaceClearance\": 0, \"allowFluid\": false, \"biome\": \"two\"}"); + biomes.addAll(List.of("one", "two")); + ListedCaveCarving carving = carving(List.of("first", "second"), true); + ChunkSurface surface = new ChunkSurface(surfaceEverywhere(), null, null); + CaveListing both = carving.list(terrainEverywhere(NOWHERE_SPECIAL), 2, 2); + CaveListing onlyFirst = new CaveListing(both.caves().subList(0, 1), false); + + Map bothCarved = carve(carving, both, 2, 2, surface); + Map firstCarved = carve(carving, onlyFirst, 2, 2, surface); + + assertTrue(bothCarved.keySet().containsAll(firstCarved.keySet())); + assertTrue("some blocks only the second carves", bothCarved.size() > firstCarved.size()); + for (Long key : firstCarved.keySet()) { + assertEquals("one", bothCarved.get(key).getCustomBiome()); + } + assertTrue(bothCarved.entrySet().stream().filter(entry -> !firstCarved.containsKey(entry.getKey())) + .allMatch(entry -> entry.getValue().getCustomBiome().equals("two"))); + } + + @Test + public void cavesBelowTheLavaHeightHoldLavaOrForcedAirAsTheyAllow() { + files("lava", "{\"cavern\": {\"size\": 40, \"height\": 24, \"coverage\": 0.5}, \"depth\": {\"min\": 0, \"max\": 9}, \"fade\": 0, \"surfaceClearance\": 0, \"allowFluid\": false}", + "dry", "{\"cavern\": {\"size\": 40, \"height\": 24, \"coverage\": 0.5}, \"depth\": {\"min\": 0, \"max\": 9}, \"fade\": 0, \"surfaceClearance\": 0, \"allowFluid\": false, \"allowLava\": false}"); + + for (String cave : List.of("lava", "dry")) { + ListedCaveCarving carving = carving(List.of(cave), true); + Map cells = carve(carving, carving.list(terrainEverywhere(NOWHERE_SPECIAL), 2, 2), 2, 2, + new ChunkSurface(surfaceEverywhere(), null, null)); + + assertFalse(cave, cells.isEmpty()); + byte expected = cave.equals("lava") ? LIQUID_LAVA : LIQUID_FORCED_AIR; + assertTrue(cave, cells.values().stream().allMatch(cell -> cell.getLiquid() == expected)); + } + } + + @Test + public void aCaveHoldsPocketsOfFluidBelowTheFluidHeightOnlyDeepEnoughBelowTheSurface() { + files("wet", "{\"cavern\": {\"size\": 60, \"height\": 30, \"coverage\": 0.6}, \"depth\": {\"min\": 20, \"max\": 60}, \"fade\": 0, \"surfaceClearance\": 0," + + " \"allowLava\": false, \"fluidRequiresFloor\": false}"); + ListedCaveCarving carving = carving(List.of("wet"), true); + int[] shallow = new int[256]; + Arrays.fill(shallow, 70); + + List fluidUnderDeepSurface = new ArrayList<>(); + List fluidUnderShallowSurface = new ArrayList<>(); + for (int chunkX = 0; chunkX < POCKET_SEARCH_CHUNKS; chunkX++) { + for (int chunkZ = 0; chunkZ < POCKET_SEARCH_CHUNKS; chunkZ++) { + CaveListing listing = carving.list(terrainEverywhere(NOWHERE_SPECIAL), chunkX, chunkZ); + addFluidHeights(carve(carving, listing, chunkX, chunkZ, new ChunkSurface(surfaceEverywhere(), null, null)), fluidUnderDeepSurface); + addFluidHeights(carve(carving, listing, chunkX, chunkZ, new ChunkSurface(shallow, null, null)), fluidUnderShallowSurface); + } + } + + assertFalse("fluid pockets deep under the surface", fluidUnderDeepSurface.isEmpty()); + assertTrue("never above the fluid height", fluidUnderDeepSurface.stream().allMatch(y -> y <= FLUID_HEIGHT)); + assertTrue("under a surface at 70 a cave may hold fluid up to 58", fluidUnderShallowSurface.stream().allMatch(y -> y <= 70 - 12)); + } + + private static void addFluidHeights(Map cells, List heights) { + cells.forEach((key, cell) -> { + if (cell.getLiquid() == LIQUID_FLUID) { + heights.add(heightOf(key)); + } + }); + } + + @Test + public void theUpperDimensionPassCarvesTheWholeDimensionBeneathItsTerrainUnderTheTopOfTheWorld() { + files("deep", DEEP_HALLS); + ListedCaveCarving carving = carving(List.of("deep"), true); + CaveListing listing = carving.list(terrainEverywhere(NOWHERE_SPECIAL), 2, 2); + Map cells = new HashMap<>(); + + carving.carveBeneathUpperTerrain(listing, 2, 2, 200, (x, y, z, cell) -> cells.put(key(x, y, z), cell), new CaveFluidSupportPlan()); + + assertFalse(cells.isEmpty()); + assertTrue("only inside the upper terrain, whatever the cave's own depth", cells.keySet().stream().allMatch(key -> heightOf(key) >= 200)); + assertTrue("closed under the top of the world", cells.keySet().stream().allMatch(key -> heightOf(key) < WORLD_HEIGHT - 1)); + assertNotEquals("a carve the cave's own depth would have kept out", 0, cells.size()); + } + + @Test + public void sameSettingsAndSeedCarveTheSameCaveAndAnotherSeedAnother() { + files("halls", HALLS); + ListedCaveCarving first = carving(List.of("halls"), true); + ListedCaveCarving again = carving(List.of("halls"), true); + ListedCaveCarving other = carving(List.of("halls"), true, new CaveWorld(0, WORLD_HEIGHT, CARVE_SEED + 1, FLUID_HEIGHT, LAVA_HEIGHT)); + ChunkSurface surface = new ChunkSurface(surfaceEverywhere(), null, null); + + Map one = carve(first, first.list(terrainEverywhere(NOWHERE_SPECIAL), 2, 2), 2, 2, surface); + Map same = carve(again, again.list(terrainEverywhere(NOWHERE_SPECIAL), 2, 2), 2, 2, surface); + Map different = carve(other, other.list(terrainEverywhere(NOWHERE_SPECIAL), 2, 2), 2, 2, surface); + + assertEquals(one.keySet(), same.keySet()); + assertNotEquals(one.keySet(), different.keySet()); + } + + private void files(String... keysAndFiles) { + for (int index = 0; index < keysAndFiles.length; index += 2) { + caveFiles.put(keysAndFiles[index], keysAndFiles[index + 1]); + } + } + + private ListedCaveCarving carving(List dimensionCaves, boolean onlyDimensionLists) { + return carving(dimensionCaves, onlyDimensionLists, new CaveWorld(0, WORLD_HEIGHT, CARVE_SEED, FLUID_HEIGHT, LAVA_HEIGHT)); + } + + private ListedCaveCarving carving(List dimensionCaves, boolean onlyDimensionLists, CaveWorld world) { + return new ListedCaveCarving(dimensionCaves, onlyDimensionLists, world, CngNoiseFactory.standalone(), + key -> caveFiles.containsKey(key) ? TestSettings.of(IrisCave.class, caveFiles.get(key)) : null, + biomes::contains, + new ListedCaveCarving.Problems() { + @Override + public void missingCave(String caveKey) { + missingCaves.add(caveKey); + } + + @Override + public void missingCaveBiome(String caveKey, String biomeKey) { + missingBiomes.add(caveKey + ":" + biomeKey); + } + }); + } + + private static CaveTerrain terrainEverywhere(CavePlace place) { + return terrain((x, z) -> place, List.of()); + } + + private static CaveTerrain terrain(BiFunction placeAt, List bands) { + return new CaveTerrain() { + @Override + public CavePlace placeAt(int worldX, int worldZ) { + return placeAt.apply(worldX, worldZ); + } + + @Override + public List bandsOf(int chunkX, int chunkZ) { + return bands; + } + }; + } + + private static int[] surfaceEverywhere() { + int[] surface = new int[256]; + Arrays.fill(surface, SURFACE_Y); + return surface; + } + + private static List keysOf(CaveListing listing) { + return listing.caves().stream().map(listed -> listed.cave().key()).toList(); + } + + private static Map carve(ListedCaveCarving carving, CaveListing listing, int chunkX, int chunkZ, ChunkSurface surface) { + return carve(carving, listing, chunkX, chunkZ, surface, new CaveFluidSupportPlan()); + } + + private static Map carve(ListedCaveCarving carving, CaveListing listing, int chunkX, int chunkZ, ChunkSurface surface, + CaveFluidSupportPlan plan) { + Map cells = new HashMap<>(); + carving.carve(listing, chunkX, chunkZ, surface, (x, y, z, cell) -> cells.put(key(x, y, z), cell), plan); + return cells; + } + + private static long key(int localX, int y, int localZ) { + return ((long) y << 8) | (localX << 4) | localZ; + } + + private static int heightOf(long key) { + return (int) (key >> 8); + } +} diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvingComponentBakedFieldTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvingComponentBakedFieldTest.java index 64f8bb1ac..1042173c3 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvingComponentBakedFieldTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvingComponentBakedFieldTest.java @@ -4,78 +4,80 @@ import art.arcane.iris.generation.bake.BakePlane; import art.arcane.iris.generation.bake.ChunkBakeCache; import art.arcane.iris.generation.bake.PlaneSource; import art.arcane.iris.generation.biome.IrisBiome; -import art.arcane.iris.generation.cave.IrisCaveProfile; +import art.arcane.iris.generation.cave.IrisCave; +import art.arcane.iris.generation.cave.TestSettings; import art.arcane.iris.generation.context.ChunkContext; +import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.EngineMetrics; -import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; import art.arcane.iris.generation.runtime.IrisComplex; -import art.arcane.iris.testsupport.FakeHydrology; +import art.arcane.iris.generation.runtime.SeedManager; import art.arcane.iris.generation.stream.BakedDoubleStream; import art.arcane.iris.generation.stream.BakedStream; import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.iris.generation.terrain.IrisRegion; -import art.arcane.iris.pack.value.IrisRange; +import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.pack.loading.ResourceLoader; +import art.arcane.iris.testsupport.FakeHydrology; import art.arcane.iris.world.IrisWorld; +import art.arcane.iris.world.storage.matter.IrisMatterSupport; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; +import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.mantle.runtime.Mantle; +import art.arcane.volmlib.util.mantle.runtime.MantleChunk; +import art.arcane.volmlib.util.matter.IrisMatter; import art.arcane.volmlib.util.matter.Matter; +import art.arcane.volmlib.util.matter.MatterCavern; import art.arcane.volmlib.util.stream.ProceduralStream; import org.junit.Test; -import java.lang.reflect.Field; import java.util.ArrayList; -import java.util.Arrays; -import java.util.IdentityHashMap; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyDouble; import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class MantleCarvingComponentBakedFieldTest { private static final double FLUID_HEIGHT = 63D; + private static final int WORLD_HEIGHT = 128; private static final int[][] ORDER = { {1, 1}, {-2, 0}, {0, 0}, {2, -1}, {-1, -1}, {0, 1}, {1, -2}, {-2, 2}, {2, 2}, {-1, 1}, {0, -1}, {1, 0} }; + private static final String HALLS = "{\"cavern\": {\"size\": 40, \"height\": 24, \"coverage\": 0.4}, \"surfaceClearance\": 4, \"allowFluid\": false}"; - private final IrisCaveProfile dimensionProfile = new IrisCaveProfile().setEnabled(true); - private final IrisCaveProfile regionProfile = new IrisCaveProfile().setEnabled(true); - private final IrisCaveProfile surfaceProfile = new IrisCaveProfile().setEnabled(true); - private final IrisCaveProfile shallowCaveProfile = new IrisCaveProfile().setEnabled(true); - private final IrisCaveProfile deepCaveProfile = new IrisCaveProfile().setEnabled(true); - private final IrisRegion profiledRegion = new IrisRegion().setCaveProfile(regionProfile); + private final IrisRegion listingRegion = new IrisRegion().setCaves(new KList<>("region-cave")); private final IrisRegion plainRegion = new IrisRegion(); - private final IrisBiome profiledSurface = new IrisBiome().setCaveProfile(surfaceProfile); + private final IrisBiome listingSurface = new IrisBiome().setCaves(new KList<>("surface-cave")); private final IrisBiome plainSurface = new IrisBiome(); - private final IrisBiome shallowCave = new IrisBiome().setCaveProfile(shallowCaveProfile); - private final IrisBiome deepCave = new IrisBiome().setCaveProfile(deepCaveProfile).setCaveMinDepthBelowSurface(60); + private final IrisBiome shallowCave = new IrisBiome().setCaves(new KList<>("shallow-cave")); + private final IrisBiome deepCave = new IrisBiome().setCaves(new KList<>("deep-cave")).setCaveMinDepthBelowSurface(60); private final IrisBiome plainCave = new IrisBiome(); private final NativeBlockState water = fluid(true); private final NativeBlockState air = fluid(false); @Test - public void bakedFieldReadsMatchPerColumnStreamReads() throws Exception { - List plain = run(false, false); - List baked = run(true, false); - List warmed = run(true, true); + public void bakedFieldReadsMatchPerColumnStreamReads() { + List plain = run(false, false, true); + List baked = run(true, false, true); + List warmed = run(true, true, true); - assertTrue(plain.size() > ORDER.length); + assertEquals(ORDER.length, plain.size()); + assertTrue(plain.toString(), plain.stream().anyMatch(carved -> !carved.contains(" carved=0 "))); assertEquals(plain, baked); assertEquals(plain, warmed); } @Test - public void apronHeightsAreComputedThroughThePlaneSourceAndNeverPerColumn() throws Exception { + public void whenOnlyTheDimensionListsCavesTheFluidBoundaryFieldNeverReadsAHeightPerColumn() { AtomicInteger scalarHeights = new AtomicInteger(); - Harness harness = harness(true, scalarHeights); + Harness harness = harness(true, false, scalarHeights); for (int[] chunk : ORDER) { harness.component.generateLayer(harness.writer, chunk[0], chunk[1], harness.context); } @@ -83,8 +85,8 @@ public class MantleCarvingComponentBakedFieldTest { assertEquals(0, scalarHeights.get()); } - private List run(boolean baked, boolean warm) throws Exception { - Harness harness = harness(baked, new AtomicInteger()); + private List run(boolean baked, boolean warm, boolean regionLists) { + Harness harness = harness(baked, regionLists, new AtomicInteger()); if (warm) { for (int x = -40; x < 56; x += 3) { for (int z = -40; z < 56; z += 5) { @@ -94,23 +96,56 @@ public class MantleCarvingComponentBakedFieldTest { } } } + List carved = new ArrayList<>(); for (int[] chunk : ORDER) { harness.component.generateLayer(harness.writer, chunk[0], chunk[1], harness.context); + carved.add(signature(chunk, harness.chunks.get(key(chunk[0], chunk[1])))); } - return harness.calls; + return carved; + } + + private static String signature(int[] chunk, Matter[] sections) { + int carved = 0; + long hash = 17; + for (int y = 0; y < WORLD_HEIGHT; y++) { + Matter section = sections[y >> 4]; + if (section == null) { + continue; + } + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + MatterCavern cell = section.slice(MatterCavern.class).get(x, y & 15, z); + if (cell != null) { + carved++; + hash = (hash * 31) + (((long) y << 8) | (x << 4) | z) + (cell.getLiquid() * 7919L); + } + } + } + } + return chunk[0] + "," + chunk[1] + " carved=" + carved + " hash=" + hash; + } + + private static long key(int chunkX, int chunkZ) { + return ((long) chunkX << 32) | (chunkZ & 0xffffffffL); } @SuppressWarnings("unchecked") - private Harness harness(boolean baked, AtomicInteger scalarHeights) throws ReflectiveOperationException { + private Harness harness(boolean baked, boolean regionLists, AtomicInteger scalarHeights) { + IrisMatterSupport.ensureRegistered(); Engine engine = mock(Engine.class); EngineMantle engineMantle = mock(EngineMantle.class); when(engineMantle.getEngine()).thenReturn(engine); MantleCarvingComponent component = new MantleCarvingComponent(engineMantle); - IrisDimension dimension = new IrisDimension(); - dimension.setCaveProfile(dimensionProfile); + IrisDimension dimension = new IrisDimension().setCaves(new KList<>("dimension-cave")).setRegions(new KList<>("region")); when(engine.getDimension()).thenReturn(dimension); - when(engine.getWorld()).thenReturn(IrisWorld.builder().minHeight(0).maxHeight(128).build()); + when(engine.getWorld()).thenReturn(IrisWorld.builder().minHeight(0).maxHeight(WORLD_HEIGHT).build()); when(engine.getMetrics()).thenReturn(new EngineMetrics(16)); + when(engine.getHeight()).thenReturn(WORLD_HEIGHT); + SeedManager seeds = mock(SeedManager.class); + when(seeds.getCarve()).thenReturn(4_711L); + when(engine.getSeedManager()).thenReturn(seeds); + IrisData data = data(regionLists); + when(engine.getData()).thenReturn(data); HydrologyRuntime hydrology = FakeHydrology.disabled(); IrisComplex complex = mock(IrisComplex.class); when(complex.allowsMantleChunkWrite(anyInt(), anyInt())).thenReturn(true); @@ -144,31 +179,42 @@ public class MantleCarvingComponentBakedFieldTest { when(context.getComplex()).thenReturn(complex); MantleWriter writer = mock(MantleWriter.class); Mantle storage = mock(Mantle.class); - when(storage.getWorldHeight()).thenReturn(128); + when(storage.getWorldHeight()).thenReturn(WORLD_HEIGHT); when(writer.getMantle()).thenReturn(storage); + Map chunks = new HashMap<>(); + when(writer.acquireChunk(anyInt(), anyInt())).thenAnswer(call -> + chunk(chunks.computeIfAbsent(key(call.getArgument(0), call.getArgument(1)), ignored -> new Matter[WORLD_HEIGHT >> 4]))); + return new Harness(component, complex, context, writer, chunks); + } - List calls = new ArrayList<>(); - Map carvers = new IdentityHashMap<>(); - IrisCaveProfile[] profiles = {dimensionProfile, regionProfile, surfaceProfile, shallowCaveProfile, deepCaveProfile}; - for (int index = 0; index < profiles.length; index++) { - int profileIndex = index; - IrisCaveCarver3D carver = mock(IrisCaveCarver3D.class); - doAnswer(call -> { - IrisRange range = call.getArgument(6); - calls.add(call.getArgument(1) + "," + call.getArgument(2) + " profile=" + profileIndex - + " range=" + (range == null ? "-" : range.getMin() + ".." + range.getMax()) - + " weights=" + Arrays.toString((double[]) call.getArgument(3)) - + " heights=" + Arrays.toString((int[]) call.getArgument(7)) - + " boundaries=" + Arrays.toString((long[]) call.getArgument(8))); - return 0; - }).when(carver).carve(any(), anyInt(), anyInt(), any(), anyDouble(), anyDouble(), - any(), any(), any(), any(), any(), any()); - carvers.put(profiles[index], carver); + @SuppressWarnings("unchecked") + private IrisData data(boolean regionLists) { + IrisData data = mock(IrisData.class); + ResourceLoader caves = mock(ResourceLoader.class); + for (String key : List.of("dimension-cave", "region-cave", "surface-cave", "shallow-cave", "deep-cave")) { + when(caves.load(key)).thenReturn(TestSettings.of(IrisCave.class, HALLS)); } - Field profileCarvers = MantleCarvingComponent.class.getDeclaredField("profileCarvers"); - profileCarvers.setAccessible(true); - profileCarvers.set(component, carvers); - return new Harness(component, complex, context, writer, calls); + when(data.getCaveLoader()).thenReturn(caves); + ResourceLoader regionLoader = mock(ResourceLoader.class); + when(regionLoader.load("region")).thenReturn(regionLists ? listingRegion : plainRegion); + when(data.getRegionLoader()).thenReturn(regionLoader); + when(data.getBiomeLoader()).thenReturn(mock(ResourceLoader.class)); + return data; + } + + @SuppressWarnings("unchecked") + private static MantleChunk chunk(Matter[] sections) { + MantleChunk chunk = mock(MantleChunk.class); + when(chunk.sectionCount()).thenReturn(sections.length); + when(chunk.get(anyInt())).thenAnswer(call -> sections[call.getArgument(0)]); + when(chunk.getOrCreate(anyInt())).thenAnswer(call -> { + int index = call.getArgument(0); + if (sections[index] == null) { + sections[index] = new IrisMatter(16, 16, 16); + } + return sections[index]; + }); + return chunk; } @SuppressWarnings("unchecked") @@ -184,11 +230,11 @@ public class MantleCarvingComponentBakedFieldTest { } private IrisRegion region(int x, int z) { - return Math.floorMod((x >> 3) + (z >> 3), 3) == 0 ? profiledRegion : plainRegion; + return Math.floorMod((x >> 3) + (z >> 3), 3) == 0 ? listingRegion : plainRegion; } private IrisBiome surface(int x, int z) { - return Math.floorMod(x * 7 + z * 3, 11) < 4 ? profiledSurface : plainSurface; + return Math.floorMod(x * 7 + z * 3, 11) < 4 ? listingSurface : plainSurface; } private IrisBiome cave(int x, int z) { @@ -241,6 +287,6 @@ public class MantleCarvingComponentBakedFieldTest { } private record Harness(MantleCarvingComponent component, IrisComplex complex, ChunkContext context, - MantleWriter writer, List calls) { + MantleWriter writer, Map chunks) { } } diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvingComponentJunctionTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvingComponentJunctionTest.java deleted file mode 100644 index 59d26c6cc..000000000 --- a/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvingComponentJunctionTest.java +++ /dev/null @@ -1,177 +0,0 @@ -package art.arcane.iris.generation.mantle; - -import art.arcane.iris.generation.biome.IrisBiome; -import art.arcane.iris.generation.cave.IrisCaveProfile; -import art.arcane.iris.generation.context.ChunkContext; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.generation.runtime.EngineMetrics; -import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; -import art.arcane.iris.generation.runtime.IrisComplex; -import art.arcane.iris.testsupport.FakeHydrology; -import art.arcane.iris.generation.terrain.IrisDimension; -import art.arcane.iris.generation.terrain.IrisRegion; -import art.arcane.iris.world.IrisWorld; -import art.arcane.volmlib.nativelib.terrain.NativeBlockState; -import art.arcane.volmlib.util.mantle.runtime.Mantle; -import art.arcane.volmlib.util.matter.Matter; -import art.arcane.volmlib.util.stream.ProceduralStream; -import org.junit.Test; - -import java.lang.reflect.Field; -import java.util.HashMap; -import java.util.IdentityHashMap; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyDouble; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class MantleCarvingComponentJunctionTest { - @Test - public void twoCaveProfilesBlendAcrossBothSidesOfAChunkBoundary() throws Exception { - Fixture fixture = fixture(false); - fixture.generate(false); - - assertTrue(fixture.weight(-1, fixture.west(), 15, 12) > 0D); - assertTrue(fixture.weight(-1, fixture.east(), 15, 12) > 0D); - assertTrue(fixture.weight(0, fixture.west(), 0, 12) > 0D); - assertTrue(fixture.weight(0, fixture.east(), 0, 12) > 0D); - assertEquals(fixture.weight(-1, fixture.west(), 15, 12), - fixture.weight(0, fixture.east(), 0, 12), 0D); - assertEquals(fixture.weight(-1, fixture.east(), 15, 12), - fixture.weight(0, fixture.west(), 0, 12), 0D); - } - - @Test - public void thirdProfileOutsideTheBlendRadiusDoesNotChangeBoundaryWeights() throws Exception { - Fixture control = fixture(false); - Fixture junction = fixture(true); - control.generate(false); - junction.generate(false); - - assertEquals("A third biome outside the local blend radius must not remove the east cave from the west chunk", - control.weight(-1, control.east(), 15, 12), - junction.weight(-1, junction.east(), 15, 12), 0D); - assertEquals("A third biome outside the local blend radius must not remove the west cave from the east chunk", - control.weight(0, control.west(), 0, 12), - junction.weight(0, junction.west(), 0, 12), 0D); - } - - @Test - public void threeWayJunctionRetainsEachProfileOnlyInsideItsLocalBlend() throws Exception { - Fixture fixture = fixture(true); - fixture.generate(false); - - for (int chunkX : new int[]{-1, 0}) { - int boundaryX = chunkX == -1 ? 15 : 0; - assertEquals(3, fixture.captured().get(chunkX).size()); - assertTrue(fixture.weight(chunkX, fixture.west(), boundaryX, 6) > 0D); - assertTrue(fixture.weight(chunkX, fixture.east(), boundaryX, 6) > 0D); - assertTrue(fixture.weight(chunkX, fixture.north(), boundaryX, 6) > 0D); - assertEquals(0D, fixture.weight(chunkX, fixture.north(), boundaryX, 12), 0D); - assertEquals(0D, fixture.weight(chunkX, fixture.west(), boundaryX, 0), 0D); - assertEquals(0D, fixture.weight(chunkX, fixture.east(), boundaryX, 0), 0D); - assertEquals(1D, fixture.weight(chunkX, fixture.north(), boundaryX, 0), 0D); - } - } - - @Test - public void junctionWeightsRemainStableAcrossGenerationOrder() throws Exception { - Fixture forward = fixture(true); - Fixture reverse = fixture(true); - forward.generate(false); - reverse.generate(true); - - for (int chunkX : new int[]{-1, 0}) { - for (int x = 0; x < 16; x++) { - for (int z = 0; z < 16; z++) { - assertEquals(forward.weight(chunkX, forward.west(), x, z), - reverse.weight(chunkX, reverse.west(), x, z), 0D); - assertEquals(forward.weight(chunkX, forward.east(), x, z), - reverse.weight(chunkX, reverse.east(), x, z), 0D); - assertEquals(forward.weight(chunkX, forward.north(), x, z), - reverse.weight(chunkX, reverse.north(), x, z), 0D); - } - } - } - } - - @SuppressWarnings("unchecked") - private static Fixture fixture(boolean thirdProfile) throws ReflectiveOperationException { - Engine engine = mock(Engine.class); - EngineMantle engineMantle = mock(EngineMantle.class); - when(engineMantle.getEngine()).thenReturn(engine); - MantleCarvingComponent component = new MantleCarvingComponent(engineMantle); - when(engine.getDimension()).thenReturn(new IrisDimension()); - when(engine.getWorld()).thenReturn(IrisWorld.builder().minHeight(0).maxHeight(128).build()); - when(engine.getMetrics()).thenReturn(new EngineMetrics(16)); - HydrologyRuntime hydrology = FakeHydrology.disabled(); - IrisComplex complex = mock(IrisComplex.class); - when(complex.allowsMantleChunkWrite(anyInt(), anyInt())).thenReturn(true); - when(complex.getHydrologyRuntime()).thenReturn(hydrology); - ProceduralStream heights = mock(ProceduralStream.class); - when(heights.getDouble(anyDouble(), anyDouble())).thenReturn(100D); - when(complex.getNaturalHeightStream()).thenReturn(heights); - ProceduralStream regions = mock(ProceduralStream.class); - ProceduralStream surfaces = mock(ProceduralStream.class); - ProceduralStream caves = mock(ProceduralStream.class); - ProceduralStream fluids = mock(ProceduralStream.class); - when(complex.getRegionStream()).thenReturn(regions); - when(complex.getNaturalTrueBiomeStream()).thenReturn(surfaces); - when(complex.getCaveBiomeStream()).thenReturn(caves); - when(complex.getFluidStream()).thenReturn(fluids); - IrisCaveProfile west = new IrisCaveProfile().setEnabled(true); - IrisCaveProfile east = new IrisCaveProfile().setEnabled(true); - IrisCaveProfile north = new IrisCaveProfile().setEnabled(true); - IrisBiome westBiome = new IrisBiome().setCaveProfile(west); - IrisBiome eastBiome = new IrisBiome().setCaveProfile(east); - IrisBiome northBiome = new IrisBiome().setCaveProfile(north); - when(caves.get(anyDouble(), anyDouble())).thenAnswer(call -> { - double x = call.getArgument(0); - double z = call.getArgument(1); - return thirdProfile && z < 7D ? northBiome : x < 0D ? westBiome : eastBiome; - }); - ChunkContext context = mock(ChunkContext.class); - when(context.getComplex()).thenReturn(complex); - MantleWriter writer = mock(MantleWriter.class); - Mantle storage = mock(Mantle.class); - when(storage.getWorldHeight()).thenReturn(128); - when(writer.getMantle()).thenReturn(storage); - Map> captured = new HashMap<>(); - Map carvers = new IdentityHashMap<>(); - for (IrisCaveProfile profile : new IrisCaveProfile[]{west, east, north}) { - IrisCaveCarver3D carver = mock(IrisCaveCarver3D.class); - doAnswer(call -> { - int chunkX = call.getArgument(1); - double[] weights = call.getArgument(3); - captured.computeIfAbsent(chunkX, ignored -> new IdentityHashMap<>()).put(profile, weights.clone()); - return 0; - }).when(carver).carve(any(), anyInt(), anyInt(), any(), anyDouble(), anyDouble(), - any(), any(), any(), any(), any(), any()); - carvers.put(profile, carver); - } - Field profileCarvers = MantleCarvingComponent.class.getDeclaredField("profileCarvers"); - profileCarvers.setAccessible(true); - profileCarvers.set(component, carvers); - return new Fixture(component, context, writer, west, east, north, captured); - } - - private record Fixture(MantleCarvingComponent component, ChunkContext context, MantleWriter writer, - IrisCaveProfile west, IrisCaveProfile east, IrisCaveProfile north, - Map> captured) { - private void generate(boolean reverse) { - component.generateLayer(writer, reverse ? 0 : -1, 0, context); - component.generateLayer(writer, reverse ? -1 : 0, 0, context); - } - - private double weight(int chunkX, IrisCaveProfile profile, int x, int z) { - double[] weights = captured.get(chunkX).get(profile); - return weights == null ? 0D : weights[(x << 4) | z]; - } - } -} diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvingComponentScratchTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvingComponentScratchTest.java deleted file mode 100644 index 3f38ff6ac..000000000 --- a/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvingComponentScratchTest.java +++ /dev/null @@ -1,172 +0,0 @@ -package art.arcane.iris.generation.mantle; - -import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; -import art.arcane.iris.generation.runtime.IrisComplex; -import art.arcane.iris.testsupport.FakeHydrology; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.generation.runtime.EngineMetrics; -import art.arcane.iris.generation.biome.IrisBiome; -import art.arcane.iris.generation.cave.IrisCaveProfile; -import art.arcane.iris.generation.terrain.IrisDimension; -import art.arcane.iris.generation.terrain.IrisRegion; -import art.arcane.iris.world.IrisWorld; -import art.arcane.volmlib.nativelib.terrain.NativeBlockState; -import art.arcane.iris.generation.context.ChunkContext; -import art.arcane.volmlib.util.stream.ProceduralStream; -import art.arcane.volmlib.util.mantle.runtime.Mantle; -import art.arcane.volmlib.util.matter.Matter; -import org.junit.Before; -import org.junit.Test; - -import java.lang.reflect.Field; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyDouble; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class MantleCarvingComponentScratchTest { - private MantleCarvingComponent component; - private IrisDimension dimension; - private ChunkContext context; - private MantleWriter writer; - - @Before - @SuppressWarnings("unchecked") - public void prepare() { - Engine engine = mock(Engine.class); - EngineMantle mantle = mock(EngineMantle.class); - when(mantle.getEngine()).thenReturn(engine); - component = new MantleCarvingComponent(mantle); - dimension = new IrisDimension(); - when(engine.getDimension()).thenReturn(dimension); - when(engine.getWorld()).thenReturn(mock(IrisWorld.class)); - when(engine.getMetrics()).thenReturn(new EngineMetrics(16)); - HydrologyRuntime hydrology = FakeHydrology.disabled(); - IrisComplex complex = mock(IrisComplex.class); - when(complex.allowsMantleChunkWrite(anyInt(), anyInt())).thenReturn(true); - when(complex.getHydrologyRuntime()).thenReturn(hydrology); - ProceduralStream heights = mock(ProceduralStream.class); - when(heights.getDouble(anyDouble(), anyDouble())).thenAnswer(invocation -> { - double x = invocation.getArgument(0); - return x < 0D ? 90D : 70D; - }); - when(complex.getNaturalHeightStream()).thenReturn(heights); - ProceduralStream regions = mock(ProceduralStream.class); - ProceduralStream biomes = mock(ProceduralStream.class); - ProceduralStream fluids = mock(ProceduralStream.class); - when(regions.get(anyDouble(), anyDouble())).thenReturn(new IrisRegion()); - when(biomes.get(anyDouble(), anyDouble())).thenReturn(new IrisBiome()); - when(complex.getRegionStream()).thenReturn(regions); - when(complex.getNaturalTrueBiomeStream()).thenReturn(biomes); - when(complex.getCaveBiomeStream()).thenReturn(biomes); - when(complex.getFluidStream()).thenReturn(fluids); - context = mock(ChunkContext.class); - when(context.getComplex()).thenReturn(complex); - writer = mock(MantleWriter.class); - Mantle storage = mock(Mantle.class); - when(storage.getWorldHeight()).thenReturn(128); - when(writer.getMantle()).thenReturn(storage); - } - - @Test - public void nestedGenerationPreservesOuterColumnHeights() throws Exception { - IrisCaveCarver3D carver = installProfile(); - AtomicBoolean entered = new AtomicBoolean(); - AtomicInteger calls = new AtomicInteger(); - doAnswer(invocation -> { - int chunkX = invocation.getArgument(1); - int[] heights = invocation.getArgument(7); - int expectedHeight = chunkX < 0 ? 90 : 70; - assertEquals(expectedHeight, heights[0]); - calls.incrementAndGet(); - if (entered.compareAndSet(false, true)) { - component.generateLayer(writer, -3, -3, context); - } - for (int height : heights) { - assertEquals(expectedHeight, height); - } - return 0; - }).when(carver).carve(any(), anyInt(), anyInt(), any(), anyDouble(), anyDouble(), - any(), any(), any(), any(), any(), any()); - - component.generateLayer(writer, 2, 2, context); - - assertEquals(2, calls.get()); - assertReleased(); - } - - @Test - public void generationReleasesConfigurationReferencesWhenCarvingFails() throws Exception { - IrisCaveCarver3D carver = installProfile(); - doAnswer(invocation -> { - throw new IllegalStateException("Carving failed"); - }).when(carver).carve(any(), anyInt(), anyInt(), any(), anyDouble(), anyDouble(), - any(), any(), any(), any(), any(), any()); - assertThrows(IllegalStateException.class, () -> component.generateLayer(writer, 2, 2, context)); - assertReleased(); - } - - @Test - public void changedProfilesReuseNumericBuffersWithoutKeepingProfileKeys() throws Exception { - Object firstBuffer = null; - for (int index = 0; index < 4; index++) { - installProfile(); - component.generateLayer(writer, 2, 2, context); - Object scratch = assertReleased(); - List buffers = (List) field(scratch, "weightBuffers"); - assertEquals(1, buffers.size()); - if (firstBuffer == null) { - firstBuffer = buffers.get(0); - } else { - assertSame(firstBuffer, buffers.get(0)); - } - } - } - - private IrisCaveCarver3D installProfile() throws Exception { - IrisCaveProfile profile = new IrisCaveProfile().setEnabled(true); - dimension.setCaveProfile(profile); - IrisCaveCarver3D carver = mock(IrisCaveCarver3D.class); - Map carvers = new IdentityHashMap<>(); - carvers.put(profile, carver); - Field cache = MantleCarvingComponent.class.getDeclaredField("profileCarvers"); - cache.setAccessible(true); - cache.set(component, carvers); - return carver; - } - - private Object assertReleased() throws Exception { - Field scratchField = MantleCarvingComponent.class.getDeclaredField("BLEND_SCRATCH"); - scratchField.setAccessible(true); - ThreadLocal scratchCache = (ThreadLocal) scratchField.get(null); - Object scratch = scratchCache.get(); - for (String name : List.of("profileField", "kernelProfiles", "fieldRegions", "fieldSurfaceBiomes", "fieldCaveBiomes")) { - for (Object value : (Object[]) field(scratch, name)) { - assertNull(value); - } - } - assertEquals(0, ((Map) field(scratch, "columnProfileWeights")).size()); - assertEquals(0, ((List) field(scratch, "profileOrder")).size()); - assertFalse((boolean) field(scratch, "inUse")); - return scratch; - } - - private Object field(Object object, String name) throws Exception { - Field field = object.getClass().getDeclaredField(name); - field.setAccessible(true); - return field.get(object); - } -} diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvingComponentWaterMaskTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvingComponentWaterMaskTest.java index 68ec045bd..315128f4c 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvingComponentWaterMaskTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvingComponentWaterMaskTest.java @@ -2,15 +2,15 @@ package art.arcane.iris.generation.mantle; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.block.B; -import art.arcane.iris.generation.cave.IrisCaveProfile; +import art.arcane.iris.generation.cave.IrisCave; +import art.arcane.iris.generation.cave.TestSettings; import art.arcane.iris.generation.context.ChunkContext; -import art.arcane.iris.generation.hydrology.config.IrisHydrology; import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; -import art.arcane.iris.generation.hydrology.plan.HydrologySettings; import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.EngineMetrics; import art.arcane.iris.generation.runtime.IrisComplex; +import art.arcane.iris.generation.runtime.SeedManager; import art.arcane.iris.generation.runtime.UpperDimensionContext; import art.arcane.iris.generation.subterrain.IrisSubterrainFamily; import art.arcane.iris.generation.subterrain.IrisSubterrainFeature; @@ -18,28 +18,28 @@ import art.arcane.iris.generation.subterrain.SubterrainPlan; import art.arcane.iris.generation.subterrain.SubterrainPlanner; import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.iris.generation.terrain.IrisRegion; +import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.pack.loading.ResourceLoader; import art.arcane.iris.pack.value.IrisRange; import art.arcane.iris.world.IrisWorld; +import art.arcane.iris.world.storage.matter.IrisMatterSupport; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; +import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.mantle.runtime.Mantle; +import art.arcane.volmlib.util.mantle.runtime.MantleChunk; +import art.arcane.volmlib.util.matter.IrisMatter; import art.arcane.volmlib.util.matter.Matter; -import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; import art.arcane.volmlib.util.matter.MatterCavern; import art.arcane.volmlib.util.stream.ProceduralStream; import org.junit.Before; import org.junit.Test; import org.mockito.MockedStatic; -import java.lang.reflect.Field; import java.util.ArrayList; -import java.util.IdentityHashMap; import java.util.List; -import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyDouble; @@ -51,7 +51,15 @@ import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; public class MantleCarvingComponentWaterMaskTest { - private static final int ROOF_CLEARANCE = 6; + private static final int WORLD_HEIGHT = 128; + private static final int MINIMUM_HEIGHT = -64; + private static final int SURFACE_Y = 70; + private static final int UPPER_SURFACE_Y = 100; + private static final String HALLS = """ + {"cavern": {"size": 40, "height": 24, "coverage": 0.4}, "depth": {"min": -50, "max": 20}, + "surfaceClearance": 4, "allowFluid": false, "allowLava": false} + """; + private Engine engine; private MantleCarvingComponent component; private IrisDimension dimension; @@ -59,26 +67,36 @@ public class MantleCarvingComponentWaterMaskTest { private HydrologyRuntime hydrology; private ChunkContext context; private MantleWriter writer; + private Matter[] sections; @Before @SuppressWarnings("unchecked") public void prepare() { + IrisMatterSupport.ensureRegistered(); engine = mock(Engine.class); EngineMantle mantle = mock(EngineMantle.class); when(mantle.getEngine()).thenReturn(engine); component = new MantleCarvingComponent(mantle); - dimension = new IrisDimension(); + dimension = new IrisDimension().setCaves(new KList<>("halls")); when(engine.getDimension()).thenReturn(dimension); - when(engine.getWorld()).thenReturn(IrisWorld.builder().minHeight(-64).maxHeight(64).build()); + when(engine.getWorld()).thenReturn(IrisWorld.builder().minHeight(MINIMUM_HEIGHT).maxHeight(MINIMUM_HEIGHT + WORLD_HEIGHT).build()); when(engine.getMetrics()).thenReturn(new EngineMetrics(16)); - when(engine.getHeight()).thenReturn(128); + when(engine.getHeight()).thenReturn(WORLD_HEIGHT); + SeedManager seeds = mock(SeedManager.class); + when(seeds.getCarve()).thenReturn(4_711L); + when(engine.getSeedManager()).thenReturn(seeds); + IrisData data = mock(IrisData.class); + ResourceLoader caves = mock(ResourceLoader.class); + when(caves.load("halls")).thenReturn(TestSettings.of(IrisCave.class, HALLS)); + when(data.getCaveLoader()).thenReturn(caves); + when(engine.getData()).thenReturn(data); hydrology = mock(HydrologyRuntime.class); when(hydrology.raster(anyInt(), anyInt())).thenReturn(ChunkWaterRaster.EMPTY); complex = mock(IrisComplex.class); when(complex.allowsMantleChunkWrite(anyInt(), anyInt())).thenReturn(true); when(complex.getHydrologyRuntime()).thenReturn(hydrology); ProceduralStream heights = mock(ProceduralStream.class); - when(heights.getDouble(anyDouble(), anyDouble())).thenReturn(70D); + when(heights.getDouble(anyDouble(), anyDouble())).thenReturn((double) SURFACE_Y); when(complex.getNaturalHeightStream()).thenReturn(heights); ProceduralStream regions = mock(ProceduralStream.class); ProceduralStream biomes = mock(ProceduralStream.class); @@ -93,37 +111,64 @@ public class MantleCarvingComponentWaterMaskTest { when(context.getComplex()).thenReturn(complex); writer = mock(MantleWriter.class); Mantle storage = mock(Mantle.class); - when(storage.getWorldHeight()).thenReturn(128); + when(storage.getWorldHeight()).thenReturn(WORLD_HEIGHT); when(writer.getMantle()).thenReturn(storage); + sections = new Matter[WORLD_HEIGHT >> 4]; + MantleChunk chunk = mock(MantleChunk.class); + when(chunk.sectionCount()).thenReturn(sections.length); + when(chunk.get(anyInt())).thenAnswer(call -> sections[call.getArgument(0)]); + when(chunk.getOrCreate(anyInt())).thenAnswer(call -> { + int index = call.getArgument(0); + if (sections[index] == null) { + sections[index] = new IrisMatter(16, 16, 16); + } + return sections[index]; + }); + when(writer.acquireChunk(anyInt(), anyInt())).thenReturn(chunk); } @Test - public void mainTerrainWaterMasksTheProfilePassButNotTheUpperDimensionPass() throws Exception { - maskEverywhere(40); - IrisCaveCarver3D carver = installProfile(); - UpperDimensionContext upper = mock(UpperDimensionContext.class); - when(upper.getEffectiveSurfaceY(anyInt(), anyInt())).thenReturn(100); - when(engine.getUpperContext()).thenReturn(upper); - dimension.setUpperDimensionCarving(true); - List calls = new ArrayList<>(); - doAnswer(call -> { - calls.add(new Object[]{call.getArgument(9), call.getArgument(10)}); - return 0; - }).when(carver).carve(any(), anyInt(), anyInt(), any(), anyDouble(), anyDouble(), any(), any(), any(), any(), any(), any()); - + public void theListedCavesCarveTheChunk() { component.generateLayer(writer, 2, 2, context); - assertEquals(2, calls.size()); - int[] profileCeilings = (int[]) calls.get(0)[0]; - assertNotNull(profileCeilings); - assertEquals(40 - CaveCeilingMask.ROOF, profileCeilings[0]); - assertNull(calls.get(0)[1]); - assertNull("the upper-dimension pass ignores main-terrain water", calls.get(1)[0]); - assertNotNull(calls.get(1)[1]); + List carved = carvedHeights(); + assertTrue("carved cells " + carved.size(), carved.size() > 500); + int lowest = carved.stream().mapToInt(Integer::intValue).min().orElseThrow(); + int highest = carved.stream().mapToInt(Integer::intValue).max().orElseThrow(); + assertTrue("lowest " + lowest, lowest >= -50 - MINIMUM_HEIGHT - 12); + assertTrue("highest " + highest, highest <= 20 - MINIMUM_HEIGHT + 12); + } + + @Test + public void waterMasksTheCavePassOfTheMainTerrain() { + int ceilingY = 40; + List unmasked = carvedHeightsOfNewChunk(2, 2); + maskEverywhere(ceilingY + CaveCeilingMask.ROOF); + + List masked = carvedHeightsOfNewChunk(2, 2); + + assertTrue("an unmasked chunk carves above " + ceilingY, unmasked.stream().anyMatch(y -> y > ceilingY)); + assertFalse(masked.isEmpty()); + assertTrue("masked chunk carved above its ceiling", masked.stream().allMatch(y -> y <= ceilingY)); + } + + @Test + public void theUpperDimensionPassCarvesBeneathItsTerrainAndIgnoresMainTerrainWater() { + maskEverywhere(40 + CaveCeilingMask.ROOF); + UpperDimensionContext upper = mock(UpperDimensionContext.class); + when(upper.getEffectiveSurfaceY(anyInt(), anyInt())).thenReturn(UPPER_SURFACE_Y); + when(engine.getUpperContext()).thenReturn(upper); + dimension.setUpperDimensionCarving(true); + + List carved = carvedHeightsOfNewChunk(2, 2); + + assertTrue("the upper pass carves where its terrain hangs", carved.stream().anyMatch(y -> y >= UPPER_SURFACE_Y)); + assertTrue("the upper pass stays inside its terrain", carved.stream().noneMatch(y -> y >= UPPER_SURFACE_Y - 1 && y < UPPER_SURFACE_Y)); } @Test public void subterrainFeaturesNeverOpenACellAboveTheCaveCeiling() { + dimension.setCaves(new KList<>()); IrisSubterrainFeature feature = new IrisSubterrainFeature().setId("room").setFamily(IrisSubterrainFamily.CENOTE) .setProbability(1).setLength(64).setRadius(12).setHeight(24).setPillarSpacing(0).setFormationFraction(0) .setWorldYRange(new IrisRange(-48, 60)); @@ -146,19 +191,28 @@ public class MantleCarvingComponentWaterMaskTest { } } - private List openedCells(int chunkX, int chunkZ) { - List opened = new ArrayList<>(); - Mantle storage = writer.getMantle(); - MantleWriter capture = mock(MantleWriter.class); - when(capture.getMantle()).thenReturn(storage); - doAnswer(call -> { - if (call.getArgument(3) instanceof MatterCavern) { - opened.add(new int[]{call.getArgument(0), call.getArgument(1), call.getArgument(2)}); + private List carvedHeightsOfNewChunk(int chunkX, int chunkZ) { + java.util.Arrays.fill(sections, null); + component.generateLayer(writer, chunkX, chunkZ, context); + return carvedHeights(); + } + + private List carvedHeights() { + List carved = new ArrayList<>(); + for (int y = 0; y < WORLD_HEIGHT; y++) { + Matter section = sections[y >> 4]; + if (section == null) { + continue; } - return null; - }).when(capture).setData(anyInt(), anyInt(), anyInt(), any()); - component.generateLayer(capture, chunkX, chunkZ, context); - return opened; + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + if (section.slice(MatterCavern.class).get(x, y & 15, z) != null) { + carved.add(y); + } + } + } + } + return carved; } private List openedHeights(int chunkX, int chunkZ) { @@ -181,16 +235,4 @@ public class MantleCarvingComponentWaterMaskTest { when(raster.caveCeiling(anyInt(), anyInt())).thenReturn(ceiling); when(hydrology.raster(anyInt(), anyInt())).thenReturn(raster); } - - private IrisCaveCarver3D installProfile() throws Exception { - IrisCaveProfile profile = new IrisCaveProfile().setEnabled(true); - dimension.setCaveProfile(profile); - IrisCaveCarver3D carver = mock(IrisCaveCarver3D.class); - Map carvers = new IdentityHashMap<>(); - carvers.put(profile, carver); - Field cache = MantleCarvingComponent.class.getDeclaredField("profileCarvers"); - cache.setAccessible(true); - cache.set(component, carvers); - return carver; - } } diff --git a/core/src/test/java/art/arcane/iris/generation/terrain/IrisDimensionReachableBiomesTest.java b/core/src/test/java/art/arcane/iris/generation/terrain/IrisDimensionReachableBiomesTest.java index e11438427..0a99cd2d8 100644 --- a/core/src/test/java/art/arcane/iris/generation/terrain/IrisDimensionReachableBiomesTest.java +++ b/core/src/test/java/art/arcane/iris/generation/terrain/IrisDimensionReachableBiomesTest.java @@ -69,19 +69,15 @@ public class IrisDimensionReachableBiomesTest { .setId("disabled-band") .setEnabled(false) .setBiome("disabled-deep"); - IrisDimensionCarvingEntry floatingCarvingEntry = new IrisDimensionCarvingEntry() - .setId("floating-carving-entry") - .setEnabled(false) - .setBiome("entry-floating-carve"); IrisDimension dimension = new IrisDimension().setRegions(new KList<>("reachable", "missing")); - dimension.setCarving(new KList<>(deepBand, disabledBand, floatingCarvingEntry)); + dimension.setCarving(new KList<>(deepBand, disabledBand)); IrisRegion reachable = new IrisRegion() .setLandBiomes(new KList<>("parent", "shared")) .setSeaBiomes(new KList<>("shared")); IrisBiome parent = biome("parent") .setChildren(new KList<>("child", "shared")) .setCarvingBiome("carve") - .setFloatingChildBiomes(new KList<>(floating("floating-target", "direct-floating-carve"))); + .setFloatingChildBiomes(new KList<>(floating("floating-target"))); IrisBiome child = biome("child").setChildren(new KList<>("parent")); IrisBiome shared = biome("shared"); IrisBiome carve = biome("carve"); @@ -89,11 +85,8 @@ public class IrisDimensionReachableBiomesTest { .setChildren(new KList<>("floating-child")) .setCarvingBiome("floating-carve"); IrisBiome floatingChild = biome("floating-child") - .setFloatingChildBiomes(new KList<>(floating("nested-floating", "floating-carving-entry"))); + .setFloatingChildBiomes(new KList<>(floating("nested-floating"))); IrisBiome floatingCarve = biome("floating-carve"); - IrisBiome directFloatingCarve = biome("direct-floating-carve"); - IrisBiome entryFloatingCarve = biome("entry-floating-carve"); - IrisBiome shadowedFloatingCarve = biome("floating-carving-entry"); IrisBiome nestedFloating = biome("nested-floating") .setFloatingChildBiomes(new KList<>(floating("parent"))); IrisBiome deepRoot = biome("deep-root").setChildren(new KList<>("deep-child")); @@ -117,9 +110,6 @@ public class IrisDimensionReachableBiomesTest { when(biomeLoader.load("floating-target")).thenReturn(floatingTarget); when(biomeLoader.load("floating-child")).thenReturn(floatingChild); when(biomeLoader.load("floating-carve")).thenReturn(floatingCarve); - when(biomeLoader.load("direct-floating-carve")).thenReturn(directFloatingCarve); - when(biomeLoader.load("entry-floating-carve")).thenReturn(entryFloatingCarve); - when(biomeLoader.load("floating-carving-entry")).thenReturn(shadowedFloatingCarve); when(biomeLoader.load("nested-floating")).thenReturn(nestedFloating); when(biomeLoader.load("deep-root")).thenReturn(deepRoot); when(biomeLoader.load("deep-child")).thenReturn(deepChild); @@ -133,8 +123,7 @@ public class IrisDimensionReachableBiomesTest { assertEquals(Set.of( "parent", "child", "shared", "carve", - "floating-target", "floating-child", "floating-carve", "direct-floating-carve", - "entry-floating-carve", "nested-floating", + "floating-target", "floating-child", "floating-carve", "nested-floating", "deep-root", "deep-child", "deep-carve", "deep-floating" ), keys); assertEquals(keys.size(), biomes.size()); @@ -147,7 +136,7 @@ public class IrisDimensionReachableBiomesTest { IrisRegion reachable = new IrisRegion().setLandBiomes(new KList<>("a")); IrisBiome a = biome("a").setChildren(new KList<>("b")); IrisBiome b = biome("b").setCarvingBiome("c"); - IrisBiome c = biome("c").setFloatingChildBiomes(new KList<>(floating("d", "a"))); + IrisBiome c = biome("c").setFloatingChildBiomes(new KList<>(floating("d"))); IrisBiome d = biome("d") .setChildren(new KList<>("a")) .setFloatingChildBiomes(new KList<>(floating("b"))); @@ -316,7 +305,4 @@ public class IrisDimensionReachableBiomesTest { return new IrisFloatingChildBiomes().setBiome(biomeKey); } - private IrisFloatingChildBiomes floating(String biomeKey, String carvingKey) { - return floating(biomeKey).setCarving(carvingKey); - } } diff --git a/core/src/test/java/art/arcane/iris/pack/PackCaveProfileValidatorTest.java b/core/src/test/java/art/arcane/iris/pack/PackCaveProfileValidatorTest.java deleted file mode 100644 index f3ed36a12..000000000 --- a/core/src/test/java/art/arcane/iris/pack/PackCaveProfileValidatorTest.java +++ /dev/null @@ -1,67 +0,0 @@ -package art.arcane.iris.pack; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - -import java.io.File; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class PackCaveProfileValidatorTest { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - @Test - public void rejectsLegacyWaterFieldsAcrossEveryCaveProfileLocation() throws Exception { - File pack = temporaryFolder.newFolder("pack"); - write(pack, "dimensions/main.json", "{\"caveProfile\":{\"allowWater\":false}}"); - write(pack, "regions/nested/region.json", "{\"caveProfile\":{\"waterMinDepthBelowSurface\":20}}"); - write(pack, "biomes/nested/biome.json", "{\"caveProfile\":{\"waterRequiresFloor\":true}}"); - write(pack, "snippet/cave-profile/nested/profile.json", "{\"allowWater\":true}"); - - assertEquals(List.of( - "Dimension 'main' caveProfile.allowWater was removed; use caveProfile.allowFluid. Cave aquifers use the dimension fluidPalette, which defaults to water.", - "Region 'nested/region' caveProfile.waterMinDepthBelowSurface was removed; use caveProfile.fluidMinDepthBelowSurface. Cave aquifers use the dimension fluidPalette, which defaults to water.", - "Biome 'nested/biome' caveProfile.waterRequiresFloor was removed; use caveProfile.fluidRequiresFloor. Cave aquifers use the dimension fluidPalette, which defaults to water.", - "Cave-profile snippet 'nested/profile' allowWater was removed; use allowFluid. Cave aquifers use the dimension fluidPalette, which defaults to water." - ), PackCaveProfileValidator.validateLegacyFields(pack)); - } - - @Test - public void acceptsGenericFluidFields() throws Exception { - File pack = temporaryFolder.newFolder("pack"); - write(pack, "dimensions/main.json", "{\"caveProfile\":{\"allowFluid\":true," - + "\"fluidMinDepthBelowSurface\":20,\"fluidRequiresFloor\":true}}"); - write(pack, "snippet/cave-profile/profile.json", "{\"allowFluid\":true," - + "\"fluidMinDepthBelowSurface\":20,\"fluidRequiresFloor\":true}"); - - assertTrue(PackCaveProfileValidator.validateLegacyFields(pack).isEmpty()); - } - - @Test - public void legacyFieldBlocksFullPackValidation() throws Exception { - File pack = temporaryFolder.newFolder("pack"); - write(pack, "dimensions/main.json", "{\"regions\":[\"region\"]}"); - write(pack, "regions/region.json", "{\"landBiomes\":[\"biome\"]}"); - write(pack, "biomes/biome.json", "{\"name\":\"Biome\",\"caveProfile\":{\"allowWater\":false}}"); - - PackValidationResult result = PackValidator.validate(pack); - - assertFalse(result.isLoadable()); - assertTrue(result.getBlockingErrors().contains( - "Biome 'biome' caveProfile.allowWater was removed; use caveProfile.allowFluid. Cave aquifers use the dimension fluidPalette, which defaults to water.")); - } - - private void write(File root, String relative, String content) throws Exception { - Path path = root.toPath().resolve(relative); - Files.createDirectories(path.getParent()); - Files.writeString(path, content, StandardCharsets.UTF_8); - } -} diff --git a/core/src/test/java/art/arcane/iris/pack/PackStyledRangeDefaultValidatorTest.java b/core/src/test/java/art/arcane/iris/pack/PackStyledRangeDefaultValidatorTest.java index ea24b3f85..2e793d7a5 100644 --- a/core/src/test/java/art/arcane/iris/pack/PackStyledRangeDefaultValidatorTest.java +++ b/core/src/test/java/art/arcane/iris/pack/PackStyledRangeDefaultValidatorTest.java @@ -67,18 +67,6 @@ public class PackStyledRangeDefaultValidatorTest { assertTrue(validation.errors().get(0).contains("via snippet 'snippet/style-range/empty'")); } - @Test - public void flagsEmptyCaveDensityThreshold() throws Exception { - File pack = temporaryFolder.newFolder("pack"); - write(pack, "dimensions/main.json", "{\"caveProfile\":{\"densityThreshold\":{}}}"); - - PackStyledRangeDefaultValidator.Validation validation = PackStyledRangeDefaultValidator.validate(pack); - - assertEquals(1, validation.errors().size()); - assertTrue(validation.errors().get(0).startsWith( - "Dimension 'main' caveProfile.densityThreshold omits both min and max")); - } - @Test public void emptyDensityStyleBlocksFullPackValidation() throws Exception { File pack = temporaryFolder.newFolder("pack"); diff --git a/core/src/test/java/art/arcane/iris/pack/PackValidatorTerrainSamplingTest.java b/core/src/test/java/art/arcane/iris/pack/PackValidatorTerrainSamplingTest.java index 75cbcbfa5..dcff9214b 100644 --- a/core/src/test/java/art/arcane/iris/pack/PackValidatorTerrainSamplingTest.java +++ b/core/src/test/java/art/arcane/iris/pack/PackValidatorTerrainSamplingTest.java @@ -17,7 +17,7 @@ public class PackValidatorTerrainSamplingTest { @Test public void acceptsOmittedAndSupportedSamplingSteps() throws Exception { assertTrue(validate("terrainSamplingStep", null).isLoadable()); - for (String field : new String[]{"terrainSamplingStep", "caveDensitySamplingStep"}) { + for (String field : new String[]{"terrainSamplingStep"}) { for (String value : new String[]{"1", "2", "4", "8"}) { PackValidationResult result = validate(field, value); assertTrue(result.getBlockingErrors().toString(), result.isLoadable()); @@ -27,7 +27,7 @@ public class PackValidatorTerrainSamplingTest { @Test public void rejectsInvalidSamplingStepsBeforeWorldCreation() throws Exception { - for (String field : new String[]{"terrainSamplingStep", "caveDensitySamplingStep"}) { + for (String field : new String[]{"terrainSamplingStep"}) { for (String value : new String[]{"0", "-1", "3", "16", "4.5", "\"4\"", "null", "true"}) { PackValidationResult result = validate(field, value); assertFalse("Accepted " + field + "=" + value, result.isLoadable()); diff --git a/core/src/test/java/art/arcane/iris/pack/schema/IrisBiomeBoundsSamplingSchemaTest.java b/core/src/test/java/art/arcane/iris/pack/schema/IrisBiomeBoundsSamplingSchemaTest.java index 65e51e78c..f31fad77e 100644 --- a/core/src/test/java/art/arcane/iris/pack/schema/IrisBiomeBoundsSamplingSchemaTest.java +++ b/core/src/test/java/art/arcane/iris/pack/schema/IrisBiomeBoundsSamplingSchemaTest.java @@ -29,7 +29,7 @@ public class IrisBiomeBoundsSamplingSchemaTest { @Test public void schemaListsOnlySupportedIntegerSteps() throws Exception { SchemaBuilder builder = new SchemaBuilder(IrisDimension.class, null); - for (String name : new String[]{"biomeBoundsSamplingStep", "terrainSamplingStep", "caveDensitySamplingStep"}) { + for (String name : new String[]{"biomeBoundsSamplingStep", "terrainSamplingStep"}) { int minimum = name.equals("biomeBoundsSamplingStep") ? 4 : 1; Field field = IrisDimension.class.getDeclaredField(name); JSONObject property = new SchemaPropertyBuilder(builder).buildProperty(field, IrisDimension.class); diff --git a/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java b/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java index 51b0cce16..d05c450cd 100644 --- a/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java +++ b/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java @@ -85,7 +85,7 @@ public class SchemaBuilderIdentityTest { @ClassRule public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean(); - private static final String EXPECTED_SCHEMA_DIGEST = "3f8aa1e56a2bd9e68c6b4d0036da22a9d5f3b64542ab6c90044d98ba3e5705c5"; + private static final String EXPECTED_SCHEMA_DIGEST = "b0a57ea87eda4aa074911c72202f227e8f54ac0fea3ff27179180ee8956d3626"; private static final List> SCHEMA_ROOTS = List.of( IrisDimension.class, diff --git a/probe/src/main/java/art/arcane/iris/probe/GenerationProbe.java b/probe/src/main/java/art/arcane/iris/probe/GenerationProbe.java index bf5b9b176..86fb5d44a 100644 --- a/probe/src/main/java/art/arcane/iris/probe/GenerationProbe.java +++ b/probe/src/main/java/art/arcane/iris/probe/GenerationProbe.java @@ -20,7 +20,6 @@ package art.arcane.iris.probe; import art.arcane.iris.generation.bake.BakePlane; import art.arcane.iris.generation.bake.GeneratorEvaluations; -import art.arcane.iris.generation.mantle.IrisCaveCarver3D; import art.arcane.iris.pack.datapack.DataVersion; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.PackValidationResult; @@ -321,7 +320,6 @@ public final class GenerationProbe { try { ProbeResult result = run(configuration, options); System.out.println(result.machineLine()); - System.out.println(IrisCaveCarver3D.cellCounters().machineLine()); exitCode = result.failedChunks() == 0 ? 0 : 1; } catch (Throwable e) { System.out.println("[genprobe] FAIL: probe execution failed"); diff --git a/probe/src/test/resources/seed-cohesion/dimensions/cohesion.json b/probe/src/test/resources/seed-cohesion/dimensions/cohesion.json index e0736cf40..abd8ab37e 100644 --- a/probe/src/test/resources/seed-cohesion/dimensions/cohesion.json +++ b/probe/src/test/resources/seed-cohesion/dimensions/cohesion.json @@ -6,6 +6,5 @@ "environment": "NORMAL", "dimensionHeight": {"min": 0, "max": 64}, "logicalHeight": 64, - "fluidHeight": 10, - "caveProfile": {"enabled": false} + "fluidHeight": 10 } diff --git a/probe/src/test/resources/terrain3d-pack/dimensions/terrain3d.json b/probe/src/test/resources/terrain3d-pack/dimensions/terrain3d.json index 988437b6c..62ffb7050 100644 --- a/probe/src/test/resources/terrain3d-pack/dimensions/terrain3d.json +++ b/probe/src/test/resources/terrain3d-pack/dimensions/terrain3d.json @@ -6,6 +6,5 @@ "environment": "NORMAL", "dimensionHeight": {"min": 0, "max": 256}, "logicalHeight": 256, - "fluidHeight": 0, - "caveProfile": {"enabled": false} + "fluidHeight": 0 } diff --git a/probe/src/test/resources/transition-packs/boundary-structure/dimensions/transition.json b/probe/src/test/resources/transition-packs/boundary-structure/dimensions/transition.json index 8ff620567..c4059d0f2 100644 --- a/probe/src/test/resources/transition-packs/boundary-structure/dimensions/transition.json +++ b/probe/src/test/resources/transition-packs/boundary-structure/dimensions/transition.json @@ -14,9 +14,6 @@ }, "logicalHeight": 128, "fluidHeight": 40, - "caveProfile": { - "enabled": false - }, "structures": [ { "structures": [ diff --git a/probe/src/test/resources/transition-packs/boundary-tree/dimensions/transition.json b/probe/src/test/resources/transition-packs/boundary-tree/dimensions/transition.json index ae9846d8b..dcfdb6bfb 100644 --- a/probe/src/test/resources/transition-packs/boundary-tree/dimensions/transition.json +++ b/probe/src/test/resources/transition-packs/boundary-tree/dimensions/transition.json @@ -13,8 +13,5 @@ "max": 128 }, "logicalHeight": 128, - "fluidHeight": 40, - "caveProfile": { - "enabled": false - } + "fluidHeight": 40 } diff --git a/probe/src/test/resources/transition-packs/calcite-mountain/dimensions/transition.json b/probe/src/test/resources/transition-packs/calcite-mountain/dimensions/transition.json index cfdf30b35..59ff051e2 100644 --- a/probe/src/test/resources/transition-packs/calcite-mountain/dimensions/transition.json +++ b/probe/src/test/resources/transition-packs/calcite-mountain/dimensions/transition.json @@ -14,9 +14,6 @@ }, "logicalHeight": 128, "fluidHeight": 40, - "caveProfile": { - "enabled": false - }, "rockPalette": { "palette": [ { diff --git a/probe/src/test/resources/transition-packs/cave-lowland/caves/slab.json b/probe/src/test/resources/transition-packs/cave-lowland/caves/slab.json new file mode 100644 index 000000000..2d31468db --- /dev/null +++ b/probe/src/test/resources/transition-packs/cave-lowland/caves/slab.json @@ -0,0 +1,18 @@ +{ + "tunnel": { + "width": 64, + "spacing": { + "horizontal": 16, + "vertical": 8 + } + }, + "depth": { + "min": 32, + "max": 47 + }, + "fade": 0, + "ceilingFade": 0, + "surfaceClearance": 4, + "allowFluid": false, + "allowLava": false +} diff --git a/probe/src/test/resources/transition-packs/cave-lowland/dimensions/transition.json b/probe/src/test/resources/transition-packs/cave-lowland/dimensions/transition.json index 5c3bfb61f..70a3be875 100644 --- a/probe/src/test/resources/transition-packs/cave-lowland/dimensions/transition.json +++ b/probe/src/test/resources/transition-packs/cave-lowland/dimensions/transition.json @@ -14,27 +14,9 @@ }, "logicalHeight": 128, "fluidHeight": 40, - "caveProfile": { - "enabled": true, - "verticalRange": { - "min": 32, - "max": 47 - }, - "verticalEdgeFade": 0, - "baseDensityStyle": { - "style": "FLAT" - }, - "detailWeight": 0, - "densityThreshold": { - "min": 1, - "max": 1 - }, - "thresholdBias": 0, - "adaptiveSampling": false, - "allowSurfaceBreak": false, - "allowFluid": false, - "allowLava": false - }, + "caves": [ + "slab" + ], "rockPalette": { "palette": [ { diff --git a/probe/src/test/resources/transition-packs/granite-lowland/dimensions/transition.json b/probe/src/test/resources/transition-packs/granite-lowland/dimensions/transition.json index ae937aea3..80a248112 100644 --- a/probe/src/test/resources/transition-packs/granite-lowland/dimensions/transition.json +++ b/probe/src/test/resources/transition-packs/granite-lowland/dimensions/transition.json @@ -14,9 +14,6 @@ }, "logicalHeight": 128, "fluidHeight": 40, - "caveProfile": { - "enabled": false - }, "rockPalette": { "palette": [ { diff --git a/probe/src/test/resources/transition-packs/lowland/dimensions/transition.json b/probe/src/test/resources/transition-packs/lowland/dimensions/transition.json index 5e1a92dd5..072d5f13e 100644 --- a/probe/src/test/resources/transition-packs/lowland/dimensions/transition.json +++ b/probe/src/test/resources/transition-packs/lowland/dimensions/transition.json @@ -13,8 +13,5 @@ "max": 128 }, "logicalHeight": 128, - "fluidHeight": 40, - "caveProfile": { - "enabled": false - } + "fluidHeight": 40 } diff --git a/probe/src/test/resources/transition-packs/mountain/dimensions/transition.json b/probe/src/test/resources/transition-packs/mountain/dimensions/transition.json index 75471f60a..fabc311f4 100644 --- a/probe/src/test/resources/transition-packs/mountain/dimensions/transition.json +++ b/probe/src/test/resources/transition-packs/mountain/dimensions/transition.json @@ -13,8 +13,5 @@ "max": 128 }, "logicalHeight": 128, - "fluidHeight": 40, - "caveProfile": { - "enabled": false - } + "fluidHeight": 40 } diff --git a/probe/src/test/resources/transition-packs/ocean-highwater/dimensions/transition.json b/probe/src/test/resources/transition-packs/ocean-highwater/dimensions/transition.json index 9d608c9a3..45e4d7f79 100644 --- a/probe/src/test/resources/transition-packs/ocean-highwater/dimensions/transition.json +++ b/probe/src/test/resources/transition-packs/ocean-highwater/dimensions/transition.json @@ -13,8 +13,5 @@ "max": 128 }, "logicalHeight": 128, - "fluidHeight": 48, - "caveProfile": { - "enabled": false - } + "fluidHeight": 48 } diff --git a/probe/src/test/resources/transition-packs/ocean/dimensions/transition.json b/probe/src/test/resources/transition-packs/ocean/dimensions/transition.json index eeee1ef95..4e3edd38f 100644 --- a/probe/src/test/resources/transition-packs/ocean/dimensions/transition.json +++ b/probe/src/test/resources/transition-packs/ocean/dimensions/transition.json @@ -13,8 +13,5 @@ "max": 128 }, "logicalHeight": 128, - "fluidHeight": 40, - "caveProfile": { - "enabled": false - } + "fluidHeight": 40 } diff --git a/probe/src/test/resources/transition-packs/ripple-mountain/dimensions/transition.json b/probe/src/test/resources/transition-packs/ripple-mountain/dimensions/transition.json index 75471f60a..fabc311f4 100644 --- a/probe/src/test/resources/transition-packs/ripple-mountain/dimensions/transition.json +++ b/probe/src/test/resources/transition-packs/ripple-mountain/dimensions/transition.json @@ -13,8 +13,5 @@ "max": 128 }, "logicalHeight": 128, - "fluidHeight": 40, - "caveProfile": { - "enabled": false - } + "fluidHeight": 40 } diff --git a/probe/src/test/resources/transition-packs/slope-lowland/dimensions/transition.json b/probe/src/test/resources/transition-packs/slope-lowland/dimensions/transition.json index 5e1a92dd5..072d5f13e 100644 --- a/probe/src/test/resources/transition-packs/slope-lowland/dimensions/transition.json +++ b/probe/src/test/resources/transition-packs/slope-lowland/dimensions/transition.json @@ -13,8 +13,5 @@ "max": 128 }, "logicalHeight": 128, - "fluidHeight": 40, - "caveProfile": { - "enabled": false - } + "fluidHeight": 40 } diff --git a/probe/src/test/resources/transition-packs/slope-mountain/dimensions/transition.json b/probe/src/test/resources/transition-packs/slope-mountain/dimensions/transition.json index 75471f60a..fabc311f4 100644 --- a/probe/src/test/resources/transition-packs/slope-mountain/dimensions/transition.json +++ b/probe/src/test/resources/transition-packs/slope-mountain/dimensions/transition.json @@ -13,8 +13,5 @@ "max": 128 }, "logicalHeight": 128, - "fluidHeight": 40, - "caveProfile": { - "enabled": false - } + "fluidHeight": 40 } diff --git a/probe/src/test/resources/transition-packs/volumetric-lowland/dimensions/transition.json b/probe/src/test/resources/transition-packs/volumetric-lowland/dimensions/transition.json index 8ca03e460..089ec4e9a 100644 --- a/probe/src/test/resources/transition-packs/volumetric-lowland/dimensions/transition.json +++ b/probe/src/test/resources/transition-packs/volumetric-lowland/dimensions/transition.json @@ -13,8 +13,5 @@ "max": 256 }, "logicalHeight": 256, - "fluidHeight": 0, - "caveProfile": { - "enabled": false - } + "fluidHeight": 0 } diff --git a/probe/src/test/resources/transition-packs/volumetric-mountain/dimensions/transition.json b/probe/src/test/resources/transition-packs/volumetric-mountain/dimensions/transition.json index 978e9a178..e72bf460d 100644 --- a/probe/src/test/resources/transition-packs/volumetric-mountain/dimensions/transition.json +++ b/probe/src/test/resources/transition-packs/volumetric-mountain/dimensions/transition.json @@ -13,8 +13,5 @@ "max": 256 }, "logicalHeight": 256, - "fluidHeight": 0, - "caveProfile": { - "enabled": false - } + "fluidHeight": 0 }