diff --git a/core/src/main/java/art/arcane/iris/generation/cave/field/CarveSink.java b/core/src/main/java/art/arcane/iris/generation/cave/field/CarveSink.java new file mode 100644 index 000000000..489003ef1 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/cave/field/CarveSink.java @@ -0,0 +1,25 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.cave.field; + +/** Takes the blocks a cave shape carves in a chunk, by their place in the chunk and their height above the dimension's bottom. */ +@FunctionalInterface +public interface CarveSink { + void carve(int localX, int y, int localZ); +} diff --git a/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 new file mode 100644 index 000000000..38f1e1423 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/cave/field/CaveCarver.java @@ -0,0 +1,194 @@ +/* + * 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; + +import art.arcane.iris.generation.cave.CaveDepth; +import art.arcane.iris.generation.cave.CaveValue; +import art.arcane.iris.generation.cave.IrisCave; +import art.arcane.iris.generation.cave.field.CaveLimits.Columns; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * One cave of a pack, ready to carve chunks of one world: its shapes with their noise built for the world's seed, and + * the heights it may carve at. Heights count from the dimension's bottom. Safe to use from several threads at once. + */ +public final class CaveCarver { + /** Caves stay this far above the dimension's bottom, clear of the bedrock floor. */ + private static final int ROCK_KEPT_ABOVE_BOTTOM_BLOCKS = 5; + private static final int SEED_MIX_PER_CAVE_KEY = 31; + + private final List shapes = new ArrayList<>(); + private final int worldBottomY; + private final int worldHeight; + private final ValueField depthMin; + private final ValueField depthMax; + private final ValueField fade; + private final ValueField surfaceClearance; + private final ValueField ceilingFade; + private final boolean opensToSurface; + + /** + * @param seed the seed of this cave in this world; two caves with the same settings and seed carve the same + * @param worldBottomY world Y of the dimension's lowest block + * @param worldHeight the dimension's height in blocks + */ + public CaveCarver(IrisCave cave, NoiseFactory noise, long seed, int worldBottomY, int worldHeight) { + CaveNoise caveNoise = new CaveNoise(noise, seed); + this.worldBottomY = worldBottomY; + this.worldHeight = worldHeight; + CaveDepth depth = cave.depth().orElse(null); + this.depthMin = depth == null ? ValueField.constant(worldBottomY) : caveValue(depth.min(), caveNoise, "depth.min"); + this.depthMax = depth == null ? ValueField.constant(worldBottomY + worldHeight - 1) : caveValue(depth.max(), caveNoise, "depth.max"); + this.fade = caveValue(cave.fade(), caveNoise, "fade"); + this.surfaceClearance = caveValue(cave.surfaceClearance(), caveNoise, "surfaceClearance"); + this.ceilingFade = caveValue(cave.ceilingFade(), caveNoise, "ceilingFade"); + this.opensToSurface = cave.opensToSurface(); + cave.tunnel().ifPresent(tunnel -> shapes.add(new PartShape(CavePart.TUNNEL, new TunnelShape(caveNoise, tunnel)))); + cave.cavern().ifPresent(cavern -> shapes.add(new PartShape(CavePart.CAVERN, new CavernShape(caveNoise, cavern)))); + } + + private static ValueField caveValue(CaveValue value, CaveNoise caveNoise, String name) { + return ValueField.inColumns(value, caveNoise, name, IrisCave.VALUE_CHANGE_BLOCKS); + } + + /** The seed the cave filed under {@code caveKey} carves with in a world whose carve seed is {@code carveSeed}. */ + public static long seedOf(long carveSeed, String caveKey) { + return carveSeed + (SEED_MIX_PER_CAVE_KEY * (long) caveKey.hashCode()); + } + + public boolean opensToSurface() { + return opensToSurface; + } + + /** Which parts the cave has, in the order it carves them. */ + public List parts() { + return shapes.stream().map(PartShape::part).toList(); + } + + /** {@link #carve}, telling the sink which part carved each block. A block two parts carve is reported for each. */ + public void carveByPart(int originX, int originZ, int[] surfaceY, double[] columnWeight, boolean[] sealed, PartSink sink) { + carveByPart(originX, originZ, new ChunkColumns(surfaceY, columnWeight, sealed, null), HeightBand.UNLIMITED, sink); + } + + /** Takes the blocks a cave carves, with the part that carved each. */ + @FunctionalInterface + public interface PartSink { + void carve(CavePart part, int localX, int y, int localZ); + } + + /** + * What a chunk's columns allow the cave, indexed as {@code (localX << 4) | localZ}. + * + * @param surfaceY the height of the surface in each column + * @param weight how much each column lists this cave, from 0 to 1 + * @param sealed columns whose surface the cave must not cut through, even if it opens to the surface + * @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 + */ + public record ChunkColumns(int[] surfaceY, double[] weight, boolean[] sealed, int[] topLimitY) { + } + + private record PartShape(CavePart part, LatticeShape shape) { + } + + /** + * Carves the chunk whose first block is {@code originX}, {@code originZ}. Columns are indexed as + * {@code (localX << 4) | localZ}. + * + * @param surfaceY the height of the surface in each column + * @param columnWeight how much each column lists this cave, from 0 to 1 + * @param sealed columns whose surface the cave must not cut through, even if it opens to the surface + */ + public void carve(int originX, int originZ, int[] surfaceY, double[] columnWeight, boolean[] sealed, CarveSink sink) { + carve(originX, originZ, new ChunkColumns(surfaceY, columnWeight, sealed, null), HeightBand.UNLIMITED, sink); + } + + /** {@link #carve} within {@code band}, with the caps and seals of {@code columns}. */ + public void carve(int originX, int originZ, ChunkColumns columns, HeightBand band, CarveSink sink) { + carveByPart(originX, originZ, columns, band, (part, localX, y, localZ) -> sink.carve(localX, y, localZ)); + } + + private void carveByPart(int originX, int originZ, ChunkColumns columns, HeightBand band, PartSink sink) { + if (shapes.isEmpty()) { + return; + } + CaveLimits limits = limitsOf(originX, originZ, columns, band); + if (limits.carvesNothing()) { + return; + } + ChunkLattice lattice = ChunkLattice.covering(originX, originZ, limits.lowestY(), limits.highestY()); + for (PartShape shape : shapes) { + shape.shape().carve(lattice, limits, (localX, y, localZ) -> sink.carve(shape.part(), localX, y, localZ)); + } + } + + private CaveLimits limitsOf(int originX, int originZ, ChunkColumns chunk, HeightBand band) { + Columns columns = Columns.of(chunk.weight()); + fillBlocks(fade, originX, originZ, columns.fadeBlocks()); + fillBlocks(ceilingFade, originX, originZ, columns.ceilingFadeBlocks()); + boolean depthVaries = depthMin.varies() || depthMax.varies(); + int constantClearance = surfaceClearanceAt(originX, originZ); + int constantDepthMinY = depthMinYAt(originX, originZ); + int constantDepthMaxY = depthMaxYAt(originX, originZ); + for (int column = 0; column < CaveLimits.CHUNK_COLUMNS; column++) { + double x = originX + (column >> 4); + double z = originZ + (column & 15); + columns.depthMinY()[column] = depthVaries ? depthMinYAt(x, z) : constantDepthMinY; + columns.depthMaxY()[column] = depthVaries ? depthMaxYAt(x, z) : constantDepthMaxY; + int clearance = surfaceClearance.varies() ? surfaceClearanceAt(x, z) : constantClearance; + boolean opens = opensToSurface && !chunk.sealed()[column]; + int topY = opens ? chunk.surfaceY()[column] : chunk.surfaceY()[column] - clearance; + if (chunk.topLimitY() != null && chunk.topLimitY()[column] < topY) { + topY = chunk.topLimitY()[column]; + opens = false; + } + columns.opensToSurface()[column] = opens; + columns.topY()[column] = topY; + } + return new CaveLimits(columns, band); + } + + /** Fills {@code blocks} with the value in each column of the chunk, at least 0. */ + private static void fillBlocks(ValueField value, int originX, int originZ, double[] blocks) { + if (!value.varies()) { + Arrays.fill(blocks, Math.max(0D, value.min())); + return; + } + for (int column = 0; column < CaveLimits.CHUNK_COLUMNS; column++) { + blocks[column] = Math.max(0D, value.at(originX + (column >> 4), originZ + (column & 15))); + } + } + + private int depthMinYAt(double x, double z) { + double lowest = Math.min(depthMin.at(x, z), depthMax.at(x, z)); + return Math.max(ROCK_KEPT_ABOVE_BOTTOM_BLOCKS, (int) Math.floor(lowest) - worldBottomY); + } + + private int depthMaxYAt(double x, double z) { + double highest = Math.max(depthMin.at(x, z), depthMax.at(x, z)); + return Math.min(worldHeight - 1, (int) Math.ceil(highest) - worldBottomY); + } + + private int surfaceClearanceAt(double x, double z) { + return (int) Math.round(Math.max(0D, surfaceClearance.at(x, z))); + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/cave/field/CaveLimits.java b/core/src/main/java/art/arcane/iris/generation/cave/field/CaveLimits.java new file mode 100644 index 000000000..01022d0d7 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/cave/field/CaveLimits.java @@ -0,0 +1,172 @@ +/* + * 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; + +import java.util.Arrays; + +/** + * Where one cave may carve in one chunk, and how freely: fully inside its depth range and well under the surface, + * narrowing to nothing towards the ends of the range, towards the rock it keeps under the surface and towards columns + * that do not list it. Columns are indexed as {@code (localX << 4) | localZ}; heights count from the dimension's bottom. + */ +final class CaveLimits { + static final int CHUNK_COLUMNS = 256; + private static final int CELL_COLUMNS = ChunkLattice.CELLS_PER_CHUNK_AXIS * ChunkLattice.CELLS_PER_CHUNK_AXIS; + + private final int[] depthMinYs; + private final int[] depthMaxYs; + private final double[] fadeBlocks; + private final double[] ceilingFadeBlocks; + private final int[] topY; + private final boolean[] opensToSurface; + private final double[] weight; + /** Whether depth and fades are the same in every column, as they are for plain numbers; then they are read once. */ + private final boolean sameRangeInEveryColumn; + private final int depthMinY; + private final int depthMaxY; + private final double fade; + private final double ceilingFade; + private final int lowestY; + private final int highestY; + private final int[] cellTopY = new int[CELL_COLUMNS]; + private final boolean[] cellHasWeight = new boolean[CELL_COLUMNS]; + + /** + * What the cave allows in each column of the chunk. + * + * @param depthMinY lowest height of the cave's depth range + * @param depthMaxY highest height of the cave's depth range + * @param fadeBlocks blocks over which the cave narrows at both ends of the range + * @param topY highest height the cave may carve + * @param opensToSurface whether the cave reaches its top at full width, instead of closing under it + * @param ceilingFadeBlocks blocks over which a cave that does not open to the surface closes under its top + * @param weight how much the column lists the cave, from 0 to 1 + */ + record Columns(int[] depthMinY, int[] depthMaxY, double[] fadeBlocks, int[] topY, boolean[] opensToSurface, + double[] ceilingFadeBlocks, double[] weight) { + static Columns of(double[] weight) { + return new Columns(new int[CHUNK_COLUMNS], new int[CHUNK_COLUMNS], new double[CHUNK_COLUMNS], new int[CHUNK_COLUMNS], + new boolean[CHUNK_COLUMNS], new double[CHUNK_COLUMNS], weight); + } + } + + CaveLimits(Columns columns, HeightBand band) { + this.depthMinYs = columns.depthMinY(); + this.depthMaxYs = columns.depthMaxY(); + this.fadeBlocks = columns.fadeBlocks(); + this.ceilingFadeBlocks = columns.ceilingFadeBlocks(); + this.topY = columns.topY(); + this.opensToSurface = columns.opensToSurface(); + this.weight = columns.weight(); + this.sameRangeInEveryColumn = isTheSameInEveryColumn(depthMinYs) && isTheSameInEveryColumn(depthMaxYs) + && isTheSameInEveryColumn(fadeBlocks) && isTheSameInEveryColumn(ceilingFadeBlocks); + this.depthMinY = depthMinYs[0]; + this.depthMaxY = depthMaxYs[0]; + this.fade = fadeBlocks[0]; + this.ceilingFade = ceilingFadeBlocks[0]; + Arrays.fill(cellTopY, Integer.MIN_VALUE); + int lowest = Integer.MAX_VALUE; + int highest = Integer.MIN_VALUE; + for (int column = 0; column < CHUNK_COLUMNS; column++) { + if (columns.weight()[column] <= 0D) { + continue; + } + int cell = cellOf(column >> 4, column & 15); + cellHasWeight[cell] = true; + cellTopY[cell] = Math.max(cellTopY[cell], topY[column]); + lowest = Math.min(lowest, depthMinYs[column]); + highest = Math.max(highest, Math.min(depthMaxYs[column], topY[column])); + } + this.lowestY = Math.max(lowest, band.lowestY()); + this.highestY = Math.min(highest, band.highestY()); + } + + private static int cellOf(int localX, int localZ) { + return ((localX / ChunkLattice.CELL_BLOCKS) * ChunkLattice.CELLS_PER_CHUNK_AXIS) + (localZ / ChunkLattice.CELL_BLOCKS); + } + + int lowestY() { + return lowestY; + } + + int highestY() { + return highestY; + } + + /** Whether the cave carves nothing in this chunk. */ + boolean carvesNothing() { + return highestY < lowestY; + } + + /** Whether no column of the cell lets the cave carve at or above {@code bottomY}. */ + boolean cellIsClosed(int cellX, int cellZ, int bottomY) { + int cell = (cellX * ChunkLattice.CELLS_PER_CHUNK_AXIS) + cellZ; + return !cellHasWeight[cell] || cellTopY[cell] < bottomY; + } + + /** How freely the cave carves the block, from 0 (not at all) to 1 (at its full size). */ + double openness(int column, int y) { + if (sameRangeInEveryColumn) { + return openness(column, y, depthMinY, depthMaxY, fade, ceilingFade); + } + return openness(column, y, depthMinYs[column], depthMaxYs[column], fadeBlocks[column], ceilingFadeBlocks[column]); + } + + private double openness(int column, int y, int columnDepthMinY, int columnDepthMaxY, double columnFade, double columnCeilingFade) { + double columnWeight = weight[column]; + if (columnWeight <= 0D || y < columnDepthMinY || y > columnDepthMaxY) { + return 0D; + } + int belowTop = topY[column] - y; + if (belowTop < 0) { + return 0D; + } + double openness = columnWeight * easeIn(Math.min(y - columnDepthMinY, columnDepthMaxY - y), columnFade); + if (!opensToSurface[column]) { + openness *= easeIn(belowTop, columnCeilingFade); + } + return openness; + } + + private static boolean isTheSameInEveryColumn(int[] values) { + for (int column = 1; column < values.length; column++) { + if (values[column] != values[0]) { + return false; + } + } + return true; + } + + private static boolean isTheSameInEveryColumn(double[] values) { + for (int column = 1; column < values.length; column++) { + if (values[column] != values[0]) { + return false; + } + } + return true; + } + + private static double easeIn(int distance, double fadeBlocks) { + if (fadeBlocks <= 0D || distance >= fadeBlocks) { + return 1D; + } + double share = distance / fadeBlocks; + return share * share * (3D - (2D * share)); + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/cave/field/CaveNoise.java b/core/src/main/java/art/arcane/iris/generation/cave/field/CaveNoise.java new file mode 100644 index 000000000..02cdf5e6c --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/cave/field/CaveNoise.java @@ -0,0 +1,196 @@ +/* + * 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; + +import art.arcane.iris.generation.noise.IrisGeneratorStyle; +import art.arcane.iris.generation.noise.NoiseStyle; + +import java.util.OptionalDouble; + +/** + * Builds the noise fields of cave shapes, sized in blocks instead of in a noise style's zoom. Every field takes the + * next seed of the cave, whichever way it is built, so changing how one field is built leaves the others alone. + */ +final class CaveNoise { + /** Measured on the SIMPLEX style at zoom 1: the mean distance in blocks between two sign changes along a line. */ + private static final double SIMPLEX_ZERO_SPACING_BLOCKS = 52.6D; + /** Measured on the same style: how much its value typically changes per block, times the spacing above. */ + private static final double SIMPLEX_SLOPE_TIMES_SPACING = 2.43D; + /** The features of a field's finer second layer are this much smaller than its own. */ + private static final double DETAIL_SHRINK = 2.7D; + /** Below this size a detail layer is finer than the sampling lattice can carry. */ + private static final double MIN_DETAIL_SPACING_BLOCKS = 12D; + /** A pack style is rescaled until its measured feature spacing is within this share of the one asked for. */ + private static final double SCALING_TOLERANCE = 0.1D; + private static final int MOST_SCALING_ROUNDS = 6; + private static final long NAME_SEED_MIX = 0x9E3779B97F4A7C15L; + private static final Field3 LEVEL = (x, y, z) -> 0D; + + private final NoiseFactory noise; + private final long seed; + private int fieldsBuilt; + + CaveNoise(NoiseFactory noise, long seed) { + this.noise = noise; + this.seed = seed; + } + + /** + * The fields of one named value of the cave, seeded by the name: a value that varies takes no seed from the + * cave's own fields, so writing a range anywhere leaves every other field of the cave where it was. + */ + CaveNoise named(String name) { + return new CaveNoise(noise, seed ^ (name.hashCode() * NAME_SEED_MIX)); + } + + /** How much a field with this spacing typically changes over one block. */ + static double typicalSlope(double spacing) { + return SIMPLEX_SLOPE_TIMES_SPACING / spacing; + } + + /** A field whose sign changes about every {@code spacing} blocks horizontally and {@code verticalSpacing} vertically. */ + Field3 smooth(double spacing, double verticalSpacing) { + NoiseSampler sampler = nextSampler(simplexStyle()); + double horizontal = SIMPLEX_ZERO_SPACING_BLOCKS / spacing; + double vertical = SIMPLEX_ZERO_SPACING_BLOCKS / verticalSpacing; + return (x, y, z) -> sampler.signed(x * horizontal, y * vertical, z * horizontal); + } + + /** {@link #smooth} with a finer layer of {@code detailWeight} times its strength on top, where the lattice can carry one. */ + Field3 detailed(double spacing, double verticalSpacing, double detailWeight) { + Field3 base = smooth(spacing, verticalSpacing); + double detailSpacing = spacing / DETAIL_SHRINK; + double detailVerticalSpacing = verticalSpacing / DETAIL_SHRINK; + if (Math.min(detailSpacing, detailVerticalSpacing) < MIN_DETAIL_SPACING_BLOCKS) { + return base; + } + Field3 detail = smooth(detailSpacing, detailVerticalSpacing); + double normalization = 1D / (1D + detailWeight); + return (x, y, z) -> (base.at(x, y, z) + (detail.at(x, y, z) * detailWeight)) * normalization; + } + + /** {@link #detailed} with a detail weight that may vary from place to place. */ + Field3 detailed(double spacing, double verticalSpacing, ValueField detailWeight) { + if (!detailWeight.varies()) { + return detailed(spacing, verticalSpacing, detailWeight.min()); + } + Field3 base = smooth(spacing, verticalSpacing); + double detailSpacing = spacing / DETAIL_SHRINK; + double detailVerticalSpacing = verticalSpacing / DETAIL_SHRINK; + if (Math.min(detailSpacing, detailVerticalSpacing) < MIN_DETAIL_SPACING_BLOCKS) { + return base; + } + Field3 detail = smooth(detailSpacing, detailVerticalSpacing); + return (x, y, z) -> { + double weight = detailWeight.at(x, y, z); + return (base.at(x, y, z) + (detail.at(x, y, z) * weight)) / (1D + weight); + }; + } + + /** A field that only varies over X and Z, changing sign about every {@code spacing} blocks. */ + Field3 columns(double spacing) { + NoiseSampler sampler = nextSampler(simplexStyle()); + double scale = SIMPLEX_ZERO_SPACING_BLOCKS / spacing; + return (x, y, z) -> sampler.signed(x * scale, z * scale); + } + + /** A pack's style read in blocks as the pack wrote it, its zoom included. A flat style gives a level field at 0. */ + Field3 inBlocks(IrisGeneratorStyle style) { + if (style.isFlat()) { + nextSeed(); + return LEVEL; + } + NoiseSampler sampler = nextSampler(style); + return sampler::signed; + } + + /** {@link #inBlocks} for a field that only varies over X and Z. */ + Field3 columnsInBlocks(IrisGeneratorStyle style) { + if (style.isFlat()) { + nextSeed(); + return LEVEL; + } + NoiseSampler sampler = nextSampler(style); + return (x, y, z) -> sampler.signed(x, z); + } + + /** A pack's style rescaled so its features lie about {@code spacing} blocks apart horizontally and {@code verticalSpacing} vertically. */ + Field3 scaledTo(IrisGeneratorStyle style, double spacing, double verticalSpacing) { + if (style.isFlat()) { + nextSeed(); + return LEVEL; + } + NoiseSampler sampler = scaledToSpacing(nextSampler(style), style, spacing); + double vertical = spacing / verticalSpacing; + return (x, y, z) -> sampler.signed(x, y * vertical, z); + } + + /** {@link #scaledTo} for a field that only varies over X and Z. */ + Field3 columnsScaledTo(IrisGeneratorStyle style, double spacing) { + if (style.isFlat()) { + nextSeed(); + return LEVEL; + } + NoiseSampler sampler = scaledToSpacing(nextSampler(style), style, spacing); + return (x, y, z) -> sampler.signed(x, z); + } + + /** How far apart the features of {@code field}, read from {@code style} in blocks, roughly lie. */ + static double featureBlocks(Field3 field, IrisGeneratorStyle style) { + double guess = simplexLikeFeatureBlocks(style.getZoom()); + return FieldStats.featureBlocks(field, guess).orElse(guess); + } + + /** + * Rescales {@code sampler} until its measured feature spacing matches {@code spacing}, starting from where a style + * built like SIMPLEX would land. The scale is folded into the noise, so a fracture still moves it in blocks. + */ + private static NoiseSampler scaledToSpacing(NoiseSampler sampler, IrisGeneratorStyle style, double spacing) { + double factor = simplexLikeFeatureBlocks(style.getZoom()) / spacing; + for (int round = 0; round < MOST_SCALING_ROUNDS; round++) { + NoiseSampler scaled = sampler.scaled(factor); + OptionalDouble measured = FieldStats.featureBlocks((x, y, z) -> scaled.signed(x, y, z), spacing); + if (measured.isEmpty()) { + return scaled; + } + double measuredShare = measured.getAsDouble() / spacing; + if (Math.abs(measuredShare - 1D) <= SCALING_TOLERANCE) { + return scaled; + } + factor *= measuredShare; + } + return sampler.scaled(factor); + } + + private static double simplexLikeFeatureBlocks(double zoom) { + return SIMPLEX_ZERO_SPACING_BLOCKS * zoom; + } + + private static IrisGeneratorStyle simplexStyle() { + return new IrisGeneratorStyle(NoiseStyle.SIMPLEX); + } + + private NoiseSampler nextSampler(IrisGeneratorStyle style) { + return noise.sampler(style, nextSeed()); + } + + private long nextSeed() { + fieldsBuilt++; + return seed + (fieldsBuilt * 1_000_003L); + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/cave/field/CavePart.java b/core/src/main/java/art/arcane/iris/generation/cave/field/CavePart.java new file mode 100644 index 000000000..375bf7781 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/cave/field/CavePart.java @@ -0,0 +1,25 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.cave.field; + +/** The shapes a cave is made of, in the order a cave carves them. */ +public enum CavePart { + TUNNEL, + CAVERN +} diff --git a/core/src/main/java/art/arcane/iris/generation/cave/field/CavernShape.java b/core/src/main/java/art/arcane/iris/generation/cave/field/CavernShape.java new file mode 100644 index 000000000..f0fa9580d --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/cave/field/CavernShape.java @@ -0,0 +1,237 @@ +/* + * 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; + +import art.arcane.iris.generation.cave.CaveCavern; +import art.arcane.iris.generation.cave.CavePillars; +import art.arcane.iris.generation.noise.IrisGeneratorStyle; + +/** + * Caverns: the rooms where one slow field rises above a threshold. Pillars stand where a second field peaks: there the + * room has to be more open to be carved, so a pillar widens towards floor and ceiling, where the room is least open. + * The pillar field varies only across X and Z unless the pack lets pillars change with height; then it is read in 3D + * on the lattice, and a pillar whose field fades out mid-room narrows and breaks off, leaving stubs that flare into + * floor and ceiling. + * + *

A value that varies moves the threshold it sets point by point: the lattice then carries the room field less its + * threshold, and the pillar thresholds, so blocks interpolate them like any field. A plain number keeps them constant. + */ +final class CavernShape extends LatticeShape { + private static final int ROOMS = 0; + private static final int NOT_READ = -1; + /** A room is the part of a feature above the threshold, which is narrower than the feature itself. */ + private static final double FEATURE_BLOCKS_PER_ROOM_BLOCK = 1.6D; + /** Closing a cavern takes a little more than its most open spot, so nothing is left at the very edge of its limits. */ + private static final double CLOSING_MARGIN = 1.1D; + /** Pillars are two features apart: one peak, one trough. */ + private static final double PILLAR_FEATURES_PER_SPACING = 0.5D; + private static final double LARGEST_PILLAR_AREA_SHARE = 0.3D; + private static final double NO_PILLAR = 0D; + private static final double FULL_PILLAR = 1D; + /** Where the threshold is worked out at the lattice points, a block subtracts nothing more. */ + private static final double THRESHOLD_WORKED_OUT_AT_POINTS = 0D; + + private final Field3 rooms; + private final FieldStats roomStats; + private final ValueField coverage; + private final double threshold; + private final double mostOpen; + private final Field3 pillars; + private final boolean pillarsChangeWithHeight; + private final FieldStats pillarStats; + private final ValueField pillarSpacing; + private final ValueField pillarThickness; + private final ValueField pillarFlare; + private final boolean pillarSizeVaries; + private final double pillarMiddle; + private final double pillarFoot; + private final int mostOpenField; + private final int pillarField; + private final int pillarMiddleField; + private final int pillarFootField; + private final int fieldCount; + + CavernShape(CaveNoise noise, CaveCavern cavern) { + double valueChangeBlocks = cavern.size().middle() * CaveCavern.VALUE_CHANGE_SIZES; + ValueField size = ValueField.inBlocks(cavern.size(), noise, "cavern.size", valueChangeBlocks); + ValueField height = ValueField.inColumns(cavern.height(), noise, "cavern.height", valueChangeBlocks); + ValueField roughness = ValueField.inBlocks(cavern.roughness(), noise, "cavern.roughness", valueChangeBlocks); + this.coverage = ValueField.inBlocks(cavern.coverage(), noise, "cavern.coverage", valueChangeBlocks); + this.rooms = roomField(noise, cavern, size, height, roughness); + this.roomStats = FieldStats.measure(rooms, size.middle() * FEATURE_BLOCKS_PER_ROOM_BLOCK); + this.threshold = coverage.varies() ? THRESHOLD_WORKED_OUT_AT_POINTS : roomStats.valueAboveShare(coverage.min()); + this.mostOpen = Math.max(0D, roomStats.highest() - threshold); + int nextField = ROOMS + 1; + this.mostOpenField = coverage.varies() ? nextField++ : NOT_READ; + if (cavern.pillars().isEmpty()) { + this.pillars = null; + this.pillarsChangeWithHeight = false; + this.pillarStats = null; + this.pillarSpacing = null; + this.pillarThickness = null; + this.pillarFlare = null; + this.pillarSizeVaries = false; + this.pillarMiddle = Double.POSITIVE_INFINITY; + this.pillarFoot = Double.POSITIVE_INFINITY; + this.pillarField = NOT_READ; + this.pillarMiddleField = NOT_READ; + this.pillarFootField = NOT_READ; + this.fieldCount = nextField; + return; + } + CavePillars settings = cavern.pillars().get(); + this.pillarSpacing = ValueField.inColumns(settings.spacing(), noise, "cavern.pillars.spacing", valueChangeBlocks); + this.pillarThickness = ValueField.inColumns(settings.thickness(), noise, "cavern.pillars.thickness", valueChangeBlocks); + this.pillarFlare = ValueField.inColumns(settings.flare(), noise, "cavern.pillars.flare", valueChangeBlocks); + this.pillarSizeVaries = pillarSpacing.varies() || pillarThickness.varies() || pillarFlare.varies(); + this.pillarsChangeWithHeight = settings.vertical().isPresent(); + ValueField vertical = settings.vertical() + .map(value -> ValueField.inColumns(value, noise, "cavern.pillars.vertical", valueChangeBlocks)) + .orElseGet(() -> ValueField.constant(0D)); + this.pillars = pillarField(noise, settings, pillarSpacing, vertical); + this.pillarStats = FieldStats.measure(pillars, pillarSpacing.middle() * PILLAR_FEATURES_PER_SPACING); + this.pillarMiddle = pillarSizeVaries ? Double.NaN : pillarMiddleAt(0D, 0D); + this.pillarFoot = pillarSizeVaries ? Double.NaN : pillarFootAt(0D, 0D); + this.pillarField = pillarsChangeWithHeight ? nextField++ : NOT_READ; + boolean thresholdsAtPoints = pillarsChangeWithHeight && pillarSizeVaries; + this.pillarMiddleField = thresholdsAtPoints ? nextField++ : NOT_READ; + this.pillarFootField = thresholdsAtPoints ? nextField++ : NOT_READ; + this.fieldCount = nextField; + } + + private static Field3 roomField(CaveNoise noise, CaveCavern cavern, ValueField size, ValueField height, ValueField roughness) { + IrisGeneratorStyle style = cavern.style().orElse(null); + return VaryingScale.of(noise, size, height, "cavern.rooms", (fieldNoise, roomSize, roomHeight) -> { + double span = roomSize * FEATURE_BLOCKS_PER_ROOM_BLOCK; + double featureHeight = roomHeight * FEATURE_BLOCKS_PER_ROOM_BLOCK; + return style == null ? fieldNoise.detailed(span, featureHeight, roughness) : fieldNoise.scaledTo(style, span, featureHeight); + }); + } + + private static Field3 pillarField(CaveNoise noise, CavePillars settings, ValueField spacing, ValueField vertical) { + IrisGeneratorStyle style = settings.style().orElse(null); + boolean straight = settings.vertical().isEmpty(); + return VaryingScale.of(noise, spacing, vertical, "cavern.pillars", (fieldNoise, pillarSpacing, verticalBlocks) -> { + double featureBlocks = pillarSpacing * PILLAR_FEATURES_PER_SPACING; + if (straight) { + return style == null ? fieldNoise.columns(featureBlocks) : fieldNoise.columnsScaledTo(style, featureBlocks); + } + return style == null ? fieldNoise.smooth(featureBlocks, verticalBlocks) : fieldNoise.scaledTo(style, featureBlocks, verticalBlocks); + }); + } + + /** The pillar field value above which a column is the middle of a pillar. */ + private double pillarMiddleAt(double x, double z) { + return pillarStats.valueAboveShare(middleAreaShareAt(x, z)); + } + + /** The pillar field value above which a column is on the foot a pillar widens into towards floor and ceiling. */ + private double pillarFootAt(double x, double z) { + return pillarStats.valueAboveShare(Math.min(1D, middleAreaShareAt(x, z) * pillarFlare.at(x, z))); + } + + private double middleAreaShareAt(double x, double z) { + double radius = pillarThickness.at(x, z) / 2D; + double spacing = pillarSpacing.at(x, z); + return Math.min(LARGEST_PILLAR_AREA_SHARE, (Math.PI * radius * radius) / (spacing * spacing)); + } + + @Override + protected int fieldCount() { + return fieldCount; + } + + @Override + protected void readFields(int x, int y, int z, double[] values) { + double room = rooms.at(x, y, z); + if (mostOpenField == NOT_READ) { + values[ROOMS] = room; + } else { + double pointThreshold = roomStats.valueAboveShare(coverage.at(x, y, z)); + values[ROOMS] = room - pointThreshold; + values[mostOpenField] = Math.max(0D, roomStats.highest() - pointThreshold); + } + if (pillarField != NOT_READ) { + values[pillarField] = pillars.at(x, y, z); + } + if (pillarMiddleField != NOT_READ) { + values[pillarMiddleField] = pillarMiddleAt(x, z); + values[pillarFootField] = pillarFootAt(x, z); + } + } + + @Override + protected boolean mayCarveIn(Pass pass) { + return pass.cell(ROOMS).highest() > threshold; + } + + @Override + protected boolean carvesAt(Pass pass, double shareX, double shareY, double shareZ, double openness, int column) { + double mostOpenHere = mostOpenField == NOT_READ ? mostOpen : pass.cell(mostOpenField).at(shareX, shareY, shareZ); + double open = pass.cell(ROOMS).at(shareX, shareY, shareZ) - threshold - ((1D - openness) * mostOpenHere * CLOSING_MARGIN); + if (open <= 0D) { + return false; + } + if (pillars == null) { + return true; + } + double strength = pillarsChangeWithHeight + ? pointPillarStrength(pass, shareX, shareY, shareZ) + : columnPillarStrength(pass, column); + return open > strength * mostOpenHere; + } + + private double pointPillarStrength(Pass pass, double shareX, double shareY, double shareZ) { + double value = pass.cell(pillarField).at(shareX, shareY, shareZ); + if (pillarMiddleField == NOT_READ) { + return pillarStrength(value, pillarMiddle, pillarFoot); + } + return pillarStrength(value, pass.cell(pillarMiddleField).at(shareX, shareY, shareZ), pass.cell(pillarFootField).at(shareX, shareY, shareZ)); + } + + /** {@link #pillarStrength} of a straight pillar, read once per column of the chunk. */ + private double columnPillarStrength(Pass pass, int column) { + double[] strengths = pass.columnValues(); + double known = strengths[column]; + if (!Double.isNaN(known)) { + return known; + } + double x = pass.lattice().originX() + (column >> 4); + double z = pass.lattice().originZ() + (column & 15); + double value = pillars.at(x, 0D, z); + double strength = pillarSizeVaries + ? pillarStrength(value, pillarMiddleAt(x, z), pillarFootAt(x, z)) + : pillarStrength(value, pillarMiddle, pillarFoot); + strengths[column] = strength; + return strength; + } + + /** How strongly a pillar field value is a pillar: 0 outside one, 1 in its middle, in between on the foot it widens into. */ + private static double pillarStrength(double value, double middle, double foot) { + if (value >= middle) { + return FULL_PILLAR; + } + double footWidth = middle - foot; + if (footWidth <= 0D) { + return NO_PILLAR; + } + double intoPillar = Math.max(0D, Math.min(1D, (value - foot) / footWidth)); + return intoPillar * intoPillar; + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/cave/field/ChunkLattice.java b/core/src/main/java/art/arcane/iris/generation/cave/field/ChunkLattice.java new file mode 100644 index 000000000..8e1e030c3 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/cave/field/ChunkLattice.java @@ -0,0 +1,94 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.cave.field; + +/** + * The points one chunk samples its cave fields at: every fourth block along each axis, over the heights a cave may + * carve. A shape reads its fields at these points only and interpolates between them, which is where the carver's + * speed comes from. Points sit at multiples of four in world coordinates, so neighboring chunks sample the very same + * points along their shared border and their caves meet without a seam. + */ +public final class ChunkLattice { + public static final int CELL_BLOCKS = 4; + public static final int CELLS_PER_CHUNK_AXIS = 16 / CELL_BLOCKS; + private static final int POINTS_PER_AXIS = CELLS_PER_CHUNK_AXIS + 1; + private static final int POINTS_PER_LAYER = POINTS_PER_AXIS * POINTS_PER_AXIS; + + private final int originX; + private final int originZ; + private final int baseY; + private final int cellsY; + + private ChunkLattice(int originX, int originZ, int baseY, int cellsY) { + this.originX = originX; + this.originZ = originZ; + this.baseY = baseY; + this.cellsY = cellsY; + } + + /** The lattice of the chunk whose first block is {@code originX}, {@code originZ}, covering heights {@code minY} to {@code maxY}. */ + public static ChunkLattice covering(int originX, int originZ, int minY, int maxY) { + int baseY = Math.floorDiv(minY, CELL_BLOCKS) * CELL_BLOCKS; + int cellsY = Math.max(1, Math.floorDiv(maxY - baseY, CELL_BLOCKS) + 1); + return new ChunkLattice(originX, originZ, baseY, cellsY); + } + + public int originX() { + return originX; + } + + public int originZ() { + return originZ; + } + + public int baseY() { + return baseY; + } + + public int cellsY() { + return cellsY; + } + + public int pointCount() { + return POINTS_PER_LAYER * (cellsY + 1); + } + + /** Takes the lattice's points one by one, each with its place in a list of {@link #pointCount()} values. */ + @FunctionalInterface + interface PointReader { + void read(int index, int x, int y, int z); + } + + void forEachPoint(PointReader reader) { + int index = 0; + for (int layer = 0; layer <= cellsY; layer++) { + int y = baseY + (layer * CELL_BLOCKS); + for (int pointX = 0; pointX < POINTS_PER_AXIS; pointX++) { + int x = originX + (pointX * CELL_BLOCKS); + for (int pointZ = 0; pointZ < POINTS_PER_AXIS; pointZ++) { + reader.read(index++, x, y, originZ + (pointZ * CELL_BLOCKS)); + } + } + } + } + + int pointIndex(int pointX, int layer, int pointZ) { + return (layer * POINTS_PER_LAYER) + (pointX * POINTS_PER_AXIS) + pointZ; + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/cave/field/CngNoiseFactory.java b/core/src/main/java/art/arcane/iris/generation/cave/field/CngNoiseFactory.java new file mode 100644 index 000000000..7a90d4ae7 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/cave/field/CngNoiseFactory.java @@ -0,0 +1,82 @@ +/* + * 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; + +import art.arcane.iris.generation.noise.IrisGeneratorStyle; +import art.arcane.iris.pack.loading.IrisData; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.noise.CNG; + +import java.util.function.Supplier; + +/** + * Noise of cave fields from Iris's own generators: a style builds the same {@link CNG} the rest of Iris builds from it, + * seeded from an {@link RNG} of the seed. The pack's data resolves expressions and image maps; without it only plain styles work. + */ +public final class CngNoiseFactory implements NoiseFactory { + private static final double NO_EXTRA_SCALE = 1D; + + private final IrisData data; + + public CngNoiseFactory(IrisData data) { + this.data = data; + } + + /** Noise with no pack behind it: the plain styles, but no expressions and no image maps. */ + public static CngNoiseFactory standalone() { + return new CngNoiseFactory(null); + } + + @Override + public NoiseSampler sampler(IrisGeneratorStyle style, long seed) { + return new CngSampler(style.create(new RNG(seed), data), () -> style.createNoCache(new RNG(seed), data), NO_EXTRA_SCALE); + } + + /** + * {@code fresh} builds the same generator again, unshared, for {@link #scaled}: scaling a generator changes it, and + * the one in use is shared. + */ + private record CngSampler(CNG noise, Supplier fresh, double extraScale) implements NoiseSampler { + @Override + public double sample(double worldX, double worldZ) { + return noise.noise(worldX, worldZ); + } + + @Override + public double sample(double worldX, double y, double worldZ) { + return noise.noise(worldX, y, worldZ); + } + + @Override + public double signed(double worldX, double worldZ) { + return noise.noiseFastSigned2D(worldX, worldZ); + } + + @Override + public double signed(double worldX, double y, double worldZ) { + return noise.noiseFastSigned3D(worldX, y, worldZ); + } + + @Override + public NoiseSampler scaled(double factor) { + double total = extraScale * factor; + return new CngSampler(fresh.get().bake().scale(total).bake(), fresh, total); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/cave/field/Field3.java b/core/src/main/java/art/arcane/iris/generation/cave/field/Field3.java new file mode 100644 index 000000000..58a541409 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/cave/field/Field3.java @@ -0,0 +1,25 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.cave.field; + +/** A smooth value over the world's blocks, from -1 to 1, that a cave shape reads to decide where it carves. */ +@FunctionalInterface +public interface Field3 { + double at(double x, double y, double z); +} diff --git a/core/src/main/java/art/arcane/iris/generation/cave/field/FieldStats.java b/core/src/main/java/art/arcane/iris/generation/cave/field/FieldStats.java new file mode 100644 index 000000000..b11ccc2be --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/cave/field/FieldStats.java @@ -0,0 +1,110 @@ +/* + * 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; + +import java.util.Arrays; +import java.util.OptionalDouble; + +/** + * What a field's values look like, measured once on fixed sample points so every server measures the same: which value + * a given share of the world lies above, and how far apart its features lie. Shapes turn a share of the underground + * into a field threshold with it, and a pack's noise style into a size in blocks. + */ +final class FieldStats { + private static final int SAMPLES = 4096; + /** Samples spread over this many features, far enough apart to be independent. */ + private static final double SPAN_IN_FEATURES = 200D; + private static final double STEP_X = 0.7548776662466927D; + private static final double STEP_Y = 0.5698402909980532D; + private static final double STEP_Z = 0.8191725133961645D; + private static final int LINES = 64; + private static final int LINE_SAMPLES = 128; + private static final double LINE_STEPS_PER_FEATURE = 16D; + private static final int FEWEST_CROSSINGS = 16; + + private final double[] sortedValues; + + private FieldStats(double[] sortedValues) { + this.sortedValues = sortedValues; + } + + /** Measures {@code field}, whose features are about {@code featureBlocks} blocks apart. */ + static FieldStats measure(Field3 field, double featureBlocks) { + double span = featureBlocks * SPAN_IN_FEATURES; + double[] values = new double[SAMPLES]; + for (int sample = 0; sample < SAMPLES; sample++) { + values[sample] = field.at(coordinate(sample, STEP_X, span), coordinate(sample, STEP_Y, span), coordinate(sample, STEP_Z, span)); + } + Arrays.sort(values); + return new FieldStats(values); + } + + /** + * How far apart the features of {@code field} lie in blocks, measured as the mean distance between two crossings + * of its middle value along horizontal lines. Lines are read in steps of a fraction of {@code expectedBlocks}, so a + * field far finer than expected measures too coarse; measuring again at the answer corrects that. Empty for a field + * that hardly crosses its middle, such as a level one. + */ + static OptionalDouble featureBlocks(Field3 field, double expectedBlocks) { + double step = expectedBlocks / LINE_STEPS_PER_FEATURE; + double span = expectedBlocks * SPAN_IN_FEATURES; + double[] values = new double[LINES * LINE_SAMPLES]; + for (int line = 0; line < LINES; line++) { + double startX = coordinate(line, STEP_X, span); + double y = coordinate(line, STEP_Y, span); + double startZ = coordinate(line, STEP_Z, span); + boolean alongX = (line & 1) == 0; + for (int sample = 0; sample < LINE_SAMPLES; sample++) { + double along = sample * step; + values[(line * LINE_SAMPLES) + sample] = alongX ? field.at(startX + along, y, startZ) : field.at(startX, y, startZ + along); + } + } + double[] sorted = values.clone(); + Arrays.sort(sorted); + double middle = sorted[sorted.length / 2]; + int crossings = 0; + for (int index = 1; index < values.length; index++) { + boolean sameLine = index % LINE_SAMPLES != 0; + if (sameLine && (values[index - 1] >= middle) != (values[index] >= middle)) { + crossings++; + } + } + if (crossings < FEWEST_CROSSINGS) { + return OptionalDouble.empty(); + } + double measuredLength = LINES * (LINE_SAMPLES - 1) * step; + return OptionalDouble.of(measuredLength / crossings); + } + + private static double coordinate(int sample, double step, double span) { + double fraction = (sample * step) % 1D; + return (fraction - 0.5D) * span; + } + + /** The value that {@code share} of the world lies above, from 0 to 1. */ + double valueAboveShare(double share) { + double clamped = Math.max(0D, Math.min(1D, share)); + int index = (int) Math.round((1D - clamped) * (sortedValues.length - 1)); + return sortedValues[index]; + } + + double highest() { + return sortedValues[sortedValues.length - 1]; + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/cave/field/HeightBand.java b/core/src/main/java/art/arcane/iris/generation/cave/field/HeightBand.java new file mode 100644 index 000000000..cbe6deef0 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/cave/field/HeightBand.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; + +/** + * The heights a carve is limited to, counted from the dimension's bottom and both included. A cave carved inside a + * band is the very cave it would be without one, cut off at the band's ends. + */ +public record HeightBand(int lowestY, int highestY) { + public static final HeightBand UNLIMITED = new HeightBand(Integer.MIN_VALUE, Integer.MAX_VALUE); +} diff --git a/core/src/main/java/art/arcane/iris/generation/cave/field/LatticeCell.java b/core/src/main/java/art/arcane/iris/generation/cave/field/LatticeCell.java new file mode 100644 index 000000000..5c6e42888 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/cave/field/LatticeCell.java @@ -0,0 +1,100 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.cave.field; + +/** + * One field's values at the eight corners of a lattice cell, and the value interpolated between them at any block of + * the cell. An interpolated value never leaves the range of the corners, so a shape can rule a whole cell out from + * {@link #lowest()} and {@link #highest()} without looking at its blocks. + */ +final class LatticeCell { + /** A face holds four corners, and opposite faces are one cell apart. */ + private static final double SLOPE_PER_FACE_SUM = 1D / (4D * ChunkLattice.CELL_BLOCKS); + + private double lowWestNorth; + private double lowWestSouth; + private double lowEastNorth; + private double lowEastSouth; + private double highWestNorth; + private double highWestSouth; + private double highEastNorth; + private double highEastSouth; + + void load(double[] values, ChunkLattice lattice, int cellX, int cellY, int cellZ) { + lowWestNorth = values[lattice.pointIndex(cellX, cellY, cellZ)]; + lowWestSouth = values[lattice.pointIndex(cellX, cellY, cellZ + 1)]; + lowEastNorth = values[lattice.pointIndex(cellX + 1, cellY, cellZ)]; + lowEastSouth = values[lattice.pointIndex(cellX + 1, cellY, cellZ + 1)]; + highWestNorth = values[lattice.pointIndex(cellX, cellY + 1, cellZ)]; + highWestSouth = values[lattice.pointIndex(cellX, cellY + 1, cellZ + 1)]; + highEastNorth = values[lattice.pointIndex(cellX + 1, cellY + 1, cellZ)]; + highEastSouth = values[lattice.pointIndex(cellX + 1, cellY + 1, cellZ + 1)]; + } + + double lowest() { + return Math.min(Math.min(Math.min(lowWestNorth, lowWestSouth), Math.min(lowEastNorth, lowEastSouth)), + Math.min(Math.min(highWestNorth, highWestSouth), Math.min(highEastNorth, highEastSouth))); + } + + double highest() { + return Math.max(Math.max(Math.max(lowWestNorth, lowWestSouth), Math.max(lowEastNorth, lowEastSouth)), + Math.max(Math.max(highWestNorth, highWestSouth), Math.max(highEastNorth, highEastSouth))); + } + + /** How far every value of the cell stays from zero; 0 when the cell may cross it. */ + double distanceFromZero() { + double lowest = lowest(); + if (lowest > 0D) { + return lowest; + } + double highest = highest(); + return highest < 0D ? -highest : 0D; + } + + /** How much the value changes per block towards higher X, averaged over the cell. */ + double slopeX() { + return ((lowEastNorth + lowEastSouth + highEastNorth + highEastSouth) + - (lowWestNorth + lowWestSouth + highWestNorth + highWestSouth)) * SLOPE_PER_FACE_SUM; + } + + /** How much the value changes per block upwards, averaged over the cell. */ + double slopeY() { + return ((highWestNorth + highWestSouth + highEastNorth + highEastSouth) + - (lowWestNorth + lowWestSouth + lowEastNorth + lowEastSouth)) * SLOPE_PER_FACE_SUM; + } + + /** How much the value changes per block towards higher Z, averaged over the cell. */ + double slopeZ() { + return ((lowWestSouth + lowEastSouth + highWestSouth + highEastSouth) + - (lowWestNorth + lowEastNorth + highWestNorth + highEastNorth)) * SLOPE_PER_FACE_SUM; + } + + /** The value at a block of the cell, each coordinate as its share of the way across the cell, from 0 to 1. */ + double at(double shareX, double shareY, double shareZ) { + double low = across(lowWestNorth, lowWestSouth, lowEastNorth, lowEastSouth, shareX, shareZ); + double high = across(highWestNorth, highWestSouth, highEastNorth, highEastSouth, shareX, shareZ); + return low + ((high - low) * shareY); + } + + private static double across(double westNorth, double westSouth, double eastNorth, double eastSouth, double shareX, double shareZ) { + double west = westNorth + ((westSouth - westNorth) * shareZ); + double east = eastNorth + ((eastSouth - eastNorth) * shareZ); + return west + ((east - west) * shareX); + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/cave/field/LatticeShape.java b/core/src/main/java/art/arcane/iris/generation/cave/field/LatticeShape.java new file mode 100644 index 000000000..c79083868 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/cave/field/LatticeShape.java @@ -0,0 +1,149 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.cave.field; + +import java.util.Arrays; + +/** + * A cave shape that reads smooth fields on a chunk's lattice and decides block by block from their interpolated + * values. The fields are interpolated, never the decision, so a passage thinner than a lattice cell survives: its + * fields still cross zero between the points. + */ +abstract class LatticeShape { + private static final ThreadLocal PASS = ThreadLocal.withInitial(Pass::new); + private static final double CELL_SHARE = 1D / ChunkLattice.CELL_BLOCKS; + + /** How many fields the shape reads. {@link Pass#cell} numbers them from 0. */ + protected abstract int fieldCount(); + + /** Reads every field of the shape at one block into {@code values}, one value per field. */ + protected abstract void readFields(int x, int y, int z, double[] values); + + /** Whether the shape can carve anywhere in the cell the pass has loaded, whatever the limits allow. */ + protected abstract boolean mayCarveIn(Pass pass); + + /** Whether the shape carves the block at these shares of the way across the loaded cell. */ + protected abstract boolean carvesAt(Pass pass, double shareX, double shareY, double shareZ, double openness, int column); + + final void carve(ChunkLattice lattice, CaveLimits limits, CarveSink sink) { + Pass pass = PASS.get(); + pass.begin(lattice, this); + for (int cellY = 0; cellY < lattice.cellsY(); cellY++) { + int bottomY = lattice.baseY() + (cellY * ChunkLattice.CELL_BLOCKS); + if (bottomY > limits.highestY() || bottomY + ChunkLattice.CELL_BLOCKS <= limits.lowestY()) { + continue; + } + for (int cellX = 0; cellX < ChunkLattice.CELLS_PER_CHUNK_AXIS; cellX++) { + for (int cellZ = 0; cellZ < ChunkLattice.CELLS_PER_CHUNK_AXIS; cellZ++) { + if (limits.cellIsClosed(cellX, cellZ, bottomY)) { + continue; + } + pass.load(cellX, cellY, cellZ); + if (mayCarveIn(pass)) { + carveCell(pass, limits, sink, cellX, bottomY, cellZ); + } + } + } + } + } + + private void carveCell(Pass pass, CaveLimits limits, CarveSink sink, int cellX, int bottomY, int cellZ) { + for (int stepY = 0; stepY < ChunkLattice.CELL_BLOCKS; stepY++) { + int y = bottomY + stepY; + if (y < limits.lowestY() || y > limits.highestY()) { + continue; + } + for (int stepX = 0; stepX < ChunkLattice.CELL_BLOCKS; stepX++) { + int localX = (cellX * ChunkLattice.CELL_BLOCKS) + stepX; + for (int stepZ = 0; stepZ < ChunkLattice.CELL_BLOCKS; stepZ++) { + int localZ = (cellZ * ChunkLattice.CELL_BLOCKS) + stepZ; + int column = (localX << 4) | localZ; + double openness = limits.openness(column, y); + if (openness > 0D && carvesAt(pass, stepX * CELL_SHARE, stepY * CELL_SHARE, stepZ * CELL_SHARE, openness, column)) { + sink.carve(localX, y, localZ); + } + } + } + } + } + + /** One chunk's carving by one shape on one thread: the sampled fields, the cell being decided and a value per column. */ + static final class Pass { + private static final int CHUNK_COLUMNS = 256; + private static final int CELL_VALUES = 12; + + private ChunkLattice lattice; + private double[] pointValues = new double[0]; + private double[][] values = new double[0][]; + private LatticeCell[] cells = new LatticeCell[0]; + private int fieldCount; + private final double[] columnValues = new double[CHUNK_COLUMNS]; + private final double[] cellValues = new double[CELL_VALUES]; + + private void begin(ChunkLattice lattice, LatticeShape shape) { + this.lattice = lattice; + this.fieldCount = shape.fieldCount(); + if (values.length < fieldCount) { + values = Arrays.copyOf(values, fieldCount); + cells = Arrays.copyOf(cells, fieldCount); + pointValues = new double[fieldCount]; + } + int points = lattice.pointCount(); + for (int field = 0; field < fieldCount; field++) { + if (values[field] == null || values[field].length < points) { + values[field] = new double[points]; + } + if (cells[field] == null) { + cells[field] = new LatticeCell(); + } + } + lattice.forEachPoint((index, x, y, z) -> { + shape.readFields(x, y, z, pointValues); + for (int field = 0; field < fieldCount; field++) { + values[field][index] = pointValues[field]; + } + }); + Arrays.fill(columnValues, Double.NaN); + } + + private void load(int cellX, int cellY, int cellZ) { + for (int field = 0; field < fieldCount; field++) { + cells[field].load(values[field], lattice, cellX, cellY, cellZ); + } + } + + LatticeCell cell(int field) { + return cells[field]; + } + + ChunkLattice lattice() { + return lattice; + } + + /** A value the shape keeps per column of the chunk for the length of the pass; NaN until the shape sets it. */ + double[] columnValues() { + return columnValues; + } + + /** Values the shape works out in {@link LatticeShape#mayCarveIn} for the blocks of the loaded cell. */ + double[] cellValues() { + return cellValues; + } + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/cave/field/NoiseFactory.java b/core/src/main/java/art/arcane/iris/generation/cave/field/NoiseFactory.java new file mode 100644 index 000000000..db78f6647 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/cave/field/NoiseFactory.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; + +import art.arcane.iris.generation.noise.IrisGeneratorStyle; + +/** Builds the noise of the styles a cave's pack writes. The same style and seed give the same values every time. */ +@FunctionalInterface +public interface NoiseFactory { + NoiseSampler sampler(IrisGeneratorStyle style, long seed); +} diff --git a/core/src/main/java/art/arcane/iris/generation/cave/field/NoiseSampler.java b/core/src/main/java/art/arcane/iris/generation/cave/field/NoiseSampler.java new file mode 100644 index 000000000..3c8a4c25b --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/cave/field/NoiseSampler.java @@ -0,0 +1,44 @@ +/* + * 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; + +/** Noise a cave field reads, built from one pack style and one seed. Safe for concurrent reads. */ +public interface NoiseSampler { + /** The noise at a column, from 0 to 1. */ + double sample(double worldX, double worldZ); + + /** The noise at a block, from 0 to 1. */ + double sample(double worldX, double y, double worldZ); + + /** The noise at a column, from -1 to 1. */ + default double signed(double worldX, double worldZ) { + return sample(worldX, worldZ) * 2D - 1D; + } + + /** The noise at a block, from -1 to 1. */ + default double signed(double worldX, double y, double worldZ) { + return sample(worldX, y, worldZ) * 2D - 1D; + } + + /** + * This noise with its coordinates multiplied by {@code factor}: above 1 squeezes the pattern, below 1 stretches it. + * The factor is folded into the generator's own scale, so a fracture still moves the noise in blocks. + */ + NoiseSampler scaled(double factor); +} diff --git a/core/src/main/java/art/arcane/iris/generation/cave/field/TunnelShape.java b/core/src/main/java/art/arcane/iris/generation/cave/field/TunnelShape.java new file mode 100644 index 000000000..4ee52b3db --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/cave/field/TunnelShape.java @@ -0,0 +1,411 @@ +/* + * 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; + +import art.arcane.iris.generation.cave.CaveTunnel; +import art.arcane.iris.generation.cave.CaveTunnelCoverage; +import art.arcane.iris.generation.cave.CaveValue; +import art.arcane.iris.generation.noise.IrisGeneratorStyle; + +/** + * Tunnels: the lines along which two of three fields are both zero. Each field is zero on winding sheets through the + * rock and two sheets meet in a line, which never ends on its own, so tunnels are long. Every line runs inside two + * sheets and sooner or later crosses the third, and there all three lines meet: that is a junction, and it is what + * joins the tunnels into one network. + * + *

A tunnel is every block within its radius of a line. The distance is worked out in blocks from how steeply the + * fields change in the cell, so a tunnel keeps the width the pack asks for wherever the noise is steep or shallow. + * An oval tunnel measures the distance with the vertical axis stretched by its width over its height, which keeps its + * width and gives it its height. The fields are read at warped places, which makes a tunnel's path bend without ever + * breaking it. + */ +final class TunnelShape extends LatticeShape { + private static final int SHEETS = 3; + private static final int NOT_READ = -1; + private static final int[] PAIR_FIRST = {0, 0, 1}; + private static final int[] PAIR_SECOND = {1, 2, 2}; + private static final int PAIRS = PAIR_FIRST.length; + /** A round tunnel keeps, per pair of sheets, the three terms of its squared distance from their line and whether it is near. */ + private static final int ROUND_VALUES_PER_PAIR = 4; + private static final int FIRST_SQUARED = 0; + private static final int FIRST_TIMES_SECOND = 1; + private static final int SECOND_SQUARED = 2; + private static final int PAIR_IS_NEAR = 3; + /** An oval tunnel keeps each sheet's slope along the three axes, then whether each pair is near. */ + private static final int OVAL_SLOPE_X = 0; + private static final int OVAL_SLOPE_Y = 1; + private static final int OVAL_SLOPE_Z = 2; + private static final int OVAL_VALUES_PER_SHEET = 3; + private static final int OVAL_PAIR_IS_NEAR = SHEETS * OVAL_VALUES_PER_SHEET; + /** An oval tunnel's terms depend on its height over its width at the block, so they are worked out block by block here. */ + private static final ThreadLocal OVAL_TERMS = ThreadLocal.withInitial(() -> new double[PAIR_IS_NEAR]); + private static final double NEAR = 1D; + private static final double FAR = 0D; + private static final double ROUND = 1D; + /** Without a warp, a path shifts by this share of the horizontal spacing, and changes direction this many times per spacing. */ + private static final double DEFAULT_WARP_SHARE_OF_SPACING = 0.06D; + private static final double DEFAULT_WARPS_PER_SPACING = 3D; + private static final double SMALLEST_DEFAULT_WARP_SPACING_BLOCKS = 16D; + /** Without a coverage style, the areas with tunnels are this many horizontal spacings across. */ + private static final double DEFAULT_PRESENCE_SPACINGS = 3D; + /** + * Field value over which tunnels widen from nothing to full size at the edge of an area that has them, at a + * softness of 1. A softness of 0 still keeps the least edge, so the share never divides by zero. + */ + private static final double SOFTEST_PRESENCE_EDGE = 0.5D; + private static final double LEAST_PRESENCE_EDGE = 0.005D; + /** Where the share of an area's tunnels is worked out at the lattice points, a block divides by nothing and subtracts nothing. */ + private static final double PRESENCE_WORKED_OUT_AT_POINTS = 0D; + private static final double EDGE_WORKED_OUT_AT_POINTS = 1D; + /** A tunnel narrower or lower than this is not a passage any more, so it ends instead. */ + private static final double NARROWEST_RADIUS_BLOCKS = 1D; + /** A cell's slope is an average, so a cell is only ruled out when the line is clearly further than the widest tunnel. */ + private static final double CELL_REACH_SLACK = 1.5D; + /** + * Where a field is nearly flat, a small value says little about how far its sheet is, and the tunnel would swell + * into a blob. A field counts as changing at least this share of its typical slope. + */ + private static final double LEAST_SLOPE_SHARE = 0.45D; + /** Where two sheets run nearly side by side the line between them is ill-defined; they count as crossing at least this squarely. */ + private static final double LEAST_CROSSING = 0.03D; + + private final Field3[] sheets = new Field3[SHEETS]; + private final Field3 warpX; + private final Field3 warpY; + private final Field3 warpZ; + private final double warpBlocks; + private final ValueField verticalWarp; + private final Field3 width; + private final double narrowRadius; + private final double wideRadius; + private final TunnelHeight heightKind; + private final boolean oval; + private final double lowRadius; + private final double tallRadius; + private final ValueField height; + private final Field3 presence; + private final FieldStats presenceStats; + private final ValueField presenceShare; + private final ValueField presenceSoftness; + private final boolean presenceWorkedOutAtPoints; + private final double presenceThreshold; + private final double presenceEdge; + private final int widthField; + private final int heightField; + private final int presenceField; + private final int fieldCount; + private final double leastSteepness; + + /** How tall a tunnel is against how wide. */ + private enum TunnelHeight { + /** As tall as it is wide. */ + ROUND, + /** Between its low and tall height, as far as it is between its narrow and wide width. */ + FOLLOWS_WIDTH, + /** The height its own noise picks. */ + OWN_NOISE + } + + TunnelShape(CaveNoise noise, CaveTunnel tunnel) { + double spacing = tunnel.spacing().horizontal(); + double verticalSpacing = tunnel.spacing().vertical(); + double valueChangeBlocks = spacing * CaveTunnel.VALUE_CHANGE_SPACINGS; + for (int sheet = 0; sheet < SHEETS; sheet++) { + sheets[sheet] = noise.smooth(spacing, verticalSpacing); + } + this.verticalWarp = ValueField.inBlocks(tunnel.verticalWarp(), noise, "tunnel.verticalWarp", valueChangeBlocks); + IrisGeneratorStyle warp = tunnel.warp().orElse(null); + if (warp == null) { + double warpSpacing = Math.max(SMALLEST_DEFAULT_WARP_SPACING_BLOCKS, spacing / DEFAULT_WARPS_PER_SPACING); + this.warpX = noise.smooth(warpSpacing, warpSpacing); + this.warpY = noise.smooth(warpSpacing, warpSpacing); + this.warpZ = noise.smooth(warpSpacing, warpSpacing); + this.warpBlocks = spacing * DEFAULT_WARP_SHARE_OF_SPACING; + } else { + this.warpX = noise.inBlocks(warp); + this.warpY = noise.inBlocks(warp); + this.warpZ = noise.inBlocks(warp); + this.warpBlocks = warp.isFlat() ? 0D : warp.getMultiplier() / 2D; + } + CaveValue widthValue = tunnel.width(); + double widthChangeBlocks = spacing * CaveTunnel.WIDTH_CHANGE_SPACINGS; + this.width = widthValue.style().map(noise::inBlocks).orElseGet(() -> noise.smooth(widthChangeBlocks, widthChangeBlocks)); + this.narrowRadius = widthValue.lowest() / 2D; + this.wideRadius = widthValue.highest() / 2D; + CaveValue heightValue = tunnel.height().orElse(null); + this.heightKind = heightKindOf(heightValue); + this.oval = heightKind != TunnelHeight.ROUND; + this.lowRadius = heightValue == null ? 0D : heightValue.lowest() / 2D; + this.tallRadius = heightValue == null ? 0D : heightValue.highest() / 2D; + this.height = heightKind == TunnelHeight.OWN_NOISE + ? ValueField.inBlocks(heightValue, noise, "tunnel.height", widthChangeBlocks) + : null; + double leastSlope = CaveNoise.typicalSlope(spacing) * LEAST_SLOPE_SHARE; + this.leastSteepness = leastSlope * leastSlope; + CaveTunnelCoverage coverage = tunnel.coverage(); + this.presenceShare = ValueField.inBlocks(coverage.share(), noise, "tunnel.coverage.share", valueChangeBlocks); + this.presenceSoftness = ValueField.inBlocks(coverage.softness(), noise, "tunnel.coverage.softness", valueChangeBlocks); + this.presenceWorkedOutAtPoints = presenceShare.varies() || presenceSoftness.varies(); + boolean heightReadsTheWidthNoise = heightKind == TunnelHeight.FOLLOWS_WIDTH && heightValue.varies(); + boolean readsWidth = widthValue.varies() || heightReadsTheWidthNoise; + this.widthField = readsWidth ? SHEETS : NOT_READ; + int nextField = readsWidth ? SHEETS + 1 : SHEETS; + this.heightField = height == null ? NOT_READ : nextField++; + if (presenceShare.lowest() >= 1D) { + this.presence = null; + this.presenceStats = null; + this.presenceThreshold = Double.NEGATIVE_INFINITY; + this.presenceEdge = EDGE_WORKED_OUT_AT_POINTS; + this.presenceField = NOT_READ; + this.fieldCount = nextField; + return; + } + double presenceSpacing = spacing * DEFAULT_PRESENCE_SPACINGS; + IrisGeneratorStyle presenceStyle = coverage.style().orElse(null); + this.presence = presenceStyle == null ? noise.smooth(presenceSpacing, presenceSpacing) : noise.inBlocks(presenceStyle); + double presenceFeatureBlocks = presenceStyle == null ? presenceSpacing : CaveNoise.featureBlocks(presence, presenceStyle); + this.presenceStats = FieldStats.measure(presence, presenceFeatureBlocks); + this.presenceThreshold = presenceWorkedOutAtPoints ? PRESENCE_WORKED_OUT_AT_POINTS : presenceStats.valueAboveShare(presenceShare.min()); + this.presenceEdge = presenceWorkedOutAtPoints ? EDGE_WORKED_OUT_AT_POINTS : presenceEdgeOf(presenceSoftness.min()); + this.presenceField = nextField++; + this.fieldCount = nextField; + } + + private static TunnelHeight heightKindOf(CaveValue height) { + if (height == null) { + return TunnelHeight.ROUND; + } + return height.varies() && height.style().isPresent() ? TunnelHeight.OWN_NOISE : TunnelHeight.FOLLOWS_WIDTH; + } + + private static double presenceEdgeOf(double softness) { + return Math.max(LEAST_PRESENCE_EDGE, softness * SOFTEST_PRESENCE_EDGE); + } + + @Override + protected int fieldCount() { + return fieldCount; + } + + @Override + protected void readFields(int x, int y, int z, double[] values) { + readSheets(x, y, z, values); + if (widthField != NOT_READ) { + values[widthField] = width.at(x, y, z); + } + if (heightField != NOT_READ) { + values[heightField] = height.at(x, y, z); + } + if (presenceField != NOT_READ) { + values[presenceField] = presenceAt(x, y, z); + } + } + + /** + * The presence field, or where share or softness vary, how far into an area with tunnels the point lies in + * edges: the threshold and edge are only known point by point then. + */ + private double presenceAt(int x, int y, int z) { + double value = presence.at(x, y, z); + if (!presenceWorkedOutAtPoints) { + return value; + } + double threshold = presenceStats.valueAboveShare(presenceShare.at(x, y, z)); + return (value - threshold) / presenceEdgeOf(presenceSoftness.at(x, y, z)); + } + + private void readSheets(int x, int y, int z, double[] values) { + if (warpBlocks == 0D) { + for (int sheet = 0; sheet < SHEETS; sheet++) { + values[sheet] = sheets[sheet].at(x, y, z); + } + return; + } + double warpedX = x + (warpX.at(x, y, z) * warpBlocks); + double warpedY = y + (warpY.at(x, y, z) * warpBlocks * verticalWarp.at(x, y, z)); + double warpedZ = z + (warpZ.at(x, y, z) * warpBlocks); + for (int sheet = 0; sheet < SHEETS; sheet++) { + values[sheet] = sheets[sheet].at(warpedX, warpedY, warpedZ); + } + } + + @Override + protected boolean mayCarveIn(Pass pass) { + if (presence != null && pass.cell(presenceField).highest() <= presenceThreshold) { + return false; + } + double reach = Math.max(wideRadius, tallRadius) * CELL_REACH_SLACK; + double[] cellValues = pass.cellValues(); + if (oval) { + keepSlopes(pass, cellValues); + } + boolean anyPairNear = false; + for (int pair = 0; pair < PAIRS; pair++) { + LatticeCell first = pass.cell(PAIR_FIRST[pair]); + LatticeCell second = pass.cell(PAIR_SECOND[pair]); + boolean near = isNear(first, reach) && isNear(second, reach); + if (near && !oval) { + keepTerms(first, second, ROUND, cellValues, pair * ROUND_VALUES_PER_PAIR); + } + cellValues[nearIndex(pair)] = near ? NEAR : FAR; + anyPairNear |= near; + } + return anyPairNear; + } + + private int nearIndex(int pair) { + return oval ? OVAL_PAIR_IS_NEAR + pair : (pair * ROUND_VALUES_PER_PAIR) + PAIR_IS_NEAR; + } + + /** Whether the sheet of a field may come within {@code reach} blocks of the cell. */ + private boolean isNear(LatticeCell cell, double reach) { + double fieldDistance = cell.distanceFromZero(); + double squaredSlope = Math.max(squaredSlope(cell, ROUND), leastSteepness); + return fieldDistance * fieldDistance <= reach * reach * squaredSlope; + } + + private static void keepSlopes(Pass pass, double[] cellValues) { + for (int sheet = 0; sheet < SHEETS; sheet++) { + LatticeCell cell = pass.cell(sheet); + int offset = sheet * OVAL_VALUES_PER_SHEET; + cellValues[offset + OVAL_SLOPE_X] = cell.slopeX(); + cellValues[offset + OVAL_SLOPE_Y] = cell.slopeY(); + cellValues[offset + OVAL_SLOPE_Z] = cell.slopeZ(); + } + } + + /** + * Works out, for the line where two sheets meet, the terms that turn the two field values at a block into its + * squared distance from that line in blocks, with the vertical axis squeezed by {@code verticalScale}. + */ + private void keepTerms(LatticeCell first, LatticeCell second, double verticalScale, double[] terms, int offset) { + keepTerms(first.slopeX(), first.slopeY(), first.slopeZ(), second.slopeX(), second.slopeY(), second.slopeZ(), verticalScale, terms, offset); + } + + private void keepTerms(double firstX, double firstY, double firstZ, double secondX, double secondY, double secondZ, + double verticalScale, double[] terms, int offset) { + double squaredScale = verticalScale * verticalScale; + double firstSteepness = Math.max((firstX * firstX) + (squaredScale * firstY * firstY) + (firstZ * firstZ), leastSteepness); + double secondSteepness = Math.max((secondX * secondX) + (squaredScale * secondY * secondY) + (secondZ * secondZ), leastSteepness); + double together = (firstX * secondX) + (squaredScale * firstY * secondY) + (firstZ * secondZ); + double crossing = Math.max((firstSteepness * secondSteepness) - (together * together), firstSteepness * secondSteepness * LEAST_CROSSING); + terms[offset + FIRST_SQUARED] = secondSteepness / crossing; + terms[offset + FIRST_TIMES_SECOND] = (-2D * together) / crossing; + terms[offset + SECOND_SQUARED] = firstSteepness / crossing; + } + + private static double squaredSlope(LatticeCell cell, double verticalScale) { + double squaredScale = verticalScale * verticalScale; + return (cell.slopeX() * cell.slopeX()) + (squaredScale * cell.slopeY() * cell.slopeY()) + (cell.slopeZ() * cell.slopeZ()); + } + + @Override + protected boolean carvesAt(Pass pass, double shareX, double shareY, double shareZ, double openness, int column) { + double widthShare = widthShareAt(pass, shareX, shareY, shareZ); + double sizeShare = presenceShareAt(pass, shareX, shareY, shareZ); + double radius = ((narrowRadius + ((wideRadius - narrowRadius) * widthShare)) * sizeShare) * openness; + if (radius < NARROWEST_RADIUS_BLOCKS) { + return false; + } + if (!oval) { + return isWithinRoundTunnel(pass, shareX, shareY, shareZ, radius); + } + double heightRadius = (fullHeightRadiusAt(pass, shareX, shareY, shareZ, widthShare) * sizeShare) * openness; + if (heightRadius < NARROWEST_RADIUS_BLOCKS) { + return false; + } + return isWithinOvalTunnel(pass, shareX, shareY, shareZ, radius, heightRadius); + } + + private boolean isWithinRoundTunnel(Pass pass, double shareX, double shareY, double shareZ, double radius) { + double squaredRadius = radius * radius; + double[] terms = pass.cellValues(); + for (int pair = 0; pair < PAIRS; pair++) { + int offset = pair * ROUND_VALUES_PER_PAIR; + if (terms[offset + PAIR_IS_NEAR] == FAR) { + continue; + } + if (squaredBlocksFromLine(pass, pair, terms, offset, shareX, shareY, shareZ) < squaredRadius) { + return true; + } + } + return false; + } + + /** + * Measures with the vertical axis stretched by the tunnel's width over its height, where the oval is a circle as + * wide as the tunnel: a field's upward slope shrinks by the same share. + */ + private boolean isWithinOvalTunnel(Pass pass, double shareX, double shareY, double shareZ, double radius, double heightRadius) { + double squaredRadius = radius * radius; + double verticalScale = heightRadius / radius; + double[] cellValues = pass.cellValues(); + double[] terms = OVAL_TERMS.get(); + for (int pair = 0; pair < PAIRS; pair++) { + if (cellValues[OVAL_PAIR_IS_NEAR + pair] == FAR) { + continue; + } + int first = PAIR_FIRST[pair] * OVAL_VALUES_PER_SHEET; + int second = PAIR_SECOND[pair] * OVAL_VALUES_PER_SHEET; + keepTerms(cellValues[first + OVAL_SLOPE_X], cellValues[first + OVAL_SLOPE_Y], cellValues[first + OVAL_SLOPE_Z], + cellValues[second + OVAL_SLOPE_X], cellValues[second + OVAL_SLOPE_Y], cellValues[second + OVAL_SLOPE_Z], + verticalScale, terms, 0); + if (squaredBlocksFromLine(pass, pair, terms, 0, shareX, shareY, shareZ) < squaredRadius) { + return true; + } + } + return false; + } + + private static double squaredBlocksFromLine(Pass pass, int pair, double[] terms, int offset, double shareX, double shareY, double shareZ) { + double first = pass.cell(PAIR_FIRST[pair]).at(shareX, shareY, shareZ); + double second = pass.cell(PAIR_SECOND[pair]).at(shareX, shareY, shareZ); + return (terms[offset + FIRST_SQUARED] * first * first) + + (terms[offset + FIRST_TIMES_SECOND] * first * second) + + (terms[offset + SECOND_SQUARED] * second * second); + } + + /** How far between its narrow and its wide width the tunnel is at the block, from 0 to 1; 0 where the width is fixed. */ + private double widthShareAt(Pass pass, double shareX, double shareY, double shareZ) { + if (widthField == NOT_READ) { + return 0D; + } + return ValueField.shareAt(pass.cell(widthField).at(shareX, shareY, shareZ)); + } + + /** Half the height of an oval tunnel at the block, before it narrows at the edges of its areas and limits. */ + private double fullHeightRadiusAt(Pass pass, double shareX, double shareY, double shareZ, double widthShare) { + if (heightKind == TunnelHeight.OWN_NOISE) { + return pass.cell(heightField).at(shareX, shareY, shareZ) / 2D; + } + return lowRadius + ((tallRadius - lowRadius) * widthShare); + } + + /** How far the block lies into an area with tunnels: 1 inside, falling to 0 over the edge. */ + private double presenceShareAt(Pass pass, double shareX, double shareY, double shareZ) { + if (presence == null) { + return 1D; + } + return clampToShare((pass.cell(presenceField).at(shareX, shareY, shareZ) - presenceThreshold) / presenceEdge); + } + + private static double clampToShare(double value) { + return Math.max(0D, Math.min(1D, value)); + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/cave/field/ValueField.java b/core/src/main/java/art/arcane/iris/generation/cave/field/ValueField.java new file mode 100644 index 000000000..cec3bba57 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/cave/field/ValueField.java @@ -0,0 +1,113 @@ +/* + * 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; + +import art.arcane.iris.generation.cave.CaveValue; + +/** + * A {@link CaveValue} ready to read at a place: the same number everywhere, or the number its noise picks there. The + * noise's middle picks the middle of the range and the value reaches min and max half a unit either side of it, so a + * range has stretches at each end as well as the slopes between them. + */ +final class ValueField { + private static final double MIDDLE_SHARE = 0.5D; + + private final double min; + private final double max; + private final Field3 noise; + + private ValueField(double min, double max, Field3 noise) { + this.min = min; + this.max = max; + this.noise = noise; + } + + static ValueField constant(double value) { + return new ValueField(value, value, null); + } + + /** + * {@code value} read in 3D, under its own seed of {@code name}. Without a style it changes over about + * {@code changeBlocks} blocks in every direction. + */ + static ValueField inBlocks(CaveValue value, CaveNoise caveNoise, String name, double changeBlocks) { + if (!value.varies()) { + return constant(value.min()); + } + CaveNoise noise = caveNoise.named(name); + Field3 field = value.style().map(noise::inBlocks).orElseGet(() -> noise.smooth(changeBlocks, changeBlocks)); + return new ValueField(value.min(), value.max(), field); + } + + /** {@link #inBlocks} for a value that only varies over X and Z. */ + static ValueField inColumns(CaveValue value, CaveNoise caveNoise, String name, double changeBlocks) { + if (!value.varies()) { + return constant(value.min()); + } + CaveNoise noise = caveNoise.named(name); + Field3 field = value.style().map(noise::columnsInBlocks).orElseGet(() -> noise.columns(changeBlocks)); + return new ValueField(value.min(), value.max(), field); + } + + /** The share of the way from min to max that a noise value picks, from 0 to 1. */ + static double shareAt(double signedNoise) { + return Math.max(0D, Math.min(1D, MIDDLE_SHARE + signedNoise)); + } + + boolean varies() { + return noise != null; + } + + double min() { + return min; + } + + double max() { + return max; + } + + double middle() { + return (min + max) / 2D; + } + + double lowest() { + return Math.min(min, max); + } + + double highest() { + return Math.max(min, max); + } + + double at(double x, double y, double z) { + if (noise == null) { + return min; + } + return min + ((max - min) * shareAt(noise.at(x, y, z))); + } + + /** How far from min towards max the value is here, from 0 to 1; 0 where it does not vary. */ + double share(double x, double y, double z) { + return noise == null ? 0D : shareAt(noise.at(x, y, z)); + } + + /** {@link #at} for a value read in columns. */ + double at(double x, double z) { + return at(x, 0D, z); + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/cave/field/VaryingScale.java b/core/src/main/java/art/arcane/iris/generation/cave/field/VaryingScale.java new file mode 100644 index 000000000..575b7c293 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/cave/field/VaryingScale.java @@ -0,0 +1,71 @@ +/* + * 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; + +/** + * A field whose features' size varies from place to place. A noise read at a scale that changes along the way shears + * and tears, so the scale a field is read at never changes: a field is built at the smallest and at the largest size + * and the two are blended, horizontal and vertical sizes alike. Each size that varies doubles the fields read. + */ +final class VaryingScale { + /** Builds a field whose features lie about {@code horizontal} blocks apart sideways and {@code vertical} blocks apart upwards. */ + @FunctionalInterface + interface Builder { + Field3 build(CaveNoise noise, double horizontal, double vertical); + } + + private VaryingScale() { + } + + /** + * The field {@code builder} makes at the sizes {@code horizontal} and {@code vertical} pick. The smallest field + * takes the seeds of {@code noise}, so a field whose sizes are plain numbers is exactly the one the builder makes; + * the others are seeded by {@code name}. + */ + static Field3 of(CaveNoise noise, ValueField horizontal, ValueField vertical, String name, Builder builder) { + Field3 lowest = alongHorizontal(noise, horizontal, vertical.min(), name, builder); + if (!vertical.varies()) { + return lowest; + } + Field3 tallest = alongHorizontal(noise.named(name + ".tallest"), horizontal, vertical.max(), name, builder); + return blended(lowest, tallest, vertical); + } + + private static Field3 alongHorizontal(CaveNoise noise, ValueField horizontal, double vertical, String name, Builder builder) { + Field3 smallest = builder.build(noise, horizontal.min(), vertical); + if (!horizontal.varies()) { + return smallest; + } + Field3 largest = builder.build(noise.named(name + ".largest"), horizontal.max(), vertical); + return blended(smallest, largest, horizontal); + } + + /** + * {@code atMin} where {@code scale} is at its min, {@code atMax} where it is at its max, and both in between, + * weighted so the blend spreads as far as either field alone and a threshold keeps its share. + */ + private static Field3 blended(Field3 atMin, Field3 atMax, ValueField scale) { + return (x, y, z) -> { + double towardsMax = scale.share(x, y, z); + double towardsMin = 1D - towardsMax; + double spread = Math.sqrt((towardsMin * towardsMin) + (towardsMax * towardsMax)); + return ((atMin.at(x, y, z) * towardsMin) + (atMax.at(x, y, z) * towardsMax)) / spread; + }; + } +} diff --git a/core/src/test/java/art/arcane/iris/generation/cave/field/CarvedArea.java b/core/src/test/java/art/arcane/iris/generation/cave/field/CarvedArea.java new file mode 100644 index 000000000..98d83de5b --- /dev/null +++ b/core/src/test/java/art/arcane/iris/generation/cave/field/CarvedArea.java @@ -0,0 +1,220 @@ +package art.arcane.iris.generation.cave.field; + +import art.arcane.iris.generation.cave.IrisCave; +import art.arcane.iris.generation.cave.TestSettings; + +import java.util.ArrayDeque; +import java.util.Arrays; +import java.util.BitSet; +import java.util.function.IntPredicate; + +/** + * The blocks a cave carves in a square of chunks under a flat surface, in a world from Y 0 to 256, with measurements of + * their shape: shares, runs along an axis and connected pieces. Blocks are indexed by {@link #index}. + */ +final class CarvedArea { + static final int WORLD_BOTTOM_Y = 0; + static final int WORLD_HEIGHT = 256; + static final int SURFACE_Y = 160; + static final int LAYERS = SURFACE_Y + 1; + + final int size; + final BitSet carved; + + private CarvedArea(int size, BitSet carved) { + this.size = size; + this.carved = carved; + } + + static CarvedArea carve(NoiseFactory noise, String caveJson, long seed, int chunks) { + return carveAt(noise, caveJson, seed, chunks, 0, 0); + } + + /** {@link #carve} of the square whose first block is {@code offsetX}, {@code offsetZ}; blocks are indexed from that corner. */ + static CarvedArea carveAt(NoiseFactory noise, String caveJson, long seed, int chunks, int offsetX, int offsetZ) { + CaveCarver carver = new CaveCarver(TestSettings.of(IrisCave.class, caveJson), noise, seed, WORLD_BOTTOM_Y, WORLD_HEIGHT); + int size = chunks * 16; + int[] surfaceY = new int[256]; + Arrays.fill(surfaceY, SURFACE_Y); + double[] weight = new double[256]; + Arrays.fill(weight, 1D); + boolean[] sealed = new boolean[256]; + BitSet carved = new BitSet(size * size * LAYERS); + for (int chunkX = 0; chunkX < chunks; chunkX++) { + for (int chunkZ = 0; chunkZ < chunks; chunkZ++) { + int originX = chunkX * 16; + int originZ = chunkZ * 16; + carver.carve(offsetX + originX, offsetZ + originZ, surfaceY, weight, sealed, + (localX, y, localZ) -> carved.set((y * size * size) + ((originZ + localZ) * size) + originX + localX)); + } + } + return new CarvedArea(size, carved); + } + + int index(int x, int y, int z) { + return (y * size * size) + (z * size) + x; + } + + int x(int block) { + return block % size; + } + + int z(int block) { + return (block / size) % size; + } + + int y(int block) { + return block / (size * size); + } + + /** {@code where}, tested once for every block of the area, for tests that ask it about every block more than once. */ + IntPredicate cached(IntPredicate where) { + BitSet holds = new BitSet(size * size * LAYERS); + for (int block = 0; block < size * size * LAYERS; block++) { + if (where.test(block)) { + holds.set(block); + } + } + return holds::get; + } + + /** Carved blocks among the blocks {@code where} takes, as a share of them. */ + double carvedShare(IntPredicate where) { + long inside = 0; + long carvedInside = 0; + for (int block = 0; block < size * size * LAYERS; block++) { + if (!where.test(block)) { + continue; + } + inside++; + if (carved.get(block)) { + carvedInside++; + } + } + return carvedInside / (double) Math.max(1, inside); + } + + /** Mean length of the unbroken runs of carved blocks along one axis, counting runs that start where {@code where} holds. */ + double meanRun(int stepX, int stepY, int stepZ, IntPredicate where) { + long blocks = 0; + long runs = 0; + for (int block = carved.nextSetBit(0); block >= 0; block = carved.nextSetBit(block + 1)) { + if (!where.test(block)) { + continue; + } + blocks++; + int previousX = x(block) - stepX; + int previousY = y(block) - stepY; + int previousZ = z(block) - stepZ; + boolean previousInside = previousX >= 0 && previousY >= 0 && previousZ >= 0; + if (!previousInside || !carved.get(index(previousX, previousY, previousZ))) { + runs++; + } + } + return blocks / (double) Math.max(1, runs); + } + + double horizontalMeanRun(IntPredicate where) { + return (meanRun(1, 0, 0, where) + meanRun(0, 0, 1, where)) / 2D; + } + + /** Share of the blocks either area carves that only one of them carves, among blocks {@code where} takes. */ + double differenceShare(CarvedArea other, IntPredicate where) { + long either = 0; + long onlyOne = 0; + for (int block = 0; block < size * size * LAYERS; block++) { + if (!where.test(block)) { + continue; + } + boolean mine = carved.get(block); + boolean theirs = other.carved.get(block); + if (mine || theirs) { + either++; + } + if (mine != theirs) { + onlyOne++; + } + } + return onlyOne / (double) Math.max(1, either); + } + + /** Pieces of carved blocks joined face to face, smaller than {@code blocks}. */ + int carvedPiecesSmallerThan(int blocks) { + return piecesSmallerThan(carved, blocks, false); + } + + /** Pieces of rock that touch no edge of the area and are smaller than {@code blocks}: rock left floating in the caves. */ + int floatingRockSmallerThan(int blocks) { + BitSet rock = (BitSet) carved.clone(); + rock.flip(0, size * size * LAYERS); + return piecesSmallerThan(rock, blocks, true); + } + + double largestPieceShare() { + int largest = 0; + for (int piece : pieceSizes(carved, false)) { + largest = Math.max(largest, piece); + } + return largest / (double) Math.max(1, carved.cardinality()); + } + + private int piecesSmallerThan(BitSet blocks, int limit, boolean onlyEnclosed) { + int count = 0; + for (int piece : pieceSizes(blocks, onlyEnclosed)) { + if (piece < limit) { + count++; + } + } + return count; + } + + /** Sizes of the face-joined pieces of {@code blocks}; with {@code onlyEnclosed}, of those touching no edge of the area. */ + private int[] pieceSizes(BitSet blocks, boolean onlyEnclosed) { + BitSet seen = new BitSet(blocks.size()); + ArrayDeque open = new ArrayDeque<>(); + int[] sizes = new int[0]; + int count = 0; + for (int root = blocks.nextSetBit(0); root >= 0; root = blocks.nextSetBit(root + 1)) { + if (seen.get(root)) { + continue; + } + int pieceSize = 0; + boolean touchesEdge = false; + seen.set(root); + open.add(root); + while (!open.isEmpty()) { + int block = open.poll(); + pieceSize++; + int x = x(block); + int z = z(block); + int y = y(block); + touchesEdge |= x == 0 || z == 0 || y == 0 || x == size - 1 || z == size - 1 || y == LAYERS - 1; + visit(blocks, seen, open, x + 1, y, z); + visit(blocks, seen, open, x - 1, y, z); + visit(blocks, seen, open, x, y + 1, z); + visit(blocks, seen, open, x, y - 1, z); + visit(blocks, seen, open, x, y, z + 1); + visit(blocks, seen, open, x, y, z - 1); + } + if (onlyEnclosed && touchesEdge) { + continue; + } + if (count == sizes.length) { + sizes = Arrays.copyOf(sizes, Math.max(16, count * 2)); + } + sizes[count++] = pieceSize; + } + return Arrays.copyOf(sizes, count); + } + + private void visit(BitSet blocks, BitSet seen, ArrayDeque open, int x, int y, int z) { + if (x < 0 || z < 0 || y < 0 || x >= size || z >= size || y >= LAYERS) { + return; + } + int block = index(x, y, z); + if (blocks.get(block) && !seen.get(block)) { + seen.set(block); + open.add(block); + } + } +} diff --git a/core/src/test/java/art/arcane/iris/generation/cave/field/CaveCarverTest.java b/core/src/test/java/art/arcane/iris/generation/cave/field/CaveCarverTest.java new file mode 100644 index 000000000..0c9299b2b --- /dev/null +++ b/core/src/test/java/art/arcane/iris/generation/cave/field/CaveCarverTest.java @@ -0,0 +1,456 @@ +package art.arcane.iris.generation.cave.field; + +import art.arcane.iris.generation.cave.IrisCave; +import art.arcane.iris.generation.cave.TestSettings; +import art.arcane.iris.generation.noise.IrisGeneratorStyle; +import org.junit.Test; + +import java.util.ArrayDeque; +import java.util.Arrays; +import java.util.BitSet; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +public class CaveCarverTest { + private static final int CHUNKS = 8; + private static final int SIZE = CHUNKS * 16; + private static final int SURFACE_Y = 160; + private static final int LAYERS = SURFACE_Y + 1; + private static final int WORLD_BOTTOM_Y = 0; + private static final int WORLD_HEIGHT = 256; + private static final long SEED = 91_277L; + private static final String TUNNELS = "{\"tunnel\": {\"width\": {\"min\": 4, \"max\": 6}, \"spacing\": {\"horizontal\": 48, \"vertical\": 34}}, \"opensToSurface\": true}"; + private static final String OPEN_CAVERN = "{\"cavern\": {\"size\": 40, \"height\": 18, \"coverage\": 0.3}}"; + + private final NoiseFactory noise = CngNoiseFactory.standalone(); + + /** + * Caves of the shapes packs write, each with the number of blocks it carves over the test area and a hash of which + * ones. Any change to the carving math or to the noise it reads moves them, which should never happen by accident. + */ + private static final List PINNED_CAVES = List.of( + "{\"tunnel\": {\"width\": {\"min\": 4, \"max\": 6}, \"spacing\": {\"horizontal\": 48, \"vertical\": 32}}, \"opensToSurface\": true}", + "{\"tunnel\": {\"width\": {\"min\": 3, \"max\": 6}, \"spacing\": {\"horizontal\": 64, \"vertical\": 32}, \"coverage\": {\"share\": 0.5}}, \"opensToSurface\": true}", + "{\"cavern\": {\"size\": 40, \"height\": 18, \"coverage\": 0.3, \"pillars\": {\"spacing\": 14, \"thickness\": 4}}}", + "{\"tunnel\": {\"width\": {\"min\": 3, \"max\": 5}, \"spacing\": {\"horizontal\": 40, \"vertical\": 32}, \"coverage\": {\"share\": 0.6}}," + + " \"cavern\": {\"size\": 32, \"height\": 14, \"coverage\": 0.12, \"pillars\": {\"spacing\": 12, \"thickness\": 3}}}", + "{\"cavern\": {\"size\": 110, \"height\": 40, \"coverage\": 0.18, \"pillars\": {\"spacing\": 26, \"thickness\": 5}}, \"fade\": 14, \"surfaceClearance\": 16}"); + private static final List PINNED_CARVES = List.of("240424:-1318169294", "50742:-1093329420", "573305:-908930314", "302656:552677736", "456345:1514141239"); + + @Test + public void pinnedCavesCarveTheSameBlocksOnEveryRun() { + List carves = PINNED_CAVES.stream().map(cave -> carve(cave, SEED, false)).map(carved -> carved.cardinality() + ":" + carved.hashCode()).toList(); + + assertEquals(PINNED_CARVES, carves); + } + + @Test + public void spelledOutStylesCarveRoughlyWhatTheirDefaultsCarve() { + String defaults = "{\"tunnel\": {\"width\": {\"min\": 2, \"max\": 3}, \"spacing\": {\"horizontal\": 64, \"vertical\": 53}, \"coverage\": {\"share\": 0.4}}, \"surfaceClearance\": 6}"; + String spelledOut = """ + {"tunnel": { + "width": {"min": 2, "max": 3, "style": {"style": "SIMPLEX", "zoom": 1.2}}, + "spacing": {"horizontal": 64, "vertical": 53}, + "warp": {"style": "SIMPLEX", "zoom": 0.25, "multiplier": 8}, + "coverage": {"share": 0.4, "style": {"style": "SIMPLEX", "zoom": 2.4}}}, + "surfaceClearance": 6} + """; + + int byDefaults = carve(defaults, SEED, false).cardinality(); + int bySpelledOut = carve(spelledOut, SEED, false).cardinality(); + + assertWithin("spelled out against defaults", bySpelledOut, byDefaults, 0.2D); + } + + @Test + public void theSameSeedCarvesTheSameCaveAndAnotherSeedADifferentOne() { + BitSet first = carve(TUNNELS, SEED, false); + + assertFalse(first.isEmpty()); + assertEquals(first, carve(TUNNELS, SEED, false)); + assertNotEquals(first, carve(TUNNELS, SEED + 1, false)); + } + + @Test + public void tunnelsJoinIntoOneNetwork() { + BitSet carved = carve(TUNNELS, SEED, false); + + double largestShare = largestConnectedShare(carved); + + assertTrue("largest connected share " + largestShare, largestShare > 0.7D); + } + + @Test + public void thinTunnelsSurviveBetweenTheLatticePoints() { + BitSet carved = carve(tunnel("\"width\": {\"min\": 2, \"max\": 3}, \"spacing\": {\"horizontal\": 48, \"vertical\": 34}"), SEED, false); + + double largestShare = largestConnectedShare(carved); + + assertTrue("largest connected share " + largestShare, largestShare > 0.5D); + } + + @Test + public void widerSpacingCarvesSparserTunnels() { + int close = carve(tunnel("\"spacing\": {\"horizontal\": 48, \"vertical\": 34}"), SEED, false).cardinality(); + int wide = carve(tunnel("\"spacing\": {\"horizontal\": 96, \"vertical\": 34}"), SEED, false).cardinality(); + + assertTrue(close + " close against " + wide + " wide", wide < close * 0.75D); + } + + @Test + public void closerVerticalSpacingStacksMoreTunnels() { + int far = carve(tunnel("\"spacing\": {\"horizontal\": 64, \"vertical\": 64}"), SEED, false).cardinality(); + int close = carve(tunnel("\"spacing\": {\"horizontal\": 64, \"vertical\": 24}"), SEED, false).cardinality(); + + assertTrue(far + " far apart against " + close + " close", close > far * 1.4D); + } + + @Test + public void aFlatWarpLeavesTheTunnelsWhereTheSheetsMeet() { + String spacing = "\"spacing\": {\"horizontal\": 48, \"vertical\": 34}, "; + BitSet flat = carve(tunnel(spacing + "\"warp\": {\"style\": \"FLAT\", \"multiplier\": 30}"), SEED, false); + BitSet barelyMoved = carve(tunnel(spacing + "\"warp\": {\"style\": \"SIMPLEX\", \"multiplier\": 0.0001}"), SEED, false); + BitSet swung = carve(tunnel(spacing + "\"warp\": {\"style\": \"SIMPLEX\", \"zoom\": 0.3, \"multiplier\": 16}"), SEED, false); + + assertTrue("a flat warp moves nothing: " + differenceShare(flat, barelyMoved), differenceShare(flat, barelyMoved) < 0.002D); + assertTrue("a warp moves the tunnels: " + differenceShare(flat, swung), differenceShare(flat, swung) > 0.5D); + } + + @Test + public void aLargerWarpMultiplierSwingsTheTunnelsFurther() { + String spacing = "\"spacing\": {\"horizontal\": 48, \"vertical\": 34}, "; + BitSet flat = carve(tunnel(spacing + "\"warp\": {}"), SEED, false); + BitSet small = carve(tunnel(spacing + "\"warp\": {\"style\": \"SIMPLEX\", \"zoom\": 0.3, \"multiplier\": 1}"), SEED, false); + BitSet large = carve(tunnel(spacing + "\"warp\": {\"style\": \"SIMPLEX\", \"zoom\": 0.3, \"multiplier\": 12}"), SEED, false); + + assertTrue(differenceShare(flat, small) < differenceShare(flat, large)); + } + + @Test + public void aWidthStyleDecidesWhereTunnelsAreNarrowOrWide() { + String spacing = "\"spacing\": {\"horizontal\": 48, \"vertical\": 34}, "; + BitSet slow = carve(tunnel(spacing + "\"width\": {\"min\": 2, \"max\": 8}"), SEED, false); + BitSet styled = carve(tunnel(spacing + "\"width\": {\"min\": 2, \"max\": 8, \"style\": {\"style\": \"SIMPLEX\", \"zoom\": 0.2}}"), SEED, false); + BitSet even = carve(tunnel(spacing + "\"width\": {\"min\": 5, \"max\": 5}"), SEED, false); + + assertTrue(differenceShare(slow, styled) > 0.2D); + assertTrue(differenceShare(slow, even) > 0.2D); + } + + @Test + public void aHeightAsLargeAsTheWidthCarvesRoundTunnels() { + String spacing = "\"spacing\": {\"horizontal\": 48, \"vertical\": 34}, "; + + BitSet round = carve(tunnel(spacing + "\"width\": {\"min\": 3, \"max\": 6}"), SEED, false); + BitSet ovalAsRound = carve(tunnel(spacing + "\"width\": {\"min\": 3, \"max\": 6}, \"height\": {\"min\": 3, \"max\": 6}"), SEED, false); + + assertEquals(round, ovalAsRound); + } + + /** + * Runs along an axis also cross sloping tunnels lengthwise, so they change less than the height does: a sloping + * tunnel's vertical chord is partly its length, and its horizontal runs grow with its height. + */ + @Test + public void aHeightChangesHowTallTunnelsAreRatherThanHowWide() { + String spacing = "\"spacing\": {\"horizontal\": 48, \"vertical\": 34}, "; + BitSet round = carve(tunnel(spacing + "\"width\": {\"min\": 6, \"max\": 6}"), SEED, false); + BitSet tall = carve(tunnel(spacing + "\"width\": {\"min\": 6, \"max\": 6}, \"height\": {\"min\": 12, \"max\": 12}"), SEED, false); + BitSet low = carve(tunnel(spacing + "\"width\": {\"min\": 6, \"max\": 6}, \"height\": {\"min\": 3, \"max\": 3}"), SEED, false); + + double tallHeight = meanRun(tall, 0, 1, 0) / meanRun(round, 0, 1, 0); + double tallWidth = horizontalMeanRun(tall) / horizontalMeanRun(round); + double lowHeight = meanRun(low, 0, 1, 0) / meanRun(round, 0, 1, 0); + double lowWidth = horizontalMeanRun(low) / horizontalMeanRun(round); + + assertTrue("tall: height " + tallHeight + ", width " + tallWidth, tallHeight > 1.3D && tallWidth < 1.15D); + assertTrue("low: height " + lowHeight + ", width " + lowWidth, lowHeight < 0.75D && lowWidth > 0.85D); + } + + @Test + public void aLowerCoverageShareLeavesMoreRockAndAStyleShapesWhere() { + String spacing = "\"spacing\": {\"horizontal\": 48, \"vertical\": 34}, "; + BitSet everywhere = carve(tunnel(spacing + "\"coverage\": {\"share\": 1}"), SEED, false); + BitSet half = carve(tunnel(spacing + "\"coverage\": {\"share\": 0.5}"), SEED, false); + BitSet styledHalf = carve(tunnel(spacing + "\"coverage\": {\"share\": 0.5, \"style\": {\"style\": \"SIMPLEX\", \"zoom\": 0.6}}"), SEED, false); + + assertTrue(half.cardinality() < everywhere.cardinality() * 0.8D); + assertTrue(styledHalf.cardinality() < everywhere.cardinality() * 0.8D); + assertTrue(differenceShare(half, styledHalf) > 0.2D); + } + + @Test + public void aRoomStyleIsScaledToTheRoomSize() { + IrisGeneratorStyle cellular = TestSettings.of(IrisGeneratorStyle.class, "{\"style\": \"CELLULAR\"}"); + IrisGeneratorStyle simplex = TestSettings.of(IrisGeneratorStyle.class, "{\"style\": \"SIMPLEX\", \"zoom\": 7}"); + + for (IrisGeneratorStyle style : List.of(cellular, simplex)) { + for (double spacing : new double[]{30D, 150D}) { + Field3 field = new CaveNoise(noise, SEED).scaledTo(style, spacing, spacing); + + double measured = FieldStats.featureBlocks(field, spacing).orElseThrow(); + + assertWithin(style + " at " + spacing, measured, spacing, 0.15D); + } + } + } + + @Test + public void aCavernWithAStyleCarvesItsShareInOtherRooms() { + String styled = "{\"cavern\": {\"size\": 40, \"height\": 18, \"coverage\": 0.3, \"style\": {\"style\": \"CELLULAR\", \"fracture\": {\"style\": \"SIMPLEX\", \"multiplier\": 12}}}}"; + + BitSet byDefault = carve(OPEN_CAVERN, SEED, false); + BitSet byStyle = carve(styled, SEED, false); + + assertWithin("styled against default", byStyle.cardinality(), byDefault.cardinality(), 0.5D); + assertTrue(differenceShare(byDefault, byStyle) > 0.5D); + } + + @Test + public void pillarsLeaveRockStandingInACavern() { + BitSet withoutPillars = carve(OPEN_CAVERN, SEED, false); + BitSet withPillars = carve(pillared("\"spacing\": 14, \"thickness\": 4"), SEED, false); + + assertTrue(withPillars.cardinality() < withoutPillars.cardinality()); + BitSet onlyWithPillars = (BitSet) withPillars.clone(); + onlyWithPillars.andNot(withoutPillars); + assertTrue("pillars only ever keep rock", onlyWithPillars.isEmpty()); + } + + @Test + public void pillarsWithoutVerticalAndFlareAreTheSameFromFloorToCeiling() { + BitSet open = carve(OPEN_CAVERN, SEED, false); + BitSet straight = carve(pillared("\"spacing\": 14, \"thickness\": 4, \"flare\": 1"), SEED, false); + + assertEquals(0, columnsPartlyKept(open, straight)); + assertTrue(open.cardinality() > straight.cardinality()); + } + + @Test + public void flarePillarsWidenTowardsFloorAndCeiling() { + BitSet straight = carve(pillared("\"spacing\": 14, \"thickness\": 4, \"flare\": 1"), SEED, false); + BitSet flared = carve(pillared("\"spacing\": 14, \"thickness\": 4, \"flare\": 6"), SEED, false); + BitSet open = carve(OPEN_CAVERN, SEED, false); + + assertTrue(flared.cardinality() < straight.cardinality()); + assertTrue(columnsPartlyKept(open, flared) > 0); + } + + @Test + public void verticalLetsPillarsChangeWithHeight() { + BitSet open = carve(OPEN_CAVERN, SEED, false); + BitSet changing = carve(pillared("\"spacing\": 14, \"thickness\": 4, \"flare\": 1, \"vertical\": 16"), SEED, false); + + assertTrue(columnsPartlyKept(open, changing) > 0); + BitSet onlyWithPillars = (BitSet) changing.clone(); + onlyWithPillars.andNot(open); + assertTrue("pillars only ever keep rock", onlyWithPillars.isEmpty()); + } + + @Test + public void aPillarStyleMovesThePillars() { + BitSet byDefault = carve(pillared("\"spacing\": 14, \"thickness\": 4"), SEED, false); + BitSet byStyle = carve(pillared("\"spacing\": 14, \"thickness\": 4, \"style\": {\"style\": \"CELLULAR\"}"), SEED, false); + BitSet open = carve(OPEN_CAVERN, SEED, false); + + assertNotEquals(byDefault, byStyle); + assertTrue(byStyle.cardinality() < open.cardinality()); + } + + @Test + public void aCaveOpensTheSurfaceOnlyWhereItMayAndKeepsItsRockElsewhere() { + String cave = "{\"tunnel\": {\"width\": {\"min\": 5, \"max\": 7}, \"spacing\": {\"horizontal\": 32, \"vertical\": 23}}, \"opensToSurface\": true, \"surfaceClearance\": 10}"; + + BitSet open = carve(cave, SEED, false); + BitSet sealed = carve(cave, SEED, true); + + assertTrue("an open cave reaches the surface somewhere", highestCarvedY(open) == SURFACE_Y); + assertTrue("a sealed cave keeps its clearance: " + highestCarvedY(sealed), highestCarvedY(sealed) <= SURFACE_Y - 10); + } + + @Test + public void aHeightBandCutsTheCaveOffAtItsEndsAndLeavesTheRestAsItWas() { + int lowestY = 60; + int highestY = 100; + BitSet whole = carve(TUNNELS, SEED, false); + + BitSet banded = carveWithin(TUNNELS, new HeightBand(lowestY, highestY), null); + + BitSet wholeInsideBand = whole.get(index(0, lowestY, 0), index(0, highestY + 1, 0)); + assertFalse(banded.isEmpty()); + assertEquals(wholeInsideBand, banded.get(index(0, lowestY, 0), index(0, highestY + 1, 0))); + assertEquals(lowestY, banded.nextSetBit(0) / (SIZE * SIZE)); + assertEquals(highestY, highestCarvedY(banded)); + } + + @Test + public void aCapKeepsTheCaveUnderItAndClosesItBeneath() { + int capY = 90; + int[] cap = new int[256]; + Arrays.fill(cap, capY); + + BitSet capped = carveWithin(TUNNELS, HeightBand.UNLIMITED, cap); + + assertFalse(capped.isEmpty()); + assertTrue("a capped cave stays under its cap: " + highestCarvedY(capped), highestCarvedY(capped) <= capY); + } + + private BitSet carveWithin(String caveJson, HeightBand band, int[] topLimitY) { + CaveCarver carver = new CaveCarver(TestSettings.of(IrisCave.class, caveJson), noise, SEED, WORLD_BOTTOM_Y, WORLD_HEIGHT); + int[] surfaceY = new int[256]; + Arrays.fill(surfaceY, SURFACE_Y); + double[] weight = new double[256]; + Arrays.fill(weight, 1D); + CaveCarver.ChunkColumns columns = new CaveCarver.ChunkColumns(surfaceY, weight, new boolean[256], topLimitY); + BitSet carved = new BitSet(SIZE * SIZE * LAYERS); + for (int chunkX = 0; chunkX < CHUNKS; chunkX++) { + for (int chunkZ = 0; chunkZ < CHUNKS; chunkZ++) { + int originX = chunkX * 16; + int originZ = chunkZ * 16; + carver.carve(originX, originZ, columns, band, (localX, y, localZ) -> carved.set(index(originX + localX, y, originZ + localZ))); + } + } + return carved; + } + + private static String tunnel(String keys) { + return "{\"tunnel\": {" + keys + "}, \"opensToSurface\": true}"; + } + + private static String pillared(String pillarKeys) { + return "{\"cavern\": {\"size\": 40, \"height\": 18, \"coverage\": 0.3, \"pillars\": {" + pillarKeys + "}}}"; + } + + private static void assertWithin(String what, double actual, double expected, double share) { + assertTrue(what + ": " + actual + " against " + expected, Math.abs(actual - expected) <= expected * share); + } + + private BitSet carve(String caveJson, long seed, boolean sealEveryColumn) { + CaveCarver carver = new CaveCarver(TestSettings.of(IrisCave.class, caveJson), noise, seed, WORLD_BOTTOM_Y, WORLD_HEIGHT); + int[] surfaceY = new int[256]; + Arrays.fill(surfaceY, SURFACE_Y); + double[] weight = new double[256]; + Arrays.fill(weight, 1D); + boolean[] sealed = new boolean[256]; + Arrays.fill(sealed, sealEveryColumn); + BitSet carved = new BitSet(SIZE * SIZE * LAYERS); + for (int chunkX = 0; chunkX < CHUNKS; chunkX++) { + for (int chunkZ = 0; chunkZ < CHUNKS; chunkZ++) { + int originX = chunkX * 16; + int originZ = chunkZ * 16; + carver.carve(originX, originZ, surfaceY, weight, sealed, (localX, y, localZ) -> carved.set(index(originX + localX, y, originZ + localZ))); + } + } + return carved; + } + + private static int index(int x, int y, int z) { + return (y * SIZE * SIZE) + (z * SIZE) + x; + } + + private static int highestCarvedY(BitSet carved) { + return (carved.length() - 1) / (SIZE * SIZE); + } + + /** Share of the blocks either set carves that only one of them carves. */ + private static double differenceShare(BitSet first, BitSet second) { + BitSet either = (BitSet) first.clone(); + either.or(second); + BitSet onlyOne = (BitSet) first.clone(); + onlyOne.xor(second); + return onlyOne.cardinality() / (double) Math.max(1, either.cardinality()); + } + + /** Columns where pillars keep some, but not all, of the blocks the open cavern carves. */ + private static int columnsPartlyKept(BitSet open, BitSet pillared) { + int partly = 0; + for (int x = 0; x < SIZE; x++) { + for (int z = 0; z < SIZE; z++) { + int kept = 0; + int carvedOpen = 0; + for (int y = 0; y < LAYERS; y++) { + int block = index(x, y, z); + if (!open.get(block)) { + continue; + } + carvedOpen++; + if (!pillared.get(block)) { + kept++; + } + } + if (kept > 0 && kept < carvedOpen) { + partly++; + } + } + } + return partly; + } + + private static double horizontalMeanRun(BitSet carved) { + return (meanRun(carved, 1, 0, 0) + meanRun(carved, 0, 0, 1)) / 2D; + } + + /** Mean length of the unbroken runs of carved blocks along one axis. */ + private static double meanRun(BitSet carved, int stepX, int stepY, int stepZ) { + long blocks = 0; + long runs = 0; + for (int block = carved.nextSetBit(0); block >= 0; block = carved.nextSetBit(block + 1)) { + int x = block % SIZE; + int z = (block / SIZE) % SIZE; + int y = block / (SIZE * SIZE); + blocks++; + int previousX = x - stepX; + int previousY = y - stepY; + int previousZ = z - stepZ; + boolean previousInside = previousX >= 0 && previousY >= 0 && previousZ >= 0; + if (!previousInside || !carved.get(index(previousX, previousY, previousZ))) { + runs++; + } + } + return blocks / (double) Math.max(1, runs); + } + + private static double largestConnectedShare(BitSet carved) { + BitSet seen = new BitSet(carved.size()); + ArrayDeque open = new ArrayDeque<>(); + int largest = 0; + for (int root = carved.nextSetBit(0); root >= 0; root = carved.nextSetBit(root + 1)) { + if (seen.get(root)) { + continue; + } + int size = 0; + seen.set(root); + open.add(root); + while (!open.isEmpty()) { + int block = open.poll(); + size++; + int x = block % SIZE; + int z = (block / SIZE) % SIZE; + int y = block / (SIZE * SIZE); + visit(carved, seen, open, x + 1, y, z); + visit(carved, seen, open, x - 1, y, z); + visit(carved, seen, open, x, y + 1, z); + visit(carved, seen, open, x, y - 1, z); + visit(carved, seen, open, x, y, z + 1); + visit(carved, seen, open, x, y, z - 1); + } + largest = Math.max(largest, size); + } + return largest / (double) carved.cardinality(); + } + + private static void visit(BitSet carved, BitSet seen, ArrayDeque open, int x, int y, int z) { + if (x < 0 || z < 0 || y < 0 || x >= SIZE || z >= SIZE || y >= LAYERS) { + return; + } + int block = index(x, y, z); + if (carved.get(block) && !seen.get(block)) { + seen.set(block); + open.add(block); + } + } +} diff --git a/core/src/test/java/art/arcane/iris/generation/cave/field/CaveValuesTest.java b/core/src/test/java/art/arcane/iris/generation/cave/field/CaveValuesTest.java new file mode 100644 index 000000000..5ec96db11 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/generation/cave/field/CaveValuesTest.java @@ -0,0 +1,550 @@ +package art.arcane.iris.generation.cave.field; + +import art.arcane.iris.generation.cave.CaveBounds; +import art.arcane.iris.generation.cave.CaveValue; +import art.arcane.iris.generation.cave.IrisCave; +import art.arcane.iris.generation.cave.TestSettings; +import art.arcane.iris.generation.noise.IrisGeneratorStyle; +import com.google.gson.JsonParseException; +import org.junit.Test; + +import java.util.BitSet; +import java.util.List; +import java.util.function.IntPredicate; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +/** + * Every number that shapes a cave may be a plain number, a range a smooth noise picks from, or a range with the style + * that picks. Where a value's noise is at its low end the cave carves as its min would, and at its high end as its max + * would. The places are found by reading the value's own noise, seeded by its name as the carver seeds it. + */ +public class CaveValuesTest { + private static final long SEED = 17L; + private static final int CHUNKS = 8; + private static final int WIDE_CHUNKS = 16; + /** Patches about 50 blocks across, so a few of each end fit in the carved area. */ + private static final String PATCHES = "{\"style\": \"SIMPLEX\", \"zoom\": 0.6}"; + /** Patches about 160 blocks across, wide enough to hold rooms of the size and height they pick. */ + private static final String BROAD_PATCHES = "{\"style\": \"SIMPLEX\", \"zoom\": 2}"; + private static final String TUNNEL_SPACING = "\"spacing\": {\"horizontal\": 48, \"vertical\": 34}"; + private static final String OPEN_CAVERN_KEYS = "\"size\": 40, \"height\": 18, \"coverage\": 0.3"; + /** Rooms tall enough for the finer wall noise that roughness weighs: under about 20 blocks it is finer than the lattice. */ + private static final String TALL_CAVERN_KEYS = "\"size\": 40, \"height\": 24, \"coverage\": 0.3"; + private static final double UNUSED_CHANGE_BLOCKS = 1D; + + private final NoiseFactory noise = CngNoiseFactory.standalone(); + + private static String range(double min, double max) { + return "{\"min\": " + min + ", \"max\": " + max + ", \"style\": " + PATCHES + "}"; + } + + private static String broadRange(double min, double max) { + return "{\"min\": " + min + ", \"max\": " + max + ", \"style\": " + BROAD_PATCHES + "}"; + } + + private CarvedArea carve(String caveJson) { + return CarvedArea.carve(noise, caveJson, SEED, CHUNKS); + } + + private CarvedArea carveWide(String caveJson) { + return CarvedArea.carve(noise, caveJson, SEED, WIDE_CHUNKS); + } + + private static String tunnel(String keys) { + return "{\"tunnel\": {" + TUNNEL_SPACING + ", " + keys + "}, \"opensToSurface\": true}"; + } + + private static String cavern(String keys) { + return "{\"cavern\": {" + keys + "}}"; + } + + @Test + public void aRangeWithEqualEndsCarvesWhatThePlainNumberCarves() { + String plain = """ + {"tunnel": {"width": 5, "height": 7, "spacing": {"horizontal": 48, "vertical": 34}, "verticalWarp": 0.3, + "coverage": {"share": 0.6, "softness": 0.5}}, + "cavern": {"size": 40, "height": 24, "coverage": 0.2, "roughness": 0.5, + "pillars": {"spacing": 16, "thickness": 4, "flare": 3, "vertical": 24}}, + "depth": {"min": 20, "max": 140}, "fade": 10, "surfaceClearance": 9, "ceilingFade": 6} + """; + String equalEnds = """ + {"tunnel": {"width": {"min": 5, "max": 5, "style": {"style": "SIMPLEX"}}, "height": {"min": 7, "max": 7}, + "spacing": {"horizontal": 48, "vertical": 34}, "verticalWarp": {"min": 0.3, "max": 0.3}, + "coverage": {"share": {"min": 0.6, "max": 0.6}, "softness": {"min": 0.5, "max": 0.5}}}, + "cavern": {"size": {"min": 40, "max": 40}, "height": {"min": 24, "max": 24}, "coverage": {"min": 0.2, "max": 0.2}, + "roughness": {"min": 0.5, "max": 0.5}, + "pillars": {"spacing": {"min": 16, "max": 16}, "thickness": {"min": 4, "max": 4}, + "flare": {"min": 3, "max": 3}, "vertical": {"min": 24, "max": 24}}}, + "depth": {"min": {"min": 20, "max": 20}, "max": {"min": 140, "max": 140}}, "fade": {"min": 10, "max": 10}, + "surfaceClearance": {"min": 9, "max": 9}, "ceilingFade": {"min": 6, "max": 6}} + """; + + BitSet byPlainNumbers = carve(plain).carved; + + assertTrue(byPlainNumbers.cardinality() > 10_000); + assertEquals(byPlainNumbers, carve(equalEnds).carved); + } + + @Test + public void theNewKeysAtTheirDefaultsCarveWhatTheConstantsTheyReplaceCarved() { + String leftOut = "{\"tunnel\": {" + TUNNEL_SPACING + ", \"coverage\": 0.5}, \"cavern\": {" + TALL_CAVERN_KEYS + "}}"; + String spelledOut = "{\"tunnel\": {" + TUNNEL_SPACING + ", \"verticalWarp\": 0.5, \"coverage\": {\"share\": 0.5, \"softness\": 0.3}}," + + " \"cavern\": {" + TALL_CAVERN_KEYS + ", \"roughness\": 0.3}, \"ceilingFade\": 8}"; + + assertEquals(carve(leftOut).carved, carve(spelledOut).carved); + } + + @Test + public void eachNewKeyChangesTheCaveAwayFromItsDefault() { + String tunnels = "\"coverage\": {\"share\": 0.5}"; + CarvedArea defaultTunnels = carve(tunnel(tunnels)); + CarvedArea defaultCavern = carve(cavern(TALL_CAVERN_KEYS)); + CarvedArea closedTunnels = carve("{\"tunnel\": {" + TUNNEL_SPACING + "}}"); + + assertChanged("verticalWarp", defaultTunnels, carve(tunnel(tunnels + ", \"verticalWarp\": 0"))); + assertChanged("softness", defaultTunnels, carve(tunnel("\"coverage\": {\"share\": 0.5, \"softness\": 1}"))); + assertChanged("roughness", defaultCavern, carve(cavern(TALL_CAVERN_KEYS + ", \"roughness\": 0"))); + assertTrue("ceilingFade", closedTunnels.differenceShare(carve("{\"tunnel\": {" + TUNNEL_SPACING + "}, \"ceilingFade\": 40}"), block -> true) > 0.005D); + } + + private static void assertChanged(String key, CarvedArea byDefault, CarvedArea changed) { + double difference = byDefault.differenceShare(changed, block -> true); + assertTrue(key + " changes " + difference + " of the cave", difference > 0.05D); + } + + @Test + public void aShareAloneIsShorthandForATunnelCoverage() { + assertEquals(carve(tunnel("\"coverage\": {\"share\": 0.4}")).carved, carve(tunnel("\"coverage\": 0.4")).carved); + } + + @Test + public void aSofterCoverageThinsTunnelsOutOverALongerStretch() { + int abrupt = carve(tunnel("\"coverage\": {\"share\": 0.5, \"softness\": 0}")).carved.cardinality(); + int soft = carve(tunnel("\"coverage\": {\"share\": 0.5, \"softness\": 1}")).carved.cardinality(); + + assertTrue(abrupt + " abrupt against " + soft + " soft", soft < abrupt * 0.8D); + } + + @Test + public void aRoughnessOfZeroGivesSmoothWalls() { + double smooth = wallShare(carve(cavern(TALL_CAVERN_KEYS + ", \"roughness\": 0"))); + double rough = wallShare(carve(cavern(TALL_CAVERN_KEYS + ", \"roughness\": 1"))); + + assertTrue(smooth + " smooth against " + rough + " rough", rough > smooth * 1.1D); + } + + @Test + public void aVerticalWarpOfZeroKeepsTheWarpFromMovingTunnelsUpAndDown() { + String warp = "\"warp\": {\"style\": \"SIMPLEX\", \"zoom\": 0.3, \"multiplier\": 30}"; + double level = heightChangePerBlock(carve(tunnel(warp + ", \"verticalWarp\": 0"))); + double bobbing = heightChangePerBlock(carve(tunnel(warp + ", \"verticalWarp\": 1"))); + + assertTrue(level + " level against " + bobbing + " bobbing", bobbing > level * 1.3D); + } + + /** + * How far a tunnel rises or falls from one column to the next, on average: the middle heights of neighbouring + * columns that each cross exactly one tunnel. + */ + private static double heightChangePerBlock(CarvedArea area) { + double[] middleY = new double[area.size * area.size]; + for (int x = 0; x < area.size; x++) { + for (int z = 0; z < area.size; z++) { + middleY[(z * area.size) + x] = middleOfOnlyRun(area, x, z); + } + } + double change = 0D; + long pairs = 0; + for (int x = 0; x < area.size - 1; x++) { + for (int z = 0; z < area.size - 1; z++) { + double here = middleY[(z * area.size) + x]; + for (double next : new double[]{middleY[(z * area.size) + x + 1], middleY[((z + 1) * area.size) + x]}) { + if (!Double.isNaN(here) && !Double.isNaN(next)) { + change += Math.abs(next - here); + pairs++; + } + } + } + } + return change / Math.max(1, pairs); + } + + private static double middleOfOnlyRun(CarvedArea area, int x, int z) { + int runs = 0; + int lowest = -1; + int highest = -1; + boolean inRun = false; + for (int y = 0; y < CarvedArea.LAYERS; y++) { + boolean carved = area.carved.get(area.index(x, y, z)); + if (carved && !inRun) { + runs++; + lowest = y; + } + if (carved) { + highest = y; + } + inRun = carved; + } + return runs == 1 ? (lowest + highest) / 2D : Double.NaN; + } + + @Test + public void aValueWrittenInNoFormFailsSayingWhichFormsThereAre() { + JsonParseException text = assertThrows(JsonParseException.class, () -> TestSettings.of(IrisCave.class, "{\"fade\": \"wide\"}")); + JsonParseException misspelt = assertThrows(JsonParseException.class, () -> TestSettings.of(IrisCave.class, "{\"fade\": {\"min\": 1, \"mx\": 4}}")); + JsonParseException halfRange = assertThrows(JsonParseException.class, () -> TestSettings.of(IrisCave.class, "{\"fade\": {\"min\": 1}}")); + + assertTrue(text.getMessage(), text.getMessage().contains("a number or {min, max}")); + assertTrue(misspelt.getMessage(), misspelt.getMessage().contains("not mx")); + assertTrue(halfRange.getMessage(), halfRange.getMessage().contains("needs both min and max")); + } + + @Test + public void valuesOutsideTheirBoundsAreReportedByTheirPlaceInTheFile() { + IrisCave cave = TestSettings.of(IrisCave.class, """ + {"fade": 200, "tunnel": {"width": {"min": 0, "max": 6}, "coverage": {"share": 2}}, + "cavern": {"pillars": {"flare": 0.5}}} + """); + + assertEquals(List.of("tunnel.width.min is 0; it must be at least 1", "tunnel.coverage.share is 2; it must be at most 1", + "cavern.pillars.flare is 0.5; it must be at least 1", "fade is 200; it must be at most 128"), CaveBounds.valuesOutOfBounds(cave)); + assertEquals(List.of(), CaveBounds.valuesOutOfBounds(TestSettings.of(IrisCave.class, "{\"tunnel\": {}, \"cavern\": {\"pillars\": {}}}"))); + } + + @Test + public void aRangeWithoutAStyleChangesSmoothlyWhereAStaticStyleJumps() { + CaveValue smooth = TestSettings.of(CaveValue.class, "{\"min\": 0, \"max\": 1}"); + CaveValue jumping = TestSettings.of(CaveValue.class, "{\"min\": 0, \"max\": 1, \"style\": {\"style\": \"STATIC\"}}"); + + double smoothStep = largestStep(ValueField.inColumns(smooth, new CaveNoise(noise, SEED), "fade", IrisCave.VALUE_CHANGE_BLOCKS)); + double jumpingStep = largestStep(ValueField.inColumns(jumping, new CaveNoise(noise, SEED), "fade", IrisCave.VALUE_CHANGE_BLOCKS)); + + assertTrue("smooth range moves up to " + smoothStep + " per block", smoothStep < 0.03D); + assertTrue("static style moves up to " + jumpingStep + " per block", jumpingStep > 0.3D); + } + + private static double largestStep(ValueField value) { + double largest = 0D; + double previous = value.at(0, 0); + double spread = 0D; + double lowest = previous; + double highest = previous; + for (int x = 1; x < 4096; x++) { + double current = value.at(x, x * 0.37D); + largest = Math.max(largest, Math.abs(current - previous)); + lowest = Math.min(lowest, current); + highest = Math.max(highest, current); + previous = current; + } + spread = highest - lowest; + assertTrue("the range is used: " + spread, spread > 0.9D); + return largest; + } + + /** A value of the whole cave is read per column, so each column at an end of its noise carves exactly as that end does. */ + @Test + public void aVaryingCaveValueCarvesEachColumnExactlyAsItsLowOrHighNumberWould() { + String tunnels = "{\"tunnel\": {" + TUNNEL_SPACING + ", \"width\": 6}, "; + assertMatchesItsEndsExactly("fade", tunnels + "\"depth\": {\"min\": 30, \"max\": 120}, \"fade\": %s}", 2, 40); + assertMatchesItsEndsExactly("surfaceClearance", tunnels + "\"surfaceClearance\": %s}", 2, 40); + assertMatchesItsEndsExactly("ceilingFade", tunnels + "\"ceilingFade\": %s}", 0, 60); + assertMatchesItsEndsExactly("depth.min", tunnels + "\"depth\": {\"min\": %s, \"max\": 150}}", 10, 90); + assertMatchesItsEndsExactly("depth.max", tunnels + "\"depth\": {\"min\": 10, \"max\": %s}}", 60, 150); + } + + private void assertMatchesItsEndsExactly(String name, String caveFormat, double min, double max) { + CarvedArea byMin = carve(caveFormat.formatted(min)); + CarvedArea byMax = carve(caveFormat.formatted(max)); + CarvedArea byRange = carve(caveFormat.formatted(range(min, max))); + ValueField share = columnShares(name); + IntPredicate atMin = byRange.cached(block -> share.at(byRange.x(block), byRange.z(block)) == 0D); + IntPredicate atMax = byRange.cached(block -> share.at(byRange.x(block), byRange.z(block)) == 1D); + + assertTrue(name + " differs between its ends", byMin.differenceShare(byMax, block -> true) > 0.01D); + assertEquals(name + " at its min", 0D, byRange.differenceShare(byMin, atMin), 0D); + assertEquals(name + " at its max", 0D, byRange.differenceShare(byMax, atMax), 0D); + assertTrue(name + " carves at both ends", byRange.carvedShare(atMin) > 0D && byRange.carvedShare(atMax) > 0D); + } + + @Test + public void aVaryingTunnelValueCarvesLikeItsLowOrHighNumberWhereItsNoiseIsAtThatEnd() { + assertFollowsItsEnds("tunnel.verticalWarp", false, + tunnel("\"warp\": {\"style\": \"SIMPLEX\", \"zoom\": 0.3, \"multiplier\": 30}, \"verticalWarp\": %s"), 0, 1); + assertFollowsItsEnds("tunnel.coverage.share", false, tunnel("\"coverage\": {\"share\": %s}"), 0.2, 0.9); + assertFollowsItsEnds("tunnel.coverage.softness", false, tunnel("\"coverage\": {\"share\": 0.5, \"softness\": %s}"), 0, 1); + assertFollowsItsEnds("tunnel.height", false, tunnel("\"width\": 6, \"height\": %s"), 3, 12); + } + + @Test + public void aVaryingCavernValueCarvesLikeItsLowOrHighNumberWhereItsNoiseIsAtThatEnd() { + assertFollowsItsEnds("cavern.coverage", false, cavern("\"size\": 40, \"height\": 18, \"coverage\": %s"), 0.05, 0.4); + assertFollowsItsEnds("cavern.roughness", false, cavern(TALL_CAVERN_KEYS + ", \"roughness\": %s"), 0, 1); + assertFollowsItsEnds("cavern.pillars.thickness", true, cavern(OPEN_CAVERN_KEYS + ", \"pillars\": {\"spacing\": 14, \"thickness\": %s}"), 2, 6); + assertFollowsItsEnds("cavern.pillars.flare", true, cavern(OPEN_CAVERN_KEYS + ", \"pillars\": {\"spacing\": 14, \"thickness\": 4, \"flare\": %s}"), 1, 8); + } + + /** + * Where the value's noise is at its min, the cave carves much more like the min than the max, and the other way + * round where it is at its max. Values read on the lattice are interpolated near the edge of an end, so they only + * come close; values read per column match the ends exactly. + */ + private void assertFollowsItsEnds(String name, boolean inColumns, String caveFormat, double min, double max) { + CarvedArea byMin = carve(caveFormat.formatted(min)); + CarvedArea byMax = carve(caveFormat.formatted(max)); + CarvedArea byRange = carve(caveFormat.formatted(range(min, max))); + CaveValue shares = TestSettings.of(CaveValue.class, range(0, 1)); + CaveNoise caveNoise = new CaveNoise(noise, SEED); + ValueField share = inColumns + ? ValueField.inColumns(shares, caveNoise, name, UNUSED_CHANGE_BLOCKS) + : ValueField.inBlocks(shares, caveNoise, name, UNUSED_CHANGE_BLOCKS); + IntPredicate atMin = byRange.cached(block -> share.at(byRange.x(block), byRange.y(block), byRange.z(block)) == 0D); + IntPredicate atMax = byRange.cached(block -> share.at(byRange.x(block), byRange.y(block), byRange.z(block)) == 1D); + + double minAgainstMin = byRange.differenceShare(byMin, atMin); + double minAgainstMax = byRange.differenceShare(byMax, atMin); + double maxAgainstMax = byRange.differenceShare(byMax, atMax); + double maxAgainstMin = byRange.differenceShare(byMin, atMax); + + assertNotEquals(name + " differs between its ends", byMin.carved, byMax.carved); + assertTrue(name + " at its min: " + minAgainstMin + " from min, " + minAgainstMax + " from max", minAgainstMin < minAgainstMax * 0.5D); + assertTrue(name + " at its max: " + maxAgainstMax + " from max, " + maxAgainstMin + " from min", maxAgainstMax < maxAgainstMin * 0.5D); + } + + @Test + public void aVaryingTunnelWidthIsNarrowWhereItsNoiseIsLowAndWideWhereItIsHigh() { + CaveNoise caveNoise = new CaveNoise(noise, SEED); + for (int field = 0; field < 6; field++) { + caveNoise.smooth(48, 34); + } + Field3 widthNoise = caveNoise.inBlocks(TestSettings.of(IrisGeneratorStyle.class, PATCHES)); + CarvedArea varying = carve(tunnel("\"width\": " + range(2, 10))); + + double narrow = varying.horizontalMeanRun(block -> ValueField.shareAt(widthNoise.at(varying.x(block), varying.y(block), varying.z(block))) == 0D); + double wide = varying.horizontalMeanRun(block -> ValueField.shareAt(widthNoise.at(varying.x(block), varying.y(block), varying.z(block))) == 1D); + + assertTrue("narrow end runs " + narrow + ", wide end " + wide, wide > narrow * 2D); + } + + @Test + public void aCavernCoverageRangeFromZeroLeavesAreasWithoutRooms() { + CarvedArea varying = carve(cavern("\"size\": 40, \"height\": 18, \"coverage\": " + range(0, 0.4))); + ValueField share = ValueField.inBlocks(TestSettings.of(CaveValue.class, range(0, 1)), new CaveNoise(noise, SEED), "cavern.coverage", UNUSED_CHANGE_BLOCKS); + + double withoutRooms = varying.carvedShare(block -> share.at(varying.x(block), varying.y(block), varying.z(block)) == 0D); + double withRooms = varying.carvedShare(block -> share.at(varying.x(block), varying.y(block), varying.z(block)) == 1D); + + assertTrue("carved where coverage is 0: " + withoutRooms, withoutRooms < 0.005D); + assertTrue("carved where coverage is 0.4: " + withRooms, withRooms > 0.2D); + } + + @Test + public void aVaryingPillarThicknessKeepsMoreRockWhereItsNoiseIsHigh() { + CarvedArea open = carve(cavern(OPEN_CAVERN_KEYS)); + CarvedArea varying = carve(cavern(OPEN_CAVERN_KEYS + ", \"pillars\": {\"spacing\": 14, \"thickness\": " + range(2, 7) + "}")); + ValueField share = columnShares("cavern.pillars.thickness"); + + double thin = keptShare(open, varying, block -> share.at(open.x(block), open.z(block)) == 0D); + double thick = keptShare(open, varying, block -> share.at(open.x(block), open.z(block)) == 1D); + + assertTrue("pillars keep " + thin + " of the room where thin, " + thick + " where thick", thick > thin * 2D); + } + + @Test + public void aVaryingRoomSizeMakesLargerRoomsWhereItsNoiseIsHighWithoutLooseRock() { + String keys = "\"height\": 20, \"coverage\": 0.2}, \"depth\": {\"min\": 10, \"max\": 150}"; + CarvedArea small = carveWide("{\"cavern\": {\"size\": 30, " + keys + "}"); + CarvedArea large = carveWide("{\"cavern\": {\"size\": 90, " + keys + "}"); + CarvedArea varying = carveWide("{\"cavern\": {\"size\": " + broadRange(30, 90) + ", " + keys + "}"); + ValueField share = ValueField.inBlocks(TestSettings.of(CaveValue.class, broadRange(0, 1)), new CaveNoise(noise, SEED), "cavern.size", UNUSED_CHANGE_BLOCKS); + + double smallRuns = varying.horizontalMeanRun(block -> share.at(varying.x(block), 80, varying.z(block)) <= 0.15D); + double largeRuns = varying.horizontalMeanRun(block -> share.at(varying.x(block), 80, varying.z(block)) >= 0.85D); + + assertTrue("rooms run " + smallRuns + " where small, " + largeRuns + " where large", largeRuns > smallRuns * 1.3D); + assertNoMoreLooseRockThanEitherEnd(varying, small, large); + } + + /** + * The coverage threshold is measured once on the whole room field, so where size, height or roughness vary the + * carved share is only close to what the ends carve: within a fifth of their average over nine far-apart areas. + */ + @Test + public void aRangeInSizeHeightOrRoughnessCarvesCloseToTheShareItsEndsCarve() { + String depth = ", \"coverage\": 0.2}, \"depth\": {\"min\": 10, \"max\": 150}}"; + assertCarvesBetween("size", "{\"cavern\": {\"height\": 20, \"size\": %s" + depth, 30, 90); + assertCarvesBetween("height", "{\"cavern\": {\"size\": 40, \"height\": %s" + depth, 12, 40); + assertCarvesBetween("roughness", "{\"cavern\": {\"size\": 40, \"height\": 24, \"roughness\": %s" + depth, 0, 1); + } + + private void assertCarvesBetween(String key, String caveFormat, double min, double max) { + double byMin = carvedInFarApartAreas(caveFormat.formatted(min)); + double byMax = carvedInFarApartAreas(caveFormat.formatted(max)); + double byRange = carvedInFarApartAreas(caveFormat.formatted("{\"min\": " + min + ", \"max\": " + max + "}")); + + assertWithin(key + " range against its ends' average", byRange, (byMin + byMax) / 2D, 0.2D); + } + + private double carvedInFarApartAreas(String caveJson) { + long carved = 0; + for (int area = 0; area < 9; area++) { + carved += CarvedArea.carveAt(noise, caveJson, SEED, CHUNKS, (area % 3) * 7000, (area / 3) * 7000).carved.cardinality(); + } + return carved; + } + + @Test + public void aVaryingRoomHeightMakesTallerRoomsWhereItsNoiseIsHighWithoutLooseRock() { + String keys = "\"size\": 40, \"coverage\": 0.2}, \"depth\": {\"min\": 10, \"max\": 150}"; + CarvedArea low = carveWide("{\"cavern\": {\"height\": 12, " + keys + "}"); + CarvedArea tall = carveWide("{\"cavern\": {\"height\": 40, " + keys + "}"); + CarvedArea varying = carveWide("{\"cavern\": {\"height\": " + broadRange(12, 40) + ", " + keys + "}"); + ValueField share = ValueField.inColumns(TestSettings.of(CaveValue.class, broadRange(0, 1)), new CaveNoise(noise, SEED), "cavern.height", UNUSED_CHANGE_BLOCKS); + + double lowRuns = varying.meanRun(0, 1, 0, block -> share.at(varying.x(block), varying.z(block)) == 0D); + double tallRuns = varying.meanRun(0, 1, 0, block -> share.at(varying.x(block), varying.z(block)) == 1D); + + assertTrue("rooms run " + lowRuns + " high where low, " + tallRuns + " where tall", tallRuns > lowRuns * 1.4D); + assertNoMoreLooseRockThanEitherEnd(varying, low, tall); + } + + @Test + public void aVaryingPillarSpacingSpreadsThePillarsWhereItsNoiseIsHigh() { + CarvedArea open = carve(cavern(OPEN_CAVERN_KEYS)); + CarvedArea varying = carve(cavern(OPEN_CAVERN_KEYS + ", \"pillars\": {\"spacing\": " + range(10, 40) + ", \"thickness\": 4}")); + ValueField share = columnShares("cavern.pillars.spacing"); + + double close = keptShare(open, varying, block -> share.at(open.x(block), open.z(block)) == 0D); + double far = keptShare(open, varying, block -> share.at(open.x(block), open.z(block)) == 1D); + + assertTrue("pillars keep " + close + " of the room where close, " + far + " where far apart", close > far * 4D); + } + + @Test + public void aVaryingPillarVerticalBreaksPillarsMoreOftenWhereItIsLow() { + String pillars = OPEN_CAVERN_KEYS + ", \"pillars\": {\"spacing\": 14, \"thickness\": 4, \"flare\": 1, \"vertical\": "; + CarvedArea open = carve(cavern(OPEN_CAVERN_KEYS)); + CarvedArea varying = carve(cavern(pillars + range(12, 60) + "}")); + ValueField share = columnShares("cavern.pillars.vertical"); + + int often = partlyKeptColumns(open, varying, (x, z) -> share.at(x, z) == 0D); + int seldom = partlyKeptColumns(open, varying, (x, z) -> share.at(x, z) == 1D); + int oftenColumns = columns(open, (x, z) -> share.at(x, z) == 0D); + int seldomColumns = columns(open, (x, z) -> share.at(x, z) == 1D); + + double oftenShare = often / (double) oftenColumns; + double seldomShare = seldom / (double) seldomColumns; + assertTrue("pillars change in " + oftenShare + " of columns where vertical is low, " + seldomShare + " where high", oftenShare > seldomShare * 1.3D); + } + + private ValueField columnShares(String name) { + return ValueField.inColumns(TestSettings.of(CaveValue.class, range(0, 1)), new CaveNoise(noise, SEED), name, UNUSED_CHANGE_BLOCKS); + } + + private static void assertNoMoreLooseRockThanEitherEnd(CarvedArea varying, CarvedArea first, CarvedArea second) { + int floating = varying.floatingRockSmallerThan(200); + int fragments = varying.carvedPiecesSmallerThan(30); + int mostFloating = Math.max(first.floatingRockSmallerThan(200), second.floatingRockSmallerThan(200)); + int mostFragments = Math.max(first.carvedPiecesSmallerThan(30), second.carvedPiecesSmallerThan(30)); + + assertTrue("floating rock " + floating + " against at most " + mostFloating + " at either end", floating <= mostFloating + 2); + assertTrue("small air pockets " + fragments + " against at most " + mostFragments + " at either end", fragments <= (mostFragments * 2) + 5); + } + + private static void assertWithin(String what, double actual, double expected, double share) { + assertTrue(what + ": " + actual + " against " + expected, Math.abs(actual - expected) <= expected * share); + } + + /** Share of the blocks the open cavern carves where {@code where} holds that pillars keep as rock. */ + private static double keptShare(CarvedArea open, CarvedArea pillared, IntPredicate where) { + long openBlocks = 0; + long kept = 0; + for (int block = open.carved.nextSetBit(0); block >= 0; block = open.carved.nextSetBit(block + 1)) { + if (!where.test(block)) { + continue; + } + openBlocks++; + if (!pillared.carved.get(block)) { + kept++; + } + } + return kept / (double) Math.max(1, openBlocks); + } + + @FunctionalInterface + private interface ColumnTest { + boolean holds(int x, int z); + } + + private static int columns(CarvedArea open, ColumnTest where) { + int count = 0; + for (int x = 0; x < open.size; x++) { + for (int z = 0; z < open.size; z++) { + if (where.holds(x, z) && openColumn(open, x, z) > 0) { + count++; + } + } + } + return Math.max(1, count); + } + + private static int openColumn(CarvedArea open, int x, int z) { + int carved = 0; + for (int y = 0; y < CarvedArea.LAYERS; y++) { + if (open.carved.get(open.index(x, y, z))) { + carved++; + } + } + return carved; + } + + /** Columns where pillars keep some, but not all, of the blocks the open cavern carves. */ + private static int partlyKeptColumns(CarvedArea open, CarvedArea pillared, ColumnTest where) { + int partly = 0; + for (int x = 0; x < open.size; x++) { + for (int z = 0; z < open.size; z++) { + if (!where.holds(x, z)) { + continue; + } + int kept = 0; + int carvedOpen = 0; + for (int y = 0; y < CarvedArea.LAYERS; y++) { + int block = open.index(x, y, z); + if (!open.carved.get(block)) { + continue; + } + carvedOpen++; + if (!pillared.carved.get(block)) { + kept++; + } + } + if (kept > 0 && kept < carvedOpen) { + partly++; + } + } + } + return partly; + } + + /** Share of carved blocks with rock beside them: rougher walls have more. */ + private static double wallShare(CarvedArea area) { + long walls = 0; + for (int block = area.carved.nextSetBit(0); block >= 0; block = area.carved.nextSetBit(block + 1)) { + int x = area.x(block); + int y = area.y(block); + int z = area.z(block); + if (x == 0 || z == 0 || y == 0 || x == area.size - 1 || z == area.size - 1 || y == CarvedArea.LAYERS - 1) { + continue; + } + if (!area.carved.get(area.index(x + 1, y, z)) || !area.carved.get(area.index(x - 1, y, z)) + || !area.carved.get(area.index(x, y + 1, z)) || !area.carved.get(area.index(x, y - 1, z)) + || !area.carved.get(area.index(x, y, z + 1)) || !area.carved.get(area.index(x, y, z - 1))) { + walls++; + } + } + return walls / (double) Math.max(1, area.carved.cardinality()); + } +}