mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-12-04 04:02:11 +00:00
Compare commits
43
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4fc5914359 | ||
|
|
2a8ab26a14 | ||
|
|
ee911247b3 | ||
|
|
36b352ea05 | ||
|
|
713556bc30 | ||
|
|
94a8a9b139 | ||
|
|
ef24f2e8b2 | ||
|
|
a51802c487 | ||
|
|
5040d32cb8 | ||
|
|
d8c0c2cc61 | ||
|
|
1efb4c14db | ||
|
|
8fe8942f5d | ||
|
|
fadbcb8bb5 | ||
|
|
9489ffd4ad | ||
|
|
c6a7225fa8 | ||
|
|
2ae765ca16 | ||
|
|
5c7c2b30d8 | ||
|
|
424d8d8f51 | ||
|
|
1f27af6938 | ||
|
|
aa78f4d43d | ||
|
|
d41cbeb6db | ||
|
|
4079e0a708 | ||
|
|
2cfb3d8dcc | ||
|
|
98e296b666 | ||
|
|
3532c16906 | ||
|
|
dd7d838c6b | ||
|
|
a8470c8178 | ||
|
|
8afbff4b42 | ||
|
|
05984cf64a | ||
|
|
aafbb879df | ||
|
|
86ce2856e8 | ||
|
|
564dcdcc72 | ||
|
|
3ad55564ec | ||
|
|
b1f5c58b62 | ||
|
|
6dc2dec03b | ||
|
|
f4f2c15731 | ||
|
|
c10341af2b | ||
|
|
9d0f7a6887 | ||
|
|
1693e3f397 | ||
|
|
3922c8f57f | ||
|
|
71cac65f91 | ||
|
|
f8041b22ec | ||
|
|
64d1daf588 |
No files matched your search
-262
@@ -1,262 +0,0 @@
|
||||
package art.arcane.iris.probe;
|
||||
|
||||
import art.arcane.volmlib.nativelib.common.block.GroundSurvival;
|
||||
import art.arcane.volmlib.nativelib.minecraft26_2.modded.ModdedBlockState;
|
||||
import art.arcane.volmlib.nativelib.block.SurvivalAnswer;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.world.level.LevelReader;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.logging.Handler;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.LogRecord;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** Both platforms ask the server's own canSurvive rule where a plant may stand, against the real block tags. */
|
||||
public final class HeadlessGroundSurvivalTest {
|
||||
private static final Logger NATIVE_LOG = Logger.getLogger("VolmLib-Native");
|
||||
|
||||
@BeforeClass
|
||||
public static void bootstrap() {
|
||||
HeadlessNativeBootstrap.initialize();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void grassStandsOnSoilButNotOnStone() {
|
||||
assertPlacement(true, Blocks.SHORT_GRASS, Blocks.GRASS_BLOCK);
|
||||
assertPlacement(true, Blocks.SHORT_GRASS, Blocks.PODZOL);
|
||||
assertPlacement(false, Blocks.SHORT_GRASS, Blocks.STONE);
|
||||
assertPlacement(false, Blocks.POPPY, Blocks.STONE);
|
||||
assertPlacement(false, Blocks.FERN, Blocks.OAK_LEAVES);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void cactusNeedsSandOrCactus() {
|
||||
for (Block ground : new Block[]{Blocks.CACTUS, Blocks.SAND, Blocks.RED_SAND}) {
|
||||
assertPlacement(true, Blocks.CACTUS, ground);
|
||||
}
|
||||
assertPlacement(false, Blocks.CACTUS, Blocks.STONE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sugarCaneNeedsItsSubstrate() {
|
||||
for (Block ground : new Block[]{Blocks.SUGAR_CANE, Blocks.GRASS_BLOCK, Blocks.DIRT, Blocks.COARSE_DIRT,
|
||||
Blocks.PODZOL, Blocks.MYCELIUM, Blocks.ROOTED_DIRT, Blocks.MOSS_BLOCK, Blocks.PALE_MOSS_BLOCK,
|
||||
Blocks.MUD, Blocks.MUDDY_MANGROVE_ROOTS, Blocks.SAND, Blocks.RED_SAND, Blocks.SUSPICIOUS_SAND}) {
|
||||
assertPlacement(true, Blocks.SUGAR_CANE, ground);
|
||||
}
|
||||
for (Block ground : new Block[]{Blocks.STONE, Blocks.GRAVEL, Blocks.CLAY, Blocks.DIRT_PATH,
|
||||
Blocks.FARMLAND, Blocks.AIR, Blocks.WATER}) {
|
||||
assertPlacement(false, Blocks.SUGAR_CANE, ground);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void netherGroundCoverAcceptsNyliumAndSoulSoilButRejectsBarrenBlocks() {
|
||||
for (Block plant : new Block[]{Blocks.CRIMSON_ROOTS, Blocks.WARPED_ROOTS, Blocks.NETHER_SPROUTS}) {
|
||||
for (Block ground : new Block[]{Blocks.CRIMSON_NYLIUM, Blocks.WARPED_NYLIUM, Blocks.SOUL_SOIL}) {
|
||||
assertPlacement(true, plant, ground);
|
||||
}
|
||||
for (Block ground : new Block[]{Blocks.NETHERRACK, Blocks.STONE, Blocks.GRAVEL, Blocks.AIR}) {
|
||||
assertPlacement(false, plant, ground);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void blocksThatRestOnNoGroundStillFit() {
|
||||
assertPlacement(true, Blocks.WALL_TORCH, Blocks.STONE);
|
||||
assertPlacement(true, Blocks.VINE, Blocks.SAND);
|
||||
assertPlacement(true, Blocks.COCOA, Blocks.STONE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deadBushStaysOffGrassAsPacksExpect() {
|
||||
assertPlacement(true, Blocks.DEAD_BUSH, Blocks.SAND);
|
||||
assertPlacement(false, Blocks.DEAD_BUSH, Blocks.GRASS_BLOCK);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nothingStandsOnAir() {
|
||||
assertPlacement(false, Blocks.VINE, Blocks.AIR);
|
||||
assertPlacement(false, Blocks.SHORT_GRASS, Blocks.CAVE_AIR);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void plantsThatReadMoreOfTheLevelAreAnsweredByTheirOwnRule() {
|
||||
List<LogRecord> warnings = warningsDuring(() -> {
|
||||
assertPlacement(true, Blocks.BAMBOO, Blocks.GRASS_BLOCK);
|
||||
assertPlacement(false, Blocks.BAMBOO, Blocks.STONE);
|
||||
assertPlacement(true, Blocks.KELP, Blocks.STONE);
|
||||
assertPlacement(false, Blocks.KELP, Blocks.MAGMA_BLOCK);
|
||||
assertPlacement(true, Blocks.SEAGRASS, Blocks.SAND);
|
||||
assertPlacement(false, Blocks.SEAGRASS, Blocks.MAGMA_BLOCK);
|
||||
assertPlacement(true, Blocks.LILY_PAD, Blocks.WATER);
|
||||
assertPlacement(false, Blocks.LILY_PAD, Blocks.STONE);
|
||||
assertPlacement(true, Blocks.SWEET_BERRY_BUSH, Blocks.GRASS_BLOCK);
|
||||
assertPlacement(false, Blocks.SWEET_BERRY_BUSH, Blocks.STONE);
|
||||
assertPlacement(true, Blocks.BROWN_MUSHROOM, Blocks.STONE);
|
||||
assertPlacement(true, Blocks.RED_MUSHROOM, Blocks.MYCELIUM);
|
||||
assertPlacement(false, Blocks.BROWN_MUSHROOM, Blocks.GLASS);
|
||||
assertPlacement(true, Blocks.CRIMSON_FUNGUS, Blocks.CRIMSON_NYLIUM);
|
||||
assertPlacement(false, Blocks.WARPED_FUNGUS, Blocks.NETHERRACK);
|
||||
assertPlacement(true, Blocks.WHEAT, Blocks.FARMLAND);
|
||||
assertPlacement(false, Blocks.CARROTS, Blocks.DIRT);
|
||||
});
|
||||
assertEquals(messages(warnings), 0, warnings.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void everyVanillaBlockIsAnsweredWithoutFailingOpen() {
|
||||
GroundSurvival survival = new GroundSurvival();
|
||||
List<LogRecord> warnings = warningsDuring(() -> {
|
||||
for (Block plant : BuiltInRegistries.BLOCK) {
|
||||
if (needsARunningPaperServer(plant)) {
|
||||
continue;
|
||||
}
|
||||
for (Block ground : new Block[]{Blocks.GRASS_BLOCK, Blocks.STONE, Blocks.WATER}) {
|
||||
survival.canSurviveOn(plant.defaultBlockState(), ground.defaultBlockState());
|
||||
}
|
||||
}
|
||||
});
|
||||
assertEquals(messages(warnings), 0, warnings.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aRuleThatThrowsIsLeftUnansweredAndWarnsOncePerBlock() {
|
||||
BlockState firstState = throwingStateOf(Blocks.SHORT_GRASS);
|
||||
BlockState secondState = throwingStateOf(Blocks.SHORT_GRASS);
|
||||
GroundSurvival survival = new GroundSurvival();
|
||||
List<LogRecord> warnings = warningsDuring(() -> {
|
||||
for (BlockState plant : new BlockState[]{firstState, secondState}) {
|
||||
for (Block ground : new Block[]{Blocks.STONE, Blocks.SAND, Blocks.GRASS_BLOCK}) {
|
||||
assertEquals(SurvivalAnswer.UNANSWERED, survival.canSurviveOn(plant, ground.defaultBlockState()));
|
||||
}
|
||||
}
|
||||
});
|
||||
assertEquals(messages(warnings), 1, warnings.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aRuleThatThrowsFallsBackToThePlacementTable() {
|
||||
ModdedBlockState grass = ModdedBlockState.deferred(throwingStateOf(Blocks.SHORT_GRASS), Map.of(), "iris:test");
|
||||
warningsDuring(() -> {
|
||||
assertTrue(grass.canPlaceOnto(wrap(Blocks.GRASS_BLOCK)));
|
||||
assertFalse(grass.canPlaceOnto(wrap(Blocks.STONE)));
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aRuleThatOnlyAnswersForSomeGroundsDoesNotPassAsAWallBlock() {
|
||||
BlockState plant = mock(BlockState.class);
|
||||
when(plant.getBlock()).thenReturn(Blocks.SHORT_GRASS);
|
||||
when(plant.canSurvive(any(), any())).thenAnswer(asked -> {
|
||||
LevelReader level = asked.getArgument(0);
|
||||
BlockPos plantPos = asked.getArgument(1);
|
||||
if (level.getBlockState(plantPos.below()).is(Blocks.STONE)) {
|
||||
return false;
|
||||
}
|
||||
throw new IllegalStateException("custom rule failed");
|
||||
});
|
||||
GroundSurvival survival = new GroundSurvival();
|
||||
warningsDuring(() -> assertEquals(SurvivalAnswer.UNANSWERED,
|
||||
survival.canSurviveOn(plant, Blocks.STONE.defaultBlockState())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void generatorThreadsAskingAtOnceGetTheSameAnswers() {
|
||||
Block[] plants = {Blocks.SHORT_GRASS, Blocks.CACTUS, Blocks.SUGAR_CANE, Blocks.VINE, Blocks.BROWN_MUSHROOM};
|
||||
Block[] grounds = {Blocks.GRASS_BLOCK, Blocks.SAND, Blocks.STONE, Blocks.WATER};
|
||||
GroundSurvival alone = new GroundSurvival();
|
||||
GroundSurvival shared = new GroundSurvival();
|
||||
List<Integer> threads = Arrays.asList(new Integer[16]);
|
||||
threads.parallelStream().forEach(ignored -> {
|
||||
for (Block plant : plants) {
|
||||
for (Block ground : grounds) {
|
||||
assertEquals(plant + " on " + ground,
|
||||
alone.canSurviveOn(plant.defaultBlockState(), ground.defaultBlockState()),
|
||||
shared.canSurviveOn(plant.defaultBlockState(), ground.defaultBlockState()));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Paper's chorus plant reads Paper's global configuration, which only a running server loads.
|
||||
private static boolean needsARunningPaperServer(Block plant) {
|
||||
return plant == Blocks.CHORUS_PLANT;
|
||||
}
|
||||
|
||||
private static BlockState throwingStateOf(Block block) {
|
||||
BlockState state = mock(BlockState.class);
|
||||
when(state.getBlock()).thenReturn(block);
|
||||
when(state.isSingletonState()).thenReturn(true);
|
||||
when(state.canSurvive(any(), any())).thenThrow(new IllegalStateException("custom rule failed"));
|
||||
return state;
|
||||
}
|
||||
|
||||
private static void assertPlacement(boolean expected, Block plant, Block ground) {
|
||||
String pair = plant + " on " + ground;
|
||||
assertEquals("modded " + pair, expected, moddedPlacement(plant, ground));
|
||||
assertEquals("bukkit native " + pair, expected ? SurvivalAnswer.SURVIVES : SurvivalAnswer.FAILS,
|
||||
new GroundSurvival().canSurviveOn(plant.defaultBlockState(), ground.defaultBlockState()));
|
||||
}
|
||||
|
||||
private static boolean moddedPlacement(Block plant, Block ground) {
|
||||
return wrap(plant).canPlaceOnto(wrap(ground));
|
||||
}
|
||||
|
||||
private static ModdedBlockState wrap(Block block) {
|
||||
return ModdedBlockState.deferred(block.defaultBlockState(), Map.of(), "iris:test");
|
||||
}
|
||||
|
||||
private static List<LogRecord> warningsDuring(Runnable checks) {
|
||||
List<LogRecord> warnings = new CopyOnWriteArrayList<>();
|
||||
Handler capture = new Handler() {
|
||||
@Override
|
||||
public void publish(LogRecord record) {
|
||||
if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
|
||||
warnings.add(record);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
}
|
||||
};
|
||||
NATIVE_LOG.addHandler(capture);
|
||||
try {
|
||||
checks.run();
|
||||
} finally {
|
||||
NATIVE_LOG.removeHandler(capture);
|
||||
}
|
||||
return warnings;
|
||||
}
|
||||
|
||||
private static String messages(List<LogRecord> warnings) {
|
||||
StringBuilder text = new StringBuilder();
|
||||
for (LogRecord warning : warnings) {
|
||||
text.append(warning.getMessage()).append(" (").append(warning.getThrown()).append(")\n");
|
||||
}
|
||||
return text.toString();
|
||||
}
|
||||
}
|
||||
+30
-58
@@ -6,13 +6,14 @@ import art.arcane.iris.pack.datapack.export.WorldgenExportMode;
|
||||
import art.arcane.iris.pack.datapack.export.WorldgenExportProgress;
|
||||
import art.arcane.iris.pack.datapack.export.WorldgenExportRequest;
|
||||
import art.arcane.iris.pack.datapack.export.WorldgenExportResult;
|
||||
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
|
||||
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.chunk.ProtoChunk;
|
||||
import net.minecraft.world.level.levelgen.densityfunction.DensityFunction;
|
||||
import org.junit.ClassRule;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
@@ -23,11 +24,12 @@ import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/** Listed caves are not exported yet: the exported world has no Iris caves, and the export says so. */
|
||||
public final class WorldgenExportDeepCaves263Test {
|
||||
@ClassRule
|
||||
public static final PaperRegistryIsolation registryIsolation = new PaperRegistryIsolation();
|
||||
@@ -36,35 +38,21 @@ public final class WorldgenExportDeepCaves263Test {
|
||||
private static final String NAMESPACE = WorldgenExportRequest.DEFAULT_NAMESPACE;
|
||||
private static final String DIMENSION_ID = NAMESPACE + ":" + ExportTestPacks.DIMENSION;
|
||||
private static final int MIN_Y = -64;
|
||||
private static final int LAVA_Y = -62;
|
||||
private static final int LAVA_LINE = -54;
|
||||
private static final int CAVE_TOP = -14;
|
||||
private static final int DEEP_Y = -14;
|
||||
private static final int CHUNK_WIDTH = 16;
|
||||
private static final String CAVE_FIELD = "cave/field";
|
||||
private static final String DIMENSION = """
|
||||
{
|
||||
"regions": ["region"],
|
||||
"dimensionHeight": {"min": -64, "max": 192},
|
||||
"fluidHeight": 63,
|
||||
"caveLavaHeight": 2,
|
||||
"caveProfile": {
|
||||
"enabled": true,
|
||||
"verticalRange": {"min": 0, "max": 50},
|
||||
"verticalEdgeFade": 0,
|
||||
"baseDensityStyle": {"style": "SIMPLEX", "zoom": 0.6},
|
||||
"detailDensityStyle": {"style": "SIMPLEX", "zoom": 0.3},
|
||||
"baseWeight": 1.0,
|
||||
"detailWeight": 0.0,
|
||||
"densityThreshold": {"min": 5.0, "max": 5.0, "style": {"style": "SIMPLEX"}},
|
||||
"thresholdBias": 0.0,
|
||||
"surfaceClearance": 0,
|
||||
"allowSurfaceBreak": false,
|
||||
"allowFluid": false,
|
||||
"allowLava": true,
|
||||
"modules": []
|
||||
}
|
||||
"caves": ["tunnels"]
|
||||
}
|
||||
""";
|
||||
private static final String TUNNELS = """
|
||||
{"tunnel": {"width": {"min": 5, "max": 8}, "spacing": {"horizontal": 32, "vertical": 24}},
|
||||
"depth": {"min": -60, "max": 0}, "surfaceClearance": 0, "allowLava": true}
|
||||
""";
|
||||
|
||||
@Rule
|
||||
public TemporaryFolder temporaryFolder = new TemporaryFolder();
|
||||
@@ -73,53 +61,42 @@ public final class WorldgenExportDeepCaves263Test {
|
||||
public ExportTestPacks.BoundPlatform platform = new ExportTestPacks.BoundPlatform();
|
||||
|
||||
@Test
|
||||
public void deepCavesOpenAsAirAboveTheIrisLavaBand() throws IOException {
|
||||
public void listedCavesAreReportedAsNotExportedOnce() throws IOException {
|
||||
WorldgenExportResult result = export();
|
||||
|
||||
assertTrue(result.message() + " " + result.diagnostics(), result.isSuccess());
|
||||
JsonObject head = JsonParser.parseString(Files.readString(result.output().resolve("data/" + NAMESPACE + "/worldgen/material_rule/"
|
||||
+ ExportTestPacks.DIMENSION + ".json"), StandardCharsets.UTF_8)).getAsJsonObject().getAsJsonArray("sequence").get(0).getAsJsonObject();
|
||||
assertEquals("minecraft:ore_vein", head.get("type").getAsString());
|
||||
String opening = head.get("density").getAsString();
|
||||
assertTrue(opening, Files.isRegularFile(densityFunction(result.output(), opening)));
|
||||
long reports = result.diagnostics().stream().filter(diagnostic -> diagnostic.limit() == ExportLimit.LISTED_CAVES).count();
|
||||
assertEquals(result.diagnostics().toString(), 1, reports);
|
||||
assertTrue(result.diagnostics().stream().filter(diagnostic -> diagnostic.limit() == ExportLimit.LISTED_CAVES)
|
||||
.allMatch(diagnostic -> diagnostic.severity() == ExportDiagnostic.Severity.WARNING));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void theExportedWorldHasNoCaveFieldNoDeepCaveOpeningAndNoCaveAir() throws IOException {
|
||||
WorldgenExportResult result = export();
|
||||
assertTrue(result.message() + " " + result.diagnostics(), result.isSuccess());
|
||||
|
||||
Path materialRule = result.output().resolve("data/" + NAMESPACE + "/worldgen/material_rule/" + ExportTestPacks.DIMENSION + ".json");
|
||||
JsonObject rules = JsonParser.parseString(Files.readString(materialRule, StandardCharsets.UTF_8)).getAsJsonObject();
|
||||
assertFalse(rules.toString(), rules.toString().contains("cave/"));
|
||||
assertFalse(Files.exists(result.output().resolve("data/" + NAMESPACE + "/worldgen/density_function/cave/field.json")));
|
||||
try (WorldgenExportSampler sampler = WorldgenExportSampler.open(result.output(), WorldgenExportMode.OVERWORLD, DIMENSION_ID, SEED)) {
|
||||
ProtoChunk chunk = sampler.terrainChunk(0, 0);
|
||||
for (int x = 0; x < CHUNK_WIDTH; x++) {
|
||||
for (int z = 0; z < CHUNK_WIDTH; z++) {
|
||||
for (int y = MIN_Y; y <= CAVE_TOP; y++) {
|
||||
for (int y = MIN_Y + 1; y <= DEEP_Y; y++) {
|
||||
BlockState state = chunk.getBlockState(new BlockPos(x, y, z));
|
||||
String where = state + " at " + x + "," + y + "," + z;
|
||||
if (y <= LAVA_Y) {
|
||||
assertTrue(where, state.is(Blocks.LAVA));
|
||||
} else {
|
||||
assertTrue(where, state.isAir());
|
||||
}
|
||||
assertFalse(state + " at " + x + "," + y + "," + z, state.isAir() || state.is(Blocks.LAVA));
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue(chunk.getBlockState(new BlockPos(0, LAVA_LINE - 1, 0)).isAir());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deepCaveRuleSharesTheCaveFieldCacheWithTheFinalDensity() throws IOException {
|
||||
WorldgenExportResult result = export();
|
||||
assertTrue(result.message() + " " + result.diagnostics(), result.isSuccess());
|
||||
|
||||
try (WorldgenExportSampler sampler = WorldgenExportSampler.open(result.output(), WorldgenExportMode.OVERWORLD, DIMENSION_ID, SEED)) {
|
||||
CompiledCaches caches = CompiledCaches.open(sampler.registries(), SEED);
|
||||
DensityFunction opening = caches.oreVeins().getFirst().density();
|
||||
int field = caches.rootId(caches.function(NAMESPACE + ":" + CAVE_FIELD));
|
||||
Set<Integer> finalDensity = caches.ids(caches.finalDensity());
|
||||
|
||||
assertTrue(caches.ids(opening).toString(), caches.ids(opening).contains(field));
|
||||
assertTrue(finalDensity.toString(), finalDensity.contains(field));
|
||||
assertTrue(finalDensity.toString(), finalDensity.contains(caches.rootId(opening)));
|
||||
}
|
||||
}
|
||||
|
||||
private WorldgenExportResult export() throws IOException {
|
||||
File pack = ExportTestPacks.withDimension(temporaryFolder.newFolder("pack"), DIMENSION);
|
||||
Files.createDirectories(pack.toPath().resolve("caves"));
|
||||
Files.writeString(pack.toPath().resolve("caves/tunnels.json"), TUNNELS, StandardCharsets.UTF_8);
|
||||
WorldgenExportRequest request = WorldgenExportRequest.builder()
|
||||
.pack(pack.toPath())
|
||||
.dimension(ExportTestPacks.DIMENSION)
|
||||
@@ -128,9 +105,4 @@ public final class WorldgenExportDeepCaves263Test {
|
||||
.build();
|
||||
return WorldgenDatapackExporter.create().export(request, WorldgenExportProgress.NONE);
|
||||
}
|
||||
|
||||
private static Path densityFunction(Path datapack, String id) {
|
||||
int separator = id.indexOf(':');
|
||||
return datapack.resolve("data/" + id.substring(0, separator) + "/worldgen/density_function/" + id.substring(separator + 1) + ".json");
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ package art.arcane.iris;
|
||||
import art.arcane.iris.api.terrain.IrisTerrainService;
|
||||
import art.arcane.iris.command.CommandSVC;
|
||||
import art.arcane.iris.configuration.IrisSettings;
|
||||
import art.arcane.iris.studio.app.StudioAppInstaller;
|
||||
import art.arcane.iris.configuration.SettingsHotloadWatch;
|
||||
import art.arcane.iris.diagnostics.LogFilterSVC;
|
||||
import art.arcane.iris.diagnostics.splash.IrisSplashComposer;
|
||||
@@ -58,7 +59,6 @@ import art.arcane.iris.platform.agent.AttachSignal;
|
||||
import art.arcane.iris.platform.bootstrap.Bindings;
|
||||
import art.arcane.iris.platform.bootstrap.ServerProperties;
|
||||
import art.arcane.iris.platform.bootstrap.SlimJar;
|
||||
import art.arcane.iris.platform.bukkit.BlockRulesSVC;
|
||||
import art.arcane.iris.platform.bukkit.BoardSVC;
|
||||
import art.arcane.iris.platform.bukkit.BukkitPlatform;
|
||||
import art.arcane.iris.platform.bukkit.api.IrisApiEventSVC;
|
||||
@@ -682,7 +682,6 @@ public final class IrisRuntime implements IrisPluginRuntime {
|
||||
new GlobalCacheSVC(),
|
||||
new LogFilterSVC(),
|
||||
new ExternalDataSVC(),
|
||||
new BlockRulesSVC(),
|
||||
new EditSVC(),
|
||||
new ObjectSVC(),
|
||||
new ObjectStudioSaveService(),
|
||||
@@ -978,6 +977,7 @@ public final class IrisRuntime implements IrisPluginRuntime {
|
||||
return;
|
||||
}
|
||||
BukkitGuiHost.install();
|
||||
StudioAppInstaller.installInBackground();
|
||||
// super.onEnable() already registers this instance as a listener.
|
||||
plugin.enablePlugin();
|
||||
if (IrisStartupValidation.isRestartRequired()) {
|
||||
|
||||
@@ -28,8 +28,7 @@ import art.arcane.volmlib.util.director.annotations.Director;
|
||||
import art.arcane.volmlib.util.director.annotations.Param;
|
||||
import art.arcane.iris.localization.C;
|
||||
|
||||
import java.awt.Desktop;
|
||||
import java.awt.GraphicsEnvironment;
|
||||
import art.arcane.iris.studio.workspace.FileOpener;
|
||||
|
||||
|
||||
import art.arcane.iris.localization.IrisLanguage;
|
||||
@@ -51,15 +50,10 @@ public class CommandEdit implements DirectorExecutor {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (GraphicsEnvironment.isHeadless()) {
|
||||
if (!FileOpener.isDesktopAvailable()) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANNOT_OPEN_FILES_HEADLESS_ENVIRONMENTS));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!Desktop.isDesktopSupported()) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_DESKTOP_IS_NOT_SUPPORTED_BY_THIS_ENVIRONMENT));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -74,7 +68,7 @@ public class CommandEdit implements DirectorExecutor {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANNOT_FIND_FILE_PERHAPS_IT_WAS_NOT_LOADED_DIRECTLY_FROM));
|
||||
return;
|
||||
}
|
||||
Desktop.getDesktop().open(biome.getLoadFile());
|
||||
FileOpener.open(biome.getLoadFile());
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_OPENING_VSCODE, MessageArgument.untrusted("value", biome.getTypeName()), MessageArgument.untrusted("value2", biome.getLoadFile().getName().split("\\Q.\\E")[0])));
|
||||
} catch (Throwable e) {
|
||||
Iris.reportError(e);
|
||||
@@ -92,7 +86,7 @@ public class CommandEdit implements DirectorExecutor {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANNOT_FIND_FILE_PERHAPS_IT_WAS_NOT_LOADED_DIRECTLY_FROM_2));
|
||||
return;
|
||||
}
|
||||
Desktop.getDesktop().open(region.getLoadFile());
|
||||
FileOpener.open(region.getLoadFile());
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_OPENING_VSCODE_2, MessageArgument.untrusted("value", region.getTypeName()), MessageArgument.untrusted("value2", region.getLoadFile().getName().split("\\Q.\\E")[0])));
|
||||
} catch (Throwable e) {
|
||||
Iris.reportError(e);
|
||||
@@ -110,7 +104,7 @@ public class CommandEdit implements DirectorExecutor {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANNOT_FIND_FILE_PERHAPS_IT_WAS_NOT_LOADED_DIRECTLY_FROM_3));
|
||||
return;
|
||||
}
|
||||
Desktop.getDesktop().open(dimension.getLoadFile());
|
||||
FileOpener.open(dimension.getLoadFile());
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_OPENING_VSCODE_3, MessageArgument.untrusted("value", dimension.getTypeName()), MessageArgument.untrusted("value2", dimension.getLoadFile().getName().split("\\Q.\\E")[0])));
|
||||
} catch (Throwable e) {
|
||||
Iris.reportError(e);
|
||||
|
||||
@@ -21,9 +21,11 @@ package art.arcane.iris.command;
|
||||
import art.arcane.iris.Iris;
|
||||
import art.arcane.iris.platform.bukkit.BukkitPlatform;
|
||||
import art.arcane.iris.configuration.IrisSettings;
|
||||
import art.arcane.iris.studio.map.MapWindow;
|
||||
import art.arcane.iris.studio.map.PaletteExplorerStart;
|
||||
import art.arcane.iris.studio.view.GuiHost;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.studio.bridge.StudioBridge;
|
||||
import art.arcane.iris.studio.bridge.StudioBridges;
|
||||
import art.arcane.iris.studio.bridge.StudioLaunch;
|
||||
import art.arcane.iris.studio.bridge.StudioWindow;
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.studio.workspace.IrisProject;
|
||||
import art.arcane.iris.studio.workspace.IrisCodeWorkspace;
|
||||
@@ -104,6 +106,7 @@ import java.util.function.Consumer;
|
||||
import art.arcane.iris.localization.IrisLanguage;
|
||||
import art.arcane.iris.localization.BukkitCommandMessages;
|
||||
import art.arcane.volmlib.util.localization.MessageArgument;
|
||||
import art.arcane.volmlib.util.localization.TextKey;
|
||||
import art.arcane.volmlib.util.localization.LanguageAudience;
|
||||
import art.arcane.iris.localization.BukkitCommandMessagesExtended;
|
||||
@Director(name = "studio", aliases = {"std", "s"}, description = "Studio Commands", descriptionKey = "iris.director.commandstudio.director.studio_commands")
|
||||
@@ -267,16 +270,10 @@ public class CommandStudio implements DirectorExecutor {
|
||||
|
||||
@Director(description = "Open the noise explorer (External GUI)", descriptionKey = "iris.director.commandstudio.director.open_noise_explorer_external_gui", aliases = {"nmap"})
|
||||
public void noise(
|
||||
@Param(description = "Optional pack generator to preview", descriptionKey = "iris.director.commandstudio.param.optional_pack_generator_preview", defaultValue = "null", contextual = true, contextualOverride = true)
|
||||
IrisGenerator generator,
|
||||
@Param(description = "The seed to preview the generator with", descriptionKey = "iris.director.commandstudio.param.seed_preview_generator_with", defaultValue = "12345")
|
||||
long seed
|
||||
@Param(name = "world", description = "The Iris world whose pack the noise explorer reads", descriptionKey = "iris.director.commandstudio.param.world_open_generator", contextual = true, contextualOverride = true)
|
||||
World world
|
||||
) {
|
||||
if (noGUI()) return;
|
||||
VolmitSender commandSender = sender();
|
||||
UUID openerId = commandSender.isPlayer() ? commandSender.player().getUniqueId() : null;
|
||||
MapWindow.NoiseSelection selection = new MapWindow.NoiseSelection(generator == null ? null : generator.getLoadKey(), generator, seed);
|
||||
withPlayerContext(opener -> openNoiseAtPlayer(commandSender, openerId, opener, selection));
|
||||
openStudioApp(world, BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_NOISE_EXPLORER);
|
||||
}
|
||||
|
||||
@Director(description = "Open the image-map studio (External GUI)", descriptionKey = "iris.director.commandstudio.director.open_image_map_studio_external_gui", aliases = {"imap"})
|
||||
@@ -284,16 +281,7 @@ public class CommandStudio implements DirectorExecutor {
|
||||
@Param(name = "world", description = "The Iris world whose active pack receives image-map exports", descriptionKey = "iris.director.commandstudio.param.world_open_image_map_studio", contextual = true, contextualOverride = true)
|
||||
World world
|
||||
) {
|
||||
if (noGUI()) {
|
||||
return;
|
||||
}
|
||||
if (!IrisToolbelt.isIrisWorld(world)) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_NEED_BE_SPECIFY_IRIS_GENERATED_WORLD));
|
||||
return;
|
||||
}
|
||||
|
||||
requestMapStart(world, MapWindow::openImageMaps);
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_IMAGE_MAP_STUDIO));
|
||||
openStudioApp(world, BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_IMAGE_MAP_STUDIO);
|
||||
}
|
||||
|
||||
@Director(description = "Show loot if a chest were right here", descriptionKey = "iris.director.commandstudio.director.show_loot_if_chest_were_right_here", origin = DirectorOrigin.PLAYER, sync = true)
|
||||
@@ -377,7 +365,7 @@ public class CommandStudio implements DirectorExecutor {
|
||||
boolean progressShown = false;
|
||||
int c = -1;
|
||||
try {
|
||||
engine.getDimension().getRegions().forEach(key -> data.put(key, new AtomicInteger(0)));
|
||||
engine.getDimension().getRegionKeys().forEach(key -> data.put(key, new AtomicInteger(0)));
|
||||
multiBurst = new MultiBurst("Region Sampler");
|
||||
var executor = multiBurst.burst(Math.min(radius * radius, 1 << 20));
|
||||
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_GENERATING_DATA));
|
||||
@@ -425,66 +413,45 @@ public class CommandStudio implements DirectorExecutor {
|
||||
@Param(name = "world", description = "The world to open the generator for", descriptionKey = "iris.director.commandstudio.param.world_open_generator", contextual = true, contextualOverride = true)
|
||||
World world
|
||||
) {
|
||||
if (noGUI()) return;
|
||||
openStudioApp(world, BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP);
|
||||
}
|
||||
|
||||
@Director(description = "Open the Iris Studio app on a world", descriptionKey = "iris.director.commandstudio.director.render_world_map_external_gui", aliases = "app")
|
||||
public void studioApp(
|
||||
@Param(name = "world", description = "The world to open the generator for", descriptionKey = "iris.director.commandstudio.param.world_open_generator", contextual = true, contextualOverride = true)
|
||||
World world
|
||||
) {
|
||||
openStudioApp(world, BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP);
|
||||
}
|
||||
|
||||
/** Opens the app on the world; when it can't, tells the sender why and hands over the link to connect by hand. */
|
||||
private void openStudioApp(World world, TextKey openedMessage) {
|
||||
if (!IrisToolbelt.isIrisWorld(world)) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_NEED_BE_SPECIFY_IRIS_GENERATED_WORLD));
|
||||
return;
|
||||
}
|
||||
|
||||
requestMapStart(world, MapWindow::openMap);
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP));
|
||||
}
|
||||
|
||||
// The map opens where the player stands when they are in that world, otherwise at the world origin.
|
||||
private PaletteExplorerStart mapStartIn(World world, Player opener, UUID openerId) {
|
||||
Location center = opener != null && opener.getWorld().equals(world) ? opener.getLocation() : null;
|
||||
return new PaletteExplorerStart(
|
||||
IrisToolbelt.access(world).getEngine(),
|
||||
world.getUID(),
|
||||
openerId,
|
||||
null,
|
||||
center == null ? 0D : center.getX(),
|
||||
center == null ? 0D : center.getZ()
|
||||
);
|
||||
}
|
||||
|
||||
private void requestMapStart(World world, Consumer<PaletteExplorerStart> launch) {
|
||||
UUID openerId = sender().isPlayer() ? player().getUniqueId() : null;
|
||||
withPlayerContext(opener -> launch.accept(mapStartIn(world, opener, openerId)));
|
||||
}
|
||||
|
||||
private void openNoiseAtPlayer(VolmitSender commandSender, UUID openerId, Player opener, MapWindow.NoiseSelection selection) {
|
||||
World world = opener == null ? null : opener.getWorld();
|
||||
PlatformChunkGenerator worldGenerator = world == null ? null : IrisToolbelt.access(world);
|
||||
Engine engine = worldGenerator == null ? GuiHost.get().findActiveEngine() : worldGenerator.getEngine();
|
||||
if (engine == null) {
|
||||
commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_NEED_BE_SPECIFY_IRIS_GENERATED_WORLD));
|
||||
PlatformChunkGenerator generator = IrisToolbelt.access(world);
|
||||
StudioBridge bridge;
|
||||
try {
|
||||
bridge = StudioBridges.open(world.getName(), generator::getEngine, openerId);
|
||||
} catch (IOException error) {
|
||||
IrisLogging.warn("Could not open the studio bridge: %s", error.getMessage());
|
||||
return;
|
||||
}
|
||||
PaletteExplorerStart start = worldGenerator == null
|
||||
? new PaletteExplorerStart(engine, null, openerId, null, 0D, 0D)
|
||||
: mapStartIn(world, opener, openerId);
|
||||
MapWindow.openNoise(start, selection);
|
||||
commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_NOISE_EXPLORER));
|
||||
}
|
||||
|
||||
private void withPlayerContext(Consumer<Player> action) {
|
||||
Player opener = sender().isPlayer() ? player() : null;
|
||||
if (opener == null) {
|
||||
action.accept(null);
|
||||
StudioLaunch launch = StudioWindow.show(bridge);
|
||||
if (launch.opened()) {
|
||||
sender().sendMessage(IrisLanguage.text(openedMessage));
|
||||
return;
|
||||
}
|
||||
AtomicBoolean completed = new AtomicBoolean();
|
||||
Consumer<Player> complete = player -> {
|
||||
if (completed.compareAndSet(false, true)) {
|
||||
action.accept(player);
|
||||
}
|
||||
};
|
||||
Runnable retired = () -> complete.accept(null);
|
||||
if (!J.runEntity(opener, () -> complete.accept(opener.isOnline() ? opener : null), 0, retired)) {
|
||||
retired.run();
|
||||
}
|
||||
IrisLogging.info("Iris Studio link for %s: %s", world.getName(), bridge.link());
|
||||
sendStudioLink(launch, bridge.link());
|
||||
}
|
||||
|
||||
private void sendStudioLink(StudioLaunch launch, String link) {
|
||||
sender().sendMessage(C.RED + IrisLanguage.text(launch.failureMessage()));
|
||||
sender().sendCopyButton(IrisLanguage.text(RuntimeUiMessages.STUDIO_LINK_COPY_BUTTON),
|
||||
IrisLanguage.text(RuntimeUiMessages.STUDIO_LINK_COPY_HOVER), link);
|
||||
}
|
||||
|
||||
@Director(description = "Profiles the performance of a dimension", descriptionKey = "iris.director.commandstudio.director.profiles_performance_dimension", origin = DirectorOrigin.PLAYER)
|
||||
@@ -953,21 +920,6 @@ public class CommandStudio implements DirectorExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if server GUIs are not enabled
|
||||
*/
|
||||
private boolean noGUI() {
|
||||
if (!IrisSettings.get().getGui().isUseServerLaunchedGuis()) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_MUST_HAVE_SERVER_LAUNCHED_GUIS_ENABLED_SETTINGS));
|
||||
return true;
|
||||
}
|
||||
if (!GuiHost.isAvailable()) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_DESKTOP_UNAVAILABLE));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if no studio is open or the player is not in one
|
||||
*/
|
||||
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
package art.arcane.iris.platform.bukkit;
|
||||
|
||||
import art.arcane.iris.platform.bukkit.nms.INMS;
|
||||
import art.arcane.iris.platform.bukkit.plugin.IrisService;
|
||||
import io.papermc.paper.event.server.ServerResourcesReloadedEvent;
|
||||
import org.bukkit.event.EventHandler;
|
||||
|
||||
/** Lets the server's placement rules apply again after a resource reload, which may have changed the block tags they read. */
|
||||
public class BlockRulesSVC implements IrisService {
|
||||
@Override
|
||||
public void onEnable() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onResourcesReloaded(ServerResourcesReloadedEvent event) {
|
||||
if (INMS.isBound()) {
|
||||
INMS.get().forgetBlockRules();
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -10,6 +10,5 @@
|
||||
"dimensionHeight": {"min": 0, "max": 128},
|
||||
"logicalHeight": 128,
|
||||
"fluidHeight": 0,
|
||||
"bedrock": false,
|
||||
"caveProfile": {"enabled": false}
|
||||
"bedrock": false
|
||||
}
|
||||
-83
@@ -1,83 +0,0 @@
|
||||
package art.arcane.iris.command;
|
||||
|
||||
import art.arcane.iris.configuration.IrisSettings;
|
||||
import art.arcane.iris.platform.bukkit.plugin.VolmitSender;
|
||||
import art.arcane.iris.studio.view.GuiHost;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class CommandStudioDesktopTest {
|
||||
private IrisSettings previousSettings;
|
||||
private boolean previousSuppressed;
|
||||
private RecordingSender sender;
|
||||
private CommandStudio command;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
previousSettings = IrisSettings.settings;
|
||||
previousSuppressed = GuiHost.isDesktopSuppressed();
|
||||
IrisSettings.settings = new IrisSettings();
|
||||
IrisSettings.settings.getGui().setUseServerLaunchedGuis(true);
|
||||
GuiHost.suppressDesktop(true);
|
||||
sender = new RecordingSender();
|
||||
command = new TestCommand(sender);
|
||||
}
|
||||
|
||||
@After
|
||||
public void restore() {
|
||||
IrisSettings.settings = previousSettings;
|
||||
GuiHost.suppressDesktop(previousSuppressed);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mapReportsMissingDisplayBeforeAccessingWorld() {
|
||||
command.map(null);
|
||||
|
||||
assertDisplayMessage();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void imageMapReportsMissingDisplayInsteadOfDisabledSetting() {
|
||||
command.imagemap(null);
|
||||
|
||||
assertDisplayMessage();
|
||||
}
|
||||
|
||||
private void assertDisplayMessage() {
|
||||
assertEquals(1, sender.messages.size());
|
||||
assertTrue(sender.messages.getFirst(), sender.messages.getFirst().contains("display"));
|
||||
}
|
||||
|
||||
private static final class TestCommand extends CommandStudio {
|
||||
private final VolmitSender sender;
|
||||
|
||||
private TestCommand(VolmitSender sender) {
|
||||
this.sender = sender;
|
||||
}
|
||||
|
||||
@Override
|
||||
public VolmitSender sender() {
|
||||
return sender;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class RecordingSender extends VolmitSender {
|
||||
private final List<String> messages = new ArrayList<>();
|
||||
|
||||
private RecordingSender() {
|
||||
super(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendMessage(String message) {
|
||||
messages.add(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
-99
@@ -1,99 +0,0 @@
|
||||
package art.arcane.iris.command;
|
||||
|
||||
import art.arcane.iris.configuration.IrisSettings;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.platform.bukkit.plugin.VolmitSender;
|
||||
import art.arcane.iris.platform.generation.PlatformChunkGenerator;
|
||||
import art.arcane.iris.studio.map.MapWindow;
|
||||
import art.arcane.iris.studio.map.PaletteExplorerStart;
|
||||
import art.arcane.iris.studio.view.GuiHost;
|
||||
import art.arcane.iris.world.IrisToolbelt;
|
||||
import art.arcane.iris.world.task.J;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.junit.Test;
|
||||
import org.mockito.MockedStatic;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.same;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class StudioMapPositionTest {
|
||||
@Test
|
||||
public void mapCapturesItsStartingPositionOnThePlayerScheduler() {
|
||||
IrisSettings previous = IrisSettings.settings;
|
||||
IrisSettings.settings = new IrisSettings();
|
||||
IrisSettings.settings.getGui().setUseServerLaunchedGuis(true);
|
||||
World world = mock(World.class);
|
||||
Player player = mock(Player.class);
|
||||
VolmitSender sender = mock(VolmitSender.class);
|
||||
PlatformChunkGenerator generator = mock(PlatformChunkGenerator.class);
|
||||
Engine engine = mock(Engine.class);
|
||||
UUID playerId = UUID.randomUUID();
|
||||
UUID worldId = UUID.randomUUID();
|
||||
AtomicBoolean owned = new AtomicBoolean();
|
||||
AtomicReference<Runnable> task = new AtomicReference<>();
|
||||
AtomicReference<PaletteExplorerStart> start = new AtomicReference<>();
|
||||
when(world.getUID()).thenReturn(worldId);
|
||||
when(player.getUniqueId()).thenReturn(playerId);
|
||||
when(player.isOnline()).thenReturn(true);
|
||||
when(player.getWorld()).thenAnswer(invocation -> {
|
||||
assertTrue("world read must use the player scheduler", owned.get());
|
||||
return world;
|
||||
});
|
||||
when(player.getLocation()).thenAnswer(invocation -> {
|
||||
assertTrue("location read must use the player scheduler", owned.get());
|
||||
return new Location(world, 33.25D, 91D, -72.5D);
|
||||
});
|
||||
when(sender.isPlayer()).thenReturn(true);
|
||||
when(sender.player()).thenReturn(player);
|
||||
when(generator.getEngine()).thenReturn(engine);
|
||||
CommandStudio command = new CommandStudio() {
|
||||
@Override
|
||||
public VolmitSender sender() {
|
||||
return sender;
|
||||
}
|
||||
};
|
||||
try (MockedStatic<GuiHost> host = mockStatic(GuiHost.class);
|
||||
MockedStatic<IrisToolbelt> toolbelt = mockStatic(IrisToolbelt.class);
|
||||
MockedStatic<J> scheduling = mockStatic(J.class);
|
||||
MockedStatic<MapWindow> windows = mockStatic(MapWindow.class)) {
|
||||
host.when(GuiHost::isAvailable).thenReturn(true);
|
||||
toolbelt.when(() -> IrisToolbelt.isIrisWorld(world)).thenReturn(true);
|
||||
toolbelt.when(() -> IrisToolbelt.access(world)).thenReturn(generator);
|
||||
scheduling.when(() -> J.runEntity(same(player), any(Runnable.class), eq(0), any(Runnable.class)))
|
||||
.thenAnswer(invocation -> {
|
||||
task.set(invocation.getArgument(1));
|
||||
return true;
|
||||
});
|
||||
windows.when(() -> MapWindow.openMap(any(PaletteExplorerStart.class))).thenAnswer(invocation -> {
|
||||
start.set(invocation.getArgument(0));
|
||||
return null;
|
||||
});
|
||||
|
||||
command.map(world);
|
||||
assertNull(start.get());
|
||||
owned.set(true);
|
||||
task.get().run();
|
||||
|
||||
assertEquals(engine, start.get().engine());
|
||||
assertEquals(playerId, start.get().playerId());
|
||||
assertEquals(worldId, start.get().worldId());
|
||||
assertEquals(33.25D, start.get().centerX(), 0D);
|
||||
assertEquals(-72.5D, start.get().centerZ(), 0D);
|
||||
} finally {
|
||||
IrisSettings.settings = previous;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -104,7 +104,7 @@ repositories {
|
||||
name = 'FabricMC'
|
||||
url = uri('https://maven.fabricmc.net/')
|
||||
}
|
||||
maven { url = uri('https://repo.codemc.io/repository/maven-public/') }
|
||||
maven { url = uri('https://repo.codemc.org/repository/maven-public/') }
|
||||
maven { url = uri('https://jitpack.io') }
|
||||
maven { url = uri('https://hub.spigotmc.org/nexus/content/repositories/snapshots/') }
|
||||
}
|
||||
@@ -331,6 +331,7 @@ tasks.named('shadowJar', ShadowJar).configure {
|
||||
if ((int) irisModTarget.java == 21) {
|
||||
exclude(java21RuntimeExclusions)
|
||||
}
|
||||
exclude('META-INF/maven/**')
|
||||
exclude('META-INF/proguard/**')
|
||||
exclude('META-INF/*.SF')
|
||||
exclude('META-INF/*.DSA')
|
||||
@@ -414,7 +415,6 @@ tasks.named('assemble').configure {
|
||||
}
|
||||
|
||||
pluginPackaging {
|
||||
nativeBoundaryChecks = true
|
||||
artifacts {
|
||||
create('distribution') {
|
||||
taskName = irisModTarget.fabricRemap ? 'remapJar' : 'shadowJar'
|
||||
|
||||
@@ -121,7 +121,7 @@ repositories {
|
||||
maven fg.forgeMaven
|
||||
maven fg.minecraftLibsMaven
|
||||
mavenCentral()
|
||||
maven { url = uri('https://repo.codemc.io/repository/maven-public/') }
|
||||
maven { url = uri('https://repo.codemc.org/repository/maven-public/') }
|
||||
maven { url = uri('https://jitpack.io') }
|
||||
maven { url = uri('https://hub.spigotmc.org/nexus/content/repositories/snapshots/') }
|
||||
}
|
||||
@@ -320,6 +320,7 @@ tasks.named('shadowJar', ShadowJar).configure {
|
||||
if ((int) irisModTarget.java == 21) {
|
||||
exclude(java21RuntimeExclusions)
|
||||
}
|
||||
exclude('META-INF/maven/**')
|
||||
exclude('META-INF/proguard/**')
|
||||
exclude('META-INF/*.SF')
|
||||
exclude('META-INF/*.DSA')
|
||||
@@ -376,7 +377,6 @@ tasks.named('assemble').configure {
|
||||
}
|
||||
|
||||
pluginPackaging {
|
||||
nativeBoundaryChecks = true
|
||||
artifacts {
|
||||
create('distribution') {
|
||||
taskName = 'shadowJar'
|
||||
|
||||
@@ -46,6 +46,7 @@ import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeEntityBehavior;
|
||||
import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeStateMerger;
|
||||
import art.arcane.volmlib.nativelib.minecraft26_2.modded.ModdedServerAccess;
|
||||
|
||||
import art.arcane.iris.studio.app.StudioAppInstaller;
|
||||
import art.arcane.iris.studio.view.GuiHost;
|
||||
import art.arcane.iris.localization.IrisLanguage;
|
||||
import art.arcane.iris.generation.decoration.DecoratorPlatformHooks;
|
||||
@@ -492,6 +493,7 @@ public final class ModdedEngineBootstrap {
|
||||
GuiHost.Provider previousGuiHost = GuiHost.get();
|
||||
ModdedGuiHost.install();
|
||||
rollback.add(() -> GuiHost.set(previousGuiHost));
|
||||
StudioAppInstaller.installInBackground();
|
||||
|
||||
ModdedDecoratorHooks decoratorHooks = new ModdedDecoratorHooks();
|
||||
DecoratorPlatformHooks.Bindings previousDecoratorBindings = DecoratorPlatformHooks.bind(decoratorHooks, decoratorHooks);
|
||||
|
||||
+3
-5
@@ -19,7 +19,6 @@
|
||||
package art.arcane.iris.modded;
|
||||
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.configuration.IrisSettings;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.generation.runtime.BiomeEnvironment;
|
||||
@@ -224,18 +223,17 @@ public final class ModdedEngineEffects extends EngineAssignedComponent implement
|
||||
}
|
||||
|
||||
private void applyEffects(NativeWorld level, NativeProtocolPlayer player, Iterable<IrisEffect> effects) {
|
||||
PackRuntime runtime = PackRuntime.of(getEngine());
|
||||
for (IrisEffect effect : effects) {
|
||||
try {
|
||||
applyEffect(level, player, effect, runtime);
|
||||
applyEffect(level, player, effect);
|
||||
} catch (Throwable error) {
|
||||
IrisLogging.reportError(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void applyEffect(NativeWorld level, NativeProtocolPlayer player, IrisEffect effect, PackRuntime runtime) {
|
||||
if (!effect.shouldApplyNow(runtime)) {
|
||||
private void applyEffect(NativeWorld level, NativeProtocolPlayer player, IrisEffect effect) {
|
||||
if (!effect.shouldApplyNow()) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
+3
-5
@@ -18,7 +18,6 @@
|
||||
|
||||
package art.arcane.iris.modded;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.configuration.IrisSettings;
|
||||
import art.arcane.iris.generation.decoration.IrisSurface;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
@@ -128,7 +127,7 @@ public final class ModdedEntitySpawner {
|
||||
|
||||
entity.configureAnimal(irisEntity);
|
||||
|
||||
applySpawnEffect(irisEntity.getSpawnEffect(), entity, level, PackRuntime.of(engine));
|
||||
applySpawnEffect(irisEntity.getSpawnEffect(), entity, level);
|
||||
ModdedEntityCommandRunner.run(irisEntity.getRawCommands(), level.world(), blockX, blockY, blockZ);
|
||||
if (riseEffectActive && entity.living()) {
|
||||
startRiseEffect(engine, level, entity);
|
||||
@@ -201,9 +200,8 @@ public final class ModdedEntitySpawner {
|
||||
return level.chunksSafe(chunkX, chunkZ);
|
||||
}
|
||||
|
||||
private static void applySpawnEffect(IrisEffect effect, NativeSpawnedEntity entity, NativeEntityRuntime level,
|
||||
PackRuntime runtime) {
|
||||
if (effect == null || !effect.shouldApplyNow(runtime)) {
|
||||
private static void applySpawnEffect(IrisEffect effect, NativeSpawnedEntity entity, NativeEntityRuntime level) {
|
||||
if (effect == null || !effect.shouldApplyNow()) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -30,7 +30,6 @@ import art.arcane.iris.world.loot.IrisLootTable;
|
||||
import art.arcane.iris.structure.object.IrisObjectLoot;
|
||||
import art.arcane.iris.structure.object.IrisObjectPlacement;
|
||||
import art.arcane.iris.structure.object.IrisObjectVanillaLoot;
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
|
||||
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
|
||||
@@ -41,9 +40,6 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public final class ModdedLootApplier {
|
||||
private static final String LOOT_TABLE_KEY_KIND = "missing-loot-table";
|
||||
private static final String VANILLA_LOOT_TABLE_KEY_KIND = "missing-vanilla-loot-table";
|
||||
|
||||
private ModdedLootApplier() {
|
||||
}
|
||||
|
||||
@@ -121,8 +117,7 @@ public final class ModdedLootApplier {
|
||||
}
|
||||
IrisLootTable table = engine.getData().getLootLoader().load(loot.getName());
|
||||
if (table == null) {
|
||||
IrisLogging.warnOnce(IrisData.onceKey(engine.getData(), LOOT_TABLE_KEY_KIND, loot.getName()),
|
||||
"Couldn't find loot table " + loot.getName());
|
||||
IrisLogging.warn("Couldn't find loot table " + loot.getName());
|
||||
continue;
|
||||
}
|
||||
bucket(engine, loot, new Candidate(new IrisLootSource(table), loot.getWeight()), access, exact, basic, global);
|
||||
@@ -134,8 +129,7 @@ public final class ModdedLootApplier {
|
||||
}
|
||||
NativeContainerLoot.Table table = access.table(loot.getName());
|
||||
if (table == null) {
|
||||
IrisLogging.warnOnce(IrisData.onceKey(engine.getData(), VANILLA_LOOT_TABLE_KEY_KIND, loot.getName()),
|
||||
"Couldn't find vanilla loot table " + loot.getName());
|
||||
IrisLogging.warn("Couldn't find vanilla loot table " + loot.getName());
|
||||
continue;
|
||||
}
|
||||
bucket(engine, loot, new Candidate(new NativeLootSource(table), loot.getWeight()), access, exact, basic, global);
|
||||
|
||||
+1
-2
@@ -1,6 +1,5 @@
|
||||
package art.arcane.iris.modded;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.volmlib.nativelib.terrain.structure.StructureStagePolicy;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.generation.mantle.DeferredPlacementRecords;
|
||||
@@ -152,7 +151,7 @@ final class ModdedNativeStructurePolicy implements NativeModdedStructureStage.Po
|
||||
|
||||
@Override
|
||||
public NativeBlockState paletteBlock(StructurePalette source, RNG rng, int x, int y, int z) {
|
||||
return ((IrisMaterialPalette) source).get(rng, x, y, z, PackRuntime.of(generator.engine()));
|
||||
return ((IrisMaterialPalette) source).get(rng, x, y, z, generator.engine().getData());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+7
-3
@@ -20,18 +20,18 @@ package art.arcane.iris.modded;
|
||||
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.pack.loading.ResourceLoader;
|
||||
import art.arcane.iris.pack.loading.SnippetFolder;
|
||||
import art.arcane.iris.pack.schema.SchemaBuilder;
|
||||
import art.arcane.iris.pack.schema.annotation.Snippet;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.world.task.J;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.format.Form;
|
||||
import art.arcane.volmlib.util.io.IO;
|
||||
import art.arcane.volmlib.util.json.JSONArray;
|
||||
import art.arcane.volmlib.util.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
public final class ModdedWorkspaceGenerator {
|
||||
private ModdedWorkspaceGenerator() {
|
||||
@@ -100,7 +100,11 @@ public final class ModdedWorkspaceGenerator {
|
||||
try {
|
||||
String snipType = snippetClass.getDeclaredAnnotation(Snippet.class).value();
|
||||
JSONObject entry = new JSONObject();
|
||||
List<String> fileMatch = new SnippetFolder(snipType).workspaceFileMatches();
|
||||
KList<String> fileMatch = new KList<>();
|
||||
|
||||
for (int depth = 1; depth < 8; depth++) {
|
||||
fileMatch.add("/snippet/" + snipType + Form.repeat("/*", depth) + ".json");
|
||||
}
|
||||
|
||||
entry.put("fileMatch", new JSONArray(fileMatch.toArray()));
|
||||
entry.put("url", "./.iris/schema/snippet/" + snipType + "-schema.json");
|
||||
|
||||
+3
-3
@@ -31,7 +31,7 @@ import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeCommandSource;
|
||||
import art.arcane.volmlib.nativelib.terrain.NativeBlockPoint;
|
||||
import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeEditPlayer;
|
||||
|
||||
import java.awt.Desktop;
|
||||
import art.arcane.iris.studio.workspace.FileOpener;
|
||||
import java.io.File;
|
||||
|
||||
final class ModdedEditCommands {
|
||||
@@ -110,7 +110,7 @@ final class ModdedEditCommands {
|
||||
}
|
||||
|
||||
private static int openJson(NativeCommandSource source, IrisRegistrant registrant) {
|
||||
if (!GuiHost.isAvailable() || !Desktop.isDesktopSupported()) {
|
||||
if (!GuiHost.isAvailable() || !FileOpener.isDesktopAvailable()) {
|
||||
IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_CANNOT_OPEN_FILES_HERE, MessageArgument.untrusted("value", ModdedGuiHost.guiUnavailableReason())));
|
||||
return 0;
|
||||
}
|
||||
@@ -120,7 +120,7 @@ final class ModdedEditCommands {
|
||||
}
|
||||
File file = registrant.getLoadFile();
|
||||
try {
|
||||
Desktop.getDesktop().open(file);
|
||||
FileOpener.open(file);
|
||||
} catch (Throwable e) {
|
||||
ModdedIrisLog.error("Iris edit failed to open {}", file, e);
|
||||
IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_COULD_NOT_OPEN, MessageArgument.untrusted("value", file.getName()), MessageArgument.untrusted("value2", e.getClass().getSimpleName())));
|
||||
|
||||
+64
-66
@@ -23,8 +23,11 @@ import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeWorldView;
|
||||
|
||||
import art.arcane.iris.modded.ModdedIrisLog;
|
||||
import art.arcane.iris.configuration.IrisSettings;
|
||||
import art.arcane.iris.studio.map.MapWindow;
|
||||
import art.arcane.iris.studio.map.PaletteExplorerStart;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.studio.bridge.StudioBridge;
|
||||
import art.arcane.iris.studio.bridge.StudioBridges;
|
||||
import art.arcane.iris.studio.bridge.StudioLaunch;
|
||||
import art.arcane.iris.studio.bridge.StudioWindow;
|
||||
import art.arcane.iris.studio.view.GuiHost;
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.pack.StructurePackageClosure;
|
||||
@@ -74,7 +77,7 @@ import art.arcane.volmlib.nativelib.terrain.NativeWorld;
|
||||
import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeProtocolPlayer;
|
||||
import org.zeroturnaround.zip.ZipUtil;
|
||||
|
||||
import java.awt.Desktop;
|
||||
import art.arcane.iris.studio.workspace.FileOpener;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
@@ -93,6 +96,9 @@ import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import art.arcane.iris.localization.IrisLanguage;
|
||||
import art.arcane.iris.localization.RuntimeUiMessages;
|
||||
import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeCommandText;
|
||||
import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeCommandText.Format;
|
||||
import art.arcane.iris.modded.localization.ModdedCommandMessages;
|
||||
import art.arcane.volmlib.util.localization.LanguageAudience;
|
||||
import art.arcane.volmlib.util.localization.MessageArgument;
|
||||
@@ -226,11 +232,7 @@ public final class ModdedStudioCommands {
|
||||
|
||||
private static LiteralArgumentBuilder<NativeCommandSource> noiseTree(String name) {
|
||||
return NativeCommandRegistration.literal(name)
|
||||
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> noise(context.getSource(), null, 12345L)))
|
||||
.then(NativeCommandRegistration.argument("generator", StringArgumentType.word()).suggests(GENERATOR_KEYS)
|
||||
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> noise(context.getSource(), StringArgumentType.getString(context, "generator"), 12345L)))
|
||||
.then(NativeCommandRegistration.argument("seed", LongArgumentType.longArg())
|
||||
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> noise(context.getSource(), StringArgumentType.getString(context, "generator"), LongArgumentType.getLong(context, "seed"))))));
|
||||
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> noise(context.getSource())));
|
||||
}
|
||||
|
||||
private static LiteralArgumentBuilder<NativeCommandSource> mapTree(String name) {
|
||||
@@ -243,88 +245,77 @@ public final class ModdedStudioCommands {
|
||||
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> imageMap(context.getSource())));
|
||||
}
|
||||
|
||||
private static int noise(NativeCommandSource source, String generatorKey, long seed) {
|
||||
NativeWorld level = source.world();
|
||||
Engine engine = IrisModdedCommands.engineFor(level);
|
||||
if (!GuiHost.isAvailable() || !IrisSettings.get().getGui().isUseServerLaunchedGuis()) {
|
||||
IrisModdedCommands.fail(source, guiUnavailableMessage());
|
||||
return 0;
|
||||
}
|
||||
if (engine != null) {
|
||||
NativeProtocolPlayer player = source.player();
|
||||
ModdedGuiHost.bindContext(worldView(source.server(), level), engine, player == null ? null : player.id());
|
||||
}
|
||||
Engine mapEngine = engine != null ? engine : GuiHost.get().findActiveEngine();
|
||||
if ((generatorKey == null || generatorKey.isBlank()) && mapEngine != null) {
|
||||
MapWindow.openNoise(mapStart(mapEngine, source.player()), new MapWindow.NoiseSelection(null, null, seed));
|
||||
IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_NOISE_EXPLORER_ON_SERVER_DISPLAY));
|
||||
return 1;
|
||||
}
|
||||
private static int noise(NativeCommandSource source) {
|
||||
Engine engine = IrisModdedCommands.engineFor(source.world());
|
||||
if (engine == null) {
|
||||
IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_THIS_DIMENSION_IS_NOT_GENERATED_BY_IRIS_RUN_IRIS_STUDIO));
|
||||
return 0;
|
||||
}
|
||||
IrisGenerator generator = engine.getData().getGeneratorLoader().load(generatorKey.trim());
|
||||
if (generator == null) {
|
||||
IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_UNKNOWN_GENERATOR_PACK, MessageArgument.untrusted("generatorKey", generatorKey), MessageArgument.untrusted("value", engine.getDimension().getLoadKey())));
|
||||
return 0;
|
||||
}
|
||||
String selectedGeneratorKey = generatorKey.trim();
|
||||
MapWindow.openNoise(mapStart(engine, source.player()), new MapWindow.NoiseSelection(selectedGeneratorKey, generator, seed));
|
||||
IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_NOISE_EXPLORER_GENERATOR_SEED, MessageArgument.untrusted("value", generatorKey.trim()), MessageArgument.untrusted("seed", seed)));
|
||||
return 1;
|
||||
return openStudioApp(source, engine, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_NOISE_EXPLORER_ON_SERVER_DISPLAY));
|
||||
}
|
||||
|
||||
private static int map(NativeCommandSource source) {
|
||||
NativeWorld level = source.world();
|
||||
Engine engine = IrisModdedCommands.engineFor(level);
|
||||
Engine engine = IrisModdedCommands.engineFor(source.world());
|
||||
if (engine == null) {
|
||||
IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_THIS_DIMENSION_IS_NOT_GENERATED_BY_IRIS_STAND_IRIS_STUDIO));
|
||||
return 0;
|
||||
}
|
||||
if (!GuiHost.isAvailable() || !IrisSettings.get().getGui().isUseServerLaunchedGuis()) {
|
||||
IrisModdedCommands.fail(source, guiUnavailableMessage());
|
||||
return 0;
|
||||
}
|
||||
NativeProtocolPlayer player = source.player();
|
||||
ModdedGuiHost.bindContext(worldView(source.server(), level), engine, player == null ? null : player.id());
|
||||
MapWindow.openMap(mapStart(engine, player));
|
||||
IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_VISION_MAP_ON_SERVER_DISPLAY, MessageArgument.untrusted("value", level.name())));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Modded worlds have no Bukkit world id; the map finds the engine again through the bound GUI context.
|
||||
private static PaletteExplorerStart mapStart(Engine engine, NativeProtocolPlayer player) {
|
||||
IrisWorld world = engine.getWorld();
|
||||
NativeWorld level = world == null ? null : world.platformWorld();
|
||||
boolean inWorld = player != null && player.connected() && level != null && player.inWorld(level);
|
||||
return new PaletteExplorerStart(engine, null, player == null ? null : player.id(), null,
|
||||
inWorld ? player.x() : 0D, inWorld ? player.z() : 0D);
|
||||
return openStudioApp(source, engine, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_VISION_MAP_ON_SERVER_DISPLAY, MessageArgument.untrusted("value", source.world().name())));
|
||||
}
|
||||
|
||||
private static int imageMap(NativeCommandSource source) {
|
||||
NativeWorld level = source.world();
|
||||
Engine engine = IrisModdedCommands.engineFor(level);
|
||||
Engine engine = IrisModdedCommands.engineFor(source.world());
|
||||
if (engine == null) {
|
||||
IrisModdedCommands.fail(source, IrisLanguage.plain(
|
||||
ModdedCommandMessages.MODDED_STUDIO_COMMANDS_IMAGE_MAP_REQUIRES_IRIS_DIMENSION
|
||||
));
|
||||
return 0;
|
||||
}
|
||||
if (!GuiHost.isAvailable() || !IrisSettings.get().getGui().isUseServerLaunchedGuis()) {
|
||||
return openStudioApp(source, engine, IrisLanguage.plain(
|
||||
ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_IMAGE_MAP_STUDIO_ON_SERVER_DISPLAY,
|
||||
MessageArgument.untrusted("value", source.world().name())
|
||||
));
|
||||
}
|
||||
|
||||
/** Opens the studio app on the source's world; when it can't, tells the source why and hands over the link to connect by hand. */
|
||||
private static int openStudioApp(NativeCommandSource source, Engine engine, String openedMessage) {
|
||||
if (GuiHost.isDesktopSuppressed()) {
|
||||
IrisModdedCommands.fail(source, guiUnavailableMessage());
|
||||
return 0;
|
||||
}
|
||||
NativeWorld level = source.world();
|
||||
NativeProtocolPlayer player = source.player();
|
||||
ModdedGuiHost.bindContext(worldView(source.server(), level), engine, player == null ? null : player.id());
|
||||
MapWindow.openImageMaps(mapStart(engine, player));
|
||||
IrisModdedCommands.ok(source, IrisLanguage.plain(
|
||||
ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_IMAGE_MAP_STUDIO_ON_SERVER_DISPLAY,
|
||||
MessageArgument.untrusted("value", level.name())
|
||||
));
|
||||
UUID openerId = player == null ? null : player.id();
|
||||
ModdedGuiHost.bindContext(worldView(source.server(), level), engine, openerId);
|
||||
StudioBridge bridge;
|
||||
try {
|
||||
bridge = StudioBridges.open(level.name(), () -> engine, openerId);
|
||||
} catch (IOException error) {
|
||||
IrisModdedCommands.fail(source, "Could not open the studio bridge: " + error.getMessage());
|
||||
return 0;
|
||||
}
|
||||
StudioLaunch launch = StudioWindow.show(bridge);
|
||||
if (!launch.opened()) {
|
||||
IrisLogging.info("Iris Studio link for %s: %s", level.name(), bridge.link());
|
||||
sendStudioLink(source, launch, bridge.link());
|
||||
return 0;
|
||||
}
|
||||
IrisModdedCommands.ok(source, openedMessage);
|
||||
return 1;
|
||||
}
|
||||
|
||||
private static void sendStudioLink(NativeCommandSource source, StudioLaunch launch, String link) {
|
||||
IrisModdedCommands.fail(source, IrisLanguage.plain(launch.failureMessage()));
|
||||
if (source.player() == null) {
|
||||
return;
|
||||
}
|
||||
NativeCommandText hover = NativeCommandText.literal(IrisLanguage.plain(RuntimeUiMessages.STUDIO_LINK_COPY_HOVER));
|
||||
NativeCommandText button = NativeCommandText.literal(IrisLanguage.plain(RuntimeUiMessages.STUDIO_LINK_COPY_BUTTON))
|
||||
.withStyle(Format.GREEN)
|
||||
.withStyle(style -> style.copyToClipboard(link).hover(hover));
|
||||
IrisModdedCommands.ok(source, button);
|
||||
}
|
||||
|
||||
private static LiteralArgumentBuilder<NativeCommandSource> workspaceTree(String name, boolean open) {
|
||||
return NativeCommandRegistration.literal(name)
|
||||
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> workspace(context.getSource(), null, open)))
|
||||
@@ -349,12 +340,12 @@ public final class ModdedStudioCommands {
|
||||
if (!open) {
|
||||
return 1;
|
||||
}
|
||||
if (!GuiHost.isAvailable() || !Desktop.isDesktopSupported()) {
|
||||
if (!GuiHost.isAvailable() || !FileOpener.isDesktopAvailable()) {
|
||||
IrisModdedCommands.fail(source, guiUnavailableMessage());
|
||||
return 0;
|
||||
}
|
||||
try {
|
||||
Desktop.getDesktop().open(workspace);
|
||||
FileOpener.open(workspace);
|
||||
} catch (Throwable e) {
|
||||
ModdedIrisLog.error("Iris workspace open failed for {}", workspace, e);
|
||||
IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_COULD_NOT_OPEN, MessageArgument.untrusted("value", workspace.getName()), MessageArgument.untrusted("value2", e.getClass().getSimpleName())));
|
||||
@@ -964,6 +955,7 @@ public final class ModdedStudioCommands {
|
||||
LinkedHashSet<String> entityKeys = new LinkedHashSet<>();
|
||||
LinkedHashSet<String> spawnerKeys = new LinkedHashSet<>();
|
||||
LinkedHashSet<String> generatorKeys = new LinkedHashSet<>();
|
||||
LinkedHashSet<String> caveKeys = new LinkedHashSet<>();
|
||||
LinkedHashSet<String> lootKeys = new LinkedHashSet<>();
|
||||
LinkedHashSet<String> objectKeys = new LinkedHashSet<>();
|
||||
LinkedHashSet<String> markerKeys = new LinkedHashSet<>();
|
||||
@@ -987,6 +979,7 @@ public final class ModdedStudioCommands {
|
||||
biomeKeys.add(biome.getLoadKey());
|
||||
}
|
||||
});
|
||||
caveKeys.addAll(exportedDimension.getCaves());
|
||||
lootKeys.addAll(exportedDimension.getLoot().getTables());
|
||||
spawnerKeys.addAll(exportedDimension.getEntitySpawners());
|
||||
collectStructureKeys(structureKeys, exportedDimension.getStructures());
|
||||
@@ -998,6 +991,7 @@ public final class ModdedStudioCommands {
|
||||
if (region == null) {
|
||||
continue;
|
||||
}
|
||||
caveKeys.addAll(region.getCaves());
|
||||
lootKeys.addAll(region.getLoot().getTables());
|
||||
spawnerKeys.addAll(region.getEntitySpawners());
|
||||
collectStructureKeys(structureKeys, region.getStructures());
|
||||
@@ -1010,6 +1004,7 @@ public final class ModdedStudioCommands {
|
||||
continue;
|
||||
}
|
||||
biome.getGenerators().forEach((IrisBiomeGeneratorLink link) -> generatorKeys.add(link.getGenerator()));
|
||||
caveKeys.addAll(biome.getCaves());
|
||||
lootKeys.addAll(biome.getLoot().getTables());
|
||||
spawnerKeys.addAll(biome.getEntitySpawners());
|
||||
collectStructureKeys(structureKeys, biome.getStructures());
|
||||
@@ -1066,6 +1061,9 @@ public final class ModdedStudioCommands {
|
||||
for (String key : Stream.of(dm.getExpressionLoader().getPossibleKeys()).sorted().toList()) {
|
||||
hashes.append(copyJson(folder, "expressions", key, dm.getExpressionLoader().findFile(key)));
|
||||
}
|
||||
for (String key : caveKeys) {
|
||||
hashes.append(copyJson(folder, "caves", key, dm.getCaveLoader().findFile(key)));
|
||||
}
|
||||
hashes.append(PackExportClosure.copySnippets(packFolder, folder));
|
||||
for (String key : regionKeys) {
|
||||
hashes.append(copyJson(folder, "regions", key, dm.getRegionLoader().findFile(key)));
|
||||
@@ -1149,7 +1147,7 @@ public final class ModdedStudioCommands {
|
||||
int diameter = radius * 2;
|
||||
int totalTasks = diameter * diameter;
|
||||
KMap<String, AtomicInteger> counts = new KMap<>();
|
||||
engine.getDimension().getRegions().forEach((String key) -> counts.put(key, new AtomicInteger(0)));
|
||||
engine.getDimension().getRegionKeys().forEach((String key) -> counts.put(key, new AtomicInteger(0)));
|
||||
// finally-scoped: a throw mid-scan previously leaked the sampler's whole
|
||||
// ForkJoinPool (close() is the only thing that shuts it down).
|
||||
MultiBurst burst = new MultiBurst("Region Sampler");
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
package art.arcane.iris.modded;
|
||||
|
||||
import art.arcane.iris.generation.biome.IrisBiome;
|
||||
import art.arcane.iris.generation.biome.IrisBiomeEntry;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.generation.runtime.DimensionStackLayout;
|
||||
import art.arcane.iris.generation.terrain.IrisDimension;
|
||||
@@ -174,9 +175,9 @@ public class ModdedBiomePolicyTest {
|
||||
isles.setLoadKey("isles");
|
||||
IrisBiome meadow = new IrisBiome().setDerivative("minecraft:plains");
|
||||
meadow.setLoadKey("meadow");
|
||||
IrisRegion main = new IrisRegion().setLandBiomes(new KList<>("meadow"));
|
||||
IrisRegion main = new IrisRegion().setLandBiomes(IrisBiomeEntry.plainList("meadow"));
|
||||
main.setLoadKey("main");
|
||||
IrisRegion archipelago = new IrisRegion().setLandBiomes(new KList<>("isles"));
|
||||
IrisRegion archipelago = new IrisRegion().setLandBiomes(IrisBiomeEntry.plainList("isles"));
|
||||
archipelago.setLoadKey("archipelago");
|
||||
IrisDimension dimension = mock(IrisDimension.class);
|
||||
when(dimension.getReachableBiomes(any())).thenReturn(new KList<>(meadow, isles));
|
||||
|
||||
@@ -105,7 +105,7 @@ repositories {
|
||||
name = 'NeoForged'
|
||||
url = uri('https://maven.neoforged.net/releases/')
|
||||
}
|
||||
maven { url = uri('https://repo.codemc.io/repository/maven-public/') }
|
||||
maven { url = uri('https://repo.codemc.org/repository/maven-public/') }
|
||||
maven { url = uri('https://jitpack.io') }
|
||||
maven { url = uri('https://hub.spigotmc.org/nexus/content/repositories/snapshots/') }
|
||||
}
|
||||
@@ -304,6 +304,7 @@ tasks.named('shadowJar', ShadowJar).configure {
|
||||
if ((int) irisModTarget.java == 21) {
|
||||
exclude(java21RuntimeExclusions)
|
||||
}
|
||||
exclude('META-INF/maven/**')
|
||||
exclude('META-INF/proguard/**')
|
||||
exclude('META-INF/*.SF')
|
||||
exclude('META-INF/*.DSA')
|
||||
@@ -360,7 +361,6 @@ tasks.named('assemble').configure {
|
||||
}
|
||||
|
||||
pluginPackaging {
|
||||
nativeBoundaryChecks = true
|
||||
artifacts {
|
||||
create('distribution') {
|
||||
taskName = 'shadowJar'
|
||||
|
||||
+73
-7
@@ -1,4 +1,5 @@
|
||||
import art.arcane.volmit.packaging.PackedJar
|
||||
import art.arcane.volmit.packaging.PackagingMode
|
||||
import art.arcane.volmit.packaging.NativeDevelopmentTargets
|
||||
import io.papermc.paperweight.userdev.PaperweightUser
|
||||
import io.papermc.paperweight.userdev.PaperweightUserDependenciesExtension
|
||||
@@ -189,6 +190,63 @@ def generateNoiseNatives = tasks.register('generateNoiseNatives') {
|
||||
}
|
||||
}
|
||||
}
|
||||
// The studio app ships inside the Bukkit jar. The Electron build it runs on is 100+ MB per platform, so it stays out
|
||||
// and is pinned instead: StudioAppInstaller downloads the host's archive from Electron's release at startup and
|
||||
// checks it against these checksums.
|
||||
File studioAppDirectory = file('studio')
|
||||
List<String> electronPlatforms = ['linux-x64', 'linux-arm64', 'win32-x64', 'win32-arm64', 'darwin-x64', 'darwin-arm64']
|
||||
Provider<String> electronVersion = providers.fileContents(layout.projectDirectory.file('studio/package-lock.json')).asText.map { String lock ->
|
||||
(String) ((Map) ((Map) new groovy.json.JsonSlurper().parseText(lock)).packages).get('node_modules/electron').version
|
||||
}
|
||||
List<String> npmCommand = System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('win') ? ['cmd', '/c', 'npm'] : ['npm']
|
||||
def installStudioDependencies = tasks.register('installStudioDependencies', Exec) {
|
||||
inputs.files('studio/package.json', 'studio/package-lock.json')
|
||||
outputs.file('studio/node_modules/.package-lock.json')
|
||||
workingDir(studioAppDirectory)
|
||||
commandLine(npmCommand + ['ci', '--no-audit', '--no-fund'])
|
||||
}
|
||||
def buildStudioApp = tasks.register('buildStudioApp', Exec) {
|
||||
dependsOn(installStudioDependencies)
|
||||
inputs.dir('studio/src')
|
||||
inputs.files('studio/package.json', 'studio/package-lock.json', 'studio/electron.vite.config.ts', 'studio/tsconfig.json', 'studio/components.json')
|
||||
outputs.dir('studio/out')
|
||||
workingDir(studioAppDirectory)
|
||||
commandLine(npmCommand + ['run', 'build'])
|
||||
}
|
||||
def bundleStudioApp = tasks.register('bundleStudioApp', Zip) {
|
||||
from(buildStudioApp) {
|
||||
into('out')
|
||||
}
|
||||
from('studio/package.json')
|
||||
archiveFileName.set('studio-app.zip')
|
||||
destinationDirectory.set(layout.buildDirectory.dir('generated/studio-app'))
|
||||
preserveFileTimestamps = false
|
||||
reproducibleFileOrder = true
|
||||
}
|
||||
def pinElectronRuntime = tasks.register('pinElectronRuntime') {
|
||||
inputs.property('electronVersion', electronVersion)
|
||||
inputs.property('platforms', electronPlatforms)
|
||||
def pins = layout.buildDirectory.file('generated/studio-app-pins/studio-app.properties')
|
||||
outputs.file(pins)
|
||||
doLast {
|
||||
String version = electronVersion.get()
|
||||
String checksums = URI.create("https://github.com/electron/electron/releases/download/v${version}/SHASUMS256.txt")
|
||||
.toURL().getText('UTF-8')
|
||||
Map<String, String> checksumByArchive = checksums.readLines().collectEntries { String line ->
|
||||
def match = line.trim() =~ /^([0-9a-f]{64}) \*?(\S+)$/
|
||||
match.matches() ? [(match.group(2)): match.group(1)] : [:]
|
||||
}
|
||||
List<String> lines = ["electron.version=${version}".toString()]
|
||||
electronPlatforms.each { String platform ->
|
||||
String checksum = checksumByArchive.get("electron-v${version}-${platform}.zip".toString())
|
||||
if (checksum == null) {
|
||||
throw new GradleException("Electron ${version} publishes no ${platform} archive")
|
||||
}
|
||||
lines.add("${platform}.sha256=${checksum}".toString())
|
||||
}
|
||||
pins.get().asFile.setText(lines.join('\n') + '\n', 'UTF-8')
|
||||
}
|
||||
}
|
||||
def jarJar = configurations.create('jarJar')
|
||||
dependencies {
|
||||
add('included', project(path: ':core', configuration: 'shadow'))
|
||||
@@ -207,6 +265,12 @@ tasks.named('jar', Jar).configure {
|
||||
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||
includeEmptyDirs = false
|
||||
from(jarJar)
|
||||
from(bundleStudioApp) {
|
||||
into('META-INF/iris')
|
||||
}
|
||||
from(pinElectronRuntime) {
|
||||
into('META-INF/iris')
|
||||
}
|
||||
from(provider { included.resolve().collect { zipTree(it) } }) {
|
||||
exclude('META-INF/INDEX.LIST')
|
||||
exclude('languages/**')
|
||||
@@ -528,6 +592,8 @@ List<String> requiredBukkitArtifactEntries = [
|
||||
'slimjar-resolutions.dat',
|
||||
'META-INF/iris/native-runtime.properties',
|
||||
NoiseNativeArtifacts.MANIFEST,
|
||||
'META-INF/iris/studio-app.zip',
|
||||
'META-INF/iris/studio-app.properties',
|
||||
'META-INF/volmit/volmlib.properties',
|
||||
'iris-language-source.properties',
|
||||
'agent.jar',
|
||||
@@ -653,7 +719,7 @@ allprojects {
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven { url = uri('https://repo.papermc.io/repository/maven-public/') }
|
||||
maven { url = uri('https://repo.codemc.io/repository/maven-public/') }
|
||||
maven { url = uri('https://repo.codemc.org/repository/maven-public/') }
|
||||
|
||||
maven {
|
||||
url = uri('https://jitpack.io')
|
||||
@@ -758,6 +824,11 @@ pluginPackaging {
|
||||
packedJarAccessors = ['art/arcane/iris/platform/bukkit/plugin/VolmitPlugin#getJarFile']
|
||||
packedPayloadOnlyPrefixes = ['iris-language-guides/', 'META-INF/iris/generation-kernels/abi-', 'iris/icons/views/', 'iris/datapack/']
|
||||
packedMaximumBootstrapClasses = 90
|
||||
stripDirectories = true
|
||||
stripLocalVariables = true
|
||||
releaseCompression = providers.gradleProperty('compactRelease')
|
||||
.map { String value -> value.toBoolean() }
|
||||
.getOrElse(!PackagingMode.resolve(providers).development())
|
||||
prunePrefixes = ['art/arcane/volmlib/']
|
||||
keepPrefixes = ['art/arcane/volmlib/util/matter/slices/', 'art/arcane/volmlib/nativelib/']
|
||||
shrinkRules = [file('packaging/shrink.pro'), nativeRuntimeRules.get().asFile]
|
||||
@@ -1004,12 +1075,7 @@ tasks.withType(PackedJar).configureEach {
|
||||
dependsOn(tasks.named('verifyBukkitArtifact'), nativeRuntime)
|
||||
nativeArtifacts.set(providers.provider { embeddedNatives() })
|
||||
doLast { PackedJar task ->
|
||||
File artifact = task.outputJar.get().asFile
|
||||
Map<String, byte[]> outer = NativeRuntimeArtifacts.entries(artifact)
|
||||
Map<String, byte[]> runtime = outer.containsKey('META-INF/volmit/runtime.properties')
|
||||
? PackedJar.readRuntime(artifact.toPath()) : outer
|
||||
NativeRuntimeArtifacts.verifyPacked(runtime, outer.get(NativeRuntimeArtifacts.MANIFEST), nativeRuntimeModules,
|
||||
embeddedNatives())
|
||||
NativeRuntimeArtifacts.verifyPacked(task.outputJar.get().asFile, nativeRuntimeModules, embeddedNatives())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ dependencies {
|
||||
implementation(gradleApi())
|
||||
implementation('org.ow2.asm:asm:9.10.1')
|
||||
implementation('org.apache.commons:commons-compress:1.28.0')
|
||||
implementation('org.tukaani:xz:1.10')
|
||||
implementation('io.papermc.paperweight:paperweight-userdev:2.0.0-beta.21')
|
||||
testImplementation('junit:junit:4.13.2')
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import org.gradle.api.GradleException;
|
||||
import org.tukaani.xz.XZInputStream;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
@@ -27,6 +28,7 @@ import java.util.zip.ZipInputStream;
|
||||
public final class NativeRuntimeArtifacts {
|
||||
public static final String MANIFEST = "META-INF/iris/native-runtime.properties";
|
||||
public static final String RESOURCES = "META-INF/iris/native/";
|
||||
private static final String PAYLOAD = "META-INF/volmit/runtime.jar.xz";
|
||||
private static final String GROUP = "com.github.VolmitSoftware.VolmLib";
|
||||
private static final String NATIVE = "art/arcane/volmlib/nativelib/";
|
||||
|
||||
@@ -97,20 +99,35 @@ public final class NativeRuntimeArtifacts {
|
||||
}
|
||||
}
|
||||
|
||||
/** Checks the native providers inside {@code runtime}, the entries the plugin runs from, against the resolved build. */
|
||||
public static void verifyPacked(Map<String, byte[]> runtime, byte[] outerManifest, List<String> modules,
|
||||
Map<String, File> natives) throws IOException {
|
||||
public static void verifyPacked(File artifact, List<String> modules, Map<String, File> natives) throws IOException {
|
||||
requireModules(natives, modules);
|
||||
byte[] manifest = runtime.get(MANIFEST);
|
||||
Map<String, byte[]> contents;
|
||||
try (JarFile jar = new JarFile(artifact)) {
|
||||
JarEntry payload = jar.getJarEntry(PAYLOAD);
|
||||
if (payload == null) {
|
||||
contents = read(Files.newInputStream(artifact.toPath()));
|
||||
} else {
|
||||
try (InputStream input = new XZInputStream(jar.getInputStream(payload))) {
|
||||
contents = read(new ByteArrayInputStream(input.readAllBytes()));
|
||||
}
|
||||
JarEntry outer = jar.getJarEntry(MANIFEST);
|
||||
byte[] embedded = contents.get(MANIFEST);
|
||||
if (outer != null && embedded != null) {
|
||||
try (InputStream input = jar.getInputStream(outer)) {
|
||||
if (!Arrays.equals(input.readAllBytes(), embedded)) {
|
||||
throw new GradleException("Packed native runtime manifests differ");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
byte[] manifest = contents.get(MANIFEST);
|
||||
if (manifest == null) {
|
||||
throw new GradleException("Missing native runtime dependency manifest");
|
||||
}
|
||||
if (outerManifest != null && !Arrays.equals(outerManifest, manifest)) {
|
||||
throw new GradleException("Packed native runtime manifests differ");
|
||||
}
|
||||
verifyManifest(manifest, natives);
|
||||
for (String module : natives.keySet()) {
|
||||
byte[] provider = runtime.get(RESOURCES + module + ".jar");
|
||||
byte[] provider = contents.get(RESOURCES + module + ".jar");
|
||||
if (provider == null) {
|
||||
throw new GradleException("Missing embedded native provider: " + module);
|
||||
}
|
||||
@@ -120,18 +137,6 @@ public final class NativeRuntimeArtifacts {
|
||||
}
|
||||
}
|
||||
|
||||
public static Map<String, byte[]> entries(File artifact) throws IOException {
|
||||
Map<String, byte[]> contents = new TreeMap<>();
|
||||
try (ZipInputStream archive = new ZipInputStream(Files.newInputStream(artifact.toPath()))) {
|
||||
for (ZipEntry entry = archive.getNextEntry(); entry != null; entry = archive.getNextEntry()) {
|
||||
if (!entry.isDirectory()) {
|
||||
contents.put(entry.getName(), archive.readAllBytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
return contents;
|
||||
}
|
||||
|
||||
private static void verifyManifest(byte[] bytes, Map<String, File> natives) throws IOException {
|
||||
Properties manifest = new Properties();
|
||||
manifest.load(new ByteArrayInputStream(bytes));
|
||||
@@ -158,6 +163,18 @@ public final class NativeRuntimeArtifacts {
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, byte[]> read(InputStream source) throws IOException {
|
||||
Map<String, byte[]> contents = new TreeMap<>();
|
||||
try (ZipInputStream archive = new ZipInputStream(source)) {
|
||||
for (ZipEntry entry = archive.getNextEntry(); entry != null; entry = archive.getNextEntry()) {
|
||||
if (!entry.isDirectory()) {
|
||||
contents.put(entry.getName(), archive.readAllBytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
return contents;
|
||||
}
|
||||
|
||||
private static boolean implementation(String name) {
|
||||
if (!name.startsWith(NATIVE)) {
|
||||
return false;
|
||||
|
||||
@@ -4,11 +4,13 @@ import org.junit.Test;
|
||||
import org.junit.rules.TemporaryFolder;
|
||||
import org.objectweb.asm.ClassWriter;
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.tukaani.xz.LZMA2Options;
|
||||
import org.tukaani.xz.XZOutputStream;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
@@ -20,7 +22,6 @@ import java.util.TreeMap;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarOutputStream;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
@@ -88,35 +89,15 @@ public class NativeRuntimeArtifactsTest {
|
||||
public void verifiesTheEmbeddedProviderBytesInsideThePackedRuntime() throws Exception {
|
||||
Map<String, File> natives = natives();
|
||||
Map<String, byte[]> runtime = runtime(natives, natives);
|
||||
byte[] manifest = runtime.get(NativeRuntimeArtifacts.MANIFEST);
|
||||
NativeRuntimeArtifacts.verifyPacked(runtime, manifest, MODULES, natives);
|
||||
NativeRuntimeArtifacts.verifyPacked(runtime, null, MODULES, natives);
|
||||
NativeRuntimeArtifacts.verifyPacked(packed(runtime), MODULES, natives);
|
||||
NativeRuntimeArtifacts.verifyPacked(jar("ordinary.jar", runtime), MODULES, natives);
|
||||
Map<String, File> rebuilt = new TreeMap<>(natives);
|
||||
rebuilt.put("native-v26_2_R1", provider("rebuilt.jar", "art/arcane/volmlib/util/collection/KMap"));
|
||||
assertThrows(GradleException.class, () -> NativeRuntimeArtifacts.verifyPacked(runtime(natives, rebuilt),
|
||||
manifest, MODULES, natives));
|
||||
assertThrows(GradleException.class, () -> NativeRuntimeArtifacts.verifyPacked(packed(runtime(natives, rebuilt)),
|
||||
MODULES, natives));
|
||||
Map<String, byte[]> missing = new TreeMap<>(runtime);
|
||||
missing.remove(NativeRuntimeArtifacts.RESOURCES + "native-v26_2_R1.jar");
|
||||
assertThrows(GradleException.class, () -> NativeRuntimeArtifacts.verifyPacked(missing, manifest, MODULES, natives));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectsAnOuterManifestThatDiffersFromTheRuntimeOne() throws Exception {
|
||||
Map<String, File> natives = natives();
|
||||
Map<String, byte[]> runtime = runtime(natives, natives);
|
||||
byte[] outer = (new String(runtime.get(NativeRuntimeArtifacts.MANIFEST), StandardCharsets.UTF_8) + "extra=1\n")
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
assertThrows(GradleException.class, () -> NativeRuntimeArtifacts.verifyPacked(runtime, outer, MODULES, natives));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void readsEveryFileEntryOfAnOrdinaryJar() throws Exception {
|
||||
Map<String, byte[]> runtime = runtime(natives(), natives());
|
||||
Map<String, byte[]> read = NativeRuntimeArtifacts.entries(jar("ordinary.jar", runtime));
|
||||
assertEquals(runtime.keySet(), read.keySet());
|
||||
for (Map.Entry<String, byte[]> entry : runtime.entrySet()) {
|
||||
assertArrayEquals(entry.getValue(), read.get(entry.getKey()));
|
||||
}
|
||||
assertThrows(GradleException.class, () -> NativeRuntimeArtifacts.verifyPacked(packed(missing), MODULES, natives));
|
||||
}
|
||||
|
||||
private Map<String, File> natives() throws IOException {
|
||||
@@ -156,6 +137,17 @@ public class NativeRuntimeArtifactsTest {
|
||||
return contents;
|
||||
}
|
||||
|
||||
private File packed(Map<String, byte[]> runtime) throws IOException {
|
||||
ByteArrayOutputStream compressed = new ByteArrayOutputStream();
|
||||
try (XZOutputStream xz = new XZOutputStream(compressed, new LZMA2Options(1))) {
|
||||
xz.write(Files.readAllBytes(jar("payload.jar", runtime).toPath()));
|
||||
}
|
||||
Map<String, byte[]> outer = new TreeMap<>();
|
||||
outer.put(NativeRuntimeArtifacts.MANIFEST, runtime.get(NativeRuntimeArtifacts.MANIFEST));
|
||||
outer.put("META-INF/volmit/runtime.jar.xz", compressed.toByteArray());
|
||||
return jar("packed.jar", outer);
|
||||
}
|
||||
|
||||
private File jar(String name, Map<String, byte[]> contents) throws IOException {
|
||||
Path file = temporary.newFolder().toPath().resolve(name);
|
||||
try (JarOutputStream jar = new JarOutputStream(Files.newOutputStream(file))) {
|
||||
|
||||
+1
-1
@@ -482,7 +482,7 @@ List<String> dependencyBuildMetadata = [
|
||||
'META-INF/versions/*/OSGI-INF/**'
|
||||
]
|
||||
|
||||
String languageTomlSupportClassPattern = 'art/arcane/volmlib/util/config/(?:TomlCodec|TomlSegments|ConfigComments|ConfigJson|ConfigExposePolicy|ConfigDoc|ConfigDescription|ConfigDocumentation)(?:\\$[^/]+)?\\.class'
|
||||
String languageTomlSupportClassPattern = 'art/arcane/volmlib/util/config/(?:TomlCodec|ConfigJson|ConfigExposePolicy|ConfigDoc|ConfigDescription|ConfigDocumentation)(?:\\$[^/]+)?\\.class'
|
||||
|
||||
tasks.named('shadowJar', ShadowJar).configure {
|
||||
inputs.property('languageTomlSupportClassPattern', languageTomlSupportClassPattern)
|
||||
|
||||
@@ -404,6 +404,9 @@ public class IrisSettings {
|
||||
public boolean disableTimeAndWeather = true;
|
||||
public boolean entitySpawning = true;
|
||||
public boolean autoStartDefaultStudio = false;
|
||||
public boolean downloadApp = true;
|
||||
public String studioApp = "";
|
||||
public String electron = "electron";
|
||||
}
|
||||
|
||||
@Data
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package art.arcane.iris.generation.bake;
|
||||
|
||||
import art.arcane.iris.generation.runtime.ThreadSlots;
|
||||
import art.arcane.iris.generation.cache.ConcurrentClockCache;
|
||||
import art.arcane.iris.generation.stream.ProvisionalSampling;
|
||||
|
||||
@@ -17,7 +16,7 @@ public final class ChunkBakeCache {
|
||||
|
||||
private final PlaneSource source;
|
||||
private final ConcurrentClockCache<ChunkPlanes> entries;
|
||||
private final ThreadSlots<Recent> recent = new ThreadSlots<>(Recent::new);
|
||||
private final ThreadLocal<Recent> recent = ThreadLocal.withInitial(Recent::new);
|
||||
private volatile int generation;
|
||||
|
||||
public ChunkBakeCache(PlaneSource source, int capacityChunks) {
|
||||
|
||||
@@ -3,7 +3,6 @@ package art.arcane.iris.generation.bake;
|
||||
import art.arcane.iris.generation.noise.GeneratorProgram;
|
||||
import art.arcane.iris.generation.noise.IrisGenerator;
|
||||
import art.arcane.iris.generation.noise.TerrainBatchScratch;
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.volmlib.util.math.M;
|
||||
|
||||
import java.util.Arrays;
|
||||
@@ -13,28 +12,26 @@ public final class TerrainProgram {
|
||||
private static final int CONSTANT = 1;
|
||||
private static final int ACTIVE = 2;
|
||||
|
||||
private final PackRuntime runtime;
|
||||
private final IrisGenerator[][] generators;
|
||||
private final GeneratorProgram[][] programs;
|
||||
private final long heightSeed;
|
||||
|
||||
private TerrainProgram(PackRuntime runtime, IrisGenerator[][] generators, GeneratorProgram[][] programs, long heightSeed) {
|
||||
this.runtime = runtime;
|
||||
private TerrainProgram(IrisGenerator[][] generators, GeneratorProgram[][] programs, long heightSeed) {
|
||||
this.generators = generators;
|
||||
this.programs = programs;
|
||||
this.heightSeed = heightSeed;
|
||||
}
|
||||
|
||||
public static TerrainProgram compile(PackRuntime runtime, IrisGenerator[][] generators, long heightSeed) {
|
||||
public static TerrainProgram compile(IrisGenerator[][] generators, long heightSeed) {
|
||||
GeneratorProgram[][] programs = new GeneratorProgram[generators.length][];
|
||||
for (int group = 0; group < generators.length; group++) {
|
||||
programs[group] = new GeneratorProgram[generators[group].length];
|
||||
for (int index = 0; index < generators[group].length; index++) {
|
||||
IrisGenerator generator = generators[group][index];
|
||||
programs[group][index] = generator.supportsBatch() ? generator.compileProgram(runtime, heightSeed) : null;
|
||||
programs[group][index] = generator.supportsBatch() ? generator.compileProgram(heightSeed) : null;
|
||||
}
|
||||
}
|
||||
return new TerrainProgram(runtime, generators, programs, heightSeed);
|
||||
return new TerrainProgram(generators, programs, heightSeed);
|
||||
}
|
||||
|
||||
public long heightSeed() {
|
||||
@@ -61,7 +58,7 @@ public final class TerrainProgram {
|
||||
GeneratorProgram[] compiled = programs[group];
|
||||
for (int member = 0; member < members.length; member++) {
|
||||
GeneratorProgram program = compiled[member];
|
||||
double noise = program != null ? program.height(scratch, x, z) : members[member].getHeight(runtime, x, z, heightSeed);
|
||||
double noise = program != null ? program.height(scratch, x, z) : members[member].getHeight(x, z, heightSeed);
|
||||
if (!Double.isFinite(noise)) {
|
||||
throw new IllegalStateException("Terrain generator noise was not finite at " + x + "," + z
|
||||
+ " (generator=" + members[member].getLoadKey() + ", noise=" + noise
|
||||
@@ -151,7 +148,7 @@ public final class TerrainProgram {
|
||||
program.heights(scratch, activeX, activeZ, activeCount, noise);
|
||||
} else {
|
||||
for (int index = 0; index < activeCount; index++) {
|
||||
noise[index] = members[member].getHeight(runtime, activeX[index], activeZ[index], heightSeed);
|
||||
noise[index] = members[member].getHeight(activeX[index], activeZ[index], heightSeed);
|
||||
}
|
||||
}
|
||||
for (int index = 0; index < activeCount; index++) {
|
||||
|
||||
@@ -1,155 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.generation.biome;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.runtime.SeedTable;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.noise.CNG;
|
||||
|
||||
import art.arcane.iris.generation.decoration.DecoratorRuntime;
|
||||
import art.arcane.iris.generation.decoration.IrisDecorationPart;
|
||||
import art.arcane.iris.generation.decoration.IrisDecorator;
|
||||
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicReferenceArray;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* What one engine derives from an {@link IrisBiome}: its scatter generators, the children generators per shrink
|
||||
* scale, the height generators of its layer palettes and the runtimes of those palettes, linked by layer index so
|
||||
* painting a column reads them without looking each layer up.
|
||||
*/
|
||||
public final class BiomeRuntime {
|
||||
private static final int BIOME_SEED_CAPACITY = 8;
|
||||
private static final int CHILD_SEED_CAPACITY = 8;
|
||||
private static final int LAYER_HEIGHT_SEED_CAPACITY = 32;
|
||||
private static final int SURFACE_LAYER_SEED_OFFSET = 7235;
|
||||
private static final int SEA_LAYER_SEED_OFFSET = 7735;
|
||||
private static final int CEILING_LAYER_SEED_OFFSET = 7235;
|
||||
|
||||
private final IrisBiome biome;
|
||||
private final PackRuntime runtime;
|
||||
private final SeedTable<CNG> biomeGenerators;
|
||||
private final ConcurrentHashMap<Long, SeedTable<CNG>> childGeneratorsByScale = new ConcurrentHashMap<>();
|
||||
private final SeedTable<KList<CNG>> layerHeights;
|
||||
private final SeedTable<KList<CNG>> seaLayerHeights;
|
||||
private final SeedTable<KList<CNG>> ceilingLayerHeights;
|
||||
private final LinkedLayers surfaceLayers;
|
||||
private final LinkedLayers seaLayers;
|
||||
private final LinkedLayers ceilingLayers;
|
||||
private final AtomicReferenceArray<LinkedDecorators> decoratorBuckets =
|
||||
new AtomicReferenceArray<>(IrisDecorationPart.values().length);
|
||||
|
||||
public BiomeRuntime(IrisBiome biome, PackRuntime runtime) {
|
||||
this.biome = biome;
|
||||
this.runtime = runtime;
|
||||
this.biomeGenerators = new SeedTable<>(BIOME_SEED_CAPACITY, seed -> biome.createBiomeGenerator(seed, runtime));
|
||||
this.layerHeights = new SeedTable<>(LAYER_HEIGHT_SEED_CAPACITY, seed ->
|
||||
IrisBiomeLayerGenerator.createHeightGenerators(biome.getLayers(), SURFACE_LAYER_SEED_OFFSET, seed, runtime));
|
||||
this.seaLayerHeights = new SeedTable<>(LAYER_HEIGHT_SEED_CAPACITY, seed ->
|
||||
IrisBiomeLayerGenerator.createHeightGenerators(biome.getSeaLayers(), SEA_LAYER_SEED_OFFSET, seed, runtime));
|
||||
this.ceilingLayerHeights = new SeedTable<>(LAYER_HEIGHT_SEED_CAPACITY, seed ->
|
||||
IrisBiomeLayerGenerator.createHeightGenerators(biome.getCaveCeilingLayers(), CEILING_LAYER_SEED_OFFSET, seed, runtime));
|
||||
this.surfaceLayers = new LinkedLayers(biome::getLayers);
|
||||
this.seaLayers = new LinkedLayers(biome::getSeaLayers);
|
||||
this.ceilingLayers = new LinkedLayers(biome::getCaveCeilingLayers);
|
||||
}
|
||||
|
||||
public CNG biomeGenerator(long seed) {
|
||||
return biomeGenerators.get(seed);
|
||||
}
|
||||
|
||||
public CNG childrenGenerator(long seed, double scale) {
|
||||
return childGeneratorsByScale.computeIfAbsent(Double.doubleToLongBits(scale), ignored ->
|
||||
new SeedTable<>(CHILD_SEED_CAPACITY, childSeed -> biome.createChildrenGenerator(childSeed, scale, runtime)))
|
||||
.get(seed);
|
||||
}
|
||||
|
||||
public KList<CNG> layerHeights(long seed) {
|
||||
return layerHeights.get(seed);
|
||||
}
|
||||
|
||||
public KList<CNG> seaLayerHeights(long seed) {
|
||||
return seaLayerHeights.get(seed);
|
||||
}
|
||||
|
||||
public KList<CNG> ceilingLayerHeights(long seed) {
|
||||
return ceilingLayerHeights.get(seed);
|
||||
}
|
||||
|
||||
/** The runtime of the surface layer at this index of {@link IrisBiome#getLayers()}. */
|
||||
public PaletteLayerRuntime surfaceLayer(int index) {
|
||||
return surfaceLayers.get(index);
|
||||
}
|
||||
|
||||
/** The runtime of the sea layer at this index of {@link IrisBiome#getSeaLayers()}. */
|
||||
public PaletteLayerRuntime seaLayer(int index) {
|
||||
return seaLayers.get(index);
|
||||
}
|
||||
|
||||
/** The runtime of the cave ceiling layer at this index of {@link IrisBiome#getCaveCeilingLayers()}. */
|
||||
public PaletteLayerRuntime ceilingLayer(int index) {
|
||||
return ceilingLayers.get(index);
|
||||
}
|
||||
|
||||
/** The runtimes of this part's {@link IrisBiome#getDecoratorBucket} decorators, in bucket order. */
|
||||
public DecoratorRuntime[] decorators(IrisDecorationPart part) {
|
||||
IrisDecorator[] bucket = biome.getDecoratorBucket(part);
|
||||
LinkedDecorators linked = decoratorBuckets.getAcquire(part.ordinal());
|
||||
if (linked != null && linked.bucket() == bucket) {
|
||||
return linked.runtimes();
|
||||
}
|
||||
DecoratorRuntime[] runtimes = new DecoratorRuntime[bucket.length];
|
||||
for (int index = 0; index < bucket.length; index++) {
|
||||
runtimes[index] = runtime.decorator(bucket[index]);
|
||||
}
|
||||
decoratorBuckets.setRelease(part.ordinal(), new LinkedDecorators(bucket, runtimes));
|
||||
return runtimes;
|
||||
}
|
||||
|
||||
private record LinkedDecorators(IrisDecorator[] bucket, DecoratorRuntime[] runtimes) {
|
||||
}
|
||||
|
||||
private final class LinkedLayers {
|
||||
private final Supplier<KList<IrisBiomePaletteLayer>> layers;
|
||||
private volatile PaletteLayerRuntime[] linked;
|
||||
|
||||
private LinkedLayers(Supplier<KList<IrisBiomePaletteLayer>> layers) {
|
||||
this.layers = layers;
|
||||
}
|
||||
|
||||
private PaletteLayerRuntime get(int index) {
|
||||
PaletteLayerRuntime[] current = linked;
|
||||
if (current == null) {
|
||||
current = link(layers.get());
|
||||
linked = current;
|
||||
}
|
||||
return current[index];
|
||||
}
|
||||
|
||||
private PaletteLayerRuntime[] link(KList<IrisBiomePaletteLayer> source) {
|
||||
PaletteLayerRuntime[] result = new PaletteLayerRuntime[source.size()];
|
||||
for (int index = 0; index < result.length; index++) {
|
||||
result[index] = runtime.paletteLayer(source.get(index));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.generation.biome;
|
||||
|
||||
import art.arcane.iris.generation.cave.IrisCaveProfileSampler;
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.runtime.SeedTable;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* What one engine derives from an {@link IrisFloatingChildBiomes} entry: its edge taper profile per base seed and the
|
||||
* cave profile sampler of the biome it carves with.
|
||||
*/
|
||||
public final class FloatingChildRuntime {
|
||||
private static final int EDGE_PROFILE_SEED_CAPACITY = 8;
|
||||
|
||||
private final IrisFloatingChildBiomes entry;
|
||||
private final PackRuntime runtime;
|
||||
private final SeedTable<FloatingIslandEdgeProfile> edgeProfiles;
|
||||
private volatile Optional<IrisCaveProfileSampler> carvingProfileSampler;
|
||||
|
||||
public FloatingChildRuntime(IrisFloatingChildBiomes entry, PackRuntime runtime) {
|
||||
this.entry = entry;
|
||||
this.runtime = runtime;
|
||||
this.edgeProfiles = new SeedTable<>(EDGE_PROFILE_SEED_CAPACITY, seed -> entry.createEdgeTaperProfile(seed, runtime));
|
||||
}
|
||||
|
||||
public FloatingIslandEdgeProfile edgeTaperProfile(long baseSeed) {
|
||||
return edgeProfiles.get(baseSeed);
|
||||
}
|
||||
|
||||
public IrisCaveProfileSampler carvingProfileSampler() {
|
||||
Optional<IrisCaveProfileSampler> resolved = carvingProfileSampler;
|
||||
if (resolved == null) {
|
||||
resolved = Optional.ofNullable(entry.createCarvingProfileSampler(runtime));
|
||||
carvingProfileSampler = resolved;
|
||||
}
|
||||
return resolved.orElse(null);
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.generation.biome;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
/**
|
||||
* One worker's floating island samples for the chunk it is generating. A runtime scope keeps one per worker thread,
|
||||
* so the memo never outlives the engine that produced its samples.
|
||||
*/
|
||||
public final class FloatingIslandMemo {
|
||||
private static final int CHUNK_COLUMN_COUNT = 256;
|
||||
|
||||
private final HashMap<Long, MemoizedSample> samples = new HashMap<>(CHUNK_COLUMN_COUNT);
|
||||
private MemoContext context;
|
||||
|
||||
public void clear() {
|
||||
samples.clear();
|
||||
context = null;
|
||||
}
|
||||
|
||||
/** The memoized sample for this column and parent, which may itself be null; null when not sampled yet. */
|
||||
MemoizedSample find(IrisBiome parent, long column) {
|
||||
MemoizedSample cached = samples.get(column);
|
||||
return cached != null && cached.parent == parent ? cached : null;
|
||||
}
|
||||
|
||||
void remember(IrisBiome parent, long column, FloatingIslandSample sample) {
|
||||
samples.put(column, new MemoizedSample(parent, sample));
|
||||
}
|
||||
|
||||
void enterChunk(int chunkX, int chunkZ, int height, long seed, FloatingIslandBoundarySampler boundarySampler) {
|
||||
if (context != null && context.matches(chunkX, chunkZ, height, seed, boundarySampler)) {
|
||||
return;
|
||||
}
|
||||
samples.clear();
|
||||
context = new MemoContext(chunkX, chunkZ, height, seed, boundarySampler);
|
||||
}
|
||||
|
||||
private record MemoContext(int chunkX, int chunkZ, int height, long seed,
|
||||
FloatingIslandBoundarySampler boundarySampler) {
|
||||
private boolean matches(int chunkX, int chunkZ, int height, long seed,
|
||||
FloatingIslandBoundarySampler boundarySampler) {
|
||||
return this.chunkX == chunkX && this.chunkZ == chunkZ && this.height == height && this.seed == seed
|
||||
&& this.boundarySampler == boundarySampler;
|
||||
}
|
||||
}
|
||||
|
||||
record MemoizedSample(IrisBiome parent, FloatingIslandSample sample) {
|
||||
}
|
||||
}
|
||||
@@ -18,14 +18,17 @@
|
||||
|
||||
package art.arcane.iris.generation.biome;
|
||||
|
||||
import art.arcane.iris.generation.cave.IrisCaveProfileSampler;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.volmlib.util.noise.CNG;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
public final class FloatingIslandSample {
|
||||
@@ -47,6 +50,8 @@ public final class FloatingIslandSample {
|
||||
private static final double CARVE_MAX_VERTICAL_RUN_FRACTION = 0.18D;
|
||||
private static final ThreadLocal<int[]> LAST_REJECT = ThreadLocal.withInitial(() -> new int[1]);
|
||||
private static final ThreadLocal<double[]> LAST_DENSITY = ThreadLocal.withInitial(() -> new double[2]);
|
||||
private static final ThreadLocal<ChunkMemo> CHUNK_MEMO = ThreadLocal.withInitial(ChunkMemo::new);
|
||||
private static final ThreadLocal<IdentityHashMap<CNG, Long2DoubleOpenHashMap>> FOOTPRINT_MEMO = ThreadLocal.withInitial(IdentityHashMap::new);
|
||||
private static final AtomicBoolean NULL_CNG_WARNED = new AtomicBoolean(false);
|
||||
|
||||
public static int getLastReject() {
|
||||
@@ -61,20 +66,33 @@ public final class FloatingIslandSample {
|
||||
return LAST_DENSITY.get()[1];
|
||||
}
|
||||
|
||||
public static void clearChunkMemo(PackRuntime runtime) {
|
||||
runtime.floatingIslandMemo().clear();
|
||||
public static void clearThreadCaches() {
|
||||
CHUNK_MEMO.remove();
|
||||
FOOTPRINT_MEMO.remove();
|
||||
LAST_REJECT.remove();
|
||||
LAST_DENSITY.remove();
|
||||
}
|
||||
|
||||
public static FloatingIslandSample sampleMemoized(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, PackRuntime runtime, FloatingIslandBoundarySampler boundarySampler) {
|
||||
long column = (((long) wx) << 32) ^ (wz & 0xFFFFFFFFL);
|
||||
FloatingIslandMemo memo = runtime.floatingIslandMemo();
|
||||
memo.enterChunk(wx >> 4, wz >> 4, chunkHeight, baseSeed, boundarySampler);
|
||||
FloatingIslandMemo.MemoizedSample cached = memo.find(parent, column);
|
||||
if (cached != null) {
|
||||
return cached.sample();
|
||||
public static void clearChunkMemo() {
|
||||
CHUNK_MEMO.get().samples.clear();
|
||||
FOOTPRINT_MEMO.get().clear();
|
||||
}
|
||||
|
||||
public static FloatingIslandSample sampleMemoized(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler) {
|
||||
long key = (((long) wx) << 32) ^ (wz & 0xFFFFFFFFL);
|
||||
ChunkMemo memo = CHUNK_MEMO.get();
|
||||
if (memo.context == null || !memo.context.matches(wx >> 4, wz >> 4, chunkHeight, baseSeed,
|
||||
data, engine, boundarySampler)) {
|
||||
memo.samples.clear();
|
||||
FOOTPRINT_MEMO.get().clear();
|
||||
memo.context = new MemoContext(wx >> 4, wz >> 4, chunkHeight, baseSeed, data, engine, boundarySampler);
|
||||
}
|
||||
FloatingIslandSample result = sample(parent, wx, wz, chunkHeight, baseSeed, runtime, boundarySampler);
|
||||
memo.remember(parent, column, result);
|
||||
MemoizedSample cached = memo.samples.get(key);
|
||||
if (cached != null && cached.parent == parent) {
|
||||
return cached.sample;
|
||||
}
|
||||
FloatingIslandSample result = sample(parent, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler);
|
||||
memo.samples.put(key, new MemoizedSample(parent, result));
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -165,18 +183,18 @@ public final class FloatingIslandSample {
|
||||
}
|
||||
|
||||
private static int maximumEdgeFieldWidth(KList<IrisFloatingChildBiomes> entries, long baseSeed,
|
||||
PackRuntime runtime, IrisBiome parent) {
|
||||
IrisData data, IrisBiome parent) {
|
||||
int maximumWidth = FloatingIslandEdgeProfile.MIN_WIDTH;
|
||||
for (IrisFloatingChildBiomes entry : entries) {
|
||||
FloatingIslandEdgeProfile profile = resolveEdgeProfile(entry, baseSeed, runtime, parent);
|
||||
FloatingIslandEdgeProfile profile = resolveEdgeProfile(entry, baseSeed, data, parent);
|
||||
maximumWidth = Math.max(maximumWidth, profile.fieldWidth());
|
||||
}
|
||||
return maximumWidth;
|
||||
}
|
||||
|
||||
private static FloatingIslandEdgeProfile resolveEdgeProfile(IrisFloatingChildBiomes entry, long baseSeed,
|
||||
PackRuntime runtime, IrisBiome parent) {
|
||||
FloatingIslandEdgeProfile profile = entry.getEdgeTaperProfile(baseSeed, runtime);
|
||||
IrisData data, IrisBiome parent) {
|
||||
FloatingIslandEdgeProfile profile = entry.getEdgeTaperProfile(baseSeed, data);
|
||||
if (profile != null) {
|
||||
return profile;
|
||||
}
|
||||
@@ -184,17 +202,17 @@ public final class FloatingIslandSample {
|
||||
return FloatingIslandEdgeProfile.DEFAULT;
|
||||
}
|
||||
|
||||
public static FloatingIslandSample sample(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, PackRuntime runtime, FloatingIslandBoundarySampler boundarySampler) {
|
||||
public static FloatingIslandSample sample(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler) {
|
||||
KList<IrisFloatingChildBiomes> entries = parent.getFloatingChildBiomes();
|
||||
if (entries == null || entries.isEmpty()) {
|
||||
return reject(REJECT_NO_ENTRIES);
|
||||
}
|
||||
|
||||
int boundaryFieldWidth = maximumEdgeFieldWidth(entries, baseSeed, runtime, parent);
|
||||
int boundaryFieldWidth = maximumEdgeFieldWidth(entries, baseSeed, data, parent);
|
||||
int parentBoundaryDistance = boundarySampler.edgeDistance(parent, wx, wz, boundaryFieldWidth);
|
||||
|
||||
if (parent.isMergeFloatingChildBiomes()) {
|
||||
return sampleMerged(parent, entries, wx, wz, chunkHeight, baseSeed, runtime, boundarySampler,
|
||||
return sampleMerged(parent, entries, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler,
|
||||
parentBoundaryDistance, boundaryFieldWidth);
|
||||
}
|
||||
|
||||
@@ -204,7 +222,7 @@ public final class FloatingIslandSample {
|
||||
entry = entries.getFirst();
|
||||
} else {
|
||||
IrisFloatingChildBiomes reference = entries.getFirst();
|
||||
CNG picker = reference.getPickerCng(baseSeed, runtime);
|
||||
CNG picker = reference.getPickerCng(baseSeed, data);
|
||||
if (picker == null) {
|
||||
warnNullCng("pickerStyle", parent);
|
||||
return reject(REJECT_NO_PICK);
|
||||
@@ -218,20 +236,20 @@ public final class FloatingIslandSample {
|
||||
ownershipBoundaryDistance = ownership.boundaryDistance();
|
||||
}
|
||||
|
||||
return sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, runtime, boundarySampler,
|
||||
return sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler,
|
||||
parentBoundaryDistance, ownershipBoundaryDistance);
|
||||
}
|
||||
|
||||
private static FloatingIslandSample sampleMerged(IrisBiome parent, KList<IrisFloatingChildBiomes> entries,
|
||||
int wx, int wz, int chunkHeight, long baseSeed, PackRuntime runtime,
|
||||
FloatingIslandBoundarySampler boundarySampler,
|
||||
int wx, int wz, int chunkHeight, long baseSeed, IrisData data,
|
||||
Engine engine, FloatingIslandBoundarySampler boundarySampler,
|
||||
int parentBoundaryDistance, int boundaryFieldWidth) {
|
||||
KList<FloatingIslandSample> samples = new KList<>();
|
||||
int minY = Integer.MAX_VALUE;
|
||||
int maxY = Integer.MIN_VALUE;
|
||||
|
||||
for (IrisFloatingChildBiomes entry : entries) {
|
||||
FloatingIslandSample sample = sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, runtime,
|
||||
FloatingIslandSample sample = sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, data, engine,
|
||||
boundarySampler, parentBoundaryDistance, boundaryFieldWidth + 1);
|
||||
if (sample == null) {
|
||||
continue;
|
||||
@@ -294,11 +312,11 @@ public final class FloatingIslandSample {
|
||||
}
|
||||
|
||||
private static FloatingIslandSample sampleEntry(IrisBiome parent, IrisFloatingChildBiomes entry, int wx, int wz,
|
||||
int chunkHeight, long baseSeed, PackRuntime runtime,
|
||||
int chunkHeight, long baseSeed, IrisData data, Engine engine,
|
||||
FloatingIslandBoundarySampler boundarySampler,
|
||||
int parentBoundaryDistance, int ownershipBoundaryDistance) {
|
||||
FloatingIslandEdgeProfile edgeProfile = resolveEdgeProfile(entry, baseSeed, runtime, parent);
|
||||
CNG footprintCng = entry.getFootprintCng(baseSeed, runtime);
|
||||
FloatingIslandEdgeProfile edgeProfile = resolveEdgeProfile(entry, baseSeed, data, parent);
|
||||
CNG footprintCng = entry.getFootprintCng(baseSeed, data);
|
||||
if (footprintCng == null) {
|
||||
warnNullCng("footprintStyle", parent);
|
||||
return reject(REJECT_NO_SEED);
|
||||
@@ -324,23 +342,23 @@ public final class FloatingIslandSample {
|
||||
return reject(REJECT_NO_THICKNESS);
|
||||
}
|
||||
|
||||
CNG altitudeCng = entry.getAltitudeCng(baseSeed, runtime);
|
||||
CNG altitudeCng = entry.getAltitudeCng(baseSeed, data);
|
||||
if (altitudeCng == null) {
|
||||
warnNullCng("altitudeStyle", parent);
|
||||
return reject(REJECT_NO_SEED);
|
||||
}
|
||||
double altNoise = altitudeCng.noise(wx, wz);
|
||||
double altClamped = Math.max(0, Math.min(1, altNoise));
|
||||
int worldMin = runtime.engine().getWorld().minHeight();
|
||||
int worldMin = engine.getWorld().minHeight();
|
||||
int minAlt = Math.max(0, entry.getMinHeightAboveSurface() - worldMin);
|
||||
int maxAlt = Math.max(minAlt, entry.getMaxHeightAboveSurface() - worldMin);
|
||||
int baseY = minAlt + (int) Math.round(altClamped * (maxAlt - minAlt));
|
||||
|
||||
IrisBiome target = entry.getRealBiome(parent, runtime.data());
|
||||
int fullTopHeight = computeTopHeight(entry, target, runtime, baseSeed, wx, wz);
|
||||
IrisBiome target = entry.getRealBiome(parent, data);
|
||||
int fullTopHeight = computeTopHeight(entry, target, engine, baseSeed, wx, wz, data);
|
||||
int topH = roundedEdgeHeight(fullTopHeight, edgeFade);
|
||||
|
||||
CNG bottomCng = entry.getBottomCng(baseSeed, runtime);
|
||||
CNG bottomCng = entry.getBottomCng(baseSeed, data);
|
||||
if (bottomCng == null) {
|
||||
warnNullCng("bottomStyle", parent);
|
||||
return reject(REJECT_NO_SEED);
|
||||
@@ -397,16 +415,14 @@ public final class FloatingIslandSample {
|
||||
}
|
||||
|
||||
boolean[] solidMask = new boolean[thickness];
|
||||
CNG wallWarp = entry.getWallWarpCng(baseSeed, runtime);
|
||||
CNG wallWarp = entry.getWallWarpCng(baseSeed, data);
|
||||
double warpAmp = Math.max(0, entry.getWallWarpAmplitude());
|
||||
double effectiveWarpAmp = effectiveWallWarpAmplitude(warpAmp, edgeFade);
|
||||
IrisCaveProfileSampler carvingProfileSampler = entry.getCarvingProfileSampler(runtime);
|
||||
CNG carve = carvingProfileSampler == null && !entry.hasCarvingReference() ? entry.getCarveCng(baseSeed, runtime) : null;
|
||||
CNG carve = entry.getCarveCng(baseSeed, data);
|
||||
double carveThreshold = entry.getCarveThreshold();
|
||||
boolean useWarp = wallWarp != null && effectiveWarpAmp > 0;
|
||||
boolean useProfileCarve = carvingProfileSampler != null;
|
||||
boolean useCarve = directCarveEnabled(entry, carvingProfileSampler, carve, carveThreshold);
|
||||
boolean[] lateralCarveMask = useProfileCarve || useCarve ? new boolean[thickness] : null;
|
||||
boolean useCarve = directCarveEnabled(carve, carveThreshold);
|
||||
boolean[] lateralCarveMask = useCarve ? new boolean[thickness] : null;
|
||||
boolean baseCarveInterior = lateralCarveMask != null && canCarveLaterally(edgeFade, footprintSupport);
|
||||
|
||||
if (useWarp) {
|
||||
@@ -433,9 +449,7 @@ public final class FloatingIslandSample {
|
||||
}
|
||||
|
||||
int solidCount = solidifyUncarvedInterior(solidMask);
|
||||
if (useProfileCarve) {
|
||||
solidCount = carveSolidInterior(solidMask, lateralCarveMask, botY, wx, wz, carvingProfileSampler, carveThreshold);
|
||||
} else if (useCarve) {
|
||||
if (useCarve) {
|
||||
solidCount = carveSolidInterior(solidMask, lateralCarveMask, botY, wx, wz, carve, carveThreshold);
|
||||
}
|
||||
int highestSolidIdx = highestSolidIndex(solidMask);
|
||||
@@ -469,8 +483,8 @@ public final class FloatingIslandSample {
|
||||
return amplitude * fade;
|
||||
}
|
||||
|
||||
static boolean directCarveEnabled(IrisFloatingChildBiomes entry, IrisCaveProfileSampler carvingProfileSampler, CNG carve, double carveThreshold) {
|
||||
return carvingProfileSampler == null && (entry == null || !entry.hasCarvingReference()) && carve != null && carveThreshold < 1.0;
|
||||
static boolean directCarveEnabled(CNG carve, double carveThreshold) {
|
||||
return carve != null && carveThreshold < 1.0;
|
||||
}
|
||||
|
||||
static boolean canCarveLaterally(double edgeFade, NeighborSupport support) {
|
||||
@@ -485,10 +499,6 @@ public final class FloatingIslandSample {
|
||||
});
|
||||
}
|
||||
|
||||
static int carveSolidInterior(boolean[] solidMask, boolean[] lateralCarveMask, int botY, int wx, int wz, IrisCaveProfileSampler carve, double carveThreshold) {
|
||||
return carveSolidInterior(solidMask, lateralCarveMask, botY, wx, wz, (x, y, z) -> carve.shouldCarve(x, y, z, carveThreshold));
|
||||
}
|
||||
|
||||
private static int carveSolidInterior(boolean[] solidMask, boolean[] lateralCarveMask, int botY, int wx, int wz, CarveSampler carve) {
|
||||
int firstSolid = -1;
|
||||
int lastSolid = -1;
|
||||
@@ -664,7 +674,27 @@ public final class FloatingIslandSample {
|
||||
}
|
||||
|
||||
private static double footprintSigned(CNG footprintCng, int wx, int wz) {
|
||||
return signedFromUnit(footprintCng.noise(wx, wz));
|
||||
IdentityHashMap<CNG, Long2DoubleOpenHashMap> memoByCng = FOOTPRINT_MEMO.get();
|
||||
Long2DoubleOpenHashMap memo = memoByCng.get(footprintCng);
|
||||
if (memo == null) {
|
||||
memo = new Long2DoubleOpenHashMap(512);
|
||||
memo.defaultReturnValue(Double.NaN);
|
||||
memoByCng.put(footprintCng, memo);
|
||||
}
|
||||
|
||||
long key = columnKey(wx, wz);
|
||||
double cached = memo.get(key);
|
||||
if (!Double.isNaN(cached)) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
double signed = signedFromUnit(footprintCng.noise(wx, wz));
|
||||
memo.put(key, signed);
|
||||
return signed;
|
||||
}
|
||||
|
||||
private static long columnKey(int wx, int wz) {
|
||||
return ((long) wx << 32) ^ (wz & 0xFFFFFFFFL);
|
||||
}
|
||||
|
||||
private static double signedFromUnit(double value) {
|
||||
@@ -740,7 +770,7 @@ public final class FloatingIslandSample {
|
||||
}
|
||||
}
|
||||
|
||||
private static int computeTopHeight(IrisFloatingChildBiomes entry, IrisBiome target, PackRuntime runtime, long baseSeed, int wx, int wz) {
|
||||
private static int computeTopHeight(IrisFloatingChildBiomes entry, IrisBiome target, Engine engine, long baseSeed, int wx, int wz, IrisData data) {
|
||||
int maxTopHeight = Math.max(0, entry.getMaxTopHeight());
|
||||
if (maxTopHeight == 0) {
|
||||
return 0;
|
||||
@@ -748,7 +778,7 @@ public final class FloatingIslandSample {
|
||||
return switch (entry.getTopShapeMode()) {
|
||||
case FLAT -> maxTopHeight;
|
||||
case NOISE -> {
|
||||
CNG topCng = entry.getTopShapeCng(baseSeed, runtime);
|
||||
CNG topCng = entry.getTopShapeCng(baseSeed, data);
|
||||
if (topCng == null) {
|
||||
warnNullCng("topShapeStyle", null);
|
||||
yield maxTopHeight / 2;
|
||||
@@ -762,7 +792,7 @@ public final class FloatingIslandSample {
|
||||
if (target == null) {
|
||||
yield maxTopHeight / 2;
|
||||
}
|
||||
double h = target.getHeight(runtime, wx, wz, baseSeed);
|
||||
double h = target.getHeight(engine, wx, wz, baseSeed);
|
||||
int rounded = (int) Math.round(h);
|
||||
if (rounded < 0) {
|
||||
yield 0;
|
||||
@@ -771,4 +801,21 @@ public final class FloatingIslandSample {
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static final class ChunkMemo {
|
||||
private final HashMap<Long, MemoizedSample> samples = new HashMap<>(256);
|
||||
private MemoContext context;
|
||||
}
|
||||
|
||||
private record MemoContext(int chunkX, int chunkZ, int height, long seed, IrisData data, Engine engine,
|
||||
FloatingIslandBoundarySampler boundarySampler) {
|
||||
private boolean matches(int chunkX, int chunkZ, int height, long seed, IrisData data, Engine engine,
|
||||
FloatingIslandBoundarySampler boundarySampler) {
|
||||
return this.chunkX == chunkX && this.chunkZ == chunkZ && this.height == height && this.seed == seed
|
||||
&& this.data == data && this.engine == engine && this.boundarySampler == boundarySampler;
|
||||
}
|
||||
}
|
||||
|
||||
private record MemoizedSample(IrisBiome parent, FloatingIslandSample sample) {
|
||||
}
|
||||
}
|
||||
@@ -18,8 +18,7 @@
|
||||
|
||||
package art.arcane.iris.generation.biome;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.cave.IrisCaveProfile;
|
||||
import art.arcane.iris.generation.cave.IrisCave;
|
||||
import art.arcane.iris.generation.decoration.IrisDecorationPart;
|
||||
import art.arcane.iris.generation.decoration.IrisDecorator;
|
||||
import art.arcane.iris.generation.decoration.IrisDepositGenerator;
|
||||
@@ -34,6 +33,8 @@ import art.arcane.iris.generation.terrain.InferredType;
|
||||
import art.arcane.iris.generation.terrain.IrisDimension;
|
||||
import art.arcane.iris.generation.terrain.IrisTerrain3D;
|
||||
import art.arcane.iris.pack.validation.CompatPools;
|
||||
import art.arcane.iris.pack.value.Weighted;
|
||||
import art.arcane.iris.pack.value.WeightedReference;
|
||||
import art.arcane.iris.structure.object.IrisObjectPlacement;
|
||||
import art.arcane.iris.structure.placement.IrisStructurePlacement;
|
||||
import art.arcane.iris.world.entity.IrisEffect;
|
||||
@@ -48,6 +49,7 @@ import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.pack.loading.IrisRegistrant;
|
||||
import art.arcane.iris.generation.runtime.IrisComplex;
|
||||
import art.arcane.volmlib.util.cache.AtomicCache;
|
||||
import art.arcane.iris.generation.cache.LazyBoundedCache;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.pack.schema.annotation.ArrayType;
|
||||
import art.arcane.iris.pack.schema.annotation.DependsOn;
|
||||
@@ -63,6 +65,7 @@ import art.arcane.volmlib.util.collection.KSet;
|
||||
import art.arcane.iris.generation.block.DataProvider;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import art.arcane.volmlib.util.noise.CNG;
|
||||
import art.arcane.iris.generation.context.IrisContext;
|
||||
import art.arcane.volmlib.util.stream.ProceduralStream;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Data;
|
||||
@@ -92,6 +95,7 @@ import java.util.Objects;
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
public class IrisBiome extends IrisRegistrant implements Rarity {
|
||||
public static final int CHILD_HOPS = 4;
|
||||
private static final int BIOME_GENERATOR_CACHE_SIZE = 8;
|
||||
private static final int CHILDREN_SEED_SALT = 2137;
|
||||
|
||||
private final transient AtomicCache<KMap<String, IrisBiomeGeneratorLink>> genCache = new AtomicCache<>();
|
||||
@@ -102,10 +106,26 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
|
||||
private final transient AtomicCache<Color> cacheColorDecoratorLoad = new AtomicCache<>();
|
||||
private final transient AtomicCache<Color> cacheColorLayerLoad = new AtomicCache<>();
|
||||
private final transient AtomicCache<Color> cacheColorDepositLoad = new AtomicCache<>();
|
||||
@Getter(AccessLevel.NONE)
|
||||
@Setter(AccessLevel.NONE)
|
||||
private final transient LazyBoundedCache<ChildGeneratorKey, CNG> childrenGenerators = new LazyBoundedCache<>(8);
|
||||
@Getter(AccessLevel.NONE)
|
||||
@Setter(AccessLevel.NONE)
|
||||
private transient volatile CachedChildGenerator recentChildGenerator;
|
||||
@Getter(AccessLevel.NONE)
|
||||
private final transient LazyBoundedCache<Long, CNG> biomeGenerators =
|
||||
new LazyBoundedCache<>(BIOME_GENERATOR_CACHE_SIZE);
|
||||
@Getter(AccessLevel.NONE)
|
||||
@Setter(AccessLevel.NONE)
|
||||
private transient volatile SeededBiomeGenerator recentBiomeGenerator;
|
||||
private final transient AtomicCache<Integer> maxHeight = new AtomicCache<>();
|
||||
private final transient AtomicCache<Integer> maxWithObjectHeight = new AtomicCache<>();
|
||||
private final transient AtomicCache<IrisBiome> realCarveBiome = new AtomicCache<>();
|
||||
private final transient AtomicCache<KList<IrisBiome>> realChildren = new AtomicCache<>();
|
||||
private final transient AtomicCache<KList<Weighted<IrisBiome>>> weightedChildren = new AtomicCache<>();
|
||||
private final transient IrisBiomeLayerHeightCache layerHeightGenerators = new IrisBiomeLayerHeightCache();
|
||||
private final transient IrisBiomeLayerHeightCache layerCeilingHeightGenerators = new IrisBiomeLayerHeightCache();
|
||||
private final transient IrisBiomeLayerHeightCache layerSeaHeightGenerators = new IrisBiomeLayerHeightCache();
|
||||
private final transient AtomicCache<KList<IrisOreGenerator>> surfaceOreCache = new AtomicCache<>();
|
||||
private final transient AtomicCache<KList<IrisOreGenerator>> undergroundOreCache = new AtomicCache<>();
|
||||
private final transient AtomicCache<IrisOreBands> surfaceOreBandsCache = new AtomicCache<>();
|
||||
@@ -143,8 +163,10 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
|
||||
private boolean lockLayers = false;
|
||||
@Description("The max layers to iterate below the surface for locked layer biomes (mesa).")
|
||||
private int lockLayersMax = 7;
|
||||
@Description("Profile-driven 3D cave configuration")
|
||||
private IrisCaveProfile caveProfile = new IrisCaveProfile();
|
||||
@ArrayType(type = String.class, min = 1)
|
||||
@RegistryListResource(IrisCave.class)
|
||||
@Description("Caves that carve under this biome, by their file in the pack's caves folder. As a cave biome, they carve where the cave biome is. They add to the dimension's and the region's lists.")
|
||||
private KList<String> caves = new KList<>();
|
||||
@Description("Water settings for this biome: rainfall, pond density, where streams and ponds may form, and the fluid that fills them. A value left unset comes from the region, then from the dimension.")
|
||||
private IrisHydrologyPolicy hydrologyPolicy = null;
|
||||
@MinNumber(1)
|
||||
@@ -175,10 +197,9 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
|
||||
@DependsOn({"children"})
|
||||
@Description("If this biome has children biomes, and the gen layer chooses one of this biomes children, How will it be shaped?")
|
||||
private IrisGeneratorStyle childStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style();
|
||||
@RegistryListResource(IrisBiome.class)
|
||||
@ArrayType(min = 1, type = String.class)
|
||||
@Description("List any biome names (file names without.json) here as children. Portions of this biome can sometimes morph into their children. Iris supports cyclic relationships such as A > B > A > B. Iris will stop checking 4 biomes down the tree.")
|
||||
private KList<String> children = new KList<>();
|
||||
@ArrayType(min = 1, type = IrisBiomeEntry.class)
|
||||
@Description("List any biome names (file names without.json) here as children, or objects with a biome and a weight. Portions of this biome can sometimes morph into their children. Iris supports cyclic relationships such as A > B > A > B. Iris will stop checking 4 biomes down the tree. When any child is written as an object, the list is weighted: the parent itself only stays in the mix if it is listed too.")
|
||||
private KList<IrisBiomeEntry> children = new KList<>();
|
||||
@RegistryListResource(IrisBiome.class)
|
||||
@Description("Registers the referenced biome with this pack's reachable biome set. It is NOT applied as a substitute under carvings; cave biomes come from the region's caveBiomes list.")
|
||||
private String carvingBiome = "";
|
||||
@@ -257,16 +278,16 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
|
||||
return IrisBiomeOres.canReplaceSurfaceOre(this, state);
|
||||
}
|
||||
|
||||
public NativeBlockState generateOres(int x, int y, int z, RNG rng, PackRuntime runtime, boolean surface) {
|
||||
return IrisBiomeOres.generateOres(this, x, y, z, rng, runtime, surface);
|
||||
public NativeBlockState generateOres(int x, int y, int z, RNG rng, IrisData data, boolean surface) {
|
||||
return IrisBiomeOres.generateOres(this, x, y, z, rng, data, surface);
|
||||
}
|
||||
|
||||
public NativeBlockState generateSurfaceOres(int x, int y, int z, RNG rng, PackRuntime runtime) {
|
||||
return IrisBiomeOres.generateSurfaceOres(this, x, y, z, rng, runtime);
|
||||
public NativeBlockState generateSurfaceOres(int x, int y, int z, RNG rng, IrisData data) {
|
||||
return IrisBiomeOres.generateSurfaceOres(this, x, y, z, rng, data);
|
||||
}
|
||||
|
||||
public NativeBlockState generateUndergroundOres(int x, int y, int z, RNG rng, PackRuntime runtime) {
|
||||
return IrisBiomeOres.generateUndergroundOres(this, x, y, z, rng, runtime);
|
||||
public NativeBlockState generateUndergroundOres(int x, int y, int z, RNG rng, IrisData data) {
|
||||
return IrisBiomeOres.generateUndergroundOres(this, x, y, z, rng, data);
|
||||
}
|
||||
|
||||
public boolean hasSurfaceOres() {
|
||||
@@ -452,38 +473,68 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
|
||||
});
|
||||
}
|
||||
|
||||
public double getHeight(PackRuntime runtime, double x, double z, long seed) {
|
||||
public double getHeight(Engine xg, double x, double z, long seed) {
|
||||
double height = 0;
|
||||
|
||||
for (IrisBiomeGeneratorLink i : generators) {
|
||||
height += i.getHeight(runtime, x, z, seed);
|
||||
height += i.getHeight(xg, x, z, seed);
|
||||
}
|
||||
|
||||
return Math.max(0, Math.min(height, runtime.engine().getHeight()));
|
||||
return Math.max(0, Math.min(height, xg.getHeight()));
|
||||
}
|
||||
|
||||
public CNG getBiomeGenerator(RNG random) {
|
||||
IrisData loader = getLoader();
|
||||
Engine engine = resolveBiomeGeneratorEngine(loader);
|
||||
return getBiomeGenerator(random, engine);
|
||||
}
|
||||
|
||||
/** Engines seed the scatter generator from their own biome seed; engine-less tools use the caller's seed. */
|
||||
public CNG getBiomeGenerator(RNG random, Engine engine) {
|
||||
IrisData loader = getLoader();
|
||||
long seed = engine == null ? random.getSeed() : engine.getSeedManager().getBiome();
|
||||
return PackRuntime.of(engine, getLoader()).biome(this).biomeGenerator(seed);
|
||||
SeededBiomeGenerator recent = recentBiomeGenerator;
|
||||
if (recent != null && recent.seed == seed) {
|
||||
return recent.generator;
|
||||
}
|
||||
|
||||
CNG generator = biomeGenerators.computeIfAbsent(seed, ignored -> createBiomeGenerator(seed, loader));
|
||||
recentBiomeGenerator = new SeededBiomeGenerator(seed, generator);
|
||||
return generator;
|
||||
}
|
||||
|
||||
CNG createBiomeGenerator(long seed, PackRuntime runtime) {
|
||||
private Engine resolveBiomeGeneratorEngine(IrisData loader) {
|
||||
IrisContext context = IrisContext.get();
|
||||
if (context != null) {
|
||||
Engine contextEngine = context.getEngine();
|
||||
if (!contextEngine.isClosed() && (loader == null || contextEngine.getData() == loader)) {
|
||||
return contextEngine;
|
||||
}
|
||||
}
|
||||
|
||||
return loader == null ? null : loader.getEngine();
|
||||
}
|
||||
|
||||
private CNG createBiomeGenerator(long seed, IrisData loader) {
|
||||
int signature = 213949 + 228888 + getRarity() + getName().length();
|
||||
return biomeStyle.createNoCache(new RNG(seed).nextParallelRNG(signature), runtime);
|
||||
return biomeStyle.createNoCache(new RNG(seed).nextParallelRNG(signature), loader);
|
||||
}
|
||||
|
||||
public CNG getChildrenGenerator(PackRuntime runtime, RNG random, int sig, double scale) {
|
||||
return getChildrenGenerator(runtime, deriveChildStyleSeed(random, sig).getSeed(), scale);
|
||||
public CNG getChildrenGenerator(RNG random, int sig, double scale) {
|
||||
return getChildrenGenerator(deriveChildStyleSeed(random, sig).getSeed(), scale);
|
||||
}
|
||||
|
||||
public CNG getChildrenGenerator(PackRuntime runtime, long seed, double scale) {
|
||||
double childScale = getChildStyle().isSeeded() ? 1 : scale;
|
||||
return runtime.biome(this).childrenGenerator(seed, childScale);
|
||||
}
|
||||
|
||||
CNG createChildrenGenerator(long seed, double scale, PackRuntime runtime) {
|
||||
return getChildStyle().createScaledGenerator(new RNG(seed), runtime, scale);
|
||||
public CNG getChildrenGenerator(long seed, double scale) {
|
||||
IrisData data = getLoader();
|
||||
Engine engine = data == null ? null : data.getEngine();
|
||||
CachedChildGenerator recent = recentChildGenerator;
|
||||
if (recent != null && recent.key.matches(seed, scale, data, engine)) {
|
||||
return recent.generator;
|
||||
}
|
||||
ChildGeneratorKey key = new ChildGeneratorKey(seed, scale, data, engine);
|
||||
CNG generator = childrenGenerators.computeIfAbsent(key,
|
||||
ignored -> getChildStyle().createScaledGenerator(new RNG(seed), data, scale));
|
||||
recentChildGenerator = new CachedChildGenerator(key, generator);
|
||||
return generator;
|
||||
}
|
||||
|
||||
static RNG deriveChildStyleSeed(RNG random, int signature) {
|
||||
@@ -494,24 +545,24 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
|
||||
return deriveChildStyleSeed(random, signature).getSeed();
|
||||
}
|
||||
|
||||
public KList<NativeBlockState> generateLayers(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, IrisComplex complex) {
|
||||
return IrisBiomeLayerGenerator.generateLayers(this, dim, wx, wz, random, maxDepth, height, runtime, complex);
|
||||
public KList<NativeBlockState> generateLayers(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) {
|
||||
return IrisBiomeLayerGenerator.generateLayers(this, dim, wx, wz, random, maxDepth, height, rdata, complex);
|
||||
}
|
||||
|
||||
public KList<NativeBlockState> generateLayersWithSlope(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, ProceduralStream<Double> slopeStream) {
|
||||
return IrisBiomeLayerGenerator.generateLayers(this, dim, wx, wz, random, maxDepth, height, runtime, slopeStream);
|
||||
public KList<NativeBlockState> generateLayersWithSlope(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, ProceduralStream<Double> slopeStream) {
|
||||
return IrisBiomeLayerGenerator.generateLayers(this, dim, wx, wz, random, maxDepth, height, rdata, slopeStream);
|
||||
}
|
||||
|
||||
public KList<NativeBlockState> generateCeilingLayers(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, IrisComplex complex) {
|
||||
return IrisBiomeLayerGenerator.generateCeilingLayers(this, dim, wx, wz, random, maxDepth, height, runtime, complex);
|
||||
public KList<NativeBlockState> generateCeilingLayers(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) {
|
||||
return IrisBiomeLayerGenerator.generateCeilingLayers(this, dim, wx, wz, random, maxDepth, height, rdata, complex);
|
||||
}
|
||||
|
||||
public KList<NativeBlockState> generateLockedLayers(double wx, double wz, RNG random, int maxDepthf, int height, PackRuntime runtime, IrisComplex complex) {
|
||||
return IrisBiomeLayerGenerator.generateLockedLayers(this, wx, wz, random, maxDepthf, height, runtime, complex);
|
||||
public KList<NativeBlockState> generateLockedLayers(double wx, double wz, RNG random, int maxDepthf, int height, IrisData rdata, IrisComplex complex) {
|
||||
return IrisBiomeLayerGenerator.generateLockedLayers(this, wx, wz, random, maxDepthf, height, rdata, complex);
|
||||
}
|
||||
|
||||
public KList<NativeBlockState> generateSeaLayers(double wx, double wz, RNG random, int maxDepth, PackRuntime runtime) {
|
||||
return IrisBiomeLayerGenerator.generateSeaLayers(this, wx, wz, random, maxDepth, runtime);
|
||||
public KList<NativeBlockState> generateSeaLayers(double wx, double wz, RNG random, int maxDepth, IrisData rdata) {
|
||||
return IrisBiomeLayerGenerator.generateSeaLayers(this, wx, wz, random, maxDepth, rdata);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -526,20 +577,20 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
|
||||
return IrisBiomeLayerGenerator.getMaxWithObjectHeight(this, data, engine);
|
||||
}
|
||||
|
||||
public KList<CNG> getLayerHeightGenerators(RNG rng, PackRuntime runtime) {
|
||||
return runtime.biome(this).layerHeights(rng.getSeed());
|
||||
public KList<CNG> getLayerHeightGenerators(RNG rng, IrisData rdata) {
|
||||
return IrisBiomeLayerGenerator.getLayerHeightGenerators(this, rng, rdata);
|
||||
}
|
||||
|
||||
public KList<CNG> getLayerSeaHeightGenerators(RNG rng, PackRuntime runtime) {
|
||||
return runtime.biome(this).seaLayerHeights(rng.getSeed());
|
||||
public KList<CNG> getLayerSeaHeightGenerators(RNG rng, IrisData data) {
|
||||
return IrisBiomeLayerGenerator.getLayerSeaHeightGenerators(this, rng, data);
|
||||
}
|
||||
|
||||
public KList<CNG> getCaveCeilingLayerHeightGenerators(RNG rng, PackRuntime runtime) {
|
||||
return runtime.biome(this).ceilingLayerHeights(rng.getSeed());
|
||||
public KList<CNG> getCaveCeilingLayerHeightGenerators(RNG rng, IrisData data) {
|
||||
return IrisBiomeLayerGenerator.getCaveCeilingLayerHeightGenerators(this, rng, data);
|
||||
}
|
||||
|
||||
public NativeBlockState getSurfaceBlock(int x, int z, RNG rng, PackRuntime runtime) {
|
||||
return IrisBiomeLayerGenerator.getSurfaceBlock(this, x, z, rng, runtime);
|
||||
public NativeBlockState getSurfaceBlock(int x, int z, RNG rng, IrisData idm) {
|
||||
return IrisBiomeLayerGenerator.getSurfaceBlock(this, x, z, rng, idm);
|
||||
}
|
||||
|
||||
public boolean isLand() {
|
||||
@@ -569,30 +620,55 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
|
||||
return inferredType.equals(InferredType.SHORE);
|
||||
}
|
||||
|
||||
public Biome getSkyBiome(RNG rng, double x, double y, double z) {
|
||||
return IrisBiomeDerivatives.getSkyBiome(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z);
|
||||
}
|
||||
|
||||
public Biome getSkyBiome(RNG rng, Engine engine, double x, double y, double z) {
|
||||
return IrisBiomeDerivatives.getSkyBiome(this, rng, engine, x, y, z);
|
||||
}
|
||||
|
||||
public IrisBiomeCustom getCustomBiome(RNG rng, double x, double y, double z) {
|
||||
return IrisBiomeDerivatives.getCustomBiome(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z);
|
||||
}
|
||||
|
||||
public IrisBiomeCustom getCustomBiome(RNG rng, Engine engine, double x, double y, double z) {
|
||||
return IrisBiomeDerivatives.getCustomBiome(this, rng, engine, x, y, z);
|
||||
}
|
||||
|
||||
public KList<String> getChildKeys() {
|
||||
return WeightedReference.keys(children);
|
||||
}
|
||||
|
||||
public boolean hasWeightedChildren() {
|
||||
return WeightedReference.anyWrittenAsObject(children);
|
||||
}
|
||||
|
||||
public KList<IrisBiome> getRealChildren(DataProvider g) {
|
||||
return realChildren.aquire(() ->
|
||||
{
|
||||
IrisData data = g == null ? null : g.getData();
|
||||
return CompatPools.load(data == null ? null : data.getBiomeLoader(), getChildren(), data,
|
||||
return CompatPools.load(data == null ? null : data.getBiomeLoader(), getChildKeys(), data,
|
||||
"biome", getLoadKey(), "children", null);
|
||||
});
|
||||
}
|
||||
|
||||
public KList<Weighted<IrisBiome>> getWeightedChildren(DataProvider g) {
|
||||
return weightedChildren.aquire(() ->
|
||||
{
|
||||
IrisData data = g == null ? null : g.getData();
|
||||
return CompatPools.loadWeighted(data == null ? null : data.getBiomeLoader(), children, data,
|
||||
"biome", getLoadKey(), "children", null);
|
||||
});
|
||||
}
|
||||
|
||||
public KList<String> getAllChildren(DataProvider g, int limit) {
|
||||
KSet<String> m = new KSet<>();
|
||||
m.addAll(getChildren());
|
||||
m.addAll(getChildKeys());
|
||||
limit--;
|
||||
|
||||
if (limit > 0) {
|
||||
for (String i : getChildren()) {
|
||||
for (String i : getChildKeys()) {
|
||||
IrisBiome b = g.getData().getBiomeLoader().load(i);
|
||||
m.addAll(b.getAllChildren(g, limit));
|
||||
}
|
||||
@@ -601,14 +677,27 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
|
||||
return new KList<>(m);
|
||||
}
|
||||
|
||||
//TODO: Test
|
||||
public Biome getGroundBiome(RNG rng, double x, double y, double z) {
|
||||
return IrisBiomeDerivatives.getGroundBiome(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z);
|
||||
}
|
||||
|
||||
public Biome getGroundBiome(RNG rng, Engine engine, double x, double y, double z) {
|
||||
return IrisBiomeDerivatives.getGroundBiome(this, rng, engine, x, y, z);
|
||||
}
|
||||
|
||||
public String getSkyBiomeKey(RNG rng, double x, double y, double z) {
|
||||
return IrisBiomeDerivatives.getSkyBiomeKey(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z);
|
||||
}
|
||||
|
||||
public String getSkyBiomeKey(RNG rng, Engine engine, double x, double y, double z) {
|
||||
return IrisBiomeDerivatives.getSkyBiomeKey(this, rng, engine, x, y, z);
|
||||
}
|
||||
|
||||
public String getGroundBiomeKey(RNG rng, double x, double y, double z) {
|
||||
return IrisBiomeDerivatives.getGroundBiomeKey(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z);
|
||||
}
|
||||
|
||||
public String getGroundBiomeKey(RNG rng, Engine engine, double x, double y, double z) {
|
||||
return IrisBiomeDerivatives.getGroundBiomeKey(this, rng, engine, x, y, z);
|
||||
}
|
||||
@@ -646,4 +735,37 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
|
||||
public String getTypeName() {
|
||||
return "Biome";
|
||||
}
|
||||
|
||||
private static final class SeededBiomeGenerator {
|
||||
private final long seed;
|
||||
private final CNG generator;
|
||||
|
||||
private SeededBiomeGenerator(long seed, CNG generator) {
|
||||
this.seed = seed;
|
||||
this.generator = generator;
|
||||
}
|
||||
}
|
||||
|
||||
private record ChildGeneratorKey(long seed, double scale, IrisData data, Engine engine) {
|
||||
private boolean matches(long seed, double scale, IrisData data, Engine engine) {
|
||||
return this.seed == seed && Double.doubleToLongBits(this.scale) == Double.doubleToLongBits(scale)
|
||||
&& this.data == data && this.engine == engine;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object object) {
|
||||
return object instanceof ChildGeneratorKey other && matches(other.seed, other.scale, other.data, other.engine);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int hash = Long.hashCode(seed);
|
||||
hash = 31 * hash + Double.hashCode(scale);
|
||||
hash = 31 * hash + System.identityHashCode(data);
|
||||
return 31 * hash + System.identityHashCode(engine);
|
||||
}
|
||||
}
|
||||
|
||||
private record CachedChildGenerator(ChildGeneratorKey key, CNG generator) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package art.arcane.iris.generation.biome;
|
||||
|
||||
import art.arcane.iris.pack.schema.annotation.MaxNumber;
|
||||
import art.arcane.iris.pack.schema.annotation.MinNumber;
|
||||
import art.arcane.iris.pack.schema.annotation.RegistryListResource;
|
||||
import art.arcane.iris.pack.schema.annotation.Required;
|
||||
import art.arcane.iris.pack.value.Weighted;
|
||||
import art.arcane.iris.pack.value.WeightedReference;
|
||||
import art.arcane.iris.pack.value.WeightedReferenceAdapter;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.documentation.Description;
|
||||
import com.google.gson.annotations.JsonAdapter;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@Description("A biome in a list a noise picks from")
|
||||
@Data
|
||||
@JsonAdapter(IrisBiomeEntry.Adapter.class)
|
||||
public class IrisBiomeEntry implements WeightedReference {
|
||||
@Required
|
||||
@RegistryListResource(IrisBiome.class)
|
||||
@Description("The biome (file name without .json)")
|
||||
private String biome;
|
||||
@MinNumber(Weighted.MIN_WEIGHT)
|
||||
@MaxNumber(Weighted.MAX_WEIGHT)
|
||||
@Description("A weight of two is just as if this entry were listed twice in a row, making the biome more common. The noise picks along the list in the order it is written.")
|
||||
private int weight = 1;
|
||||
private transient boolean writtenAsObject;
|
||||
|
||||
public IrisBiomeEntry(String biome, int weight, boolean writtenAsObject) {
|
||||
this.biome = biome;
|
||||
this.weight = weight;
|
||||
this.writtenAsObject = writtenAsObject;
|
||||
}
|
||||
|
||||
public static IrisBiomeEntry plain(String biome) {
|
||||
return new IrisBiomeEntry(biome, Weighted.MIN_WEIGHT, false);
|
||||
}
|
||||
|
||||
public static KList<IrisBiomeEntry> plainList(String... biomes) {
|
||||
KList<IrisBiomeEntry> entries = new KList<>();
|
||||
for (String biome : biomes) {
|
||||
entries.add(plain(biome));
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getReferenceKey() {
|
||||
return biome;
|
||||
}
|
||||
|
||||
public static final class Adapter extends WeightedReferenceAdapter<IrisBiomeEntry> {
|
||||
public Adapter() {
|
||||
super("biome");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected IrisBiomeEntry create(String key, int weight, boolean writtenAsObject) {
|
||||
return new IrisBiomeEntry(key, weight, writtenAsObject);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,6 @@
|
||||
|
||||
package art.arcane.iris.generation.biome;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.noise.IrisGenerator;
|
||||
|
||||
import art.arcane.volmlib.util.cache.AtomicCache;
|
||||
@@ -82,8 +81,8 @@ public class IrisBiomeGeneratorLink {
|
||||
});
|
||||
}
|
||||
|
||||
public double getHeight(PackRuntime runtime, double x, double z, long seed) {
|
||||
double g = getCachedGenerator(runtime::data).getHeight(runtime, x, z, seed);
|
||||
public double getHeight(DataProvider xg, double x, double z, long seed) {
|
||||
double g = getCachedGenerator(xg).getHeight(x, z, seed);
|
||||
g = g < 0 ? 0 : g;
|
||||
g = g > 1 ? 1 : g;
|
||||
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
|
||||
package art.arcane.iris.generation.biome;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.terrain.IrisDimension;
|
||||
import art.arcane.iris.generation.terrain.IrisSlopeClip;
|
||||
import art.arcane.iris.structure.object.IrisObject;
|
||||
@@ -46,18 +45,18 @@ final class IrisBiomeLayerGenerator {
|
||||
private IrisBiomeLayerGenerator() {
|
||||
}
|
||||
|
||||
static KList<NativeBlockState> generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, IrisComplex complex) {
|
||||
return generateLayers(biome, dim, wx, wz, random, maxDepth, height, runtime, complex, null);
|
||||
static KList<NativeBlockState> generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) {
|
||||
return generateLayers(biome, dim, wx, wz, random, maxDepth, height, rdata, complex, null);
|
||||
}
|
||||
|
||||
static KList<NativeBlockState> generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, ProceduralStream<Double> slopeStream) {
|
||||
return generateLayers(biome, dim, wx, wz, random, maxDepth, height, runtime, null, slopeStream);
|
||||
static KList<NativeBlockState> generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, ProceduralStream<Double> slopeStream) {
|
||||
return generateLayers(biome, dim, wx, wz, random, maxDepth, height, rdata, null, slopeStream);
|
||||
}
|
||||
|
||||
private static KList<NativeBlockState> generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, IrisComplex complex, ProceduralStream<Double> slopeStream) {
|
||||
private static KList<NativeBlockState> generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex, ProceduralStream<Double> slopeStream) {
|
||||
if (biome.isLockLayers()) {
|
||||
KList<NativeBlockState> data = generateLockedLayers(biome, wx, wz, random, maxDepth, height, runtime, complex, slopeStream);
|
||||
appendSurfaceFallback(data, biome, dim, wx, wz, random, Math.min(maxDepth, biome.getLockLayersMax()), runtime);
|
||||
KList<NativeBlockState> data = generateLockedLayers(biome, wx, wz, random, maxDepth, height, rdata, complex, slopeStream);
|
||||
appendSurfaceFallback(data, biome, dim, wx, wz, random, Math.min(maxDepth, biome.getLockLayersMax()), rdata);
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -74,8 +73,7 @@ final class IrisBiomeLayerGenerator {
|
||||
return data;
|
||||
}
|
||||
|
||||
BiomeRuntime biomeRuntime = runtime.biome(biome);
|
||||
KList<CNG> heightGenerators = biomeRuntime.layerHeights(random.getSeed());
|
||||
KList<CNG> heightGenerators = getLayerHeightGenerators(biome, random, rdata);
|
||||
double surfaceSlope = 0D;
|
||||
boolean sampledSlope = false;
|
||||
|
||||
@@ -100,7 +98,7 @@ final class IrisBiomeLayerGenerator {
|
||||
continue;
|
||||
}
|
||||
|
||||
appendLayer(data, layer, biomeRuntime.surfaceLayer(i), i, d, wx, wz, random, maxDepth);
|
||||
appendLayer(data, layer, i, d, wx, wz, random, maxDepth, rdata);
|
||||
|
||||
if (data.size() >= maxDepth) {
|
||||
break;
|
||||
@@ -117,12 +115,12 @@ final class IrisBiomeLayerGenerator {
|
||||
}
|
||||
}
|
||||
|
||||
appendSurfaceFallback(data, biome, dim, wx, wz, random, maxDepth, runtime);
|
||||
appendSurfaceFallback(data, biome, dim, wx, wz, random, maxDepth, rdata);
|
||||
return data;
|
||||
}
|
||||
|
||||
private static void appendSurfaceFallback(KList<NativeBlockState> data, IrisBiome biome, IrisDimension dim,
|
||||
double wx, double wz, RNG random, int maxDepth, PackRuntime runtime) {
|
||||
double wx, double wz, RNG random, int maxDepth, IrisData rdata) {
|
||||
if (!data.isEmpty() || maxDepth <= 0 || biome.getLayers().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
@@ -131,11 +129,11 @@ final class IrisBiomeLayerGenerator {
|
||||
fallback = dim.getSurfaceLayerFallback();
|
||||
}
|
||||
if (fallback == IrisSurfaceLayerFallback.TOP_LAYER) {
|
||||
appendLayer(data, biome.getLayers().get(0), runtime.biome(biome).surfaceLayer(0), 0, 1, wx, wz, random, maxDepth);
|
||||
appendLayer(data, biome.getLayers().get(0), 0, 1, wx, wz, random, maxDepth, rdata);
|
||||
}
|
||||
}
|
||||
|
||||
static KList<NativeBlockState> generateCeilingLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, IrisComplex complex) {
|
||||
static KList<NativeBlockState> generateCeilingLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) {
|
||||
KList<NativeBlockState> data = new KList<>();
|
||||
|
||||
if (maxDepth <= 0) {
|
||||
@@ -149,8 +147,7 @@ final class IrisBiomeLayerGenerator {
|
||||
return data;
|
||||
}
|
||||
|
||||
BiomeRuntime biomeRuntime = runtime.biome(biome);
|
||||
KList<CNG> heightGenerators = biomeRuntime.ceilingLayerHeights(random.getSeed());
|
||||
KList<CNG> heightGenerators = getCaveCeilingLayerHeightGenerators(biome, random, rdata);
|
||||
|
||||
for (int i = 0; i < layerCount; i++) {
|
||||
IrisBiomePaletteLayer layer = ceilingLayers.get(i);
|
||||
@@ -162,7 +159,7 @@ final class IrisBiomeLayerGenerator {
|
||||
continue;
|
||||
}
|
||||
|
||||
appendLayer(data, layer, biomeRuntime.ceilingLayer(i), i, d, wx, wz, random, maxDepth);
|
||||
appendLayer(data, layer, i, d, wx, wz, random, maxDepth, rdata);
|
||||
|
||||
if (data.size() >= maxDepth) {
|
||||
break;
|
||||
@@ -182,11 +179,11 @@ final class IrisBiomeLayerGenerator {
|
||||
return data;
|
||||
}
|
||||
|
||||
static KList<NativeBlockState> generateLockedLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepthf, int height, PackRuntime runtime, IrisComplex complex) {
|
||||
return generateLockedLayers(biome, wx, wz, random, maxDepthf, height, runtime, complex, null);
|
||||
static KList<NativeBlockState> generateLockedLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepthf, int height, IrisData rdata, IrisComplex complex) {
|
||||
return generateLockedLayers(biome, wx, wz, random, maxDepthf, height, rdata, complex, null);
|
||||
}
|
||||
|
||||
private static KList<NativeBlockState> generateLockedLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepthf, int height, PackRuntime runtime, IrisComplex complex, ProceduralStream<Double> slopeStream) {
|
||||
private static KList<NativeBlockState> generateLockedLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepthf, int height, IrisData rdata, IrisComplex complex, ProceduralStream<Double> slopeStream) {
|
||||
KList<NativeBlockState> data = new KList<>();
|
||||
int maxDepth = Math.min(maxDepthf, biome.getLockLayersMax());
|
||||
KList<IrisBiomePaletteLayer> layers = biome.getLayers();
|
||||
@@ -195,8 +192,7 @@ final class IrisBiomeLayerGenerator {
|
||||
return data;
|
||||
}
|
||||
|
||||
BiomeRuntime biomeRuntime = runtime.biome(biome);
|
||||
KList<CNG> heightGenerators = biomeRuntime.layerHeights(random.getSeed());
|
||||
KList<CNG> heightGenerators = getLayerHeightGenerators(biome, random, rdata);
|
||||
int[] boundaries = new int[layerCount + 1];
|
||||
double surfaceSlope = 0D;
|
||||
boolean sampledSlope = false;
|
||||
@@ -231,10 +227,10 @@ final class IrisBiomeLayerGenerator {
|
||||
int layerIndex = findLayer(boundaries, position);
|
||||
IrisBiomePaletteLayer layer = layers.get(layerIndex);
|
||||
int offset = position - boundaries[layerIndex];
|
||||
double blocksPerSample = layer.blocksPerSample();
|
||||
double zoom = layer.getZoom();
|
||||
try {
|
||||
data.add(layer.get(random, layerIndex + offset,
|
||||
(wx + offset) / blocksPerSample, offset, (wz - offset) / blocksPerSample, biomeRuntime.surfaceLayer(layerIndex)));
|
||||
(wx + offset) / zoom, offset, (wz - offset) / zoom, rdata));
|
||||
} catch (Throwable error) {
|
||||
GenerationFailures.skipPlacement(error, "surface layer", "block", (int) wx, height - depth, (int) wz, biome.getLoadKey());
|
||||
}
|
||||
@@ -278,7 +274,7 @@ final class IrisBiomeLayerGenerator {
|
||||
: complex.getSlopeStream().getDouble(x, z);
|
||||
}
|
||||
|
||||
static KList<NativeBlockState> generateSeaLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepth, PackRuntime runtime) {
|
||||
static KList<NativeBlockState> generateSeaLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepth, IrisData rdata) {
|
||||
KList<NativeBlockState> data = new KList<>();
|
||||
|
||||
KList<IrisBiomePaletteLayer> seaLayers = biome.getSeaLayers();
|
||||
@@ -288,8 +284,7 @@ final class IrisBiomeLayerGenerator {
|
||||
return data;
|
||||
}
|
||||
|
||||
BiomeRuntime biomeRuntime = runtime.biome(biome);
|
||||
KList<CNG> heightGenerators = biomeRuntime.seaLayerHeights(random.getSeed());
|
||||
KList<CNG> heightGenerators = getLayerSeaHeightGenerators(biome, random, rdata);
|
||||
|
||||
for (int i = 0; i < layerCount; i++) {
|
||||
IrisBiomePaletteLayer layer = seaLayers.get(i);
|
||||
@@ -301,7 +296,7 @@ final class IrisBiomeLayerGenerator {
|
||||
continue;
|
||||
}
|
||||
|
||||
appendLayer(data, layer, biomeRuntime.seaLayer(i), i, d, wx, wz, random, maxDepth);
|
||||
appendLayer(data, layer, i, d, wx, wz, random, maxDepth, rdata);
|
||||
|
||||
if (data.size() >= maxDepth) {
|
||||
break;
|
||||
@@ -311,51 +306,46 @@ final class IrisBiomeLayerGenerator {
|
||||
return data;
|
||||
}
|
||||
|
||||
static KList<CNG> getLayerHeightGenerators(IrisBiome biome, RNG rng, PackRuntime runtime) {
|
||||
return runtime.biome(biome).layerHeights(rng.getSeed());
|
||||
static KList<CNG> getLayerHeightGenerators(IrisBiome biome, RNG rng, IrisData rdata) {
|
||||
return getHeightGenerators(biome.getLayerHeightGenerators(), biome.getLayers(), 7235, rng, rdata);
|
||||
}
|
||||
|
||||
static KList<CNG> getLayerSeaHeightGenerators(IrisBiome biome, RNG rng, PackRuntime runtime) {
|
||||
return runtime.biome(biome).seaLayerHeights(rng.getSeed());
|
||||
static KList<CNG> getLayerSeaHeightGenerators(IrisBiome biome, RNG rng, IrisData data) {
|
||||
return getHeightGenerators(biome.getLayerSeaHeightGenerators(), biome.getSeaLayers(), 7735, rng, data);
|
||||
}
|
||||
|
||||
static KList<CNG> getCaveCeilingLayerHeightGenerators(IrisBiome biome, RNG rng, PackRuntime runtime) {
|
||||
return runtime.biome(biome).ceilingLayerHeights(rng.getSeed());
|
||||
static KList<CNG> getCaveCeilingLayerHeightGenerators(IrisBiome biome, RNG rng, IrisData data) {
|
||||
return getHeightGenerators(biome.getLayerCeilingHeightGenerators(), biome.getCaveCeilingLayers(), 7235, rng, data);
|
||||
}
|
||||
|
||||
static KList<CNG> createHeightGenerators(KList<IrisBiomePaletteLayer> layers, int seedOffset, long seed,
|
||||
PackRuntime runtime) {
|
||||
RNG rng = new RNG(seed);
|
||||
KList<CNG> result = new KList<>();
|
||||
int offset = seedOffset;
|
||||
for (IrisBiomePaletteLayer layer : layers) {
|
||||
result.add(layer.getHeightGenerator(rng.nextParallelRNG((offset++) * offset * offset * offset), runtime));
|
||||
}
|
||||
return result;
|
||||
private static KList<CNG> getHeightGenerators(IrisBiomeLayerHeightCache cache,
|
||||
KList<IrisBiomePaletteLayer> layers,
|
||||
int seedOffset, RNG rng, IrisData data) {
|
||||
return cache.get(layers, seedOffset, rng, data);
|
||||
}
|
||||
|
||||
private static void appendLayer(KList<NativeBlockState> blocks, IrisBiomePaletteLayer layer,
|
||||
PaletteLayerRuntime layerRuntime, int layerIndex, int thickness, double x, double z,
|
||||
RNG random, int maxDepth) {
|
||||
double blocksPerSample = layer.blocksPerSample();
|
||||
int layerIndex, int thickness, double x, double z,
|
||||
RNG random, int maxDepth, IrisData data) {
|
||||
double zoom = layer.getZoom();
|
||||
for (int offset = 0; offset < thickness && blocks.size() < maxDepth; offset++) {
|
||||
try {
|
||||
blocks.add(layer.get(random, layerIndex + offset,
|
||||
(x + offset) / blocksPerSample, offset, (z - offset) / blocksPerSample, layerRuntime));
|
||||
(x + offset) / zoom, offset, (z - offset) / zoom, data));
|
||||
} catch (Throwable error) {
|
||||
GenerationFailures.skipPlacement(error, "surface layer", "block", (int) x, -1, (int) z, "none");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static NativeBlockState getSurfaceBlock(IrisBiome biome, int x, int z, RNG rng, PackRuntime runtime) {
|
||||
static NativeBlockState getSurfaceBlock(IrisBiome biome, int x, int z, RNG rng, IrisData idm) {
|
||||
KList<IrisBiomePaletteLayer> layers = biome.getLayers();
|
||||
|
||||
if (layers.isEmpty()) {
|
||||
return B.getState("AIR");
|
||||
}
|
||||
|
||||
return layers.get(0).get(rng, x, 0, z, runtime);
|
||||
return layers.get(0).get(rng, x, 0, z, idm);
|
||||
}
|
||||
|
||||
static int getMaxHeight(IrisBiome biome, Engine engine) {
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package art.arcane.iris.generation.biome;
|
||||
|
||||
import art.arcane.iris.generation.cache.LazyBoundedCache;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import art.arcane.volmlib.util.noise.CNG;
|
||||
|
||||
final class IrisBiomeLayerHeightCache {
|
||||
private final LazyBoundedCache<GeneratorKey, KList<CNG>> generators = new LazyBoundedCache<>(32);
|
||||
private volatile CachedGenerators recent;
|
||||
|
||||
KList<CNG> get(KList<IrisBiomePaletteLayer> layers, int seedOffset, RNG rng, IrisData data) {
|
||||
Engine engine = data == null ? null : data.getEngine();
|
||||
long seed = rng.getSeed();
|
||||
CachedGenerators cached = recent;
|
||||
if (cached != null && cached.key.matches(data, engine, seed)) {
|
||||
return cached.generators;
|
||||
}
|
||||
|
||||
GeneratorKey key = new GeneratorKey(data, engine, seed);
|
||||
KList<CNG> result = generators.computeIfAbsent(key, ignored -> create(layers, seedOffset, rng, data));
|
||||
recent = new CachedGenerators(key, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static KList<CNG> create(KList<IrisBiomePaletteLayer> layers, int seedOffset, RNG rng, IrisData data) {
|
||||
KList<CNG> result = new KList<>();
|
||||
int offset = seedOffset;
|
||||
for (IrisBiomePaletteLayer layer : layers) {
|
||||
result.add(layer.getHeightGenerator(rng.nextParallelRNG((offset++) * offset * offset * offset), data));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private record CachedGenerators(GeneratorKey key, KList<CNG> generators) {
|
||||
}
|
||||
|
||||
private static final class GeneratorKey {
|
||||
private final IrisData data;
|
||||
private final Engine engine;
|
||||
private final long seed;
|
||||
|
||||
private GeneratorKey(IrisData data, Engine engine, long seed) {
|
||||
this.data = data;
|
||||
this.engine = engine;
|
||||
this.seed = seed;
|
||||
}
|
||||
|
||||
private boolean matches(IrisData data, Engine engine, long seed) {
|
||||
return this.data == data && this.engine == engine && this.seed == seed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object object) {
|
||||
return this == object || object instanceof GeneratorKey other
|
||||
&& matches(other.data, other.engine, other.seed);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = System.identityHashCode(data);
|
||||
result = 31 * result + System.identityHashCode(engine);
|
||||
return 31 * result + Long.hashCode(seed);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,7 @@ import art.arcane.iris.generation.decoration.IrisOreGenerator;
|
||||
import art.arcane.iris.generation.decoration.IrisOreBands;
|
||||
import art.arcane.iris.generation.decoration.IrisProceduralBlocks;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.volmlib.util.cache.AtomicCache;
|
||||
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
|
||||
import art.arcane.iris.generation.block.B;
|
||||
@@ -39,17 +39,17 @@ final class IrisBiomeOres {
|
||||
private IrisBiomeOres() {
|
||||
}
|
||||
|
||||
static NativeBlockState generateOres(IrisBiome biome, int x, int y, int z, RNG rng, PackRuntime runtime, boolean surface) {
|
||||
static NativeBlockState generateOres(IrisBiome biome, int x, int y, int z, RNG rng, IrisData data, boolean surface) {
|
||||
KList<IrisOreGenerator> localOres = surface ? getSurfaceOres(biome) : getUndergroundOres(biome);
|
||||
return generateOres(localOres, x, y, z, rng, runtime);
|
||||
return generateOres(localOres, x, y, z, rng, data);
|
||||
}
|
||||
|
||||
static NativeBlockState generateSurfaceOres(IrisBiome biome, int x, int y, int z, RNG rng, PackRuntime runtime) {
|
||||
return generateOres(getSurfaceOres(biome), x, y, z, rng, runtime);
|
||||
static NativeBlockState generateSurfaceOres(IrisBiome biome, int x, int y, int z, RNG rng, IrisData data) {
|
||||
return generateOres(getSurfaceOres(biome), x, y, z, rng, data);
|
||||
}
|
||||
|
||||
static NativeBlockState generateUndergroundOres(IrisBiome biome, int x, int y, int z, RNG rng, PackRuntime runtime) {
|
||||
return generateOres(getUndergroundOres(biome), x, y, z, rng, runtime);
|
||||
static NativeBlockState generateUndergroundOres(IrisBiome biome, int x, int y, int z, RNG rng, IrisData data) {
|
||||
return generateOres(getUndergroundOres(biome), x, y, z, rng, data);
|
||||
}
|
||||
|
||||
static boolean hasSurfaceOres(IrisBiome biome) {
|
||||
@@ -122,7 +122,7 @@ final class IrisBiomeOres {
|
||||
});
|
||||
}
|
||||
|
||||
private static NativeBlockState generateOres(KList<IrisOreGenerator> localOres, int x, int y, int z, RNG rng, PackRuntime runtime) {
|
||||
private static NativeBlockState generateOres(KList<IrisOreGenerator> localOres, int x, int y, int z, RNG rng, IrisData data) {
|
||||
if (localOres.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
@@ -130,7 +130,7 @@ final class IrisBiomeOres {
|
||||
int oreCount = localOres.size();
|
||||
for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) {
|
||||
IrisOreGenerator oreGenerator = localOres.get(oreIndex);
|
||||
NativeBlockState ore = oreGenerator.generate(x, y, z, rng, runtime);
|
||||
NativeBlockState ore = oreGenerator.generate(x, y, z, rng, data);
|
||||
if (ore != null) {
|
||||
return ore;
|
||||
}
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
|
||||
package art.arcane.iris.generation.biome;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.block.IrisBlockData;
|
||||
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
|
||||
import art.arcane.iris.generation.noise.NoiseStyle;
|
||||
@@ -26,6 +25,8 @@ import art.arcane.iris.generation.terrain.IrisSlopeClip;
|
||||
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.volmlib.util.cache.AtomicCache;
|
||||
import art.arcane.iris.generation.cache.LazyBoundedCache;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.pack.schema.annotation.ArrayType;
|
||||
import art.arcane.iris.pack.schema.annotation.DependsOn;
|
||||
import art.arcane.volmlib.util.documentation.Description;
|
||||
@@ -36,12 +37,17 @@ import art.arcane.iris.pack.schema.annotation.Snippet;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import art.arcane.volmlib.util.noise.CNG;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
|
||||
import lombok.Setter;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.concurrent.atomic.AtomicReferenceArray;
|
||||
|
||||
@Snippet("biome-palette")
|
||||
@Accessors(chain = true)
|
||||
@@ -50,7 +56,24 @@ import lombok.experimental.Accessors;
|
||||
@Description("A layer of surface / subsurface material in biomes")
|
||||
@Data
|
||||
public class IrisBiomePaletteLayer {
|
||||
private static final int LAYER_GENERATOR_CACHE_SIZE = 32;
|
||||
|
||||
private final transient AtomicCache<KList<NativeBlockState>> blockData = new AtomicCache<>();
|
||||
@Getter(AccessLevel.NONE)
|
||||
@Setter(AccessLevel.NONE)
|
||||
private final transient LazyBoundedCache<LayerGeneratorKey, CNG> layerGenerators =
|
||||
new LazyBoundedCache<>(LAYER_GENERATOR_CACHE_SIZE);
|
||||
@Getter(AccessLevel.NONE)
|
||||
@Setter(AccessLevel.NONE)
|
||||
private final transient AtomicReferenceArray<CachedLayerGenerator> recentLayerGenerators =
|
||||
new AtomicReferenceArray<>(LAYER_GENERATOR_CACHE_SIZE);
|
||||
@Getter(AccessLevel.NONE)
|
||||
@Setter(AccessLevel.NONE)
|
||||
private final transient LazyBoundedCache<LayerGeneratorKey, CNG> heightGenerators =
|
||||
new LazyBoundedCache<>(LAYER_GENERATOR_CACHE_SIZE);
|
||||
@Getter(AccessLevel.NONE)
|
||||
@Setter(AccessLevel.NONE)
|
||||
private final transient AtomicReference<CachedLayerGenerator> recentHeightGenerator = new AtomicReference<>();
|
||||
@Description("The style of noise")
|
||||
private IrisGeneratorStyle style = NoiseStyle.STATIC.style();
|
||||
@DependsOn({"minHeight", "maxHeight"})
|
||||
@@ -75,17 +98,23 @@ public class IrisBiomePaletteLayer {
|
||||
@Description("The palette of blocks to be used in this layer")
|
||||
private KList<IrisBlockData> palette = new KList<IrisBlockData>().qadd(new IrisBlockData("GRASS_BLOCK"));
|
||||
|
||||
public CNG getHeightGenerator(RNG rng, PackRuntime runtime) {
|
||||
long generatorSeed = rng.getSeed() + minHeight * maxHeight + getBlockData(runtime.data()).size();
|
||||
return runtime.paletteLayer(this).heightGenerator(generatorSeed);
|
||||
public CNG getHeightGenerator(RNG rng, IrisData data) {
|
||||
Engine engine = data == null ? null : data.getEngine();
|
||||
long generatorSeed = rng.getSeed() + minHeight * maxHeight + getBlockData(data).size();
|
||||
CachedLayerGenerator recent = recentHeightGenerator.get();
|
||||
if (recent != null && recent.key.matches(data, engine, generatorSeed)) {
|
||||
return recent.generator;
|
||||
}
|
||||
|
||||
LayerGeneratorKey key = new LayerGeneratorKey(data, engine, generatorSeed);
|
||||
CNG generator = heightGenerators.computeIfAbsent(key,
|
||||
ignored -> CNG.signature(new RNG(generatorSeed)));
|
||||
recentHeightGenerator.set(new CachedLayerGenerator(key, generator));
|
||||
return generator;
|
||||
}
|
||||
|
||||
static CNG createHeightGenerator(long generatorSeed) {
|
||||
return CNG.signature(new RNG(generatorSeed));
|
||||
}
|
||||
|
||||
public NativeBlockState get(RNG rng, double x, double y, double z, PackRuntime runtime) {
|
||||
return get(rng, 0, x, y, z, runtime);
|
||||
public NativeBlockState get(RNG rng, double x, double y, double z, IrisData data) {
|
||||
return get(rng, 0, x, y, z, data);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -93,53 +122,44 @@ public class IrisBiomePaletteLayer {
|
||||
* only built inside the lazy layer generator initializer, using the exact same seed derivation
|
||||
* as {@code parent.nextParallelRNG(signature)} followed by the generator signature.
|
||||
*/
|
||||
public NativeBlockState get(RNG parent, int signature, double x, double y, double z, PackRuntime runtime) {
|
||||
KList<NativeBlockState> localBlockData = getBlockData(runtime.data());
|
||||
if (localBlockData.size() <= 1) {
|
||||
return localBlockData.isEmpty() ? null : localBlockData.get(0);
|
||||
}
|
||||
return fit(localBlockData, runtime.paletteLayer(this), parent, signature, x, y, z);
|
||||
}
|
||||
public NativeBlockState get(RNG parent, int signature, double x, double y, double z, IrisData data) {
|
||||
KList<NativeBlockState> localBlockData = getBlockData(data);
|
||||
|
||||
/** {@link #get(RNG, int, double, double, double, PackRuntime)} for a caller that already holds this layer's runtime. */
|
||||
public NativeBlockState get(RNG parent, int signature, double x, double y, double z, PaletteLayerRuntime layerRuntime) {
|
||||
KList<NativeBlockState> localBlockData = getBlockData(layerRuntime.packRuntime().data());
|
||||
if (localBlockData.size() <= 1) {
|
||||
return localBlockData.isEmpty() ? null : localBlockData.get(0);
|
||||
if (localBlockData.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return fit(localBlockData, layerRuntime, parent, signature, x, y, z);
|
||||
}
|
||||
|
||||
private NativeBlockState fit(KList<NativeBlockState> localBlockData, PaletteLayerRuntime layerRuntime,
|
||||
RNG parent, int signature, double x, double y, double z) {
|
||||
CNG generator = layerRuntime.layerGenerator(layerGeneratorSeed(parent, signature, localBlockData.size()));
|
||||
if (style.isSeeded()) {
|
||||
return generator.fit(localBlockData, x, z);
|
||||
if (localBlockData.size() == 1) {
|
||||
return localBlockData.get(0);
|
||||
}
|
||||
|
||||
double localZoom = zoom;
|
||||
return generator.fit(localBlockData, x / localZoom, y / localZoom, z / localZoom);
|
||||
double scaledX = x / localZoom;
|
||||
double scaledY = y / localZoom;
|
||||
double scaledZ = z / localZoom;
|
||||
return getLayerGenerator(parent, signature, data).fit(localBlockData, scaledX, scaledY, scaledZ);
|
||||
}
|
||||
|
||||
/** How many blocks one step of the layer's block noise spans: its zoom, or 1 for a seeded style, which is read flat. */
|
||||
public double blocksPerSample() {
|
||||
return style.isSeeded() ? 1 : zoom;
|
||||
public CNG getLayerGenerator(RNG rng, IrisData data) {
|
||||
return getLayerGenerator(rng, 0, data);
|
||||
}
|
||||
|
||||
public CNG getLayerGenerator(RNG rng, PackRuntime runtime) {
|
||||
return getLayerGenerator(rng, 0, runtime);
|
||||
}
|
||||
public CNG getLayerGenerator(RNG parent, int signature, IrisData data) {
|
||||
Engine engine = data == null ? null : data.getEngine();
|
||||
long generatorSeed = parent.getSeed() + signature + minHeight + maxHeight + getBlockData(data).size();
|
||||
int slot = (int) generatorSeed & (LAYER_GENERATOR_CACHE_SIZE - 1);
|
||||
CachedLayerGenerator recent = recentLayerGenerators.getAcquire(slot);
|
||||
if (recent != null && recent.key.matches(data, engine, generatorSeed)) {
|
||||
return recent.generator;
|
||||
}
|
||||
|
||||
public CNG getLayerGenerator(RNG parent, int signature, PackRuntime runtime) {
|
||||
long generatorSeed = layerGeneratorSeed(parent, signature, getBlockData(runtime.data()).size());
|
||||
return runtime.paletteLayer(this).layerGenerator(generatorSeed);
|
||||
}
|
||||
|
||||
private long layerGeneratorSeed(RNG parent, int signature, int blockCount) {
|
||||
return parent.getSeed() + signature + minHeight + maxHeight + blockCount;
|
||||
}
|
||||
|
||||
CNG createLayerGenerator(long generatorSeed, PackRuntime runtime) {
|
||||
return style.createNoCache(new RNG(generatorSeed), runtime);
|
||||
LayerGeneratorKey key = new LayerGeneratorKey(data, engine, generatorSeed);
|
||||
CNG generator = layerGenerators.computeIfAbsent(key,
|
||||
ignored -> style.create(new RNG(generatorSeed), data, engine));
|
||||
if (generator != null) {
|
||||
recentLayerGenerators.setRelease(slot, new CachedLayerGenerator(key, generator));
|
||||
}
|
||||
return generator;
|
||||
}
|
||||
|
||||
public KList<IrisBlockData> add(String b) {
|
||||
@@ -175,4 +195,49 @@ public class IrisBiomePaletteLayer {
|
||||
palette.clear();
|
||||
return this;
|
||||
}
|
||||
|
||||
private static final class LayerGeneratorKey {
|
||||
private final IrisData data;
|
||||
private final Engine engine;
|
||||
private final long seed;
|
||||
|
||||
private LayerGeneratorKey(IrisData data, Engine engine, long seed) {
|
||||
this.data = data;
|
||||
this.engine = engine;
|
||||
this.seed = seed;
|
||||
}
|
||||
|
||||
private boolean matches(IrisData data, Engine engine, long seed) {
|
||||
return this.data == data && this.engine == engine && this.seed == seed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object object) {
|
||||
if (this == object) {
|
||||
return true;
|
||||
}
|
||||
if (!(object instanceof LayerGeneratorKey other)) {
|
||||
return false;
|
||||
}
|
||||
return data == other.data && engine == other.engine && seed == other.seed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = System.identityHashCode(data);
|
||||
result = 31 * result + System.identityHashCode(engine);
|
||||
result = 31 * result + Long.hashCode(seed);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class CachedLayerGenerator {
|
||||
private final LayerGeneratorKey key;
|
||||
private final CNG generator;
|
||||
|
||||
private CachedLayerGenerator(LayerGeneratorKey key, CNG generator) {
|
||||
this.key = key;
|
||||
this.generator = generator;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,13 +18,8 @@
|
||||
|
||||
package art.arcane.iris.generation.biome;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.cave.IrisCaveProfileSampler;
|
||||
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
|
||||
import art.arcane.iris.generation.noise.NoiseStyle;
|
||||
import art.arcane.iris.generation.terrain.IrisDimension;
|
||||
import art.arcane.iris.generation.terrain.IrisDimensionCarvingEntry;
|
||||
import art.arcane.iris.generation.terrain.IrisDimensionCarvingResolver;
|
||||
import art.arcane.iris.pack.validation.CompatPools;
|
||||
import art.arcane.iris.pack.value.OverrideMode;
|
||||
import art.arcane.iris.structure.object.IrisObjectPlacement;
|
||||
@@ -34,6 +29,10 @@ import art.arcane.volmlib.util.math.Rarity;
|
||||
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.volmlib.util.cache.AtomicCache;
|
||||
import art.arcane.iris.generation.cache.LazyBoundedCache;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.pack.schema.annotation.ArrayType;
|
||||
import art.arcane.volmlib.util.documentation.Description;
|
||||
@@ -59,96 +58,69 @@ import lombok.experimental.Accessors;
|
||||
@Data
|
||||
public class IrisFloatingChildBiomes implements Rarity {
|
||||
private final transient AtomicCache<IrisBiome> resolvedBiome = new AtomicCache<>();
|
||||
@Getter(AccessLevel.NONE)
|
||||
@Setter(AccessLevel.NONE)
|
||||
private final transient LazyBoundedCache<RuntimeKey, FloatingIslandEdgeProfile> edgeTaperProfiles = new LazyBoundedCache<>(8);
|
||||
@Getter(AccessLevel.NONE)
|
||||
@Setter(AccessLevel.NONE)
|
||||
private transient volatile CachedEdgeProfile recentEdgeProfile;
|
||||
private final transient AtomicCache<IrisObjectScale> shrinkScaleCache = new AtomicCache<>();
|
||||
|
||||
public CNG getFootprintCng(long baseSeed, PackRuntime runtime) {
|
||||
return getFootprintStyle().create(baseSeed ^ 0xF007B17DL, runtime);
|
||||
public CNG getFootprintCng(long baseSeed, IrisData data) {
|
||||
return getFootprintStyle().create(baseSeed ^ 0xF007B17DL, data);
|
||||
}
|
||||
|
||||
public FloatingIslandEdgeProfile getEdgeTaperProfile(long baseSeed, PackRuntime runtime) {
|
||||
return runtime.floatingChild(this).edgeTaperProfile(baseSeed);
|
||||
public FloatingIslandEdgeProfile getEdgeTaperProfile(long baseSeed, IrisData data) {
|
||||
Engine engine = data == null ? null : data.getEngine();
|
||||
CachedEdgeProfile recent = recentEdgeProfile;
|
||||
if (recent != null && recent.key.matches(baseSeed, data, engine)) {
|
||||
return recent.profile;
|
||||
}
|
||||
RuntimeKey key = new RuntimeKey(baseSeed, data, engine);
|
||||
FloatingIslandEdgeProfile profile = edgeTaperProfiles.computeIfAbsent(key, ignored -> {
|
||||
int width = FloatingIslandEdgeProfile.clampWidth(getEdgeTaperWidth());
|
||||
double amplitude = FloatingIslandEdgeProfile.clampVariationAmplitude(
|
||||
getEdgeTaperVariationAmplitude(), width);
|
||||
IrisGeneratorStyle style = getEdgeTaperVariationStyle();
|
||||
CNG variation = amplitude > 0.0D && style != null
|
||||
? style.create(baseSeed ^ 0xED6E7A9E5L, data)
|
||||
: null;
|
||||
return new FloatingIslandEdgeProfile(width, getEdgeTaperExponent(), amplitude, variation);
|
||||
});
|
||||
recentEdgeProfile = new CachedEdgeProfile(key, profile);
|
||||
return profile;
|
||||
}
|
||||
|
||||
FloatingIslandEdgeProfile createEdgeTaperProfile(long baseSeed, PackRuntime runtime) {
|
||||
int width = FloatingIslandEdgeProfile.clampWidth(getEdgeTaperWidth());
|
||||
double amplitude = FloatingIslandEdgeProfile.clampVariationAmplitude(getEdgeTaperVariationAmplitude(), width);
|
||||
IrisGeneratorStyle style = getEdgeTaperVariationStyle();
|
||||
CNG variation = amplitude > 0.0D && style != null
|
||||
? style.create(baseSeed ^ 0xED6E7A9E5L, runtime)
|
||||
: null;
|
||||
return new FloatingIslandEdgeProfile(width, getEdgeTaperExponent(), amplitude, variation);
|
||||
public CNG getPickerCng(long baseSeed, IrisData data) {
|
||||
return getPickerStyle().create(baseSeed ^ 0x91C4E72DL, data);
|
||||
}
|
||||
|
||||
public CNG getPickerCng(long baseSeed, PackRuntime runtime) {
|
||||
return getPickerStyle().create(baseSeed ^ 0x91C4E72DL, runtime);
|
||||
public CNG getAltitudeCng(long baseSeed, IrisData data) {
|
||||
return getAltitudeStyle().create(baseSeed ^ 0xA17DEBBL, data);
|
||||
}
|
||||
|
||||
public CNG getAltitudeCng(long baseSeed, PackRuntime runtime) {
|
||||
return getAltitudeStyle().create(baseSeed ^ 0xA17DEBBL, runtime);
|
||||
public CNG getTopShapeCng(long baseSeed, IrisData data) {
|
||||
return getTopShapeStyle().create(baseSeed ^ 0x70970601DEFL, data);
|
||||
}
|
||||
|
||||
public CNG getTopShapeCng(long baseSeed, PackRuntime runtime) {
|
||||
return getTopShapeStyle().create(baseSeed ^ 0x70970601DEFL, runtime);
|
||||
public CNG getBottomCng(long baseSeed, IrisData data) {
|
||||
return getBottomStyle().create(baseSeed ^ 0xB0770075CAFEL, data);
|
||||
}
|
||||
|
||||
public CNG getBottomCng(long baseSeed, PackRuntime runtime) {
|
||||
return getBottomStyle().create(baseSeed ^ 0xB0770075CAFEL, runtime);
|
||||
}
|
||||
|
||||
public CNG getWallWarpCng(long baseSeed, PackRuntime runtime) {
|
||||
public CNG getWallWarpCng(long baseSeed, IrisData data) {
|
||||
IrisGeneratorStyle style = getWallWarpStyle();
|
||||
if (style == null) {
|
||||
return null;
|
||||
}
|
||||
return style.create(baseSeed ^ 0xA117BA17E0FL, runtime);
|
||||
return style.create(baseSeed ^ 0xA117BA17E0FL, data);
|
||||
}
|
||||
|
||||
public CNG getCarveCng(long baseSeed, PackRuntime runtime) {
|
||||
public CNG getCarveCng(long baseSeed, IrisData data) {
|
||||
IrisGeneratorStyle style = getCarveStyle();
|
||||
if (style == null) {
|
||||
return null;
|
||||
}
|
||||
return style.create(baseSeed ^ 0xCA5EC1EE5EL, runtime);
|
||||
}
|
||||
|
||||
public IrisCaveProfileSampler getCarvingProfileSampler(PackRuntime runtime) {
|
||||
if (!hasCarvingReference()) {
|
||||
return null;
|
||||
}
|
||||
return runtime.floatingChild(this).carvingProfileSampler();
|
||||
}
|
||||
|
||||
IrisCaveProfileSampler createCarvingProfileSampler(PackRuntime runtime) {
|
||||
Engine engine = runtime.engine();
|
||||
IrisBiome resolved = resolveCarvingBiome(carving, engine, runtime.data());
|
||||
if (resolved == null || resolved.getCaveProfile() == null || !resolved.getCaveProfile().isEnabled()) {
|
||||
return null;
|
||||
}
|
||||
return new IrisCaveProfileSampler(engine, resolved.getCaveProfile());
|
||||
}
|
||||
|
||||
public boolean hasCarvingReference() {
|
||||
return carving != null && !carving.isBlank();
|
||||
}
|
||||
|
||||
static IrisBiome resolveCarvingBiome(String carving, Engine engine, IrisData data) {
|
||||
if (carving == null || carving.isBlank() || engine == null || data == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
IrisDimension dimension = engine.getDimension();
|
||||
if (dimension != null && dimension.getCarvingEntryIndex() != null) {
|
||||
IrisDimensionCarvingEntry entry = dimension.getCarvingEntryIndex().get(carving);
|
||||
if (entry != null) {
|
||||
return IrisDimensionCarvingResolver.resolveEntryBiome(engine, entry);
|
||||
}
|
||||
}
|
||||
|
||||
if (data.getBiomeLoader() == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return data.getBiomeLoader().load(carving);
|
||||
return style.create(baseSeed ^ 0xCA5EC1EE5EL, data);
|
||||
}
|
||||
|
||||
@RegistryListResource(IrisBiome.class)
|
||||
@@ -265,12 +237,9 @@ public class IrisFloatingChildBiomes implements Rarity {
|
||||
@Description("Optional 3D noise that swiss-cheeses the island interior by marking individual blocks as air when the noise exceeds carveThreshold. Leave null to keep the island solid. Good defaults: {\"style\":\"CELLULAR\",\"zoom\":0.3} for bubble pockets, {\"style\":\"VASCULAR\",\"zoom\":0.25} for wormy tunnels.")
|
||||
private IrisGeneratorStyle carveStyle = null;
|
||||
|
||||
@Description("Optional carving biome key or dimension carving entry id whose caveProfile drives floating-island internal air pockets. Dimension carving ids resolve first; biome keys such as carving/mushroom resolve second. When set, this overrides carveStyle while carveThreshold remains a final tuning bias.")
|
||||
private String carving = "";
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(1)
|
||||
@Description("Threshold (0..1) above which carveStyle noise carves air pockets. 1.0 = no direct-noise carving. 0.75 = sparse pockets. 0.55 = heavy swiss-cheese. 0.4 = shredded lattice. When carving is set, lower values add a final positive threshold bias to the referenced caveProfile.")
|
||||
@Description("Threshold (0..1) above which carveStyle noise carves air pockets. 1.0 = no direct-noise carving. 0.75 = sparse pockets. 0.55 = heavy swiss-cheese. 0.4 = shredded lattice.")
|
||||
private double carveThreshold = 1.0;
|
||||
|
||||
@Description("Optional water surface height above the island base, in blocks. null = no internal water. Positive = water fills any dip in the top profile up to baseY + localFluidHeight (forms lakes/ponds in concavities of the biome-top heightmap).")
|
||||
@@ -372,4 +341,25 @@ public class IrisFloatingChildBiomes implements Rarity {
|
||||
return loaded;
|
||||
});
|
||||
}
|
||||
|
||||
private record RuntimeKey(long seed, IrisData data, Engine engine) {
|
||||
private boolean matches(long seed, IrisData data, Engine engine) {
|
||||
return this.seed == seed && this.data == data && this.engine == engine;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object object) {
|
||||
return object instanceof RuntimeKey other && matches(other.seed, other.data, other.engine);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int hash = Long.hashCode(seed);
|
||||
hash = 31 * hash + System.identityHashCode(data);
|
||||
return 31 * hash + System.identityHashCode(engine);
|
||||
}
|
||||
}
|
||||
|
||||
private record CachedEdgeProfile(RuntimeKey key, FloatingIslandEdgeProfile profile) {
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.generation.biome;
|
||||
|
||||
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.runtime.SeedTable;
|
||||
import art.arcane.volmlib.util.noise.CNG;
|
||||
|
||||
/**
|
||||
* What one engine derives from an {@link IrisBiomePaletteLayer}: the block selection and depth generators of the
|
||||
* seeds that sample it. A column walk asks for one layer seed per depth, so the layer table holds the layer's whole
|
||||
* thickness for a few parent seeds instead of rebuilding a generator on every depth step.
|
||||
*/
|
||||
public final class PaletteLayerRuntime {
|
||||
private static final int LAYER_SEED_CAPACITY = 32;
|
||||
private static final int LAYER_RECENT_SLOTS = 32;
|
||||
private static final int MAX_LAYER_RECENT_SLOTS = 4096;
|
||||
private static final int PARENT_SEEDS_PER_LAYER = 4;
|
||||
private static final int HEIGHT_SEED_CAPACITY = 32;
|
||||
|
||||
private final PackRuntime runtime;
|
||||
private final SeedTable<CNG> layerGenerators;
|
||||
private final SeedTable<CNG> heightGenerators;
|
||||
private final boolean shareGenerator;
|
||||
|
||||
public PaletteLayerRuntime(IrisBiomePaletteLayer layer, PackRuntime runtime) {
|
||||
this.runtime = runtime;
|
||||
IrisGeneratorStyle style = layer.getStyle();
|
||||
// A seeded style rolls from its own seed and the world seed, never the caller's, so every depth builds the same noise.
|
||||
this.shareGenerator = style != null
|
||||
&& (style.isSeeded() || style.canShareExpressionGenerator(runtime.data()));
|
||||
int depthSeeds = Math.max(1, Math.max(layer.getMinHeight(), layer.getMaxHeight()));
|
||||
this.layerGenerators = new SeedTable<>(Math.max(LAYER_SEED_CAPACITY, depthSeeds * PARENT_SEEDS_PER_LAYER),
|
||||
recentSlots(depthSeeds), seed -> layer.createLayerGenerator(seed, runtime));
|
||||
this.heightGenerators = new SeedTable<>(HEIGHT_SEED_CAPACITY, IrisBiomePaletteLayer::createHeightGenerator);
|
||||
}
|
||||
|
||||
/** The scope this runtime was built in, whose pack data resolves the layer's palette. */
|
||||
public PackRuntime packRuntime() {
|
||||
return runtime;
|
||||
}
|
||||
|
||||
public CNG layerGenerator(long seed) {
|
||||
return layerGenerators.get(shareGenerator ? 0L : seed);
|
||||
}
|
||||
|
||||
public CNG heightGenerator(long seed) {
|
||||
return heightGenerators.get(seed);
|
||||
}
|
||||
|
||||
/** Consecutive depth seeds land in distinct slots when the slot count covers the thickness. */
|
||||
private static int recentSlots(int depthSeeds) {
|
||||
int covering = Integer.highestOneBit(Math.min(depthSeeds, MAX_LAYER_RECENT_SLOTS) - 1) << 1;
|
||||
return Math.clamp(covering, LAYER_RECENT_SLOTS, MAX_LAYER_RECENT_SLOTS);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package art.arcane.iris.generation.cache;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
|
||||
public final class LazyBoundedCache<K, V> {
|
||||
private final int maximumSize;
|
||||
private transient LinkedHashMap<K, V> entries;
|
||||
|
||||
public LazyBoundedCache(int maximumSize) {
|
||||
if (maximumSize <= 0) {
|
||||
throw new IllegalArgumentException("Maximum cache size must be positive");
|
||||
}
|
||||
this.maximumSize = maximumSize;
|
||||
}
|
||||
|
||||
public synchronized V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
|
||||
K requiredKey = Objects.requireNonNull(key, "Cache key");
|
||||
Function<? super K, ? extends V> requiredMapping = Objects.requireNonNull(mappingFunction, "Cache mapping function");
|
||||
if (entries != null) {
|
||||
V cached = entries.get(requiredKey);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
|
||||
V computed = requiredMapping.apply(requiredKey);
|
||||
if (computed == null) {
|
||||
return null;
|
||||
}
|
||||
if (entries == null) {
|
||||
entries = new LinkedHashMap<>(maximumSize, 1F, true);
|
||||
}
|
||||
entries.put(requiredKey, computed);
|
||||
if (entries.size() > maximumSize) {
|
||||
entries.sequencedKeySet().removeFirst();
|
||||
}
|
||||
return computed;
|
||||
}
|
||||
|
||||
synchronized boolean isInitialized() {
|
||||
return entries != null;
|
||||
}
|
||||
|
||||
synchronized int size() {
|
||||
return entries == null ? 0 : entries.size();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.generation.cave;
|
||||
|
||||
import art.arcane.iris.pack.schema.annotation.MaxNumber;
|
||||
import art.arcane.iris.pack.schema.annotation.MinNumber;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The numbers a cave file writes outside what their keys allow, read from the {@link MinNumber} and {@link MaxNumber} of
|
||||
* each key and reported by their place in the file. A {@link CaveValue} is not a plain number, so the schema cannot
|
||||
* bound its ends: this does. It reads the file as written, so a style that names a snippet needs no resolving.
|
||||
*/
|
||||
public final class CaveBounds {
|
||||
private static final String CAVE_PACKAGE = IrisCave.class.getPackageName();
|
||||
private static final String MIN = "min";
|
||||
private static final String MAX = "max";
|
||||
private static final String COVERAGE_SHARE = "share";
|
||||
|
||||
private CaveBounds() {
|
||||
}
|
||||
|
||||
/** Each number of the cave file outside what its key allows, such as {@code fade is 200; it must be at most 128}. */
|
||||
public static List<String> valuesOutOfBounds(JsonObject cave) {
|
||||
List<String> problems = new ArrayList<>();
|
||||
collect(IrisCave.class, cave, "", problems);
|
||||
return problems;
|
||||
}
|
||||
|
||||
private static void collect(Class<?> type, JsonObject written, String path, List<String> problems) {
|
||||
for (Map.Entry<String, JsonElement> member : written.entrySet()) {
|
||||
Field field = declaredField(type, member.getKey());
|
||||
if (field != null) {
|
||||
collectMember(field, member.getValue(), path.isEmpty() ? member.getKey() : path + "." + member.getKey(), problems);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void collectMember(Field field, JsonElement value, String path, List<String> problems) {
|
||||
Class<?> type = field.getType();
|
||||
if (type == CaveValue.class) {
|
||||
collectValue(field, value, path, problems);
|
||||
} else if (type == CaveTunnelCoverage.class && value.isJsonPrimitive()) {
|
||||
collectValue(declaredField(CaveTunnelCoverage.class, COVERAGE_SHARE), value, path + "." + COVERAGE_SHARE, problems);
|
||||
} else if (value.isJsonObject() && type.getPackageName().equals(CAVE_PACKAGE)) {
|
||||
collect(type, value.getAsJsonObject(), path, problems);
|
||||
} else if (isNumber(value)) {
|
||||
requireWithin(field, value.getAsDouble(), path, problems);
|
||||
}
|
||||
}
|
||||
|
||||
private static void collectValue(Field field, JsonElement value, String path, List<String> problems) {
|
||||
if (isNumber(value)) {
|
||||
requireWithin(field, value.getAsDouble(), path, problems);
|
||||
return;
|
||||
}
|
||||
if (!value.isJsonObject() || !isNumber(value.getAsJsonObject().get(MIN)) || !isNumber(value.getAsJsonObject().get(MAX))) {
|
||||
return;
|
||||
}
|
||||
double min = value.getAsJsonObject().get(MIN).getAsDouble();
|
||||
double max = value.getAsJsonObject().get(MAX).getAsDouble();
|
||||
if (min == max) {
|
||||
requireWithin(field, min, path, problems);
|
||||
return;
|
||||
}
|
||||
requireWithin(field, min, path + "." + MIN, problems);
|
||||
requireWithin(field, max, path + "." + MAX, problems);
|
||||
}
|
||||
|
||||
private static boolean isNumber(JsonElement element) {
|
||||
return element != null && element.isJsonPrimitive() && element.getAsJsonPrimitive().isNumber();
|
||||
}
|
||||
|
||||
private static Field declaredField(Class<?> type, String name) {
|
||||
try {
|
||||
return type.getDeclaredField(name);
|
||||
} catch (NoSuchFieldException unknown) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireWithin(Field field, double value, String path, List<String> problems) {
|
||||
MinNumber least = field.getAnnotation(MinNumber.class);
|
||||
MaxNumber most = field.getAnnotation(MaxNumber.class);
|
||||
if (least != null && value < least.value()) {
|
||||
problems.add(path + " is " + shortNumber(value) + "; it must be at least " + shortNumber(least.value()));
|
||||
} else if (most != null && value > most.value()) {
|
||||
problems.add(path + " is " + shortNumber(value) + "; it must be at most " + shortNumber(most.value()));
|
||||
}
|
||||
}
|
||||
|
||||
private static String shortNumber(double value) {
|
||||
return value == Math.rint(value) ? Long.toString((long) value) : Double.toString(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.generation.cave;
|
||||
|
||||
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
|
||||
import art.arcane.iris.pack.schema.annotation.MaxNumber;
|
||||
import art.arcane.iris.pack.schema.annotation.MinNumber;
|
||||
import art.arcane.volmlib.util.documentation.Description;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/** The caverns of a {@link IrisCave}: large open rooms, with pillars left standing in them where the cave asks for some. */
|
||||
@Description("Large open rooms.")
|
||||
public final class CaveCavern {
|
||||
/** Without a style, a value of the caverns or their pillars changes over this many room sizes. */
|
||||
public static final int VALUE_CHANGE_SIZES = 4;
|
||||
|
||||
@MinNumber(16)
|
||||
@MaxNumber(512)
|
||||
@Description("Rough span of a room in blocks, 16 to 512. A range changes over about " + VALUE_CHANGE_SIZES + " room sizes.")
|
||||
private CaveValue size = CaveValue.of(56);
|
||||
|
||||
@MinNumber(8)
|
||||
@MaxNumber(256)
|
||||
@Description("Rough height of a room in blocks, 8 to 256. A range changes over about " + VALUE_CHANGE_SIZES + " room sizes.")
|
||||
private CaveValue height = CaveValue.of(22);
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(0.6)
|
||||
@Description("Share of the underground that is cavern, 0 to 0.6. 0.1 gives scattered rooms, 0.3 joins them into halls. A range changes over about "
|
||||
+ VALUE_CHANGE_SIZES + " room sizes; a min of 0 leaves areas without rooms. A range in size, height or roughness makes the share approximate.")
|
||||
private CaveValue coverage = CaveValue.of(0.1);
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(1)
|
||||
@Description("Strength of the finer noise on room walls, 0 to 1. 0 gives smooth bubbles. Ignored with a style, and in rooms under about 20 blocks tall or across. A range changes over about "
|
||||
+ VALUE_CHANGE_SIZES + " room sizes.")
|
||||
private CaveValue roughness = CaveValue.of(0.3);
|
||||
|
||||
@Description("Noise that shapes the rooms. Scaled to size and height, so its zoom has no effect; a fracture stays in blocks. Detail under about 12 blocks is lost. Leave out for smooth rooms with rough walls.")
|
||||
private IrisGeneratorStyle style;
|
||||
|
||||
@Description("Rock columns left standing inside the rooms. Leave out for open rooms.")
|
||||
private CavePillars pillars;
|
||||
|
||||
public CaveCavern() {
|
||||
}
|
||||
|
||||
/** The noise that shapes the rooms; empty where the pack wrote none. */
|
||||
public Optional<IrisGeneratorStyle> style() {
|
||||
return Optional.ofNullable(style);
|
||||
}
|
||||
|
||||
public CaveValue size() {
|
||||
return size;
|
||||
}
|
||||
|
||||
public CaveValue height() {
|
||||
return height;
|
||||
}
|
||||
|
||||
public CaveValue coverage() {
|
||||
return coverage;
|
||||
}
|
||||
|
||||
public CaveValue roughness() {
|
||||
return roughness;
|
||||
}
|
||||
|
||||
public Optional<CavePillars> pillars() {
|
||||
return Optional.ofNullable(pillars);
|
||||
}
|
||||
}
|
||||
+21
-12
@@ -16,18 +16,27 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.map;
|
||||
package art.arcane.iris.generation.cave;
|
||||
|
||||
/**
|
||||
* Terrain as the 3D noise view draws it: its columns and their block faces, for any hole finer terrain cuts in it.
|
||||
*/
|
||||
record TerrainLayer(NoiseTerrain terrain, BlockFaces faces) {
|
||||
/**
|
||||
* @param floorY how far down sides on the terrain's edge or next to a hole reach, so they meet the terrain beside it
|
||||
* whatever its height
|
||||
*/
|
||||
static TerrainLayer of(NoiseTerrain terrain, int floorY) {
|
||||
int reachedFloorY = terrain.isEmpty() ? floorY : Math.min(floorY, terrain.baseY());
|
||||
return new TerrainLayer(terrain, BlockFaces.of(terrain, reachedFloorY));
|
||||
import art.arcane.volmlib.util.documentation.Description;
|
||||
|
||||
/** The world Y range a {@link IrisCave} occurs in. Either end may vary across the world. */
|
||||
@Description("World Y range a cave occurs in.")
|
||||
public final class CaveDepth {
|
||||
@Description("Lowest world Y. A range changes over about " + IrisCave.VALUE_CHANGE_BLOCKS + " blocks.")
|
||||
private CaveValue min = CaveValue.of(16);
|
||||
|
||||
@Description("Highest world Y. A range changes over about " + IrisCave.VALUE_CHANGE_BLOCKS + " blocks.")
|
||||
private CaveValue max = CaveValue.of(32);
|
||||
|
||||
public CaveDepth() {
|
||||
}
|
||||
|
||||
public CaveValue min() {
|
||||
return min;
|
||||
}
|
||||
|
||||
public CaveValue max() {
|
||||
return max;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.generation.cave;
|
||||
|
||||
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonDeserializationContext;
|
||||
import com.google.gson.JsonDeserializer;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParseException;
|
||||
import com.google.gson.JsonSerializationContext;
|
||||
import com.google.gson.JsonSerializer;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Reads and writes the two cave types a pack may write as a plain number or as an object: {@link CaveValue} and
|
||||
* {@link CaveTunnelCoverage}. Both keep their object members to the ones named here, so a typo is an error, not a default.
|
||||
*/
|
||||
public final class CaveJson {
|
||||
private static final String MIN = "min";
|
||||
private static final String MAX = "max";
|
||||
private static final String SHARE = "share";
|
||||
private static final String SOFTNESS = "softness";
|
||||
private static final String STYLE = "style";
|
||||
private static final Set<String> VALUE_MEMBERS = Set.of(MIN, MAX, STYLE);
|
||||
private static final Set<String> COVERAGE_MEMBERS = Set.of(SHARE, SOFTNESS, STYLE);
|
||||
|
||||
private CaveJson() {
|
||||
}
|
||||
|
||||
public static void register(GsonBuilder builder) {
|
||||
builder.registerTypeAdapter(CaveValue.class, new ValueCodec());
|
||||
builder.registerTypeAdapter(CaveTunnelCoverage.class, new CoverageCodec());
|
||||
}
|
||||
|
||||
private static final class ValueCodec implements JsonDeserializer<CaveValue>, JsonSerializer<CaveValue> {
|
||||
@Override
|
||||
public CaveValue deserialize(JsonElement json, Type type, JsonDeserializationContext context) {
|
||||
return readValue(json, context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public JsonElement serialize(CaveValue value, Type type, JsonSerializationContext context) {
|
||||
return writeValue(value, context);
|
||||
}
|
||||
}
|
||||
|
||||
private static final class CoverageCodec implements JsonDeserializer<CaveTunnelCoverage>, JsonSerializer<CaveTunnelCoverage> {
|
||||
@Override
|
||||
public CaveTunnelCoverage deserialize(JsonElement json, Type type, JsonDeserializationContext context) {
|
||||
return readCoverage(json, context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public JsonElement serialize(CaveTunnelCoverage coverage, Type type, JsonSerializationContext context) {
|
||||
return writeCoverage(coverage, context);
|
||||
}
|
||||
}
|
||||
|
||||
private static CaveValue readValue(JsonElement json, JsonDeserializationContext context) {
|
||||
if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isNumber()) {
|
||||
return CaveValue.of(json.getAsDouble());
|
||||
}
|
||||
if (!json.isJsonObject()) {
|
||||
throw new JsonParseException("A cave value is a number or {min, max} with an optional style, not " + json);
|
||||
}
|
||||
JsonObject object = json.getAsJsonObject();
|
||||
requireOnlyMembers(object, VALUE_MEMBERS, "A varying cave value has min, max and style, not ");
|
||||
if (!object.has(MIN) || !object.has(MAX)) {
|
||||
throw new JsonParseException("A varying cave value needs both min and max: " + object);
|
||||
}
|
||||
return CaveValue.between(number(object, MIN), number(object, MAX), styleOf(object, context));
|
||||
}
|
||||
|
||||
private static JsonElement writeValue(CaveValue value, JsonSerializationContext context) {
|
||||
if (value.isWrittenAsPlainNumber()) {
|
||||
return context.serialize(value.min());
|
||||
}
|
||||
JsonObject object = new JsonObject();
|
||||
object.addProperty(MIN, value.min());
|
||||
object.addProperty(MAX, value.max());
|
||||
value.style().ifPresent(style -> object.add(STYLE, context.serialize(style)));
|
||||
return object;
|
||||
}
|
||||
|
||||
private static CaveTunnelCoverage readCoverage(JsonElement json, JsonDeserializationContext context) {
|
||||
CaveTunnelCoverage everywhere = CaveTunnelCoverage.EVERYWHERE;
|
||||
if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isNumber()) {
|
||||
return CaveTunnelCoverage.of(CaveValue.of(json.getAsDouble()), everywhere.softness(), null);
|
||||
}
|
||||
if (!json.isJsonObject()) {
|
||||
throw new JsonParseException("A tunnel coverage is a share or {share, softness, style}, not " + json);
|
||||
}
|
||||
JsonObject object = json.getAsJsonObject();
|
||||
requireOnlyMembers(object, COVERAGE_MEMBERS, "A tunnel coverage has share, softness and style, not ");
|
||||
CaveValue share = object.has(SHARE) ? context.deserialize(object.get(SHARE), CaveValue.class) : everywhere.share();
|
||||
CaveValue softness = object.has(SOFTNESS) ? context.deserialize(object.get(SOFTNESS), CaveValue.class) : everywhere.softness();
|
||||
return CaveTunnelCoverage.of(share, softness, styleOf(object, context));
|
||||
}
|
||||
|
||||
private static JsonElement writeCoverage(CaveTunnelCoverage coverage, JsonSerializationContext context) {
|
||||
if (coverage.isWrittenAsShareOnly()) {
|
||||
return context.serialize(coverage.share(), CaveValue.class);
|
||||
}
|
||||
JsonObject object = new JsonObject();
|
||||
object.add(SHARE, context.serialize(coverage.share(), CaveValue.class));
|
||||
object.add(SOFTNESS, context.serialize(coverage.softness(), CaveValue.class));
|
||||
coverage.style().ifPresent(style -> object.add(STYLE, context.serialize(style)));
|
||||
return object;
|
||||
}
|
||||
|
||||
private static void requireOnlyMembers(JsonObject object, Set<String> allowed, String message) {
|
||||
for (String member : object.keySet()) {
|
||||
if (!allowed.contains(member)) {
|
||||
throw new JsonParseException(message + member);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static double number(JsonObject object, String member) {
|
||||
JsonElement written = object.get(member);
|
||||
if (written.isJsonPrimitive() && written.getAsJsonPrimitive().isNumber()) {
|
||||
return written.getAsDouble();
|
||||
}
|
||||
throw new JsonParseException(member + " needs a number, not " + written);
|
||||
}
|
||||
|
||||
private static IrisGeneratorStyle styleOf(JsonObject object, JsonDeserializationContext context) {
|
||||
return object.has(STYLE) ? context.deserialize(object.get(STYLE), IrisGeneratorStyle.class) : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.generation.cave;
|
||||
|
||||
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
|
||||
import art.arcane.iris.pack.schema.annotation.MaxNumber;
|
||||
import art.arcane.iris.pack.schema.annotation.MinNumber;
|
||||
import art.arcane.volmlib.util.documentation.Description;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/** The pillars of a {@link CaveCavern}: columns of rock left standing from floor to ceiling. */
|
||||
@Description("Rock columns left standing inside caverns.")
|
||||
public final class CavePillars {
|
||||
@MinNumber(6)
|
||||
@MaxNumber(256)
|
||||
@Description("Rough distance between pillars in blocks, 6 to 256. A range changes over about " + CaveCavern.VALUE_CHANGE_SIZES + " room sizes.")
|
||||
private CaveValue spacing = CaveValue.of(22);
|
||||
|
||||
@MinNumber(1)
|
||||
@MaxNumber(64)
|
||||
@Description("Rough thickness of a pillar at its middle, in blocks, 1 to 64. Pillars widen towards floor and ceiling. A range changes over about "
|
||||
+ CaveCavern.VALUE_CHANGE_SIZES + " room sizes.")
|
||||
private CaveValue thickness = CaveValue.of(4);
|
||||
|
||||
@MinNumber(1)
|
||||
@MaxNumber(16)
|
||||
@Description("How many times more ground a pillar covers at floor and ceiling than at its middle, 1 to 16. 1 gives straight columns. A range changes over about "
|
||||
+ CaveCavern.VALUE_CHANGE_SIZES + " room sizes.")
|
||||
private CaveValue flare = CaveValue.of(4);
|
||||
|
||||
@MinNumber(8)
|
||||
@MaxNumber(512)
|
||||
@Description("Blocks over which the pillars change with height, 8 to 512, so they lean, pinch and break off. Detail under about 12 blocks is lost. A range changes over about "
|
||||
+ CaveCavern.VALUE_CHANGE_SIZES + " room sizes. Leave out for columns that run straight from floor to ceiling.")
|
||||
private CaveValue vertical;
|
||||
|
||||
@Description("Noise that places the pillars. Scaled to spacing, so its zoom has no effect; a fracture stays in blocks. Leave out for evenly scattered pillars.")
|
||||
private IrisGeneratorStyle style;
|
||||
|
||||
public CavePillars() {
|
||||
}
|
||||
|
||||
public CaveValue flare() {
|
||||
return flare;
|
||||
}
|
||||
|
||||
/** Blocks over which the pillars change with height; empty for pillars that run straight. */
|
||||
public Optional<CaveValue> vertical() {
|
||||
return Optional.ofNullable(vertical);
|
||||
}
|
||||
|
||||
/** The noise that places the pillars; empty where the pack wrote none. */
|
||||
public Optional<IrisGeneratorStyle> style() {
|
||||
return Optional.ofNullable(style);
|
||||
}
|
||||
|
||||
public CaveValue spacing() {
|
||||
return spacing;
|
||||
}
|
||||
|
||||
public CaveValue thickness() {
|
||||
return thickness;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package art.arcane.iris.generation.cave;
|
||||
|
||||
import art.arcane.iris.generation.cave.field.CaveCarver;
|
||||
import art.arcane.iris.generation.cave.field.CavePart;
|
||||
import art.arcane.iris.generation.cave.field.CngNoiseFactory;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.studio.scene.SceneBlocks;
|
||||
import art.arcane.iris.studio.scene.SceneEntry;
|
||||
import art.arcane.iris.studio.scene.SceneRequest;
|
||||
import art.arcane.iris.studio.scene.SceneSizes;
|
||||
import art.arcane.iris.studio.scene.SceneView;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
/**
|
||||
* The space each cave of the pack carves under flat ground, as blocks coloured by depth. Each block names the part of
|
||||
* the cave that carved it, its tunnel or its cavern. Caves are only shown here; their files are edited elsewhere.
|
||||
*/
|
||||
public final class CaveSceneView implements SceneView {
|
||||
private static final SceneSizes SIZES = new SceneSizes(List.of(64, 128, 256), 128);
|
||||
private static final int VARIANTS = 4;
|
||||
private static final int VARIANT_SPACING_BLOCKS = 4096;
|
||||
private static final int SURFACE_ABOVE_SEA_BLOCKS = 48;
|
||||
private static final int MAX_DEPTH_BLOCKS = 160;
|
||||
private static final int CHUNK_BLOCKS = 16;
|
||||
private static final int CHUNK_COLUMNS = CHUNK_BLOCKS * CHUNK_BLOCKS;
|
||||
private static final byte ROCK = 0;
|
||||
private static final String GROUP = "Caves";
|
||||
private static final String[] DEPTH_BANDS = {"minecraft:yellow_concrete", "minecraft:lime_concrete", "minecraft:light_blue_concrete",
|
||||
"minecraft:purple_concrete"};
|
||||
private static final int[][] NEIGHBOURS = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}};
|
||||
|
||||
@Override
|
||||
public String id() {
|
||||
return "caves";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String label() {
|
||||
return "Caves";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String description() {
|
||||
return "The space each cave of the pack carves under flat ground, its tunnel and its cavern";
|
||||
}
|
||||
|
||||
@Override
|
||||
public SceneSizes sizes() {
|
||||
return SIZES;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<SceneEntry> entries(Engine engine) {
|
||||
return Arrays.stream(engine.getData().getCaveLoader().getPossibleKeys()).sorted()
|
||||
.map(key -> new SceneEntry(key, key, GROUP, VARIANTS))
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SceneBlocks scene(Engine engine, SceneRequest request) {
|
||||
IrisCave cave = caveOf(engine.getData(), request.key());
|
||||
int surfaceY = Math.min(engine.getHeight() - 1, engine.getDimension().getFluidHeight() + SURFACE_ABOVE_SEA_BLOCKS);
|
||||
HeightSpan span = HeightSpan.of(cave, engine.getMinHeight(), surfaceY);
|
||||
long seed = CaveCarver.seedOf(engine.getSeedManager().getCarve(), request.key());
|
||||
CaveCarver carver = new CaveCarver(cave, new CngNoiseFactory(engine.getData()), seed, engine.getMinHeight(), engine.getHeight());
|
||||
int originX = Math.floorMod(request.variant(), VARIANTS) * VARIANT_SPACING_BLOCKS;
|
||||
CarvedSpace carved = new CarvedSpace(request.size(), span);
|
||||
carveSquare(carver, originX, surfaceY, carved);
|
||||
return carved.outside();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean tracesParts() {
|
||||
return true;
|
||||
}
|
||||
|
||||
private static IrisCave caveOf(IrisData data, String key) {
|
||||
IrisCave cave = data.getCaveLoader().load(key);
|
||||
if (cave == null) {
|
||||
throw new NoSuchElementException("No cave " + key);
|
||||
}
|
||||
return cave;
|
||||
}
|
||||
|
||||
private static void carveSquare(CaveCarver carver, int originX, int surfaceY, CarvedSpace carved) {
|
||||
int[] surface = new int[CHUNK_COLUMNS];
|
||||
Arrays.fill(surface, surfaceY);
|
||||
double[] listedEverywhere = new double[CHUNK_COLUMNS];
|
||||
Arrays.fill(listedEverywhere, 1D);
|
||||
boolean[] sealed = new boolean[CHUNK_COLUMNS];
|
||||
for (int chunkX = 0; chunkX < carved.size; chunkX += CHUNK_BLOCKS) {
|
||||
for (int chunkZ = 0; chunkZ < carved.size; chunkZ += CHUNK_BLOCKS) {
|
||||
int fromX = chunkX;
|
||||
int fromZ = chunkZ;
|
||||
carver.carveByPart(originX + chunkX, chunkZ, surface, listedEverywhere, sealed,
|
||||
(part, localX, y, localZ) -> carved.mark(fromX + localX, y, fromZ + localZ, part));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The heights shown, from the dimension's bottom: the cave's own depth where it has one, below the ground. */
|
||||
private record HeightSpan(int bottomY, int topY) {
|
||||
static HeightSpan of(IrisCave cave, int worldBottomY, int surfaceY) {
|
||||
int topY = cave.depth().map(depth -> Math.min(surfaceY, (int) Math.ceil(depth.max().highest()) - worldBottomY)).orElse(surfaceY);
|
||||
int depthBottomY = cave.depth().map(depth -> (int) Math.floor(depth.min().lowest()) - worldBottomY).orElse(0);
|
||||
int bottomY = Math.max(0, Math.max(depthBottomY, topY - MAX_DEPTH_BLOCKS));
|
||||
return new HeightSpan(bottomY, Math.max(bottomY, topY));
|
||||
}
|
||||
|
||||
int height() {
|
||||
return topY - bottomY + 1;
|
||||
}
|
||||
}
|
||||
|
||||
/** The cells of the scene, each rock or carved by a part; a cell two parts carve keeps the last. */
|
||||
private static final class CarvedSpace {
|
||||
private final int size;
|
||||
private final HeightSpan span;
|
||||
private final byte[] cells;
|
||||
|
||||
CarvedSpace(int size, HeightSpan span) {
|
||||
this.size = size;
|
||||
this.span = span;
|
||||
this.cells = new byte[size * size * span.height()];
|
||||
}
|
||||
|
||||
void mark(int x, int worldY, int z, CavePart part) {
|
||||
int y = worldY - span.bottomY();
|
||||
if (y < 0 || y >= span.height()) {
|
||||
return;
|
||||
}
|
||||
cells[cellOf(x, y, z)] = (byte) (part.ordinal() + 1);
|
||||
}
|
||||
|
||||
// Only the carved blocks on the outside of the space are kept, as the inside could not be seen.
|
||||
SceneBlocks outside() {
|
||||
SceneBlocks scene = new SceneBlocks();
|
||||
int height = span.height();
|
||||
for (int y = 0; y < height; y++) {
|
||||
String band = DEPTH_BANDS[Math.min(DEPTH_BANDS.length - 1, (height - 1 - y) * DEPTH_BANDS.length / height)];
|
||||
for (int z = 0; z < size; z++) {
|
||||
for (int x = 0; x < size; x++) {
|
||||
byte cell = cells[cellOf(x, y, z)];
|
||||
if (cell != ROCK && touchesRock(x, y, z)) {
|
||||
scene.add(x, y, z, band, cell - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return scene;
|
||||
}
|
||||
|
||||
private boolean touchesRock(int x, int y, int z) {
|
||||
for (int[] step : NEIGHBOURS) {
|
||||
int nx = x + step[0];
|
||||
int ny = y + step[1];
|
||||
int nz = z + step[2];
|
||||
boolean inside = nx >= 0 && ny >= 0 && nz >= 0 && nx < size && ny < span.height() && nz < size;
|
||||
if (!inside || cells[cellOf(nx, ny, nz)] == ROCK) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private int cellOf(int x, int y, int z) {
|
||||
return (y * size + z) * size + x;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.generation.cave;
|
||||
|
||||
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
|
||||
import art.arcane.iris.pack.schema.annotation.MaxNumber;
|
||||
import art.arcane.iris.pack.schema.annotation.MinNumber;
|
||||
import art.arcane.volmlib.util.documentation.Description;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/** The tunnels of a {@link IrisCave}: long winding passages. Thin ones link other caves together. */
|
||||
@Description("Long winding passages.")
|
||||
public final class CaveTunnel {
|
||||
/** Without a style, the width changes over this many horizontal spacings. */
|
||||
public static final double WIDTH_CHANGE_SPACINGS = 1.5D;
|
||||
/** Without a style, any other value of the tunnels changes over this many horizontal spacings. */
|
||||
public static final int VALUE_CHANGE_SPACINGS = 6;
|
||||
|
||||
@MinNumber(1)
|
||||
@MaxNumber(64)
|
||||
@Description("Tunnel width in blocks, 1 to 64. A range changes over about " + WIDTH_CHANGE_SPACINGS + " horizontal spacings.")
|
||||
private CaveValue width = CaveValue.between(4, 7);
|
||||
|
||||
@MinNumber(1)
|
||||
@MaxNumber(64)
|
||||
@Description("Tunnel height in blocks, 1 to 64. A range without a style follows the width: low where the tunnel is narrow, tall where it is wide. Leave out for round tunnels.")
|
||||
private CaveValue height;
|
||||
|
||||
@Description("Blocks between neighbouring tunnels.")
|
||||
private CaveTunnelSpacing spacing = new CaveTunnelSpacing();
|
||||
|
||||
@Description("Noise that bends the tunnels: zoom sets how often they turn, multiplier how many blocks they swing. A flat style keeps them straight. Leave out for a gentle bend that scales with spacing.")
|
||||
private IrisGeneratorStyle warp;
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(1)
|
||||
@Description("How far the warp moves tunnels up and down, as a share of how far it swings them sideways, 0 to 1. 0 adds no rise and fall. A range changes over about "
|
||||
+ VALUE_CHANGE_SPACINGS + " horizontal spacings.")
|
||||
private CaveValue verticalWarp = CaveValue.of(0.5);
|
||||
|
||||
@Description("Where tunnels occur: a share of the underground from 0 to 1, or {share, softness, style}. Softness, 0 to 1, is how gradually tunnels thin out at the edge of an area, from abrupt dead ends to long tails; style is the noise that shapes the areas. Share and softness change over about "
|
||||
+ VALUE_CHANGE_SPACINGS + " horizontal spacings as a range. Leave out to put tunnels everywhere.")
|
||||
private CaveTunnelCoverage coverage;
|
||||
|
||||
public CaveTunnel() {
|
||||
}
|
||||
|
||||
public CaveValue width() {
|
||||
return width;
|
||||
}
|
||||
|
||||
/** The height of an oval tunnel; empty for a round one. */
|
||||
public Optional<CaveValue> height() {
|
||||
return Optional.ofNullable(height);
|
||||
}
|
||||
|
||||
public CaveTunnelSpacing spacing() {
|
||||
return spacing == null ? new CaveTunnelSpacing() : spacing;
|
||||
}
|
||||
|
||||
/** The noise that bends the tunnels; empty where the pack wrote none. */
|
||||
public Optional<IrisGeneratorStyle> warp() {
|
||||
return Optional.ofNullable(warp);
|
||||
}
|
||||
|
||||
public CaveValue verticalWarp() {
|
||||
return verticalWarp;
|
||||
}
|
||||
|
||||
public CaveTunnelCoverage coverage() {
|
||||
return coverage == null ? CaveTunnelCoverage.EVERYWHERE : coverage;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.generation.cave;
|
||||
|
||||
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
|
||||
import art.arcane.iris.pack.schema.annotation.AcceptsPlainNumber;
|
||||
import art.arcane.iris.pack.schema.annotation.MaxNumber;
|
||||
import art.arcane.iris.pack.schema.annotation.MinNumber;
|
||||
import art.arcane.volmlib.util.documentation.Description;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Where the tunnels of a {@link CaveTunnel} occur: the share of the underground that has them, in areas a noise shapes,
|
||||
* and how gradually they thin out at the edge of an area. Written as the share alone, {@code 0.4}, or as
|
||||
* {@code {"share": 0.4, "softness": 0.3, "style": {...}}} with each member optional.
|
||||
*/
|
||||
@AcceptsPlainNumber
|
||||
@Description("Where tunnels occur: a share, or {share, softness, style}.")
|
||||
public final class CaveTunnelCoverage {
|
||||
/** The softness that thins tunnels out over the same stretch they always did before softness was a key. */
|
||||
public static final double DEFAULT_SOFTNESS = 0.3D;
|
||||
static final CaveTunnelCoverage EVERYWHERE = new CaveTunnelCoverage();
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(1)
|
||||
@Description("Share of the underground that has tunnels, 0 to 1. A range changes over about " + CaveTunnel.VALUE_CHANGE_SPACINGS + " horizontal spacings.")
|
||||
private CaveValue share = CaveValue.of(1);
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(1)
|
||||
@Description("How gradually tunnels thin out at the edge of an area, 0 for abrupt dead ends to 1 for long tails.")
|
||||
private CaveValue softness = CaveValue.of(DEFAULT_SOFTNESS);
|
||||
|
||||
@Description("The noise that shapes the areas with tunnels. Leave out for areas a few spacings across.")
|
||||
private IrisGeneratorStyle style;
|
||||
|
||||
public CaveTunnelCoverage() {
|
||||
}
|
||||
|
||||
static CaveTunnelCoverage of(CaveValue share, CaveValue softness, IrisGeneratorStyle style) {
|
||||
CaveTunnelCoverage coverage = new CaveTunnelCoverage();
|
||||
coverage.share = share;
|
||||
coverage.softness = softness;
|
||||
coverage.style = style;
|
||||
return coverage;
|
||||
}
|
||||
|
||||
/** Share of the underground that has tunnels, from 0 to 1. */
|
||||
public CaveValue share() {
|
||||
return share;
|
||||
}
|
||||
|
||||
/** How gradually tunnels thin out at the edge of an area, from 0 for abrupt ends to 1 for long tails. */
|
||||
public CaveValue softness() {
|
||||
return softness;
|
||||
}
|
||||
|
||||
/** The noise that shapes the areas with tunnels; empty where the pack wrote none. */
|
||||
public Optional<IrisGeneratorStyle> style() {
|
||||
return Optional.ofNullable(style);
|
||||
}
|
||||
|
||||
boolean isWrittenAsShareOnly() {
|
||||
return style == null && softness.min() == DEFAULT_SOFTNESS && !softness.varies();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.generation.cave;
|
||||
|
||||
import art.arcane.iris.pack.schema.annotation.MaxNumber;
|
||||
import art.arcane.iris.pack.schema.annotation.MinNumber;
|
||||
import art.arcane.volmlib.util.documentation.Description;
|
||||
|
||||
/** How far apart the tunnels of a {@link CaveTunnel} run, side by side and stacked. */
|
||||
@Description("Blocks between neighbouring tunnels.")
|
||||
public final class CaveTunnelSpacing {
|
||||
@MinNumber(16)
|
||||
@MaxNumber(512)
|
||||
@Description("Blocks between tunnels side by side. Larger gives longer, straighter and sparser tunnels.")
|
||||
private int horizontal = 96;
|
||||
|
||||
@MinNumber(8)
|
||||
@MaxNumber(512)
|
||||
@Description("Blocks between tunnels stacked above each other. Below horizontal keeps tunnels closer to level.")
|
||||
private int vertical = 69;
|
||||
|
||||
public CaveTunnelSpacing() {
|
||||
}
|
||||
|
||||
public int horizontal() {
|
||||
return horizontal;
|
||||
}
|
||||
|
||||
public int vertical() {
|
||||
return vertical;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.generation.cave;
|
||||
|
||||
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
|
||||
import art.arcane.iris.pack.schema.annotation.AcceptsPlainNumber;
|
||||
import art.arcane.iris.pack.schema.annotation.Required;
|
||||
import art.arcane.volmlib.util.documentation.Description;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* A number that shapes how a cave looks, which may vary across the world: {@code 5} everywhere,
|
||||
* {@code {"min": 3, "max": 9}} picked by a smooth noise the cave chooses for the key, or
|
||||
* {@code {"min": 3, "max": 9, "style": {...}}} picked by that style, its zoom as written. The noise's low end gives
|
||||
* min and its high end max.
|
||||
*/
|
||||
@AcceptsPlainNumber
|
||||
@Description("A number, or {min, max} that varies across the world; add a style to decide where.")
|
||||
public final class CaveValue {
|
||||
@Required
|
||||
@Description("The value where the noise is lowest.")
|
||||
private double min;
|
||||
|
||||
@Required
|
||||
@Description("The value where the noise is highest.")
|
||||
private double max;
|
||||
|
||||
@Description("The noise that decides where the value is low or high, its zoom as written. Leave out and the cave picks a smooth noise for this key.")
|
||||
private IrisGeneratorStyle style;
|
||||
|
||||
public CaveValue() {
|
||||
}
|
||||
|
||||
private CaveValue(double min, double max, IrisGeneratorStyle style) {
|
||||
this.min = min;
|
||||
this.max = max;
|
||||
this.style = style;
|
||||
}
|
||||
|
||||
public static CaveValue of(double value) {
|
||||
return new CaveValue(value, value, null);
|
||||
}
|
||||
|
||||
public static CaveValue between(double min, double max) {
|
||||
return new CaveValue(min, max, null);
|
||||
}
|
||||
|
||||
public static CaveValue between(double min, double max, IrisGeneratorStyle style) {
|
||||
return new CaveValue(min, max, style);
|
||||
}
|
||||
|
||||
/** Whether the value differs from place to place; a plain number, or a min equal to max, does not. */
|
||||
public boolean varies() {
|
||||
return min != max;
|
||||
}
|
||||
|
||||
/** The value where the noise is lowest; the value everywhere when it does not vary. */
|
||||
public double min() {
|
||||
return min;
|
||||
}
|
||||
|
||||
/** The value where the noise is highest. */
|
||||
public double max() {
|
||||
return max;
|
||||
}
|
||||
|
||||
public double middle() {
|
||||
return (min + max) / 2D;
|
||||
}
|
||||
|
||||
public double lowest() {
|
||||
return Math.min(min, max);
|
||||
}
|
||||
|
||||
public double highest() {
|
||||
return Math.max(min, max);
|
||||
}
|
||||
|
||||
/** The noise the pack chose to pick the value; empty where it wrote none and the cave picks a smooth one. */
|
||||
public Optional<IrisGeneratorStyle> style() {
|
||||
return Optional.ofNullable(style);
|
||||
}
|
||||
|
||||
boolean isWrittenAsPlainNumber() {
|
||||
return style == null && min == max;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return isWrittenAsPlainNumber() ? Double.toString(min) : "{min " + min + ", max " + max + (style == null ? "" : ", style " + style) + "}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.generation.cave;
|
||||
|
||||
import art.arcane.iris.generation.biome.IrisBiome;
|
||||
import art.arcane.iris.pack.loading.IrisRegistrant;
|
||||
import art.arcane.iris.pack.schema.annotation.MaxNumber;
|
||||
import art.arcane.iris.pack.schema.annotation.MinNumber;
|
||||
import art.arcane.iris.pack.schema.annotation.RegistryListResource;
|
||||
import art.arcane.volmlib.util.documentation.Description;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* One kind of cave, a file of a pack's {@code caves/} folder that dimensions, regions and biomes list under
|
||||
* {@code caves}. It carves tunnels, caverns or both, within a depth range and under the surface rules it sets. Every
|
||||
* number that shapes the cave is a {@link CaveValue}, so it may vary across the world.
|
||||
*/
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Description("One kind of cave: tunnels, caverns or both, with where they may occur.")
|
||||
public final class IrisCave extends IrisRegistrant {
|
||||
/** Without a style, a value of the whole cave changes over about this many blocks. */
|
||||
public static final int VALUE_CHANGE_BLOCKS = 256;
|
||||
static final String FOLDER_NAME = "caves";
|
||||
|
||||
@Description("Winding tunnels. Leave out for a cave without tunnels.")
|
||||
private CaveTunnel tunnel;
|
||||
|
||||
@Description("Large open rooms. Leave out for a cave without caverns.")
|
||||
private CaveCavern cavern;
|
||||
|
||||
@Description("World Y range this cave occurs in. Leave out to allow every height.")
|
||||
private CaveDepth depth;
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(128)
|
||||
@Description("Blocks over which the cave narrows to nothing at both ends of its depth range, 0 to 128. A range changes over about "
|
||||
+ VALUE_CHANGE_BLOCKS + " blocks.")
|
||||
private CaveValue fade = CaveValue.of(12);
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(128)
|
||||
@Description("Blocks of rock kept between the cave and the surface, 0 to 128. Ignored when opensToSurface is set. A range changes over about "
|
||||
+ VALUE_CHANGE_BLOCKS + " blocks.")
|
||||
private CaveValue surfaceClearance = CaveValue.of(8);
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(128)
|
||||
@Description("Blocks over which the cave closes under the rock it keeps, instead of ending in a flat ceiling, 0 to 128. Ignored where it opens to the surface. A range changes over about "
|
||||
+ VALUE_CHANGE_BLOCKS + " blocks.")
|
||||
private CaveValue ceilingFade = CaveValue.of(8);
|
||||
|
||||
@Description("Let the cave cut through the surface, which makes entrances wherever it reaches the top.")
|
||||
private boolean opensToSurface = false;
|
||||
|
||||
@RegistryListResource(IrisBiome.class)
|
||||
@Description("Cave biome that paints this cave's walls. Leave out to use the cave biome of the place.")
|
||||
private String biome = "";
|
||||
|
||||
@Description("Allow pockets of the dimension's fluid in this cave below the dimension's fluid height.")
|
||||
private boolean allowFluid = true;
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(64)
|
||||
@Description("Minimum depth below the surface before this cave may hold fluid.")
|
||||
private int fluidMinDepthBelowSurface = 12;
|
||||
|
||||
@Description("Only hold fluid where the cave has a solid floor under it, which keeps fluid from running out of the cave.")
|
||||
private boolean fluidRequiresFloor = true;
|
||||
|
||||
@Description("Allow lava below the dimension's cave lava height. When false that depth stays air.")
|
||||
private boolean allowLava = true;
|
||||
|
||||
public IrisCave() {
|
||||
}
|
||||
|
||||
public Optional<CaveTunnel> tunnel() {
|
||||
return Optional.ofNullable(tunnel);
|
||||
}
|
||||
|
||||
public Optional<CaveCavern> cavern() {
|
||||
return Optional.ofNullable(cavern);
|
||||
}
|
||||
|
||||
public Optional<CaveDepth> depth() {
|
||||
return Optional.ofNullable(depth);
|
||||
}
|
||||
|
||||
public CaveValue fade() {
|
||||
return fade;
|
||||
}
|
||||
|
||||
public CaveValue surfaceClearance() {
|
||||
return surfaceClearance;
|
||||
}
|
||||
|
||||
public CaveValue ceilingFade() {
|
||||
return ceilingFade;
|
||||
}
|
||||
|
||||
public boolean opensToSurface() {
|
||||
return opensToSurface;
|
||||
}
|
||||
|
||||
public String biome() {
|
||||
return biome == null ? "" : biome;
|
||||
}
|
||||
|
||||
public boolean allowFluid() {
|
||||
return allowFluid;
|
||||
}
|
||||
|
||||
public int fluidMinDepthBelowSurface() {
|
||||
return Math.max(0, fluidMinDepthBelowSurface);
|
||||
}
|
||||
|
||||
public boolean fluidRequiresFloor() {
|
||||
return fluidRequiresFloor;
|
||||
}
|
||||
|
||||
public boolean allowLava() {
|
||||
return allowLava;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFolderName() {
|
||||
return FOLDER_NAME;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTypeName() {
|
||||
return "Cave";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerTypeAdapters(GsonBuilder builder) {
|
||||
CaveJson.register(builder);
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package art.arcane.iris.generation.cave;
|
||||
|
||||
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
|
||||
import art.arcane.iris.generation.noise.NoiseStyle;
|
||||
import art.arcane.iris.pack.value.IrisRange;
|
||||
|
||||
import art.arcane.volmlib.util.documentation.Description;
|
||||
import art.arcane.iris.pack.schema.annotation.MaxNumber;
|
||||
import art.arcane.iris.pack.schema.annotation.MinNumber;
|
||||
import art.arcane.iris.pack.schema.annotation.Snippet;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
@Snippet("cave-field-module")
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Description("Represents a modular cave-density layer.")
|
||||
@Data
|
||||
public class IrisCaveFieldModule {
|
||||
@Description("Density style used by this module.")
|
||||
private IrisGeneratorStyle style = NoiseStyle.CELLULAR_IRIS_DOUBLE.style();
|
||||
|
||||
@MinNumber(0)
|
||||
@Description("Layer contribution multiplier.")
|
||||
private double weight = 1;
|
||||
|
||||
@MinNumber(-1)
|
||||
@MaxNumber(1)
|
||||
@Description("Threshold offset applied to this layer before blending.")
|
||||
private double threshold = 0;
|
||||
|
||||
@Description("Vertical bounds where this module can contribute, in engine-local Y where 0 is the bottom of the dimension, not world Y.")
|
||||
private IrisRange verticalRange = new IrisRange(0, 384);
|
||||
|
||||
@Description("Invert this module before weighting.")
|
||||
private boolean invert = false;
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
package art.arcane.iris.generation.cave;
|
||||
|
||||
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
|
||||
import art.arcane.iris.generation.noise.IrisStyledRange;
|
||||
import art.arcane.iris.generation.noise.NoiseStyle;
|
||||
import art.arcane.iris.pack.value.IrisRange;
|
||||
import art.arcane.iris.structure.object.ObjectPlaceMode;
|
||||
|
||||
import art.arcane.iris.pack.schema.annotation.ArrayType;
|
||||
import art.arcane.volmlib.util.documentation.Description;
|
||||
import art.arcane.iris.pack.schema.annotation.MaxNumber;
|
||||
import art.arcane.iris.pack.schema.annotation.MinNumber;
|
||||
import art.arcane.iris.pack.schema.annotation.Snippet;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
@Snippet("cave-profile")
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Description("Represents a configurable 3D cave profile.")
|
||||
@Data
|
||||
public class IrisCaveProfile {
|
||||
@Description("Enable profile-driven cave carving.")
|
||||
private boolean enabled = false;
|
||||
|
||||
@Description("Global vertical bounds for profile cave carving, in engine-local Y where 0 is the bottom of the dimension, not world Y.")
|
||||
private IrisRange verticalRange = new IrisRange(0, 384);
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(128)
|
||||
@Description("Vertical fade range applied near cave profile min/max bounds to avoid abrupt hard-stop ceilings/floors.")
|
||||
private int verticalEdgeFade = 20;
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(1)
|
||||
@Description("Strength of the vertical edge fade at cave profile min/max bounds.")
|
||||
private double verticalEdgeFadeStrength = 0.18;
|
||||
|
||||
@Description("Base density style for cave field generation.")
|
||||
private IrisGeneratorStyle baseDensityStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style();
|
||||
|
||||
@Description("Detail density style blended into base caves.")
|
||||
private IrisGeneratorStyle detailDensityStyle = new IrisGeneratorStyle(NoiseStyle.SIMPLEX);
|
||||
|
||||
@Description("Warp style used to distort cave coordinates.")
|
||||
private IrisGeneratorStyle warpStyle = new IrisGeneratorStyle(NoiseStyle.FLAT);
|
||||
|
||||
@MinNumber(0)
|
||||
@Description("Base cave field multiplier.")
|
||||
private double baseWeight = 1;
|
||||
|
||||
@MinNumber(0)
|
||||
@Description("Detail cave field multiplier.")
|
||||
private double detailWeight = 0.35;
|
||||
|
||||
@MinNumber(0)
|
||||
@Description("Coordinate warp strength for cave fields.")
|
||||
private double warpStrength = 0;
|
||||
|
||||
@Description("Threshold range used for carve cutoff decisions.")
|
||||
private IrisStyledRange densityThreshold = new IrisStyledRange(-0.2, 0.2, NoiseStyle.CELLULAR_IRIS_DOUBLE.style());
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(1)
|
||||
@Description("Extra threshold bias subtracted from sampled threshold before carve tests.")
|
||||
private double thresholdBias = 0.16;
|
||||
|
||||
@MinNumber(1)
|
||||
@MaxNumber(8)
|
||||
@Description("Vertical sample step used while evaluating cave density.")
|
||||
private int sampleStep = 1;
|
||||
|
||||
@Description("Use adaptive cave density prediction so only threshold-adjacent cells fall back to full-resolution evaluation.")
|
||||
private boolean adaptiveSampling = true;
|
||||
|
||||
@MinNumber(2)
|
||||
@MaxNumber(4)
|
||||
@Description("Horizontal adaptive predictor tuning. The carver always samples the predictor grid at a fixed step of 8; values below 8 only widen the ambiguity margin slightly and do not tighten the grid.")
|
||||
private int adaptiveSampleStep = 2;
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(1)
|
||||
@Description("Additional adaptive ambiguity margin used before the cave predictor falls back to exact sampling.")
|
||||
private double adaptiveThresholdMargin = 0.04;
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(64)
|
||||
@Description("Minimum solid clearance below terrain surface where carving may occur.")
|
||||
private int surfaceClearance = 4;
|
||||
|
||||
@Description("Allow profile-driven cave carving to break through terrain surface in selected columns.")
|
||||
private boolean allowSurfaceBreak = true;
|
||||
|
||||
@Description("Noise style used to decide where surface-breaking cave columns are allowed.")
|
||||
private IrisGeneratorStyle surfaceBreakStyle = new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.08);
|
||||
|
||||
@MinNumber(-1)
|
||||
@MaxNumber(1)
|
||||
@Description("Minimum signed surface-break noise value required before near-surface carving is allowed.")
|
||||
private double surfaceBreakNoiseThreshold = 0.62;
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(64)
|
||||
@Description("Near-surface depth window used for surface-break carve logic.")
|
||||
private int surfaceBreakDepth = 18;
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(1)
|
||||
@Description("Additional threshold boost applied while carving in the surface-break depth window.")
|
||||
private double surfaceBreakThresholdBoost = 0.2;
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(64)
|
||||
@Description("Minimum depth below terrain surface required for cave-only object anchor placement.")
|
||||
private int objectMinDepthBelowSurface = 6;
|
||||
|
||||
@ArrayType(type = IrisCaveFieldModule.class, min = 1)
|
||||
@Description("Additional layered cave-density modules.")
|
||||
private KList<IrisCaveFieldModule> modules = new KList<>();
|
||||
|
||||
@Description("Default cave anchor mode for cave-only object placement.")
|
||||
private IrisCaveAnchorMode defaultObjectAnchor = IrisCaveAnchorMode.FLOOR;
|
||||
|
||||
@Description("Default placement mode for cave objects. Only applies to placements that are still on the default CENTER_HEIGHT mode; an explicit mode on the placement always wins. Stilt modes tile the object base block down to the cave floor surface. FAST_MIN_STILT is recommended for cave objects to prevent floating.")
|
||||
private ObjectPlaceMode defaultObjectPlaceMode = null;
|
||||
|
||||
@MinNumber(1)
|
||||
@MaxNumber(8)
|
||||
@Description("Vertical scan step used while searching cave anchors.")
|
||||
private int anchorScanStep = 1;
|
||||
|
||||
@MinNumber(1)
|
||||
@MaxNumber(64)
|
||||
@Description("Maximum random column retries while searching a valid cave object anchor in the chunk.")
|
||||
private int anchorSearchAttempts = 6;
|
||||
|
||||
@Description("Allow cave fluid placement from the dimension fluid palette below fluid level.")
|
||||
private boolean allowFluid = true;
|
||||
|
||||
@MinNumber(0)
|
||||
@MaxNumber(64)
|
||||
@Description("Minimum depth below terrain surface required before cave fluid may be placed.")
|
||||
private int fluidMinDepthBelowSurface = 12;
|
||||
|
||||
@Description("Require solid floor support below cave fluid to reduce unsupported fluid flows.")
|
||||
private boolean fluidRequiresFloor = true;
|
||||
|
||||
@Description("Allow cave lava placement based on lava height.")
|
||||
private boolean allowLava = true;
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.generation.cave;
|
||||
|
||||
import art.arcane.iris.pack.value.IrisRange;
|
||||
import art.arcane.iris.generation.noise.IrisStyledRange;
|
||||
import art.arcane.volmlib.util.math.M;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.volmlib.util.noise.CNG;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public final class IrisCaveProfileSampler {
|
||||
private static final double FLOATING_THRESHOLD_BIAS_SCALE = 0.2D;
|
||||
|
||||
private final IrisCaveProfile profile;
|
||||
private final CNG baseDensity;
|
||||
private final CNG detailDensity;
|
||||
private final CNG warpDensity;
|
||||
private final CNG thresholdDensity;
|
||||
private final double thresholdMin;
|
||||
private final double thresholdMax;
|
||||
private final double constantThreshold;
|
||||
private final boolean thresholdHasNoise;
|
||||
private final ModuleState[] modules;
|
||||
private final double inverseNormalization;
|
||||
private final double baseWeight;
|
||||
private final double detailWeight;
|
||||
private final double warpStrength;
|
||||
private final boolean enabled;
|
||||
private final boolean hasWarp;
|
||||
private final boolean hasModules;
|
||||
|
||||
public IrisCaveProfileSampler(Engine engine, IrisCaveProfile profile) {
|
||||
PackRuntime runtime = PackRuntime.of(engine, engine.getData());
|
||||
this.profile = profile;
|
||||
List<ModuleState> moduleStates = new ArrayList<>();
|
||||
RNG baseRng = new RNG(engine.getSeedManager().getCarve());
|
||||
this.baseDensity = profile.getBaseDensityStyle().create(baseRng.nextParallelRNG(934_447), runtime);
|
||||
this.detailDensity = profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), runtime);
|
||||
this.warpDensity = profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), runtime);
|
||||
IrisStyledRange threshold = profile.getDensityThreshold();
|
||||
thresholdMin = threshold.getMin();
|
||||
thresholdMax = threshold.getMax();
|
||||
thresholdHasNoise = thresholdMin != thresholdMax && !threshold.getStyle().isFlat();
|
||||
thresholdDensity = thresholdHasNoise ? threshold.getStyle().create(baseRng.nextParallelRNG(489_112), runtime) : null;
|
||||
constantThreshold = thresholdMin == thresholdMax ? thresholdMin : M.lerp(thresholdMin, thresholdMax, 0.5D);
|
||||
this.baseWeight = profile.getBaseWeight();
|
||||
this.detailWeight = profile.getDetailWeight();
|
||||
this.warpStrength = profile.getWarpStrength();
|
||||
this.hasWarp = warpStrength > 0D;
|
||||
|
||||
double weight = Math.abs(baseWeight) + Math.abs(detailWeight);
|
||||
int index = 0;
|
||||
for (IrisCaveFieldModule module : profile.getModules()) {
|
||||
CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), runtime);
|
||||
ModuleState state = new ModuleState(module, moduleDensity);
|
||||
moduleStates.add(state);
|
||||
weight += Math.abs(state.weight);
|
||||
index++;
|
||||
}
|
||||
|
||||
this.modules = moduleStates.toArray(new ModuleState[0]);
|
||||
double normalization = weight <= 0 ? 1D : weight;
|
||||
this.inverseNormalization = 1D / normalization;
|
||||
this.hasModules = modules.length > 0;
|
||||
this.enabled = profile.isEnabled() && baseDensity != null && detailDensity != null && (!hasWarp || warpDensity != null);
|
||||
}
|
||||
|
||||
public boolean shouldCarve(int x, int y, int z, double floatingCarveThreshold) {
|
||||
if (!enabled) {
|
||||
return false;
|
||||
}
|
||||
|
||||
double threshold = (thresholdHasNoise ? thresholdDensity.fitDouble(thresholdMin, thresholdMax, x, z)
|
||||
: constantThreshold) - profile.getThresholdBias();
|
||||
threshold += floatingThresholdBias(floatingCarveThreshold);
|
||||
return sampleDensity(x, y, z) <= threshold;
|
||||
}
|
||||
|
||||
double sampleDensity(int x, int y, int z) {
|
||||
if (hasWarp) {
|
||||
return sampleDensityWarped(x, y, z);
|
||||
}
|
||||
|
||||
return sampleDensityUnwarped(x, y, z);
|
||||
}
|
||||
|
||||
private double sampleDensityUnwarped(int x, int y, int z) {
|
||||
double density = baseDensity.noiseFastSigned3D(x, y, z) * baseWeight;
|
||||
density += detailDensity.noiseFastSigned3D(x, y, z) * detailWeight;
|
||||
if (hasModules) {
|
||||
for (ModuleState module : modules) {
|
||||
if (!module.isActive(y)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
density += module.sample(x, y, z);
|
||||
}
|
||||
}
|
||||
|
||||
return density * inverseNormalization;
|
||||
}
|
||||
|
||||
private double sampleDensityWarped(int x, int y, int z) {
|
||||
double warpA = warpDensity.noiseFastSigned3D(x, y, z);
|
||||
double warpB = warpDensity.noiseFastSigned3D(x + 31.37D, y - 17.21D, z + 23.91D);
|
||||
double warpedX = x + (warpA * warpStrength);
|
||||
double warpedY = y + (warpB * warpStrength);
|
||||
double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength);
|
||||
double density = baseDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * baseWeight;
|
||||
density += detailDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * detailWeight;
|
||||
if (hasModules) {
|
||||
for (ModuleState module : modules) {
|
||||
if (!module.isActive(y)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
density += module.sample(warpedX, warpedY, warpedZ);
|
||||
}
|
||||
}
|
||||
|
||||
return density * inverseNormalization;
|
||||
}
|
||||
|
||||
private double floatingThresholdBias(double floatingCarveThreshold) {
|
||||
double clamped = Math.max(0D, Math.min(1D, floatingCarveThreshold));
|
||||
return (1D - clamped) * FLOATING_THRESHOLD_BIAS_SCALE;
|
||||
}
|
||||
|
||||
private static final class ModuleState {
|
||||
private final CNG density;
|
||||
private final int minY;
|
||||
private final int maxY;
|
||||
private final double weight;
|
||||
private final double threshold;
|
||||
private final boolean invert;
|
||||
|
||||
private ModuleState(IrisCaveFieldModule module, CNG density) {
|
||||
IrisRange range = module.getVerticalRange();
|
||||
this.density = density;
|
||||
this.minY = (int) Math.floor(range.getMin());
|
||||
this.maxY = (int) Math.ceil(range.getMax());
|
||||
this.weight = module.getWeight();
|
||||
this.threshold = module.getThreshold();
|
||||
this.invert = module.isInvert();
|
||||
}
|
||||
|
||||
private boolean isActive(int y) {
|
||||
return density != null && y >= minY && y <= maxY;
|
||||
}
|
||||
|
||||
private double sample(double x, double y, double z) {
|
||||
double sampled = density.noiseFastSigned3D(x, y, z);
|
||||
return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.generation.cave.field;
|
||||
|
||||
/**
|
||||
* Where a cave holds pockets of the dimension's fluid: a smooth noise read above a cutoff that rises towards the
|
||||
* fluid height, so pockets fill the deepest parts of a cave first. The noise is stretched to twice its horizontal
|
||||
* size vertically, the way the caves this replaces read theirs.
|
||||
*/
|
||||
public final class AquiferPockets {
|
||||
/** The spacing of the pockets' noise horizontally, in blocks: the SIMPLEX style at zoom 1. */
|
||||
private static final double POCKET_SPACING_BLOCKS = 52.6D;
|
||||
private static final double POCKET_VERTICAL_SPACING_BLOCKS = POCKET_SPACING_BLOCKS * 2D;
|
||||
private static final double CUTOFF_AT_FLUID_HEIGHT = 0.35D;
|
||||
private static final double CUTOFF_RISE_PER_DEPTH_SPAN = 0.2D;
|
||||
private static final double DEPTH_SPAN_BLOCKS = 48D;
|
||||
private static final double MOST_DEPTH_SPANS = 1.5D;
|
||||
private static final String NOISE_NAME = "aquifer.pockets";
|
||||
|
||||
private final Field3 pockets;
|
||||
|
||||
public AquiferPockets(NoiseFactory noise, long seed) {
|
||||
this.pockets = new CaveNoise(noise, seed).named(NOISE_NAME).smooth(POCKET_SPACING_BLOCKS, POCKET_VERTICAL_SPACING_BLOCKS);
|
||||
}
|
||||
|
||||
/** Whether the block at height {@code y} below fluid height {@code fluidHeight} lies in a pocket of fluid. */
|
||||
public boolean holdsFluidAt(int x, int y, int z, int fluidHeight) {
|
||||
double depthSpans = Math.max(0D, Math.min(MOST_DEPTH_SPANS, (fluidHeight - y) / DEPTH_SPAN_BLOCKS));
|
||||
double cutoff = CUTOFF_AT_FLUID_HEIGHT + (depthSpans * CUTOFF_RISE_PER_DEPTH_SPAN);
|
||||
return pockets.at(x, y, z) > cutoff;
|
||||
}
|
||||
}
|
||||
+7
-8
@@ -1,6 +1,6 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
* 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
|
||||
@@ -16,11 +16,10 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.map;
|
||||
package art.arcane.iris.generation.cave.field;
|
||||
|
||||
/**
|
||||
* The block columns a stretch of terrain is sampled at: {@code columns} by {@code rows} from the origin, each
|
||||
* {@code step} blocks wide and deep. Heights stay in blocks whatever the step.
|
||||
*/
|
||||
record TerrainGrid(int originX, int originZ, int columns, int rows, int step) {
|
||||
/** Takes the blocks a cave shape carves in a chunk, by their place in the chunk and their height above the dimension's bottom. */
|
||||
@FunctionalInterface
|
||||
public interface CarveSink {
|
||||
void carve(int localX, int y, int localZ);
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.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<PartShape> 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<CavePart> 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
|
||||
* @param depthRange which heights the cave carves at
|
||||
*/
|
||||
public record ChunkColumns(int[] surfaceY, double[] weight, boolean[] sealed, int[] topLimitY, DepthRange depthRange) {
|
||||
public ChunkColumns(int[] surfaceY, double[] weight, boolean[] sealed, int[] topLimitY) {
|
||||
this(surfaceY, weight, sealed, topLimitY, DepthRange.OWN);
|
||||
}
|
||||
}
|
||||
|
||||
private record PartShape(CavePart part, LatticeShape shape) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 wholeDimension = chunk.depthRange() == DepthRange.WHOLE_DIMENSION;
|
||||
boolean depthVaries = !wholeDimension && (depthMin.varies() || depthMax.varies());
|
||||
int constantClearance = surfaceClearanceAt(originX, originZ);
|
||||
int constantDepthMinY = wholeDimension ? ROCK_KEPT_ABOVE_BOTTOM_BLOCKS : depthMinYAt(originX, originZ);
|
||||
int constantDepthMaxY = wholeDimension ? worldHeight - 1 : depthMaxYAt(originX, originZ);
|
||||
for (int column = 0; column < CaveLimits.CHUNK_COLUMNS; column++) {
|
||||
double x = originX + (column >> 4);
|
||||
double z = originZ + (column & 15);
|
||||
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)));
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
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);
|
||||
}
|
||||
}
|
||||
+7
-7
@@ -1,6 +1,6 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
* 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
|
||||
@@ -16,10 +16,10 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.map;
|
||||
package art.arcane.iris.generation.cave.field;
|
||||
|
||||
/**
|
||||
* A rectangle of a terrain's columns and rows, from the first up to but not including the last.
|
||||
*/
|
||||
record ColumnArea(int fromColumn, int fromRow, int toColumn, int toRow) {
|
||||
/** The shapes a cave is made of, in the order a cave carves them. */
|
||||
public enum CavePart {
|
||||
TUNNEL,
|
||||
CAVERN
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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.
|
||||
*
|
||||
* <p>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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.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;
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<CNG> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.generation.cave.field;
|
||||
|
||||
/** Which heights a cave carves at, before a {@link HeightBand} cuts them off. */
|
||||
public enum DepthRange {
|
||||
/** The depth range the cave writes, or the whole dimension where it writes none. */
|
||||
OWN,
|
||||
/** The whole dimension, whatever the cave writes: for carving the terrain of an upper dimension. */
|
||||
WHOLE_DIMENSION
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.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);
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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];
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.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> PASS = ThreadLocal.withInitial(Pass::new);
|
||||
private static final double CELL_SHARE = 1D / ChunkLattice.CELL_BLOCKS;
|
||||
|
||||
/** How many fields the shape reads. {@link Pass#cell} numbers them from 0. */
|
||||
protected abstract int fieldCount();
|
||||
|
||||
/** Reads every field of the shape at one block into {@code values}, one value per field. */
|
||||
protected abstract void readFields(int x, int y, int z, double[] values);
|
||||
|
||||
/** Whether the shape can carve anywhere in the cell the pass has loaded, whatever the limits allow. */
|
||||
protected abstract boolean mayCarveIn(Pass pass);
|
||||
|
||||
/** Whether the shape carves the block at these shares of the way across the loaded cell. */
|
||||
protected abstract boolean carvesAt(Pass pass, double shareX, double shareY, double shareZ, double openness, int column);
|
||||
|
||||
final void carve(ChunkLattice lattice, CaveLimits limits, CarveSink sink) {
|
||||
Pass pass = PASS.get();
|
||||
pass.begin(lattice, this);
|
||||
for (int cellY = 0; cellY < lattice.cellsY(); cellY++) {
|
||||
int bottomY = lattice.baseY() + (cellY * ChunkLattice.CELL_BLOCKS);
|
||||
if (bottomY > limits.highestY() || bottomY + ChunkLattice.CELL_BLOCKS <= limits.lowestY()) {
|
||||
continue;
|
||||
}
|
||||
for (int cellX = 0; cellX < ChunkLattice.CELLS_PER_CHUNK_AXIS; cellX++) {
|
||||
for (int cellZ = 0; cellZ < ChunkLattice.CELLS_PER_CHUNK_AXIS; cellZ++) {
|
||||
if (limits.cellIsClosed(cellX, cellZ, bottomY)) {
|
||||
continue;
|
||||
}
|
||||
pass.load(cellX, cellY, cellZ);
|
||||
if (mayCarveIn(pass)) {
|
||||
carveCell(pass, limits, sink, cellX, bottomY, cellZ);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void carveCell(Pass pass, CaveLimits limits, CarveSink sink, int cellX, int bottomY, int cellZ) {
|
||||
for (int stepY = 0; stepY < ChunkLattice.CELL_BLOCKS; stepY++) {
|
||||
int y = bottomY + stepY;
|
||||
if (y < limits.lowestY() || y > limits.highestY()) {
|
||||
continue;
|
||||
}
|
||||
for (int stepX = 0; stepX < ChunkLattice.CELL_BLOCKS; stepX++) {
|
||||
int localX = (cellX * ChunkLattice.CELL_BLOCKS) + stepX;
|
||||
for (int stepZ = 0; stepZ < ChunkLattice.CELL_BLOCKS; stepZ++) {
|
||||
int localZ = (cellZ * ChunkLattice.CELL_BLOCKS) + stepZ;
|
||||
int column = (localX << 4) | localZ;
|
||||
double openness = limits.openness(column, y);
|
||||
if (openness > 0D && carvesAt(pass, stepX * CELL_SHARE, stepY * CELL_SHARE, stepZ * CELL_SHARE, openness, column)) {
|
||||
sink.carve(localX, y, localZ);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One chunk's carving by one shape on one thread: the sampled fields, the cell being decided and a value per column. */
|
||||
static final class Pass {
|
||||
private static final int CHUNK_COLUMNS = 256;
|
||||
private static final int CELL_VALUES = 12;
|
||||
|
||||
private ChunkLattice lattice;
|
||||
private double[] pointValues = new double[0];
|
||||
private double[][] values = new double[0][];
|
||||
private LatticeCell[] cells = new LatticeCell[0];
|
||||
private int fieldCount;
|
||||
private final double[] columnValues = new double[CHUNK_COLUMNS];
|
||||
private final double[] cellValues = new double[CELL_VALUES];
|
||||
|
||||
private void begin(ChunkLattice lattice, LatticeShape shape) {
|
||||
this.lattice = lattice;
|
||||
this.fieldCount = shape.fieldCount();
|
||||
if (values.length < fieldCount) {
|
||||
values = Arrays.copyOf(values, fieldCount);
|
||||
cells = Arrays.copyOf(cells, fieldCount);
|
||||
pointValues = new double[fieldCount];
|
||||
}
|
||||
int points = lattice.pointCount();
|
||||
for (int field = 0; field < fieldCount; field++) {
|
||||
if (values[field] == null || values[field].length < points) {
|
||||
values[field] = new double[points];
|
||||
}
|
||||
if (cells[field] == null) {
|
||||
cells[field] = new LatticeCell();
|
||||
}
|
||||
}
|
||||
lattice.forEachPoint((index, x, y, z) -> {
|
||||
shape.readFields(x, y, z, pointValues);
|
||||
for (int field = 0; field < fieldCount; field++) {
|
||||
values[field][index] = pointValues[field];
|
||||
}
|
||||
});
|
||||
Arrays.fill(columnValues, Double.NaN);
|
||||
}
|
||||
|
||||
private void load(int cellX, int cellY, int cellZ) {
|
||||
for (int field = 0; field < fieldCount; field++) {
|
||||
cells[field].load(values[field], lattice, cellX, cellY, cellZ);
|
||||
}
|
||||
}
|
||||
|
||||
LatticeCell cell(int field) {
|
||||
return cells[field];
|
||||
}
|
||||
|
||||
ChunkLattice lattice() {
|
||||
return lattice;
|
||||
}
|
||||
|
||||
/** A value the shape keeps per column of the chunk for the length of the pass; NaN until the shape sets it. */
|
||||
double[] columnValues() {
|
||||
return columnValues;
|
||||
}
|
||||
|
||||
/** Values the shape works out in {@link LatticeShape#mayCarveIn} for the blocks of the loaded cell. */
|
||||
double[] cellValues() {
|
||||
return cellValues;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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.
|
||||
*
|
||||
* <p>A tunnel is every block within its radius of a line. The distance is worked out in blocks from how steeply the
|
||||
* fields change in the cell, so a tunnel keeps the width the pack asks for wherever the noise is steep or shallow.
|
||||
* 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<double[]> 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));
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,6 @@
|
||||
|
||||
package art.arcane.iris.generation.decoration;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.runtime.GenerationFailures;
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.generation.mantle.EngineMantle;
|
||||
@@ -47,7 +46,6 @@ final class DecoratorCore {
|
||||
private static volatile NativeBlockState twistingVines;
|
||||
private static volatile NativeBlockState twistingVinesPlant;
|
||||
|
||||
/** Per-thread placement options; callers clear the mantle reference once a placement returns. */
|
||||
static final ThreadLocal<PlaceOpts> SCRATCH_OPTS = ThreadLocal.withInitial(PlaceOpts::new);
|
||||
|
||||
|
||||
@@ -94,27 +92,25 @@ final class DecoratorCore {
|
||||
}
|
||||
|
||||
static IrisDecorator pickDecorator(IrisBiome biome, IrisDecorationPart part, RNG gRNG,
|
||||
RNG colRng, PackRuntime runtime, double realX, double realZ) {
|
||||
RNG colRng, IrisData data, double realX, double realZ) {
|
||||
IrisDecorator[] bucket = biome.getDecoratorBucket(part);
|
||||
if (bucket.length == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
DecoratorRuntime[] decoratorRuntimes = runtime.biome(biome).decorators(part);
|
||||
IrisDecorator picked = null;
|
||||
int count = 0;
|
||||
|
||||
for (int index = 0; index < bucket.length; index++) {
|
||||
IrisDecorator d = bucket[index];
|
||||
for (IrisDecorator d : bucket) {
|
||||
try {
|
||||
if (d.passesChanceGate(gRNG, realX, realZ, decoratorRuntimes[index])) {
|
||||
if (d.passesChanceGate(gRNG, realX, realZ, data)) {
|
||||
count++;
|
||||
if (count == 1 || colRng.nextInt(count) == 0) {
|
||||
picked = d;
|
||||
}
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
skip(e, d, runtime.data(), (int) realX, -1, (int) realZ, biome);
|
||||
skip(e, d, data, (int) realX, -1, (int) realZ, biome);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,14 +119,14 @@ final class DecoratorCore {
|
||||
|
||||
static void placeSurfaceSingle(IrisDecorator decorator,
|
||||
int x, int z, int realX, int height, int realZ,
|
||||
Hunk<NativeBlockState> data, RNG rng, PackRuntime runtime,
|
||||
Hunk<NativeBlockState> data, RNG rng, IrisData irisData,
|
||||
boolean underwater, boolean caveSkipFluid, EngineMantle mantle) {
|
||||
if (height < 0 || height >= data.getHeight()) {
|
||||
return;
|
||||
}
|
||||
|
||||
NativeBlockState bdx = data.get(x, height, z);
|
||||
NativeBlockState bd = decorator.pickBlockData(rng, runtime, realX, realZ);
|
||||
NativeBlockState bd = decorator.pickBlockData(rng, irisData, realX, realZ);
|
||||
|
||||
if (!IrisSpeleothems.isSpike(bd) && !underwater && !canGoOn(bd, bdx)
|
||||
&& !decorator.isForcePlace() && decorator.getForceBlock() == null) {
|
||||
@@ -142,14 +138,14 @@ final class DecoratorCore {
|
||||
return;
|
||||
}
|
||||
data.set(x, height, z, fixFacesForHunk(
|
||||
decorator.getForceBlock().getBlockData(runtime.data()), data, x, z, realX, height, realZ, mantle));
|
||||
decorator.getForceBlock().getBlockData(irisData), data, x, z, realX, height, realZ, mantle));
|
||||
}
|
||||
|
||||
if (!decorator.isForcePlace()) {
|
||||
if (decorator.getWhitelist() != null && !matchesPalette(decorator.getWhitelistArray(runtime.data()), bdx)) {
|
||||
if (decorator.getWhitelist() != null && !matchesPalette(decorator.getWhitelistArray(irisData), bdx)) {
|
||||
return;
|
||||
}
|
||||
if (decorator.getBlacklist() != null && matchesPalette(decorator.getBlacklistArray(runtime.data()), bdx)) {
|
||||
if (decorator.getBlacklist() != null && matchesPalette(decorator.getBlacklistArray(irisData), bdx)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -180,7 +176,7 @@ final class DecoratorCore {
|
||||
data.set(x, lowerY, z, lower);
|
||||
data.set(x, upperY, z, IrisProceduralBlocks.normalizeWaterlogging(upper, data.get(x, upperY, z), true));
|
||||
} catch (Throwable e) {
|
||||
skip(e, decorator, runtime.data(), realX, lowerY, realZ, null);
|
||||
skip(e, decorator, irisData, realX, lowerY, realZ, null);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -206,8 +202,8 @@ final class DecoratorCore {
|
||||
|
||||
static void placeSingleAt(IrisDecorator decorator, int x, int z,
|
||||
int realX, int height, int realZ, Hunk<NativeBlockState> data,
|
||||
RNG rng, PackRuntime runtime, boolean applyFixFaces, EngineMantle mantle) {
|
||||
NativeBlockState bd = decorator.pickBlockData(rng, runtime, realX, realZ);
|
||||
RNG rng, IrisData irisData, boolean applyFixFaces, EngineMantle mantle) {
|
||||
NativeBlockState bd = decorator.pickBlockData(rng, irisData, realX, realZ);
|
||||
if (bd == null) {
|
||||
return;
|
||||
}
|
||||
@@ -216,7 +212,7 @@ final class DecoratorCore {
|
||||
return;
|
||||
}
|
||||
if (IrisSpeleothems.isSpike(bd)) {
|
||||
if (height + 1 < data.getHeight() && allowsSurface(decorator, data.get(x, height + 1, z), runtime.data())) {
|
||||
if (height + 1 < data.getHeight() && allowsSurface(decorator, data.get(x, height + 1, z), irisData)) {
|
||||
placeSingleSpike(bd, data, x, z, height, false, false);
|
||||
}
|
||||
return;
|
||||
@@ -229,17 +225,17 @@ final class DecoratorCore {
|
||||
|
||||
static void placeStackUp(IrisDecorator decorator, int x, int z, int realX, int realZ,
|
||||
int height, int max, Hunk<NativeBlockState> data,
|
||||
RNG rng, PackRuntime runtime, PlaceOpts opts) {
|
||||
RNG rng, IrisData irisData, PlaceOpts opts) {
|
||||
if (height < 0 || height >= data.getHeight()) {
|
||||
return;
|
||||
}
|
||||
|
||||
NativeBlockState support = data.get(x, height, z);
|
||||
if (!allowsSurface(decorator, support, runtime.data())) {
|
||||
if (!allowsSurface(decorator, support, irisData)) {
|
||||
return;
|
||||
}
|
||||
int effectiveMax = opts.underwater ? Math.min(max, opts.fluidHeight - height) : max;
|
||||
int stack = computeStack(decorator, rng, realX, realZ, runtime, effectiveMax);
|
||||
int stack = computeStack(decorator, rng, realX, realZ, irisData, effectiveMax);
|
||||
int placed = 0;
|
||||
boolean hasSpikes = false;
|
||||
NativeBlockState sampledBlock = null;
|
||||
@@ -258,8 +254,8 @@ final class DecoratorCore {
|
||||
boolean top = threshold >= decorator.getTopThreshold();
|
||||
if (sampledBlock == null || top != sampledTop) {
|
||||
sampledBlock = top
|
||||
? decorator.pickBlockDataTop(rng, runtime, realX, realZ)
|
||||
: decorator.pickBlockData(rng, runtime, realX, realZ);
|
||||
? decorator.pickBlockDataTop(rng, irisData, realX, realZ)
|
||||
: decorator.pickBlockData(rng, irisData, realX, realZ);
|
||||
sampledTop = top;
|
||||
}
|
||||
NativeBlockState block = sampledBlock;
|
||||
@@ -292,15 +288,15 @@ final class DecoratorCore {
|
||||
|
||||
static void placeStackDown(IrisDecorator decorator, int x, int z, int realX, int realZ,
|
||||
int height, int minHeight, Hunk<NativeBlockState> data,
|
||||
RNG rng, PackRuntime runtime, int max, PlaceOpts opts, EngineMantle mantle) {
|
||||
RNG rng, IrisData irisData, int max, PlaceOpts opts, EngineMantle mantle) {
|
||||
if (height < 0 || height >= data.getHeight()) {
|
||||
return;
|
||||
}
|
||||
NativeBlockState support = height + 1 < data.getHeight() ? data.get(x, height + 1, z) : null;
|
||||
if (!allowsSurface(decorator, support, runtime.data())) {
|
||||
if (!allowsSurface(decorator, support, irisData)) {
|
||||
return;
|
||||
}
|
||||
int stack = computeStack(decorator, rng, realX, realZ, runtime, max);
|
||||
int stack = computeStack(decorator, rng, realX, realZ, irisData, max);
|
||||
int placed = 0;
|
||||
boolean hasSpikes = false;
|
||||
NativeBlockState sampledBlock = null;
|
||||
@@ -319,8 +315,8 @@ final class DecoratorCore {
|
||||
boolean top = threshold >= decorator.getTopThreshold();
|
||||
if (sampledBlock == null || top != sampledTop) {
|
||||
sampledBlock = top
|
||||
? decorator.pickBlockDataTop(rng, runtime, realX, realZ)
|
||||
: decorator.pickBlockData(rng, runtime, realX, realZ);
|
||||
? decorator.pickBlockDataTop(rng, irisData, realX, realZ)
|
||||
: decorator.pickBlockData(rng, irisData, realX, realZ);
|
||||
sampledTop = top;
|
||||
}
|
||||
NativeBlockState block = sampledBlock;
|
||||
@@ -353,11 +349,11 @@ final class DecoratorCore {
|
||||
static void placeFloatingSimple(IrisDecorator decorator,
|
||||
int xf, int zf, int realX, int realZ,
|
||||
int height, int max, Hunk<NativeBlockState> data,
|
||||
RNG rng, PackRuntime runtime, EngineMantle mantle) {
|
||||
RNG rng, IrisData irisData, EngineMantle mantle) {
|
||||
if (!hasFloatingSurface(data, xf, height, zf)) {
|
||||
return;
|
||||
}
|
||||
NativeBlockState bd = decorator.pickBlockData(rng, runtime, realX, realZ);
|
||||
NativeBlockState bd = decorator.pickBlockData(rng, irisData, realX, realZ);
|
||||
if (bd == null) {
|
||||
return;
|
||||
}
|
||||
@@ -367,7 +363,7 @@ final class DecoratorCore {
|
||||
}
|
||||
|
||||
if (IrisSpeleothems.isSpike(bd)) {
|
||||
if (max > 1 && allowsSurface(decorator, data.get(xf, height, zf), runtime.data())) {
|
||||
if (max > 1 && allowsSurface(decorator, data.get(xf, height, zf), irisData)) {
|
||||
placeSingleSpike(bd, data, xf, zf, height + 1, true, false);
|
||||
}
|
||||
return;
|
||||
@@ -387,7 +383,7 @@ final class DecoratorCore {
|
||||
data.set(xf, lowerY, zf, IrisProceduralBlocks.normalizeWaterlogging(lower, data.get(xf, lowerY, zf), true));
|
||||
data.set(xf, upperY, zf, IrisProceduralBlocks.normalizeWaterlogging(upper, data.get(xf, upperY, zf), true));
|
||||
} catch (Throwable e) {
|
||||
skip(e, decorator, runtime.data(), realX, lowerY, realZ, null);
|
||||
skip(e, decorator, irisData, realX, lowerY, realZ, null);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -400,11 +396,11 @@ final class DecoratorCore {
|
||||
static int placeFloatingStacked(IrisDecorator decorator,
|
||||
int xf, int zf, int realX, int realZ,
|
||||
int height, int max, Hunk<NativeBlockState> data,
|
||||
RNG rng, PackRuntime runtime, EngineMantle mantle) {
|
||||
RNG rng, IrisData irisData, EngineMantle mantle) {
|
||||
if (!hasFloatingSurface(data, xf, height, zf)) {
|
||||
return 0;
|
||||
}
|
||||
int stack = decorator.getHeight(rng, realX, realZ, runtime);
|
||||
int stack = decorator.getHeight(rng, realX, realZ, irisData);
|
||||
if (decorator.isScaleStack()) {
|
||||
stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.getAbsoluteMaxStack());
|
||||
} else {
|
||||
@@ -424,8 +420,8 @@ final class DecoratorCore {
|
||||
boolean top = threshold >= decorator.getTopThreshold();
|
||||
if (sampledBlock == null || top != sampledTop) {
|
||||
sampledBlock = top
|
||||
? decorator.pickBlockDataTop(rng, runtime, realX, realZ)
|
||||
: decorator.pickBlockData(rng, runtime, realX, realZ);
|
||||
? decorator.pickBlockDataTop(rng, irisData, realX, realZ)
|
||||
: decorator.pickBlockData(rng, irisData, realX, realZ);
|
||||
sampledTop = top;
|
||||
}
|
||||
NativeBlockState bd = sampledBlock;
|
||||
@@ -437,7 +433,7 @@ final class DecoratorCore {
|
||||
break;
|
||||
}
|
||||
if (IrisSpeleothems.isSpike(bd)) {
|
||||
if (!allowsSurface(decorator, data.get(xf, height, zf), runtime.data())
|
||||
if (!allowsSurface(decorator, data.get(xf, height, zf), irisData)
|
||||
|| !IrisSpeleothems.canPlace(bd, data, xf, zf, h, true, false)) {
|
||||
break;
|
||||
}
|
||||
@@ -585,8 +581,8 @@ final class DecoratorCore {
|
||||
}
|
||||
|
||||
static int computeStack(IrisDecorator decorator, RNG rng, double realX, double realZ,
|
||||
PackRuntime runtime, int max) {
|
||||
int stack = decorator.getHeight(rng, realX, realZ, runtime);
|
||||
IrisData irisData, int max) {
|
||||
int stack = decorator.getHeight(rng, realX, realZ, irisData);
|
||||
if (decorator.isScaleStack()) {
|
||||
stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.getAbsoluteMaxStack());
|
||||
} else {
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.generation.decoration;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.runtime.SeedTable;
|
||||
import art.arcane.volmlib.util.noise.CNG;
|
||||
|
||||
/** What one engine derives from an {@link IrisDecorator}: the stack, placement and variance generators of each seed. */
|
||||
public final class DecoratorRuntime {
|
||||
private static final int SEED_CAPACITY = 32;
|
||||
|
||||
private final PackRuntime runtime;
|
||||
private final SeedTable<CNG> heightGenerators;
|
||||
private final SeedTable<CNG> layerGenerators;
|
||||
private final SeedTable<CNG> varianceGenerators;
|
||||
|
||||
public DecoratorRuntime(IrisDecorator decorator, PackRuntime runtime) {
|
||||
this.runtime = runtime;
|
||||
this.heightGenerators = new SeedTable<>(SEED_CAPACITY, seed -> decorator.createHeightGenerator(seed, runtime));
|
||||
this.layerGenerators = new SeedTable<>(SEED_CAPACITY, seed -> decorator.createLayerGenerator(seed, runtime));
|
||||
this.varianceGenerators = new SeedTable<>(SEED_CAPACITY, seed -> decorator.createVarianceGenerator(seed, runtime));
|
||||
}
|
||||
|
||||
/** The scope this runtime was built in, whose pack data resolves the decorator's palettes. */
|
||||
public PackRuntime packRuntime() {
|
||||
return runtime;
|
||||
}
|
||||
|
||||
public CNG heightGenerator(long seed) {
|
||||
return heightGenerators.get(seed);
|
||||
}
|
||||
|
||||
public CNG layerGenerator(long seed) {
|
||||
return layerGenerators.get(seed);
|
||||
}
|
||||
|
||||
public CNG varianceGenerator(long seed) {
|
||||
return varianceGenerators.get(seed);
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.generation.decoration;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.runtime.SeedTable;
|
||||
import art.arcane.iris.structure.object.IrisObject;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
|
||||
/**
|
||||
* What one engine derives from an {@link IrisDepositGenerator}: the clump variants of the engine's deposit seed, at
|
||||
* the configured size and at each scaled size the deposit modifier asks for.
|
||||
*/
|
||||
public final class DepositRuntime {
|
||||
private static final int SCALED_SIZE_CAPACITY = 64;
|
||||
|
||||
private final IrisDepositGenerator deposit;
|
||||
private final PackRuntime runtime;
|
||||
private final long depositSeed;
|
||||
private final SeedTable<KList<IrisObject>> scaledClumps;
|
||||
private volatile KList<IrisObject> clumps;
|
||||
|
||||
public DepositRuntime(IrisDepositGenerator deposit, PackRuntime runtime) {
|
||||
this.deposit = deposit;
|
||||
this.runtime = runtime;
|
||||
this.depositSeed = runtime.engine().getSeedManager().getDeposit();
|
||||
this.scaledClumps = new SeedTable<>(SCALED_SIZE_CAPACITY, sizes -> deposit.createScaledClumps(
|
||||
depositSeed, minSize(sizes), maxSize(sizes), runtime.data()));
|
||||
}
|
||||
|
||||
public KList<IrisObject> clumps() {
|
||||
KList<IrisObject> built = clumps;
|
||||
if (built != null) {
|
||||
return built;
|
||||
}
|
||||
synchronized (this) {
|
||||
if (clumps == null) {
|
||||
clumps = deposit.createClumps(depositSeed, runtime.data());
|
||||
}
|
||||
return clumps;
|
||||
}
|
||||
}
|
||||
|
||||
public KList<IrisObject> scaledClumps(int minSize, int maxSize) {
|
||||
return scaledClumps.get(sizeKey(minSize, maxSize));
|
||||
}
|
||||
|
||||
private static long sizeKey(int minSize, int maxSize) {
|
||||
return ((long) minSize << 32) | (maxSize & 0xffffffffL);
|
||||
}
|
||||
|
||||
private static int minSize(long sizeKey) {
|
||||
return (int) (sizeKey >>> 32);
|
||||
}
|
||||
|
||||
private static int maxSize(long sizeKey) {
|
||||
return (int) sizeKey;
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,6 @@
|
||||
|
||||
package art.arcane.iris.generation.decoration;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.generation.biome.IrisBiome;
|
||||
import art.arcane.volmlib.util.hunk.Hunk;
|
||||
@@ -37,8 +36,7 @@ public class FloatingDecorator {
|
||||
int height, int max, Hunk<NativeBlockState> data, RNG rng,
|
||||
Runnable candidatesNullCallback) {
|
||||
RNG gRNG = new RNG(DecoratorCore.partSeed(engine.getSeedManager().getComponent(), part));
|
||||
PackRuntime runtime = PackRuntime.of(engine);
|
||||
IrisDecorator decorator = DecoratorCore.pickDecorator(target, part, gRNG, rng, runtime, realX, realZ);
|
||||
IrisDecorator decorator = DecoratorCore.pickDecorator(target, part, gRNG, rng, engine.getData(), realX, realZ);
|
||||
|
||||
if (decorator == null) {
|
||||
candidatesNullCallback.run();
|
||||
@@ -47,11 +45,11 @@ public class FloatingDecorator {
|
||||
|
||||
if (!decorator.isStacking()) {
|
||||
DecoratorCore.placeFloatingSimple(decorator, xf, zf, realX, realZ, height, max, data,
|
||||
gRNG, runtime, engine.getMantle());
|
||||
gRNG, engine.getData(), engine.getMantle());
|
||||
return max > 1 ? 1 : 0;
|
||||
}
|
||||
|
||||
return DecoratorCore.placeFloatingStacked(decorator, xf, zf, realX, realZ, height, max, data,
|
||||
gRNG, runtime, engine.getMantle());
|
||||
gRNG, engine.getData(), engine.getMantle());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package art.arcane.iris.generation.decoration;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.block.B;
|
||||
import art.arcane.iris.generation.block.IrisBlockData;
|
||||
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
|
||||
@@ -33,7 +32,7 @@ public final class HydrologyVegetation {
|
||||
this.shoreRng = new RNG(DecoratorCore.partSeed(this.seed, IrisDecorationPart.SHORE_LINE));
|
||||
}
|
||||
|
||||
public void decorate(Hunk<NativeBlockState> output, int localX, int localZ, int x, int z, WaterRole role, Water water, PackRuntime runtime) {
|
||||
public void decorate(Hunk<NativeBlockState> output, int localX, int localZ, int x, int z, WaterRole role, Water water, IrisData data) {
|
||||
Placement placement = placement(role);
|
||||
if (placement == Placement.NONE) {
|
||||
return;
|
||||
@@ -46,7 +45,7 @@ public final class HydrologyVegetation {
|
||||
if (ground < 0 || ground + 1 >= output.getHeight()) {
|
||||
return;
|
||||
}
|
||||
Column column = new Column(output, localX, localZ, x, z, ground, water, runtime);
|
||||
Column column = new Column(output, localX, localZ, x, z, ground, water, data);
|
||||
if (placement == Placement.SHORE) {
|
||||
decorateShore(column, decorators.shore);
|
||||
return;
|
||||
@@ -113,7 +112,7 @@ public final class HydrologyVegetation {
|
||||
int count = 0;
|
||||
for (IrisDecorator decorator : bucket) {
|
||||
try {
|
||||
if (!decorator.passesChanceGate(partRng, column.x, column.z, column.runtime)) {
|
||||
if (!decorator.passesChanceGate(partRng, column.x, column.z, column.data)) {
|
||||
continue;
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
@@ -214,10 +213,9 @@ public final class HydrologyVegetation {
|
||||
private final int z;
|
||||
private final int ground;
|
||||
private final Water water;
|
||||
private final PackRuntime runtime;
|
||||
private final IrisData data;
|
||||
|
||||
private Column(Hunk<NativeBlockState> output, int localX, int localZ, int x, int z, int ground, Water water, PackRuntime runtime) {
|
||||
private Column(Hunk<NativeBlockState> output, int localX, int localZ, int x, int z, int ground, Water water, IrisData data) {
|
||||
this.output = output;
|
||||
this.localX = localX;
|
||||
this.localZ = localZ;
|
||||
@@ -225,8 +223,7 @@ public final class HydrologyVegetation {
|
||||
this.z = z;
|
||||
this.ground = ground;
|
||||
this.water = water;
|
||||
this.runtime = runtime;
|
||||
this.data = runtime.data();
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
private boolean accepts(IrisDecorator decorator, NativeBlockState support) {
|
||||
@@ -234,7 +231,7 @@ public final class HydrologyVegetation {
|
||||
}
|
||||
|
||||
private int stack(IrisDecorator decorator, RNG rng, int room) {
|
||||
return decorator.isStacking() ? Math.min(room, DecoratorCore.computeStack(decorator, rng, x, z, runtime, room)) : 1;
|
||||
return decorator.isStacking() ? Math.min(room, DecoratorCore.computeStack(decorator, rng, x, z, data, room)) : 1;
|
||||
}
|
||||
|
||||
private void place(IrisDecorator decorator, RNG rng, int baseY, int room, Slot slot, NativeBlockState support) {
|
||||
@@ -246,7 +243,7 @@ public final class HydrologyVegetation {
|
||||
}
|
||||
|
||||
private void placePicked(IrisDecorator decorator, RNG rng, int baseY, int room, Slot slot, NativeBlockState support) {
|
||||
NativeBlockState first = decorator.pickBlockData(rng, runtime, x, z);
|
||||
NativeBlockState first = decorator.pickBlockData(rng, data, x, z);
|
||||
if (first == null) {
|
||||
return;
|
||||
}
|
||||
@@ -263,7 +260,7 @@ public final class HydrologyVegetation {
|
||||
int y = baseY + index;
|
||||
boolean top = (stack == 1 ? 1D : (double) index / (stack - 1)) >= decorator.getTopThreshold();
|
||||
if (top != sampledTop) {
|
||||
sampled = top ? decorator.pickBlockDataTop(rng, runtime, x, z) : decorator.pickBlockData(rng, runtime, x, z);
|
||||
sampled = top ? decorator.pickBlockDataTop(rng, data, x, z) : decorator.pickBlockData(rng, data, x, z);
|
||||
sampledTop = top;
|
||||
}
|
||||
NativeBlockState block = sampled == null ? null : fit(sampled, y, slot, decorator, index == 0 ? support : null);
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
|
||||
package art.arcane.iris.generation.decoration;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.generation.terrain.InferredType;
|
||||
import art.arcane.iris.generation.biome.IrisBiome;
|
||||
@@ -48,22 +47,21 @@ public class IrisCeilingDecorator extends IrisEngineDecorator {
|
||||
Hunk<NativeBlockState> data, IrisBiome biome, InferredType inferredType, int height, int max) {
|
||||
boolean caveSkipFluid = IrisSurfaceDecorator.skipsFluid(inferredType);
|
||||
RNG rng = getRNG(realX, realZ);
|
||||
PackRuntime runtime = PackRuntime.of(getEngine(), getData());
|
||||
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ);
|
||||
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
|
||||
|
||||
if (decorator == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
place(decorator, x, z, realX, realZ, data, height, max, caveSkipFluid, runtime);
|
||||
place(decorator, x, z, realX, realZ, data, height, max, caveSkipFluid);
|
||||
} catch (Throwable e) {
|
||||
DecoratorCore.skip(e, decorator, getData(), realX, height, realZ, biome);
|
||||
}
|
||||
}
|
||||
|
||||
private void place(IrisDecorator decorator, int x, int z, int realX, int realZ, Hunk<NativeBlockState> data,
|
||||
int height, int max, boolean caveSkipFluid, PackRuntime runtime) {
|
||||
int height, int max, boolean caveSkipFluid) {
|
||||
if (!decorator.isStacking()) {
|
||||
if (caveSkipFluid) {
|
||||
NativeBlockState state = data.get(x, height, z);
|
||||
@@ -71,13 +69,13 @@ public class IrisCeilingDecorator extends IrisEngineDecorator {
|
||||
return;
|
||||
}
|
||||
}
|
||||
DecoratorCore.placeSingleAt(decorator, x, z, realX, height, realZ, data, partRNG, runtime, true, getEngine().getMantle());
|
||||
DecoratorCore.placeSingleAt(decorator, x, z, realX, height, realZ, data, partRNG, getData(), true, getEngine().getMantle());
|
||||
return;
|
||||
}
|
||||
|
||||
DecoratorCore.PlaceOpts opts = DecoratorCore.SCRATCH_OPTS.get();
|
||||
opts.reset();
|
||||
opts.caveSkipFluid = caveSkipFluid;
|
||||
DecoratorCore.placeStackDown(decorator, x, z, realX, realZ, height, 0, data, partRNG, runtime, max, opts, getEngine().getMantle());
|
||||
DecoratorCore.placeStackDown(decorator, x, z, realX, realZ, height, 0, data, partRNG, getData(), max, opts, getEngine().getMantle());
|
||||
}
|
||||
}
|
||||
@@ -18,9 +18,9 @@
|
||||
|
||||
package art.arcane.iris.generation.decoration;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.biome.IrisBiome;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.generation.cache.LazyBoundedCache;
|
||||
import art.arcane.iris.generation.block.IrisBlockData;
|
||||
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
|
||||
import art.arcane.iris.generation.noise.NoiseStyle;
|
||||
@@ -52,6 +52,8 @@ import lombok.experimental.Accessors;
|
||||
@Description("A biome decorator is used for placing flowers, grass, cacti and so on")
|
||||
@Data
|
||||
public class IrisDecorator {
|
||||
private final transient LazyBoundedCache<GeneratorKey, Generators> generators = new LazyBoundedCache<>(32);
|
||||
private transient volatile Generators recentGenerators;
|
||||
private final transient AtomicCache<KList<NativeBlockState>> blockData = new AtomicCache<>();
|
||||
private final transient AtomicCache<KList<NativeBlockState>> blockDataTops = new AtomicCache<>();
|
||||
private final transient AtomicCache<NativeBlockState[]> blockDataArray = new AtomicCache<>();
|
||||
@@ -116,39 +118,50 @@ public class IrisDecorator {
|
||||
@Description("When the stack passes the top threshold, the top palette will start being used instead of the normal palette.")
|
||||
private double topThreshold = 1.0;
|
||||
|
||||
public int getHeight(RNG rng, double x, double z, PackRuntime runtime) {
|
||||
public int getHeight(RNG rng, double x, double z, IrisData data) {
|
||||
if (stackMin == stackMax) {
|
||||
return stackMin;
|
||||
}
|
||||
|
||||
return getHeightGenerator(rng, runtime)
|
||||
return getHeightGenerator(rng, data)
|
||||
.fit(stackMin, stackMax,
|
||||
x / heightVariance.getZoom(),
|
||||
z / heightVariance.getZoom());
|
||||
}
|
||||
|
||||
public CNG getHeightGenerator(RNG rng, PackRuntime runtime) {
|
||||
return runtime.decorator(this).heightGenerator(rng.getSeed());
|
||||
public CNG getHeightGenerator(RNG rng, IrisData data) {
|
||||
AtomicCache<CNG> cache = generators(rng, data).height;
|
||||
CNG cached = cache.getIfPresent();
|
||||
return cached != null ? cached : cache.aquire(() ->
|
||||
heightVariance.create(rng.nextParallelRNG(getBlockData(data).size() + stackMax + stackMin), data));
|
||||
}
|
||||
|
||||
public CNG getGenerator(RNG rng, PackRuntime runtime) {
|
||||
return runtime.decorator(this).layerGenerator(rng.getSeed());
|
||||
public CNG getGenerator(RNG rng, IrisData data) {
|
||||
AtomicCache<CNG> cache = generators(rng, data).layer;
|
||||
CNG cached = cache.getIfPresent();
|
||||
return cached != null ? cached : cache.aquire(() -> style.create(rng.nextParallelRNG(getBlockData(data).size()), data));
|
||||
}
|
||||
|
||||
public CNG getVarianceGenerator(RNG rng, PackRuntime runtime) {
|
||||
return runtime.decorator(this).varianceGenerator(rng.getSeed());
|
||||
public CNG getVarianceGenerator(RNG rng, IrisData data) {
|
||||
AtomicCache<CNG> cache = generators(rng, data).variance;
|
||||
CNG cached = cache.getIfPresent();
|
||||
return cached != null ? cached : cache.aquire(() -> createVarianceGenerator(rng, data));
|
||||
}
|
||||
|
||||
public CNG createHeightGenerator(long seed, PackRuntime runtime) {
|
||||
return heightVariance.create(new RNG(seed).nextParallelRNG(getBlockData(runtime.data()).size() + stackMax + stackMin), runtime);
|
||||
private Generators generators(RNG rng, IrisData data) {
|
||||
long seed = rng.getSeed();
|
||||
Engine engine = data == null ? null : data.getEngine();
|
||||
Generators recent = recentGenerators;
|
||||
if (recent != null && recent.key.seed == seed && recent.key.data == data && recent.key.engine == engine) {
|
||||
return recent;
|
||||
}
|
||||
Generators selected = generators.computeIfAbsent(new GeneratorKey(seed, data, engine), Generators::new);
|
||||
recentGenerators = selected;
|
||||
return selected;
|
||||
}
|
||||
|
||||
public CNG createLayerGenerator(long seed, PackRuntime runtime) {
|
||||
return style.create(new RNG(seed).nextParallelRNG(getBlockData(runtime.data()).size()), runtime);
|
||||
}
|
||||
|
||||
public CNG createVarianceGenerator(long seed, PackRuntime runtime) {
|
||||
return variance.createNoCache(deriveVarianceSeed(new RNG(seed), runtime.data()), runtime).scale(1D / variance.getZoom());
|
||||
private CNG createVarianceGenerator(RNG rng, IrisData data) {
|
||||
return variance.createNoCache(deriveVarianceSeed(rng, data), data).scale(1D / variance.getZoom());
|
||||
}
|
||||
|
||||
RNG deriveVarianceSeed(RNG rng, IrisData data) {
|
||||
@@ -160,38 +173,27 @@ public class IrisDecorator {
|
||||
return palette;
|
||||
}
|
||||
|
||||
public boolean passesChanceGate(RNG rng, double x, double z, PackRuntime runtime) {
|
||||
return passesChanceGate(rng, x, z, runtime.decorator(this));
|
||||
}
|
||||
|
||||
/** {@link #passesChanceGate(RNG, double, double, PackRuntime)} for a caller that already holds this decorator's runtime. */
|
||||
public boolean passesChanceGate(RNG rng, double x, double z, DecoratorRuntime decoratorRuntime) {
|
||||
if (getBlockData(decoratorRuntime.packRuntime().data()).isEmpty()) {
|
||||
public boolean passesChanceGate(RNG rng, double x, double z, IrisData data) {
|
||||
if (getBlockData(data).isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
double blocksPerSample = chanceBlocksPerSample();
|
||||
double xx = x / blocksPerSample;
|
||||
double zz = z / blocksPerSample;
|
||||
return decoratorRuntime.layerGenerator(rng.getSeed()).fitDouble(0D, 1D, xx, zz) <= chance;
|
||||
double xx = x / style.getZoom();
|
||||
double zz = z / style.getZoom();
|
||||
return getGenerator(rng, data).fitDouble(0D, 1D, xx, zz) <= chance;
|
||||
}
|
||||
|
||||
/** A style without a seed divides by its zoom here on top of its own scale; a seeded one is read in plain blocks. */
|
||||
private double chanceBlocksPerSample() {
|
||||
return style.isSeeded() ? 1 : style.getZoom();
|
||||
}
|
||||
|
||||
public NativeBlockState getBlockData(IrisBiome b, RNG rng, double x, double z, PackRuntime runtime) {
|
||||
if (!passesChanceGate(rng, x, z, runtime)) {
|
||||
public NativeBlockState getBlockData(IrisBiome b, RNG rng, double x, double z, IrisData data) {
|
||||
if (!passesChanceGate(rng, x, z, data)) {
|
||||
return null;
|
||||
}
|
||||
if (getBlockData(runtime.data()).size() == 1) {
|
||||
return getBlockData(runtime.data()).get(0);
|
||||
if (getBlockData(data).size() == 1) {
|
||||
return getBlockData(data).get(0);
|
||||
}
|
||||
return getVarianceGenerator(rng, runtime).fit(getBlockData(runtime.data()), z, x);
|
||||
return getVarianceGenerator(rng, data).fit(getBlockData(data), z, x);
|
||||
}
|
||||
|
||||
public NativeBlockState getBlockData100(IrisBiome b, RNG rng, double x, double y, double z, PackRuntime runtime) {
|
||||
KList<NativeBlockState> palette = getBlockData(runtime.data());
|
||||
public NativeBlockState getBlockData100(IrisBiome b, RNG rng, double x, double y, double z, IrisData data) {
|
||||
KList<NativeBlockState> palette = getBlockData(data);
|
||||
if (palette.isEmpty()) {
|
||||
IrisLogging.warnOnce("decorator-empty:" + b.getName(), "Empty Block Data for " + b.getName());
|
||||
return null;
|
||||
@@ -201,25 +203,24 @@ public class IrisDecorator {
|
||||
return palette.get(0);
|
||||
}
|
||||
|
||||
return getVarianceGenerator(rng, runtime).fit(palette, z, y, x); //X and Z must be switched
|
||||
return getVarianceGenerator(rng, data).fit(palette, z, y, x); //X and Z must be switched
|
||||
}
|
||||
|
||||
public NativeBlockState getBlockDataForTop(IrisBiome b, RNG rng, double x, double y, double z, PackRuntime runtime) {
|
||||
KList<NativeBlockState> topPalette = getBlockDataTops(runtime.data());
|
||||
public NativeBlockState getBlockDataForTop(IrisBiome b, RNG rng, double x, double y, double z, IrisData data) {
|
||||
KList<NativeBlockState> topPalette = getBlockDataTops(data);
|
||||
if (topPalette.isEmpty()) {
|
||||
return getBlockData100(b, rng, x, y, z, runtime);
|
||||
return getBlockData100(b, rng, x, y, z, data);
|
||||
}
|
||||
|
||||
double blocksPerSample = chanceBlocksPerSample();
|
||||
double xx = x / blocksPerSample;
|
||||
double zz = z / blocksPerSample;
|
||||
double xx = x / style.getZoom();
|
||||
double zz = z / style.getZoom();
|
||||
|
||||
if (getGenerator(rng, runtime).fitDouble(0D, 1D, xx, zz) <= chance) { //Exclude y from here
|
||||
if (getGenerator(rng, data).fitDouble(0D, 1D, xx, zz) <= chance) { //Exclude y from here
|
||||
if (topPalette.size() == 1) {
|
||||
return topPalette.get(0);
|
||||
}
|
||||
|
||||
return getVarianceGenerator(rng, runtime).fit(topPalette, z, y, x); //X and Z must be switched
|
||||
return getVarianceGenerator(rng, data).fit(topPalette, z, y, x); //X and Z must be switched
|
||||
}
|
||||
|
||||
return null;
|
||||
@@ -335,30 +336,55 @@ public class IrisDecorator {
|
||||
return resolved;
|
||||
}
|
||||
|
||||
public NativeBlockState pickBlockData(RNG rng, PackRuntime runtime, double x, double z) {
|
||||
NativeBlockState[] arr = getBlockDataArray(runtime.data());
|
||||
public NativeBlockState pickBlockData(RNG rng, IrisData data, double x, double z) {
|
||||
NativeBlockState[] arr = getBlockDataArray(data);
|
||||
if (arr.length == 0) {
|
||||
return null;
|
||||
}
|
||||
if (arr.length == 1) {
|
||||
return arr[0];
|
||||
}
|
||||
return arr[Math.abs((int) getVarianceGenerator(rng, runtime).fit(0, arr.length - 1, z, x))];
|
||||
return arr[Math.abs((int) getVarianceGenerator(rng, data).fit(0, arr.length - 1, z, x))];
|
||||
}
|
||||
|
||||
public NativeBlockState pickBlockDataTop(RNG rng, PackRuntime runtime, double x, double z) {
|
||||
NativeBlockState[] arr = getBlockDataTopsArray(runtime.data());
|
||||
public NativeBlockState pickBlockDataTop(RNG rng, IrisData data, double x, double z) {
|
||||
NativeBlockState[] arr = getBlockDataTopsArray(data);
|
||||
if (arr.length == 0) {
|
||||
return pickBlockData(rng, runtime, x, z);
|
||||
return pickBlockData(rng, data, x, z);
|
||||
}
|
||||
if (arr.length == 1) {
|
||||
return arr[0];
|
||||
}
|
||||
return arr[Math.abs((int) getVarianceGenerator(rng, runtime).fit(0, arr.length - 1, z, x))];
|
||||
return arr[Math.abs((int) getVarianceGenerator(rng, data).fit(0, arr.length - 1, z, x))];
|
||||
}
|
||||
|
||||
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
|
||||
public boolean isStacking() {
|
||||
return getStackMax() > 1;
|
||||
}
|
||||
|
||||
private static final class Generators {
|
||||
private final GeneratorKey key;
|
||||
private final AtomicCache<CNG> layer = new AtomicCache<>();
|
||||
private final AtomicCache<CNG> variance = new AtomicCache<>();
|
||||
private final AtomicCache<CNG> height = new AtomicCache<>();
|
||||
|
||||
private Generators(GeneratorKey key) {
|
||||
this.key = key;
|
||||
}
|
||||
}
|
||||
|
||||
private record GeneratorKey(long seed, IrisData data, Engine engine) {
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
return other instanceof GeneratorKey key
|
||||
&& seed == key.seed && data == key.data && engine == key.engine;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return 31 * (31 * Long.hashCode(seed) + System.identityHashCode(data))
|
||||
+ System.identityHashCode(engine);
|
||||
}
|
||||
}
|
||||
}
|
||||
+37
-26
@@ -18,7 +18,6 @@
|
||||
|
||||
package art.arcane.iris.generation.decoration;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.biome.IrisBiome;
|
||||
import art.arcane.iris.generation.block.IrisBlockData;
|
||||
import art.arcane.iris.structure.object.IrisObject;
|
||||
@@ -63,10 +62,12 @@ public class IrisDepositGenerator {
|
||||
private static final long FNV_OFFSET_BASIS = 0xcbf29ce484222325L;
|
||||
private static final long FNV_PRIME = 0x100000001b3L;
|
||||
|
||||
private final transient ConcurrentMap<ClumpCacheKey, KList<IrisObject>> objects = new ConcurrentHashMap<>();
|
||||
private final transient AtomicCache<KList<NativeBlockState>> blockData = new AtomicCache<>();
|
||||
private final transient AtomicCache<Boolean> ore = new AtomicCache<>();
|
||||
private final transient AtomicCache<KSet<String>> replaceableBlockData = new AtomicCache<>();
|
||||
private final transient AtomicCache<KSet<String>> surfaceReplaceableBlockData = new AtomicCache<>();
|
||||
private final transient ConcurrentMap<ClumpCacheKey, KList<IrisObject>> scaledObjects = new ConcurrentHashMap<>();
|
||||
@Required
|
||||
@MinNumber(-8192)
|
||||
@MaxNumber(8192)
|
||||
@@ -144,47 +145,54 @@ public class IrisDepositGenerator {
|
||||
@Description("If set to true, this deposit will replace bedrock")
|
||||
private boolean replaceBedrock = false;
|
||||
|
||||
public IrisObject getClump(PackRuntime runtime, RNG rng) {
|
||||
public IrisObject getClump(Engine engine, RNG rng, IrisData rdata) {
|
||||
if (shape != IrisDepositShape.IRIS) {
|
||||
return generateConfiguredClumpObject(rng, runtime.data(), minSize, maxSize);
|
||||
return generateConfiguredClumpObject(rng, rdata, minSize, maxSize);
|
||||
}
|
||||
|
||||
KList<IrisObject> objects = runtime.deposit(this).clumps();
|
||||
ClumpCacheKey cacheKey = new ClumpCacheKey(engine.getSeedManager().getDeposit(), minSize, maxSize);
|
||||
KList<IrisObject> objects = this.objects.computeIfAbsent(cacheKey, key -> {
|
||||
RNG rngv = new RNG(key.depositSeed() + stableClumpSalt(rdata));
|
||||
KList<IrisObject> objectsf = new KList<>();
|
||||
|
||||
for (int i = 0; i < varience; i++) {
|
||||
objectsf.add(generateClumpObject(
|
||||
rngv.nextParallelRNG(2349 * i + 3598), rdata, key.minSize(), key.maxSize()));
|
||||
}
|
||||
|
||||
return objectsf;
|
||||
});
|
||||
return objects.get(rng.i(0, objects.size()));
|
||||
}
|
||||
|
||||
public IrisObject getClump(PackRuntime runtime, RNG rng, double sizeMultiplier) {
|
||||
public IrisObject getClump(Engine engine, RNG rng, IrisData rdata, double sizeMultiplier) {
|
||||
if (sizeMultiplier == 1D) {
|
||||
return getClump(runtime, rng);
|
||||
return getClump(engine, rng, rdata);
|
||||
}
|
||||
|
||||
int scaledMinSize = scaledDepositSize(minSize, sizeMultiplier);
|
||||
int scaledMaxSize = scaledDepositSize(maxSize, sizeMultiplier);
|
||||
if (shape != IrisDepositShape.IRIS) {
|
||||
return generateConfiguredClumpObject(rng, runtime.data(), scaledMinSize, scaledMaxSize);
|
||||
return generateConfiguredClumpObject(rng, rdata, scaledMinSize, scaledMaxSize);
|
||||
}
|
||||
|
||||
KList<IrisObject> objects = runtime.deposit(this).scaledClumps(scaledMinSize, scaledMaxSize);
|
||||
ClumpCacheKey cacheKey = new ClumpCacheKey(
|
||||
engine.getSeedManager().getDeposit(), scaledMinSize, scaledMaxSize);
|
||||
KList<IrisObject> objects = scaledObjects.computeIfAbsent(cacheKey, key -> {
|
||||
long sizeSeed = ((long) key.minSize() << 32) ^ (key.maxSize() & 0xffffffffL);
|
||||
RNG rngv = new RNG(key.depositSeed() + stableClumpSalt(rdata) + sizeSeed);
|
||||
KList<IrisObject> generated = new KList<>();
|
||||
|
||||
for (int i = 0; i < varience; i++) {
|
||||
generated.add(generateClumpObject(
|
||||
rngv.nextParallelRNG(2349 * i + 3598), rdata, key.minSize(), key.maxSize()));
|
||||
}
|
||||
|
||||
return generated;
|
||||
});
|
||||
return objects.get(rng.i(0, objects.size()));
|
||||
}
|
||||
|
||||
public KList<IrisObject> createClumps(long depositSeed, IrisData rdata) {
|
||||
return createClumpVariants(new RNG(depositSeed + stableClumpSalt(rdata)), rdata, minSize, maxSize);
|
||||
}
|
||||
|
||||
public KList<IrisObject> createScaledClumps(long depositSeed, int scaledMinSize, int scaledMaxSize, IrisData rdata) {
|
||||
long sizeSeed = ((long) scaledMinSize << 32) ^ (scaledMaxSize & 0xffffffffL);
|
||||
return createClumpVariants(new RNG(depositSeed + stableClumpSalt(rdata) + sizeSeed), rdata, scaledMinSize, scaledMaxSize);
|
||||
}
|
||||
|
||||
private KList<IrisObject> createClumpVariants(RNG rngv, IrisData rdata, int clumpMinSize, int clumpMaxSize) {
|
||||
KList<IrisObject> variants = new KList<>();
|
||||
for (int i = 0; i < varience; i++) {
|
||||
variants.add(generateClumpObject(rngv.nextParallelRNG(2349 * i + 3598), rdata, clumpMinSize, clumpMaxSize));
|
||||
}
|
||||
return variants;
|
||||
}
|
||||
|
||||
public int getMaxDimension() {
|
||||
return Math.min(11, (int) Math.ceil(Math.cbrt(maxSize)));
|
||||
}
|
||||
@@ -271,7 +279,7 @@ public class IrisDepositGenerator {
|
||||
}
|
||||
|
||||
/**
|
||||
* Advances {@code rng} exactly as {@link #getClump(PackRuntime, RNG)} would and reports the clump's width
|
||||
* Advances {@code rng} exactly as {@link #getClump(Engine, RNG, IrisData)} would and reports the clump's width
|
||||
* and lowest block offset without building it, so a caller can reject the clump first and replay the build
|
||||
* only for clumps it keeps. Returns null without drawing when the shape has no footprint path.
|
||||
*/
|
||||
@@ -674,6 +682,9 @@ public class IrisDepositGenerator {
|
||||
return false;
|
||||
}
|
||||
|
||||
record ClumpCacheKey(long depositSeed, int minSize, int maxSize) {
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
interface CellSink {
|
||||
void add(int x, int y, int z);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package art.arcane.iris.generation.decoration;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.pack.value.IrisRange;
|
||||
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
@@ -10,24 +11,20 @@ import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* One ore list (a biome's, region's or dimension's surface or underground ores) indexed by Y. Each Y
|
||||
* holds the indices of the generators whose range contains it, in list order, so resolving a block tries exactly
|
||||
* the generators that could place there and still returns the first one that does. The seeded chance fields live in
|
||||
* an {@link OreBandsRuntime}, aligned with {@link #generators()}.
|
||||
* holds the generators whose range contains it, in list order, so resolving a block tries exactly
|
||||
* the generators that could place there and still returns the first one that does.
|
||||
*/
|
||||
public final class IrisOreBands {
|
||||
public static final IrisOreBands EMPTY = new IrisOreBands(new IrisOreGenerator[0], 0, -1, null);
|
||||
private static final int MAXIMUM_INDEXED_HEIGHT = 8192;
|
||||
|
||||
private final IrisOreGenerator[] generators;
|
||||
private final int[] everyGenerator;
|
||||
private final int minY;
|
||||
private final int maxY;
|
||||
private final int[][] byY;
|
||||
private final IrisOreGenerator[][] byY;
|
||||
|
||||
private IrisOreBands(IrisOreGenerator[] generators, int minY, int maxY, int[][] byY) {
|
||||
private IrisOreBands(IrisOreGenerator[] generators, int minY, int maxY, IrisOreGenerator[][] byY) {
|
||||
this.generators = generators;
|
||||
this.everyGenerator = new int[generators.length];
|
||||
Arrays.setAll(everyGenerator, index -> index);
|
||||
this.minY = minY;
|
||||
this.maxY = maxY;
|
||||
this.byY = byY;
|
||||
@@ -60,19 +57,19 @@ public final class IrisOreBands {
|
||||
height > MAXIMUM_INDEXED_HEIGHT ? null : index(generators, minY, (int) height));
|
||||
}
|
||||
|
||||
private static int[][] index(IrisOreGenerator[] generators, int minY, int height) {
|
||||
int[][] byY = new int[height][];
|
||||
int[] scratch = new int[generators.length];
|
||||
int[] previous = null;
|
||||
private static IrisOreGenerator[][] index(IrisOreGenerator[] generators, int minY, int height) {
|
||||
IrisOreGenerator[][] byY = new IrisOreGenerator[height][];
|
||||
IrisOreGenerator[] scratch = new IrisOreGenerator[generators.length];
|
||||
IrisOreGenerator[] previous = null;
|
||||
for (int offset = 0; offset < height; offset++) {
|
||||
int y = minY + offset;
|
||||
int count = 0;
|
||||
for (int index = 0; index < generators.length; index++) {
|
||||
if (generators[index].getRange().contains(y)) {
|
||||
scratch[count++] = index;
|
||||
for (IrisOreGenerator generator : generators) {
|
||||
if (generator.getRange().contains(y)) {
|
||||
scratch[count++] = generator;
|
||||
}
|
||||
}
|
||||
int[] candidates = Arrays.copyOf(scratch, count);
|
||||
IrisOreGenerator[] candidates = Arrays.copyOf(scratch, count);
|
||||
byY[offset] = previous != null && Arrays.equals(previous, candidates) ? previous : candidates;
|
||||
previous = byY[offset];
|
||||
}
|
||||
@@ -95,18 +92,13 @@ public final class IrisOreBands {
|
||||
return y >= minY && y <= maxY;
|
||||
}
|
||||
|
||||
/** The banded generators in list order; chance fields built for them must keep this order. */
|
||||
public IrisOreGenerator[] generators() {
|
||||
return generators.clone();
|
||||
}
|
||||
|
||||
/**
|
||||
* The ore placed at a Y inside {@link #contains(int)}, or null when no generator places one.
|
||||
*/
|
||||
NativeBlockState generate(int x, int y, int z, RNG rng, IrisOreGenerator.OreChance[] chances, PackRuntime runtime) {
|
||||
int[] candidates = byY == null ? everyGenerator : byY[y - minY];
|
||||
for (int index : candidates) {
|
||||
NativeBlockState ore = generators[index].generate(x, y, z, rng, chances[index], runtime);
|
||||
public NativeBlockState generate(int x, int y, int z, RNG rng, IrisData data, Engine engine) {
|
||||
IrisOreGenerator[] candidates = byY == null ? generators : byY[y - minY];
|
||||
for (IrisOreGenerator candidate : candidates) {
|
||||
NativeBlockState ore = candidate.generate(x, y, z, rng, data, engine);
|
||||
if (ore != null) {
|
||||
return ore;
|
||||
}
|
||||
|
||||
@@ -18,13 +18,13 @@
|
||||
|
||||
package art.arcane.iris.generation.decoration;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
|
||||
import art.arcane.iris.generation.noise.NoiseStyle;
|
||||
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
|
||||
import art.arcane.iris.pack.value.IrisRange;
|
||||
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.generation.cache.LazyBoundedCache;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.volmlib.util.documentation.Description;
|
||||
import art.arcane.iris.pack.schema.annotation.MaxNumber;
|
||||
@@ -56,46 +56,72 @@ public class IrisOreGenerator {
|
||||
@Description("Vertical band (min, max) this ore can generate in, in engine-local Y where 0 is the bottom of the dimension, not world Y.")
|
||||
private IrisRange range = new IrisRange(30, 80);
|
||||
|
||||
public void warm(RNG rng, PackRuntime runtime) {
|
||||
runtime.oreChance(this, rng.getSeed());
|
||||
palette.getLayerGenerator(rng, runtime);
|
||||
private final transient LazyBoundedCache<ChanceKey, OreChance> chanceCache = new LazyBoundedCache<>(32);
|
||||
private transient volatile CachedChance recentChance;
|
||||
|
||||
public void warm(RNG rng, IrisData data) {
|
||||
chance(rng, data);
|
||||
palette.getLayerGenerator(rng, data);
|
||||
}
|
||||
|
||||
public NativeBlockState generate(int x, int y, int z, RNG rng, PackRuntime runtime) {
|
||||
if (!canPlaceAt(y)) {
|
||||
public NativeBlockState generate(int x, int y, int z, RNG rng, IrisData data) {
|
||||
return generate(x, y, z, rng, data, data == null ? null : data.getEngine());
|
||||
}
|
||||
|
||||
public NativeBlockState generate(int x, int y, int z, RNG rng, IrisData data, Engine engine) {
|
||||
if (threshold <= 0 || !range.contains(y)) {
|
||||
return null;
|
||||
}
|
||||
return placeByChance(x, y, z, rng, runtime.oreChance(this, rng.getSeed()), runtime);
|
||||
}
|
||||
|
||||
/** Places with a chance field already resolved for {@code rng}'s seed, as {@link OreBandsRuntime} holds them. */
|
||||
public NativeBlockState generate(int x, int y, int z, RNG rng, OreChance chance, PackRuntime runtime) {
|
||||
if (!canPlaceAt(y)) {
|
||||
if (palette.getPalette().isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return placeByChance(x, y, z, rng, chance, runtime);
|
||||
}
|
||||
|
||||
private boolean canPlaceAt(int y) {
|
||||
return threshold > 0 && range.contains(y) && !palette.getPalette().isEmpty();
|
||||
}
|
||||
|
||||
private NativeBlockState placeByChance(int x, int y, int z, RNG rng, OreChance chance, PackRuntime runtime) {
|
||||
if (chance.sample(x, y, z) > threshold) {
|
||||
if (chance(rng, data, engine).sample(x, y, z) > threshold) {
|
||||
return null;
|
||||
}
|
||||
return palette.get(rng, x, y, z, runtime);
|
||||
|
||||
return palette.get(rng, x, y, z, data);
|
||||
}
|
||||
|
||||
public OreChance createChance(long seed, PackRuntime runtime) {
|
||||
return OreChance.of(chanceStyle.create(new RNG(seed), runtime));
|
||||
private OreChance chance(RNG rng, IrisData data) {
|
||||
return chance(rng, data, data == null ? null : data.getEngine());
|
||||
}
|
||||
|
||||
private OreChance chance(RNG rng, IrisData data, Engine engine) {
|
||||
long seed = rng.getSeed();
|
||||
CachedChance recent = recentChance;
|
||||
if (recent != null && recent.key.seed == seed && recent.key.data == data && recent.key.engine == engine) {
|
||||
return recent.chance;
|
||||
}
|
||||
ChanceKey key = new ChanceKey(seed, data, engine);
|
||||
OreChance selected = chanceCache.computeIfAbsent(key, ignored -> OreChance.of(chanceStyle.create(rng, data)));
|
||||
recentChance = new CachedChance(key, selected);
|
||||
return selected;
|
||||
}
|
||||
|
||||
private record ChanceKey(long seed, IrisData data, Engine engine) {
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
return other instanceof ChanceKey key
|
||||
&& seed == key.seed && data == key.data && engine == key.engine;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return 31 * (31 * Long.hashCode(seed) + System.identityHashCode(data))
|
||||
+ System.identityHashCode(engine);
|
||||
}
|
||||
}
|
||||
|
||||
private record CachedChance(ChanceKey key, OreChance chance) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The chance field, with its single value resolved once when it is constant (a FLAT style),
|
||||
* which bands such as a full deepslate layer sample at every block.
|
||||
*/
|
||||
public record OreChance(CNG noise, boolean constant, double value) {
|
||||
private record OreChance(CNG noise, boolean constant, double value) {
|
||||
private static OreChance of(CNG noise) {
|
||||
boolean constant = noise.isConstant();
|
||||
return new OreChance(noise, constant, constant ? noise.noise(0D, 0D, 0D) : 0D);
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
|
||||
package art.arcane.iris.generation.decoration;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
|
||||
import art.arcane.iris.structure.object.IrisObject;
|
||||
|
||||
@@ -60,7 +59,7 @@ public final class IrisProceduralBlocks {
|
||||
|
||||
public static NativeBlockState resolve(String block, IrisMaterialPalette palette, IrisData data, int x, int y, int z, RNG paletteRng) {
|
||||
if (paletteSet(palette)) {
|
||||
return palette.get(paletteRng, x, y, z, PackRuntime.forPack(data));
|
||||
return palette.get(paletteRng, x, y, z, data);
|
||||
}
|
||||
if (block != null && !block.isEmpty()) {
|
||||
return B.getStateOrNull(block, false);
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
|
||||
package art.arcane.iris.generation.decoration;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.generation.biome.IrisBiome;
|
||||
import art.arcane.volmlib.util.hunk.Hunk;
|
||||
@@ -43,28 +42,27 @@ public class IrisSeaFloorDecorator extends IrisEngineDecorator {
|
||||
return;
|
||||
}
|
||||
RNG rng = getRNG(realX, realZ);
|
||||
PackRuntime runtime = PackRuntime.of(getEngine(), getData());
|
||||
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ);
|
||||
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
|
||||
|
||||
if (decorator == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
place(decorator, x, z, realX, realZ, data, biome, height, max, limit, runtime);
|
||||
place(decorator, x, z, realX, realZ, data, biome, height, max, limit);
|
||||
} catch (Throwable e) {
|
||||
DecoratorCore.skip(e, decorator, getData(), realX, height, realZ, biome);
|
||||
}
|
||||
}
|
||||
|
||||
private void place(IrisDecorator decorator, int x, int z, int realX, int realZ, Hunk<NativeBlockState> data,
|
||||
IrisBiome biome, int height, int max, int limit, PackRuntime runtime) {
|
||||
IrisBiome biome, int height, int max, int limit) {
|
||||
if (!decorator.isStacking()) {
|
||||
if (!decorator.isForcePlace() && !decorator.getSlopeCondition().isDefault()
|
||||
&& !decorator.getSlopeCondition().isValid(getComplex().getSlopeStream().get(realX, realZ))) {
|
||||
return;
|
||||
}
|
||||
NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, runtime);
|
||||
NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, getData());
|
||||
if (block != null) {
|
||||
data.set(x, height, z, block);
|
||||
}
|
||||
@@ -72,13 +70,13 @@ public class IrisSeaFloorDecorator extends IrisEngineDecorator {
|
||||
}
|
||||
|
||||
int stack = Math.min(limit - height,
|
||||
DecoratorCore.computeStack(decorator, partRNG, realX, realZ, runtime, max - height));
|
||||
DecoratorCore.computeStack(decorator, partRNG, realX, realZ, getData(), max - height));
|
||||
for (int i = 0; i < stack; i++) {
|
||||
int h = height + i;
|
||||
double threshold = stack == 1 ? 1.0 : ((double) i) / (stack - 1);
|
||||
NativeBlockState block = threshold >= decorator.getTopThreshold()
|
||||
? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, runtime)
|
||||
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, runtime);
|
||||
? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, getData())
|
||||
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, getData());
|
||||
if (block == null) {
|
||||
break;
|
||||
}
|
||||
|
||||
+7
-9
@@ -18,7 +18,6 @@
|
||||
|
||||
package art.arcane.iris.generation.decoration;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.generation.biome.IrisBiome;
|
||||
import art.arcane.volmlib.util.hunk.Hunk;
|
||||
@@ -43,26 +42,25 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator {
|
||||
return;
|
||||
}
|
||||
RNG rng = getRNG(realX, realZ);
|
||||
PackRuntime runtime = PackRuntime.of(getEngine(), getData());
|
||||
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ);
|
||||
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
|
||||
|
||||
if (decorator == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
place(decorator, x, z, realX, realZ, data, biome, height, max, maxBaseY, runtime);
|
||||
place(decorator, x, z, realX, realZ, data, biome, height, max, maxBaseY);
|
||||
} catch (Throwable e) {
|
||||
DecoratorCore.skip(e, decorator, getData(), realX, height, realZ, biome);
|
||||
}
|
||||
}
|
||||
|
||||
private void place(IrisDecorator decorator, int x, int z, int realX, int realZ, Hunk<NativeBlockState> data,
|
||||
IrisBiome biome, int height, int max, int maxBaseY, PackRuntime runtime) {
|
||||
IrisBiome biome, int height, int max, int maxBaseY) {
|
||||
if (!decorator.isStacking()) {
|
||||
int targetY = height + 1;
|
||||
if (DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) {
|
||||
NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, runtime);
|
||||
NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, getData());
|
||||
if (block != null) {
|
||||
data.set(x, targetY, z, block);
|
||||
}
|
||||
@@ -71,7 +69,7 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator {
|
||||
}
|
||||
|
||||
int stack = Math.min(maxBaseY - height,
|
||||
DecoratorCore.computeStack(decorator, partRNG, realX, realZ, runtime, max - height));
|
||||
DecoratorCore.computeStack(decorator, partRNG, realX, realZ, getData(), max - height));
|
||||
for (int i = 0; i < stack; i++) {
|
||||
int h = height + i;
|
||||
int targetY = h + 1;
|
||||
@@ -80,8 +78,8 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator {
|
||||
}
|
||||
double threshold = stack == 1 ? 1.0 : ((double) i) / (stack - 1);
|
||||
NativeBlockState block = threshold >= decorator.getTopThreshold()
|
||||
? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, runtime)
|
||||
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, runtime);
|
||||
? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, getData())
|
||||
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, getData());
|
||||
if (block == null) {
|
||||
break;
|
||||
}
|
||||
|
||||
+8
-10
@@ -18,7 +18,6 @@
|
||||
|
||||
package art.arcane.iris.generation.decoration;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.generation.biome.IrisBiome;
|
||||
import art.arcane.volmlib.util.hunk.Hunk;
|
||||
@@ -79,8 +78,7 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
|
||||
int max
|
||||
) {
|
||||
RNG rng = getRNG(realX, realZ);
|
||||
PackRuntime runtime = PackRuntime.of(getEngine(), getData());
|
||||
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ);
|
||||
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
|
||||
|
||||
if (decorator == null) {
|
||||
return;
|
||||
@@ -92,14 +90,14 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
|
||||
}
|
||||
|
||||
try {
|
||||
placePicked(decorator, x, z, realX, realZ, data, biome, height, max, runtime);
|
||||
placePicked(decorator, x, z, realX, realZ, data, biome, height, max);
|
||||
} catch (Throwable e) {
|
||||
DecoratorCore.skip(e, decorator, getData(), realX, height, realZ, biome);
|
||||
}
|
||||
}
|
||||
|
||||
private void placePicked(IrisDecorator decorator, int x, int z, int realX, int realZ, Hunk<NativeBlockState> data,
|
||||
IrisBiome biome, int height, int max, PackRuntime runtime) {
|
||||
IrisBiome biome, int height, int max) {
|
||||
NativeBlockState support = data.get(x, height, z);
|
||||
if (support == null || !support.isSolid()) {
|
||||
return;
|
||||
@@ -113,7 +111,7 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
|
||||
|| !DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) {
|
||||
return;
|
||||
}
|
||||
NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, runtime);
|
||||
NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, getData());
|
||||
if (block != null && DecoratorCore.isValidShorelineSupport(decorator, block, support)
|
||||
&& IrisSugarCane.canPlace(block, data, x, targetY, z, realX, realZ, getEngine())) {
|
||||
data.set(x, targetY, z, block);
|
||||
@@ -122,7 +120,7 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
|
||||
return;
|
||||
}
|
||||
|
||||
int stack = DecoratorCore.computeStack(decorator, partRNG, realX, realZ, runtime, max - height);
|
||||
int stack = DecoratorCore.computeStack(decorator, partRNG, realX, realZ, getData(), max - height);
|
||||
|
||||
if (stack == 1) {
|
||||
int targetY = height + 1;
|
||||
@@ -130,7 +128,7 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
|
||||
return;
|
||||
}
|
||||
|
||||
NativeBlockState block = decorator.getBlockDataForTop(biome, partRNG, realX, height, realZ, runtime);
|
||||
NativeBlockState block = decorator.getBlockDataForTop(biome, partRNG, realX, height, realZ, getData());
|
||||
if (block != null && DecoratorCore.isValidShorelineSupport(decorator, block, support)
|
||||
&& IrisSugarCane.canPlace(block, data, x, targetY, z, realX, realZ, getEngine())) {
|
||||
data.set(x, targetY, z, block);
|
||||
@@ -148,8 +146,8 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
|
||||
}
|
||||
double threshold = ((double) i) / (stack - 1);
|
||||
NativeBlockState block = threshold >= decorator.getTopThreshold()
|
||||
? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, runtime)
|
||||
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, runtime);
|
||||
? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, getData())
|
||||
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, getData());
|
||||
if (block == null) {
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package art.arcane.iris.generation.decoration;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.generation.runtime.IrisComplex;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.generation.biome.IrisBiome;
|
||||
@@ -80,7 +79,7 @@ final class IrisSugarCane {
|
||||
}
|
||||
IrisBiome biome = complex.getTrueBiomeStream().get(x, z);
|
||||
KList<NativeBlockState> layers = biome.generateSeaLayers(x, z,
|
||||
new RNG(engine.getSeedManager().getTerrain()), fluidHeight - terrainHeight, PackRuntime.of(engine));
|
||||
new RNG(engine.getSeedManager().getTerrain()), fluidHeight - terrainHeight, engine.getData());
|
||||
int depth = fluidHeight - y;
|
||||
return supportsAdjacent(layers.hasIndex(depth) ? layers.get(depth) : complex.resolveSeaFluid(x, z));
|
||||
}
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
|
||||
package art.arcane.iris.generation.decoration;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.generation.context.ChunkContext;
|
||||
@@ -74,22 +73,21 @@ public class IrisSurfaceDecorator extends IrisEngineDecorator {
|
||||
}
|
||||
boolean caveSkipFluid = skipsFluid(inferredType);
|
||||
RNG rng = getRNG(realX, realZ);
|
||||
PackRuntime runtime = PackRuntime.of(getEngine(), getData());
|
||||
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ);
|
||||
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
|
||||
|
||||
if (decorator == null || !isSlopeValid(decorator, realX, height, realZ)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
place(decorator, x, z, realX, realZ, data, height, max, underwater, fluidHeight, caveSkipFluid, runtime);
|
||||
place(decorator, x, z, realX, realZ, data, height, max, underwater, fluidHeight, caveSkipFluid);
|
||||
} catch (Throwable e) {
|
||||
DecoratorCore.skip(e, decorator, getData(), realX, height, realZ, biome);
|
||||
}
|
||||
}
|
||||
|
||||
private void place(IrisDecorator decorator, int x, int z, int realX, int realZ, Hunk<NativeBlockState> data,
|
||||
int height, int max, boolean underwater, int fluidHeight, boolean caveSkipFluid, PackRuntime runtime) {
|
||||
int height, int max, boolean underwater, int fluidHeight, boolean caveSkipFluid) {
|
||||
AquaticPlacementSnapshot aquaticSnapshot = captureAquaticPlacement(
|
||||
decorator, getData(), data, x, z, height, max);
|
||||
if (decorator.isStacking()) {
|
||||
@@ -99,17 +97,13 @@ public class IrisSurfaceDecorator extends IrisEngineDecorator {
|
||||
opts.fluidHeight = fluidHeight;
|
||||
opts.caveSkipFluid = caveSkipFluid;
|
||||
opts.mantle = getEngine().getMantle();
|
||||
try {
|
||||
DecoratorCore.placeStackUp(decorator, x, z, realX, realZ, height, max, data, partRNG, runtime, opts);
|
||||
} finally {
|
||||
opts.mantle = null;
|
||||
}
|
||||
DecoratorCore.placeStackUp(decorator, x, z, realX, realZ, height, max, data, partRNG, getData(), opts);
|
||||
aquaticSnapshot.restoreIfUnsupported(data, x, z);
|
||||
return;
|
||||
}
|
||||
|
||||
DecoratorCore.placeSurfaceSingle(decorator, x, z, realX, height, realZ,
|
||||
data, partRNG, runtime, underwater, caveSkipFluid, getEngine().getMantle());
|
||||
data, partRNG, getData(), underwater, caveSkipFluid, getEngine().getMantle());
|
||||
aquaticSnapshot.restoreIfUnsupported(data, x, z);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.generation.decoration;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
|
||||
/**
|
||||
* What one engine derives from an {@link IrisOreBands} for one seed: the chance field of every banded generator,
|
||||
* resolved once so placing ores block by block reads plain fields instead of looking each generator up.
|
||||
*/
|
||||
public final class OreBandsRuntime {
|
||||
private final IrisOreBands bands;
|
||||
private final PackRuntime runtime;
|
||||
private final IrisOreGenerator.OreChance[] chances;
|
||||
|
||||
public OreBandsRuntime(IrisOreBands bands, long seed, PackRuntime runtime) {
|
||||
this.bands = bands;
|
||||
this.runtime = runtime;
|
||||
IrisOreGenerator[] generators = bands.generators();
|
||||
this.chances = new IrisOreGenerator.OreChance[generators.length];
|
||||
for (int index = 0; index < generators.length; index++) {
|
||||
chances[index] = runtime.oreChance(generators[index], seed);
|
||||
}
|
||||
}
|
||||
|
||||
public IrisOreBands bands() {
|
||||
return bands;
|
||||
}
|
||||
|
||||
public boolean hasOres() {
|
||||
return bands.hasOres();
|
||||
}
|
||||
|
||||
public int lowestY() {
|
||||
return bands.lowestY();
|
||||
}
|
||||
|
||||
public int highestY() {
|
||||
return bands.highestY();
|
||||
}
|
||||
|
||||
public boolean contains(int y) {
|
||||
return bands.contains(y);
|
||||
}
|
||||
|
||||
/** The ore placed at a Y inside {@link #contains(int)}, or null when no generator places one. */
|
||||
public NativeBlockState generate(int x, int y, int z, RNG rng) {
|
||||
return bands.generate(x, y, z, rng, chances, runtime);
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -18,7 +18,6 @@
|
||||
|
||||
package art.arcane.iris.generation.decoration.formation;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
|
||||
import art.arcane.iris.generation.decoration.IrisProceduralBlocks;
|
||||
@@ -60,7 +59,7 @@ public final class FormationBlockResolver {
|
||||
strataRng = new RNG(formation.getSeed() + band * 31L);
|
||||
strataRngs.put(band, strataRng);
|
||||
}
|
||||
NativeBlockState strataState = strata.get(strataRng, x, band, z, PackRuntime.forPack(data));
|
||||
NativeBlockState strataState = strata.get(strataRng, x, band, z, data);
|
||||
if (strataState != null) {
|
||||
return strataState;
|
||||
}
|
||||
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package art.arcane.iris.generation.decoration.formation;
|
||||
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.studio.scene.SceneBlocks;
|
||||
import art.arcane.iris.studio.scene.SceneEntry;
|
||||
import art.arcane.iris.studio.scene.SceneForm;
|
||||
import art.arcane.iris.studio.scene.SceneRequest;
|
||||
import art.arcane.iris.studio.scene.SceneView;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Set;
|
||||
|
||||
/** How each formation profile shapes a formation's width from base to top. */
|
||||
public final class FormationProfileSceneView implements SceneView {
|
||||
private static final Set<String> HIDDEN = Set.of("name", "chance", "density", "variants", "seed", "mode", "carvingSupport",
|
||||
"surfaceSupportBuffer", "underwater", "profile");
|
||||
|
||||
@Override
|
||||
public String id() {
|
||||
return "formationProfiles";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String label() {
|
||||
return "Formation profiles";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String description() {
|
||||
return "How each formation profile shapes a formation's width from base to top";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<SceneEntry> entries(Engine engine) {
|
||||
int variants = new IrisFormation().getVariants();
|
||||
return Arrays.stream(IrisFormationProfile.values()).map(profile -> SceneEntry.preset(profile, variants)).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasForm() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SceneForm form(Engine engine, String key, Map<String, String> overrides) {
|
||||
return SceneForm.of("Formation", formationOf(key, overrides), HIDDEN, overrides,
|
||||
List.of(SceneForm.describe(profileOf(key)), "Values typed here change the preview only"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public SceneBlocks scene(Engine engine, SceneRequest request) {
|
||||
IrisFormation formation = formationOf(request.key(), request.overrides());
|
||||
return SceneBlocks.ofVariant(formation.getVariantObjects(engine.getData()), request.variant(), "formation");
|
||||
}
|
||||
|
||||
private static IrisFormation formationOf(String key, Map<String, String> overrides) {
|
||||
IrisFormation formation = SceneForm.withOverrides(new IrisFormation(), overrides);
|
||||
formation.setProfile(profileOf(key));
|
||||
return formation;
|
||||
}
|
||||
|
||||
private static IrisFormationProfile profileOf(String key) {
|
||||
try {
|
||||
return IrisFormationProfile.valueOf(key);
|
||||
} catch (IllegalArgumentException unknown) {
|
||||
throw new NoSuchElementException("No formation profile " + key);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-3
@@ -18,7 +18,6 @@
|
||||
|
||||
package art.arcane.iris.generation.decoration.tree;
|
||||
|
||||
import art.arcane.iris.generation.runtime.PackRuntime;
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
|
||||
import art.arcane.iris.generation.decoration.IrisProceduralBlocks;
|
||||
@@ -85,7 +84,7 @@ public final class TreeBlockResolver {
|
||||
|
||||
private static NativeBlockState resolveSecondaryLeaf(IrisProceduralTree tree, IrisData data, TreeBlockCanvas.Vec pos, RNG paletteRng) {
|
||||
if (IrisProceduralBlocks.paletteSet(tree.getSecondaryLeavesPalette())) {
|
||||
return tree.getSecondaryLeavesPalette().get(paletteRng, pos.x(), pos.y(), pos.z(), PackRuntime.forPack(data));
|
||||
return tree.getSecondaryLeavesPalette().get(paletteRng, pos.x(), pos.y(), pos.z(), data);
|
||||
}
|
||||
if (tree.getWeightedSecondaryLeaves() != null && !tree.getWeightedSecondaryLeaves().isEmpty()) {
|
||||
String picked = pickWeighted(tree, new RNG(tree.getSeed() ^ positionHash(pos)));
|
||||
@@ -118,7 +117,7 @@ public final class TreeBlockResolver {
|
||||
|
||||
private static NativeBlockState resolveBlock(String block, IrisMaterialPalette palette, IrisData data, TreeBlockCanvas.Vec pos, RNG paletteRng) {
|
||||
if (IrisProceduralBlocks.paletteSet(palette)) {
|
||||
return palette.get(paletteRng, pos.x(), pos.y(), pos.z(), PackRuntime.forPack(data));
|
||||
return palette.get(paletteRng, pos.x(), pos.y(), pos.z(), data);
|
||||
}
|
||||
if (block != null && !block.isEmpty()) {
|
||||
return B.getStateOrNull(block, false);
|
||||
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package art.arcane.iris.generation.decoration.tree;
|
||||
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.studio.scene.SceneBlocks;
|
||||
import art.arcane.iris.studio.scene.SceneEntry;
|
||||
import art.arcane.iris.studio.scene.SceneForm;
|
||||
import art.arcane.iris.studio.scene.SceneRequest;
|
||||
import art.arcane.iris.studio.scene.SceneView;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Set;
|
||||
|
||||
/** The canopy shape each tree profile gives a procedural tree. */
|
||||
public final class TreeProfileSceneView implements SceneView {
|
||||
private static final Set<String> HIDDEN = Set.of("name", "chance", "density", "variants", "seed", "plausible", "mode",
|
||||
"carvingSupport", "underwater", "profile");
|
||||
|
||||
@Override
|
||||
public String id() {
|
||||
return "treeProfiles";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String label() {
|
||||
return "Tree profiles";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String description() {
|
||||
return "The canopy shape each tree profile gives a procedural tree";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<SceneEntry> entries(Engine engine) {
|
||||
int variants = new IrisProceduralTree().getVariants();
|
||||
return Arrays.stream(IrisTreeProfile.values()).map(profile -> SceneEntry.preset(profile, variants)).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasForm() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SceneForm form(Engine engine, String key, Map<String, String> overrides) {
|
||||
return SceneForm.of("Tree", treeOf(key, overrides), HIDDEN, overrides,
|
||||
List.of(SceneForm.describe(profileOf(key)), "Values typed here change the preview only"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public SceneBlocks scene(Engine engine, SceneRequest request) {
|
||||
IrisProceduralTree tree = treeOf(request.key(), request.overrides());
|
||||
return SceneBlocks.ofVariant(tree.getVariantObjects(engine.getData()), request.variant(), "tree");
|
||||
}
|
||||
|
||||
private static IrisProceduralTree treeOf(String key, Map<String, String> overrides) {
|
||||
IrisProceduralTree tree = SceneForm.withOverrides(new IrisProceduralTree(), overrides);
|
||||
tree.setProfile(profileOf(key));
|
||||
return tree;
|
||||
}
|
||||
|
||||
private static IrisTreeProfile profileOf(String key) {
|
||||
try {
|
||||
return IrisTreeProfile.valueOf(key);
|
||||
} catch (IllegalArgumentException unknown) {
|
||||
throw new NoSuchElementException("No tree profile " + key);
|
||||
}
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package art.arcane.iris.generation.hydrology.config;
|
||||
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.studio.scene.SceneBlocks;
|
||||
import art.arcane.iris.studio.scene.SceneEntry;
|
||||
import art.arcane.iris.studio.scene.SceneForm;
|
||||
import art.arcane.iris.studio.scene.SceneRequest;
|
||||
import art.arcane.iris.studio.scene.SceneSizes;
|
||||
import art.arcane.iris.studio.scene.SceneView;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Optional;
|
||||
|
||||
/** The blocks of each named fluid of the dimension's hydrology, in a pool lined with its seam. */
|
||||
public final class FluidProfileSceneView implements SceneView {
|
||||
private static final SceneSizes SIZES = new SceneSizes(List.of(16, 32, 64), 32);
|
||||
private static final int VARIANTS = 4;
|
||||
private static final int VARIANT_SPACING_BLOCKS = 1024;
|
||||
private static final int DEPTH_BLOCKS = 3;
|
||||
private static final String BASIN_BLOCK = "minecraft:stone";
|
||||
|
||||
@Override
|
||||
public String id() {
|
||||
return "fluidProfiles";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String label() {
|
||||
return "Fluid profiles";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String description() {
|
||||
return "The blocks of each named fluid of the dimension's hydrology, in a pool lined with its seam";
|
||||
}
|
||||
|
||||
@Override
|
||||
public SceneSizes sizes() {
|
||||
return SIZES;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<SceneEntry> entries(Engine engine) {
|
||||
return fluids(engine).stream().map(fluid -> new SceneEntry(fluid.getName(), fluid.getName(), "Fluids", VARIANTS)).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasForm() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SceneForm form(Engine engine, String key, Map<String, String> overrides) {
|
||||
IrisFluidProfile fluid = fluidOf(engine, key);
|
||||
IrisData data = engine.getData();
|
||||
List<String> notes = new ArrayList<>();
|
||||
notes.add("Blocks: " + String.join(", ", fluid.getPalette().getBlockData(data).stream().map(state -> state.key()).toList()));
|
||||
notes.add("Seam: " + (fluid.getSeam() == null ? "none" : fluid.getSeam()));
|
||||
return new SceneForm("Fluid", List.of(), notes);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SceneBlocks scene(Engine engine, SceneRequest request) {
|
||||
IrisData data = engine.getData();
|
||||
IrisFluidProfile fluid = fluidOf(engine, request.key());
|
||||
IrisFluidProfile seam = fluid.getSeam() == null ? null : fluidOf(engine, fluid.getSeam());
|
||||
int size = request.size();
|
||||
int offset = Math.floorMod(request.variant(), VARIANTS) * VARIANT_SPACING_BLOCKS;
|
||||
RNG rng = new RNG(offset + 1L);
|
||||
SceneBlocks scene = new SceneBlocks();
|
||||
for (int z = 0; z < size; z++) {
|
||||
for (int x = 0; x < size; x++) {
|
||||
scene.add(x, 0, z, BASIN_BLOCK);
|
||||
boolean wall = x == 0 || z == 0 || x == size - 1 || z == size - 1;
|
||||
boolean seamRing = seam != null && (x == 1 || z == 1 || x == size - 2 || z == size - 2);
|
||||
for (int y = 1; y <= DEPTH_BLOCKS; y++) {
|
||||
IrisFluidProfile filling = seamRing ? seam : fluid;
|
||||
scene.add(x, y, z, wall ? BASIN_BLOCK : filling.getPalette().get(rng, x + offset, y, z, data).key());
|
||||
}
|
||||
}
|
||||
}
|
||||
return scene;
|
||||
}
|
||||
|
||||
private static KList<IrisFluidProfile> fluids(Engine engine) {
|
||||
return engine.getDimension().getHydrology().getFluids();
|
||||
}
|
||||
|
||||
private static IrisFluidProfile fluidOf(Engine engine, String key) {
|
||||
Optional<IrisFluidProfile> found = fluids(engine).stream().filter(fluid -> key.equals(fluid.getName())).findFirst();
|
||||
return found.orElseThrow(() -> new NoSuchElementException("No fluid profile " + key));
|
||||
}
|
||||
}
|
||||
+2
-3
@@ -1,6 +1,5 @@
|
||||
package art.arcane.iris.generation.hydrology.engine;
|
||||
|
||||
import art.arcane.iris.generation.runtime.ThreadSlots;
|
||||
import art.arcane.iris.generation.runtime.HydrologyPlanException;
|
||||
import art.arcane.iris.generation.biome.IrisBiome;
|
||||
import art.arcane.iris.generation.concurrent.MultiBurst;
|
||||
@@ -79,7 +78,7 @@ public final class HydrologyRuntime {
|
||||
private final NaturalHeights naturalHeight;
|
||||
private final BooleanSupplier mainThread;
|
||||
private final RasterLru rasters;
|
||||
private final ThreadSlots<LastRaster> last;
|
||||
private final ThreadLocal<LastRaster> last;
|
||||
private final Set<Long> queued;
|
||||
private final ConcurrentHashMap<Long, CompletableFuture<ChunkWaterRaster>> building;
|
||||
private final RasterFailures failures;
|
||||
@@ -133,7 +132,7 @@ public final class HydrologyRuntime {
|
||||
this.naturalHeight = Objects.requireNonNull(naturalHeight, "naturalHeight");
|
||||
this.mainThread = Objects.requireNonNull(mainThread, "mainThread");
|
||||
this.rasters = new RasterLru();
|
||||
this.last = new ThreadSlots<>(LastRaster::new);
|
||||
this.last = ThreadLocal.withInitial(LastRaster::new);
|
||||
this.queued = ConcurrentHashMap.newKeySet();
|
||||
this.building = new ConcurrentHashMap<>();
|
||||
this.failures = new RasterFailures(ticker);
|
||||
|
||||
Loaded 100 of 899 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user