From 809184f78792cbfb5d05068e45408554234742fd Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 08:20:10 +0200 Subject: [PATCH 01/10] Pin the blocks of biome layers, slabs, walls and the dimension's rock and fluid palettes before they move --- .../engine/actuator/TerrainLayersPinTest.java | 156 ++++++++++++++++++ .../actuator/TerrainPalettesPinTest.java | 95 +++++++++++ 2 files changed, 251 insertions(+) create mode 100644 core/src/test/java/art/arcane/iris/engine/actuator/TerrainLayersPinTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/actuator/TerrainPalettesPinTest.java diff --git a/core/src/test/java/art/arcane/iris/engine/actuator/TerrainLayersPinTest.java b/core/src/test/java/art/arcane/iris/engine/actuator/TerrainLayersPinTest.java new file mode 100644 index 000000000..9fe8e2e97 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/actuator/TerrainLayersPinTest.java @@ -0,0 +1,156 @@ +package art.arcane.iris.engine.actuator; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.loader.ResourceLoader; +import art.arcane.iris.core.modules.IrisPackResources; +import art.arcane.iris.engine.IrisComplex; +import art.arcane.iris.engine.UsableBlockPlatform; +import art.arcane.iris.engine.object.material.IrisBlockData; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.project.stream.ProceduralStream; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import com.google.gson.Gson; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.File; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Pins what biome layers, sea layers, cave ceiling layers, locked layers, slabs and walls pick for a spread of columns + * with a fixed terrain RNG, so they can move out of {@code IrisBiome} and into the terrain module without changing what + * a world generates. The transcript hash was taken from {@code IrisBiome.generateLayers} and friends and from + * {@code IrisBiomePaletteLayer.get} before they moved. + */ +public class TerrainLayersPinTest { + private static final long TERRAIN_SEED = 1337L; + private static final int TRANSCRIPT_LENGTH = 143080; + private static final int TRANSCRIPT_HASH = -1399100638; + private static final int COLUMN_STEP_X = 61; + private static final int COLUMN_STEP_Z = 67; + private static final int COLUMN_RANGE = 400; + + private static final String MESA = """ + {"name": "Mesa", "lockLayers": true, "lockLayersMax": 9, + "layers": [ + {"minHeight": 1, "maxHeight": 3, "zoom": 0.3, "style": {"style": "SIMPLEX", "zoom": 1}, + "palette": [{"block": "red_sand"}, {"block": "terracotta", "weight": 2}, {"block": "orange_terracotta"}, {"block": "yellow_terracotta"}]}, + {"minHeight": 2, "maxHeight": 5, "palette": [{"block": "white_terracotta"}, {"block": "brown_terracotta", "weight": 3}, {"block": "light_gray_terracotta"}], + "style": {"style": "PERLIN", "zoom": 1}, "zoom": 0.2}, + {"minHeight": 1, "maxHeight": 2, "slopeCondition": {"minimumSlope": 2, "maximumSlope": 8}, "palette": [{"block": "gravel"}]} + ], + "slab": {"style": {"style": "SIMPLEX"}, "zoom": 0.5, "palette": [{"weight": 2, "block": "air"}, + {"block": "cobblestone_slab", "data": {"waterlogged": false, "type": "bottom"}}, {"block": "stone_slab"}], + "slopeCondition": {"maximumSlope": 6}}, + "wall": {"style": {"style": "SIMPLEX"}, "zoom": 0.4, "palette": [{"block": "stone"}, {"block": "andesite", "weight": 2}, {"block": "diorite"}, {"block": "granite"}]}} + """; + private static final String MEADOW = """ + {"name": "Meadow", + "layers": [ + {"minHeight": 1, "maxHeight": 1, "palette": [{"block": "grass_block"}]}, + {"minHeight": 2, "maxHeight": 4, "zoom": 0.25, "style": {"style": "CELLULAR"}, "palette": [{"block": "dirt"}, {"block": "coarse_dirt"}, {"block": "rooted_dirt"}]}, + {"minHeight": 8, "maxHeight": 20, "palette": [{"block": "stone"}]} + ], + "caveCeilingLayers": [ + {"minHeight": 1, "maxHeight": 2, "zoom": 0.3, "style": {"style": "SIMPLEX", "zoom": 1}, "palette": [{"block": "moss_block"}, {"block": "dripstone_block"}, {"block": "clay"}, {"block": "glow_lichen"}]}, + {"minHeight": 1, "maxHeight": 3, "palette": [{"block": "deepslate"}, {"block": "tuff", "weight": 2}]}, + {"minHeight": 1, "maxHeight": 1, "palette": [{"block": "calcite"}]}, + {"minHeight": 1, "maxHeight": 1, "palette": [{"block": "basalt"}]} + ]} + """; + private static final String OCEAN = """ + {"name": "Ocean", + "layers": [{"minHeight": 1, "maxHeight": 4, "zoom": 0.3, "style": {"style": "SIMPLEX", "zoom": 1}, "palette": [{"block": "sand"}, {"block": "gravel", "weight": 2}, {"block": "clay"}, {"block": "suspicious_sand"}]}], + "seaLayers": [ + {"minHeight": 1, "maxHeight": 3, "zoom": 0.3, "style": {"style": "PERLIN", "zoom": 1}, "palette": [{"block": "kelp_plant"}, {"block": "water"}, {"block": "seagrass"}, {"block": "sea_pickle"}]}, + {"minHeight": 0, "maxHeight": 2, "palette": [{"block": "prismarine"}, {"block": "dark_prismarine"}], "zoom": 2} + ]} + """; + private static final String DEFAULTS = "{\"name\": \"Plain\"}"; + private static final String[] BIOMES = {MESA, MEADOW, OCEAN, DEFAULTS}; + + private IrisData data; + private IrisComplex complex; + + @Before + public void bindPlatform() { + UsableBlockPlatform.bind(); + data = mock(IrisData.class); + @SuppressWarnings("unchecked") + ResourceLoader blocks = mock(ResourceLoader.class); + when(data.getBlockLoader()).thenReturn(blocks); + when(data.getDataFolder()).thenReturn(new File("pack")); + IrisPackResources resources = new IrisPackResources(data); + when(data.getPackResources()).thenReturn(resources); + complex = mock(IrisComplex.class); + when(complex.getSlopeStream()).thenReturn(ProceduralStream.ofDouble((x, z) -> Math.abs((x * 3 + z * 5) % 11))); + } + + @After + public void unbindPlatform() { + UsableBlockPlatform.unbind(); + } + + @Test + public void layersPickAsTheyDidInTheBiome() { + StringBuilder transcript = new StringBuilder(); + for (String json : BIOMES) { + for (boolean exploded : new boolean[]{false, true}) { + record(transcript, json, exploded); + } + } + + try { java.nio.file.Files.writeString(java.nio.file.Path.of("/tmp/iris-wt/3t/transcript.txt"), transcript.toString().replace("|", "\n")); } catch (java.io.IOException e) { throw new RuntimeException(e); } + for (String picked : List.of("terracotta", "prismarine", "moss_block", "cobblestone_slab", "andesite", "barrier")) { + assertTrue(picked + " is picked: " + transcript.length(), transcript.indexOf(picked) >= 0); + } + assertEquals("transcript " + transcript.length() + " / " + transcript.toString().hashCode(), TRANSCRIPT_LENGTH, transcript.length()); + assertEquals(TRANSCRIPT_HASH, transcript.toString().hashCode()); + } + + private void record(StringBuilder transcript, String biomeJson, boolean exploded) { + IrisDimension dimension = new IrisDimension(); + dimension.setExplodeBiomePalettes(exploded); + dimension.setExplodeBiomePaletteSize(2); + RNG rng = new RNG(TERRAIN_SEED); + IrisBiome biome = new Gson().fromJson(biomeJson, IrisBiome.class); + for (int x = -COLUMN_RANGE; x < COLUMN_RANGE; x += COLUMN_STEP_X) { + for (int z = -COLUMN_RANGE; z < COLUMN_RANGE; z += COLUMN_STEP_Z) { + transcript.append('|').append(keys(biome.generateLayers(dimension, x, z, rng, 14, 70 + Math.floorMod(x + z, 9), data, complex))); + transcript.append('|').append(keys(biome.generateCeilingLayers(dimension, x, z, rng, 12, 40, data, complex))); + transcript.append('|').append(keys(biome.generateSeaLayers(x, z, rng, 7, data))); + transcript.append('|').append(smoothing(biome, rng, x, z)); + } + } + } + + /** The block a slab and a wall place in post processing at the column, as the smoothing stage asks the biome. */ + private String smoothing(IrisBiome biome, RNG rng, int x, int z) { + int height = 60 + Math.floorMod(x - z, 7); + double slope = complex.getSlopeStream().get(x, z); + String slab = biome.getSlab().getSlopeCondition().isValid(slope) ? key(biome.getSlab().get(rng, x, height, z, data)) : "-"; + String wall = biome.getWall().getPalette().isEmpty() ? "-" : key(biome.getWall().get(rng, x + height, height + height, z + height, data)); + return slab + "," + wall; + } + + private static String keys(KList states) { + StringBuilder keys = new StringBuilder(); + for (PlatformBlockState state : states) { + keys.append(key(state)).append(' '); + } + return keys.toString(); + } + + private static String key(PlatformBlockState state) { + return state == null ? "null" : state.key().replace("minecraft:", ""); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/actuator/TerrainPalettesPinTest.java b/core/src/test/java/art/arcane/iris/engine/actuator/TerrainPalettesPinTest.java new file mode 100644 index 000000000..2f36fd219 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/actuator/TerrainPalettesPinTest.java @@ -0,0 +1,95 @@ +package art.arcane.iris.engine.actuator; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.loader.ResourceLoader; +import art.arcane.iris.core.modules.IrisPackResources; +import art.arcane.iris.engine.UsableBlockPlatform; +import art.arcane.iris.engine.object.material.IrisBlockData; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.project.stream.ProceduralStream; +import art.arcane.volmlib.util.math.RNG; +import com.google.gson.Gson; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.File; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Pins the blocks the dimension's rock and fluid palettes pick for a spread of columns, so they can move out of + * {@code IrisComplex} into the terrain module without changing what a world generates. The hash was taken from the streams + * {@code IrisComplex} built from {@code IrisDimension.getRockPalette()} and {@code getFluidPalette()} before they moved. + */ +public class TerrainPalettesPinTest { + private static final long COMPLEX_SEED = 424242L; + private static final long UPPER_DIMENSION_SEED_OFFSET = "upper".hashCode(); + private static final int TRANSCRIPT_LENGTH = 154196; + private static final int TRANSCRIPT_HASH = 1568450945; + private static final int COLUMN_RANGE = 1200; + private static final int COLUMN_STEP_X = 53; + private static final int COLUMN_STEP_Z = 59; + + private static final String STYLED = """ + {"rockPalette": {"style": {"style": "SIMPLEX", "zoom": 0.5}, "zoom": 9, + "palette": [{"block": "stone", "weight": 3}, {"block": "granite"}, {"block": "andesite", "weight": 2}, {"block": "diorite"}, {"block": "tuff"}]}, + "fluidPalette": {"style": {"style": "PERLIN", "zoom": 0.3}, + "palette": [{"block": "water"}, {"block": "lava", "weight": 2}, {"block": "packed_ice"}]}} + """; + private static final String DEFAULTS = "{}"; + private static final String SINGLE = "{\"rockPalette\": {\"palette\": [{\"block\": \"netherrack\"}]}, \"fluidPalette\": {\"palette\": [{\"block\": \"lava\"}]}}"; + + private IrisData data; + + @Before + public void bindPlatform() { + UsableBlockPlatform.bind(); + data = mock(IrisData.class); + @SuppressWarnings("unchecked") + ResourceLoader blocks = mock(ResourceLoader.class); + when(data.getBlockLoader()).thenReturn(blocks); + when(data.getDataFolder()).thenReturn(new File("pack")); + IrisPackResources resources = new IrisPackResources(data); + when(data.getPackResources()).thenReturn(resources); + } + + @After + public void unbindPlatform() { + UsableBlockPlatform.unbind(); + } + + @Test + public void rockAndFluidPickAsTheyDidInTheComplex() { + StringBuilder transcript = new StringBuilder(); + for (String json : List.of(STYLED, DEFAULTS, SINGLE)) { + IrisDimension dimension = new Gson().fromJson(json, IrisDimension.class); + record(transcript, dimension, new RNG(COMPLEX_SEED)); + record(transcript, dimension, new RNG(COMPLEX_SEED ^ UPPER_DIMENSION_SEED_OFFSET)); + } + + for (String picked : List.of("granite", "andesite", "diorite", "tuff", "lava", "packed_ice", "netherrack")) { + assertTrue(picked + " is picked", transcript.indexOf(picked) >= 0); + } + assertEquals("transcript " + transcript.length() + " / " + transcript.toString().hashCode(), TRANSCRIPT_LENGTH, transcript.length()); + assertEquals(TRANSCRIPT_HASH, transcript.toString().hashCode()); + } + + private void record(StringBuilder transcript, IrisDimension dimension, RNG complexRng) { + ProceduralStream rock = dimension.getRockPalette().getLayerGenerator(complexRng.nextParallelRNG(45), data).stream() + .select(dimension.getRockPalette().getBlockData(data)); + ProceduralStream fluid = dimension.getFluidPalette().getLayerGenerator(complexRng.nextParallelRNG(78), data).stream() + .select(dimension.getFluidPalette().getBlockData(data)); + for (int x = -COLUMN_RANGE; x < COLUMN_RANGE; x += COLUMN_STEP_X) { + for (int z = -COLUMN_RANGE; z < COLUMN_RANGE; z += COLUMN_STEP_Z) { + transcript.append(rock.get(x, z).key().replace("minecraft:", "")).append(',') + .append(fluid.get(x, z).key().replace("minecraft:", "")).append(' '); + } + } + } +} From 2c7b0cd1f7f4d0981eb5580ea7e18a8e7e348f68 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 08:20:59 +0200 Subject: [PATCH 02/10] Pin loot draws, loot reference resolution and entity resolution before the loot and spawn classes move --- .../iris/engine/loot/LootDrawPinTest.java | 83 +++++++++++ .../engine/loot/LootEnvironmentPinTest.java | 140 ++++++++++++++++++ .../engine/spawn/EntityResolutionPinTest.java | 73 +++++++++ 3 files changed, 296 insertions(+) create mode 100644 core/src/test/java/art/arcane/iris/engine/loot/LootDrawPinTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/loot/LootEnvironmentPinTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/spawn/EntityResolutionPinTest.java diff --git a/core/src/test/java/art/arcane/iris/engine/loot/LootDrawPinTest.java b/core/src/test/java/art/arcane/iris/engine/loot/LootDrawPinTest.java new file mode 100644 index 000000000..80acfa1f1 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/loot/LootDrawPinTest.java @@ -0,0 +1,83 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import art.arcane.iris.engine.object.loot.IrisLootTable; +import com.google.gson.Gson; +import com.volmit.item.ItemDrop; +import com.volmit.item.ItemRegistry; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.OptionalInt; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * What a loot table gives at fixed spots of a fixed world, as the whole drawn items, hashed. The numbers were taken + * before the loot classes became settings of the loot module; a change in them changes the loot of existing worlds. + */ +public class LootDrawPinTest { + private static final long LOOT_SEED = 8123456789L; + private static final String TABLE = """ + {"name": "Pin table", "rarity": 1, "minPicked": 2, "maxPicked": 6, "maxTries": 20, "loot": [ + {"type": "diamond_sword", "rarity": 2, "minAmount": 1, "maxAmount": 3, "minDurability": 0.25, "maxDurability": 0.75, + "displayName": "Pin blade", "lore": ["one", "two"], "unbreakable": true, "itemFlags": ["HIDE_ENCHANTS"], + "enchantments": [{"enchantment": "sharpness", "minLevel": 1, "maxLevel": 5, "chance": 0.6}, + {"enchantment": "unbreaking", "minLevel": 2, "maxLevel": 3}], + "attributes": [{"attribute": "max_health", "name": "bonus", "minAmount": 2, "maxAmount": 6, "chance": 0.7}]}, + {"type": "diamond", "minAmount": 1, "maxAmount": 5}, + {"type": "bread", "rarity": 2, "minAmount": 2, "maxAmount": 8, "customModel": 4, "dyeColor": "red", "leatherColor": "#ff0000"}, + {"type": "stick", "slotTypes": "FUEL"}, + {"type": "unknown_item"} + ]} + """; + private static final int[][] SPOTS = {{0, 64, 0}, {10, 64, -30}, {-512, 12, 777}, {4096, 200, -4096}, {7, -50, 7}}; + + private ItemRegistry registry; + + @Before + public void knowTheItems() { + registry = mock(ItemRegistry.class); + when(registry.maxDurability(anyString())).thenReturn(OptionalInt.empty()); + when(registry.maxDurability("diamond_sword")).thenReturn(OptionalInt.of(1561)); + when(registry.maxDurability("diamond")).thenReturn(OptionalInt.of(0)); + when(registry.maxDurability("bread")).thenReturn(OptionalInt.of(0)); + when(registry.maxDurability("stick")).thenReturn(OptionalInt.of(0)); + } + + @Test + public void aTableGivesThePinnedItemsAtEachSpot() { + IrisLootTable table = new Gson().fromJson(TABLE, IrisLootTable.class); + LootItems items = new LootItems(registry, false); + + List hashes = new ArrayList<>(); + for (int[] spot : SPOTS) { + List drops = items.draw(table, LOOT_SEED, spot[0], spot[1], spot[2]); + hashes.add(drops.toString().hashCode()); + } + + assertEquals(List.of(-492887340, -92432338, -1096436977, -1436497629, -1714085578), hashes); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/loot/LootEnvironmentPinTest.java b/core/src/test/java/art/arcane/iris/engine/loot/LootEnvironmentPinTest.java new file mode 100644 index 000000000..c88a3b7f7 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/loot/LootEnvironmentPinTest.java @@ -0,0 +1,140 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.ModuleResourceFixture; +import art.arcane.iris.engine.IrisComplex; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.loot.IrisLootReference; +import art.arcane.iris.engine.object.loot.IrisLootTable; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.volmlib.util.math.RNG; +import com.google.gson.Gson; +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.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Which loot tables a spot draws from, in which order and how often, for the loot references of its dimension, region and + * biomes, as written in pack JSON. Taken before the references became settings of the loot module. + */ +public class LootEnvironmentPinTest { + private static final int X = 10; + private static final int Z = 20; + private static final int SURFACE_Y = 70; + private static final int CAVE_Y = 40; + + private Engine engine; + private IrisDimension dimension; + private IrisRegion region; + private IrisBiome surface; + private IrisBiome cave; + + @Before + public void buildTheWorld() { + engine = mock(Engine.class, RETURNS_DEEP_STUBS); + IrisData data = mock(IrisData.class); + ModuleResourceFixture fixture = ModuleResourceFixture.serve(data); + for (String key : List.of("a", "b", "c", "d", "e")) { + fixture.resource(LootResources.TABLES, key, table(key)); + } + IrisComplex complex = engine.getComplex(); + when(complex.getData()).thenReturn(data); + dimension = mock(IrisDimension.class); + region = mock(IrisRegion.class); + surface = biome("surface"); + cave = biome("cave"); + when(engine.getDimension()).thenReturn(dimension); + when(complex.getRegionStream().get(X, Z)).thenReturn(region); + when(complex.getTrueBiomeStream().get(X, Z)).thenReturn(surface); + when(complex.getHeightStream().get(X, Z)).thenReturn(64D); + when(engine.getCaveBiome(X, CAVE_Y, Z)).thenReturn(cave); + when(engine.getCaveBiome(X, SURFACE_Y, Z)).thenReturn(surface); + } + + @Test + public void everyLevelAddsItsTablesInOrderAndTheMultipliersScaleTheCount() { + references("{\"tables\": [\"a\"]}", "{\"tables\": [\"b\", \"c\"], \"multiplier\": 2}", "{\"tables\": [\"d\"], \"multiplier\": 1.5}", "{}"); + + assertEquals(List.of("a", "b", "c", "d", "c", "d", "a", "b", "d", "c", "a", "b"), identities(false, SURFACE_Y)); + } + + @Test + public void fallbackReferencesStepAsideForTablesThatAnObjectDefined() { + references("{\"mode\": \"FALLBACK\", \"tables\": [\"a\"]}", "{\"tables\": [\"b\"]}", "{\"mode\": \"FALLBACK\", \"tables\": [\"c\"]}", "{}"); + + assertEquals(List.of("b"), identities(true, SURFACE_Y)); + assertEquals(List.of("a", "b", "c"), identities(false, SURFACE_Y)); + } + + @Test + public void replaceAndClearDropWhatCameBefore() { + references("{\"tables\": [\"a\"]}", "{\"mode\": \"REPLACE\", \"tables\": [\"b\"]}", "{\"tables\": [\"d\"]}", "{}"); + assertEquals(List.of("b", "d"), identities(false, SURFACE_Y)); + + references("{\"tables\": [\"a\"]}", "{\"tables\": [\"b\"]}", "{\"mode\": \"CLEAR\", \"tables\": [\"d\"]}", "{}"); + assertEquals(List.of(), identities(false, SURFACE_Y)); + } + + @Test + public void belowTheSurfaceTheCaveBiomeAddsItsTablesToo() { + references("{\"tables\": [\"a\"]}", "{}", "{\"tables\": [\"b\"]}", "{\"tables\": [\"e\"], \"multiplier\": 3}"); + + assertEquals(List.of("a", "b", "e", "e", "b", "a", "e", "a", "b"), identities(false, CAVE_Y)); + } + + private List identities(boolean objectLootDefined, int y) { + List sources = new ArrayList<>(); + LootTables.resolveEnvironmentSources(sources, engine, new RNG(19L), X, y, Z, objectLootDefined, LootTables::identity); + return sources; + } + + private void references(String dimensionJson, String regionJson, String surfaceJson, String caveJson) { + when(dimension.getLoot()).thenReturn(reference(dimensionJson)); + when(region.getLoot()).thenReturn(reference(regionJson)); + when(surface.getLoot()).thenReturn(reference(surfaceJson)); + when(cave.getLoot()).thenReturn(reference(caveJson)); + } + + private static IrisLootReference reference(String json) { + return new Gson().fromJson(json, IrisLootReference.class); + } + + private static IrisBiome biome(String key) { + IrisBiome biome = mock(IrisBiome.class); + when(biome.getLoadKey()).thenReturn(key); + return biome; + } + + private static IrisLootTable table(String key) { + IrisLootTable table = new IrisLootTable().setName(key); + table.setLoadKey(key); + return table; + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/spawn/EntityResolutionPinTest.java b/core/src/test/java/art/arcane/iris/engine/spawn/EntityResolutionPinTest.java new file mode 100644 index 000000000..fe872f7d2 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/spawn/EntityResolutionPinTest.java @@ -0,0 +1,73 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.spawn; + +import art.arcane.iris.engine.loot.LootItems; +import art.arcane.iris.engine.object.entity.IrisEntity; +import art.arcane.iris.spi.PlatformWorld; +import art.arcane.volmlib.util.math.RNG; +import com.google.gson.Gson; +import com.volmit.entity.EntitySpec; +import com.volmit.item.ItemRegistry; +import org.junit.Test; + +import java.util.OptionalInt; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * What an entity of the pack becomes when it is made from a fixed stream, hashed. The number was taken before the entity + * classes became settings of the spawn module; a change in it changes the equipment, attributes and passengers worlds spawn. + */ +public class EntityResolutionPinTest { + private static final long STREAM_SEED = 4321L; + private static final String ENTITY = """ + {"type": "minecraft:zombie", "customName": "&cPin", "aware": false, "glowing": true, "baby": true, "removable": true, + "helmet": {"type": "iron_helmet", "rarity": 2, "minDurability": 0.2, "maxDurability": 0.9, + "enchantments": [{"enchantment": "protection", "minLevel": 1, "maxLevel": 4}]}, + "mainHand": {"type": "diamond_sword", "minAmount": 1, "maxAmount": 1, + "attributes": [{"attribute": "attack_damage", "name": "pin", "minAmount": 1, "maxAmount": 9}]}, + "offHand": {"type": "bread", "minAmount": 1, "maxAmount": 6}, + "attributes": [{"attribute": "max_health", "name": "tough", "minAmount": 10, "maxAmount": 40, "chance": 0.8}, + {"attribute": "movement_speed", "name": "quick", "operation": "ADD_SCALAR", "minAmount": 0.1, "maxAmount": 0.3}], + "loot": {"tables": ["zombie/drops", "zombie/rare"]}, + "passengers": [{"type": "minecraft:chicken", "baby": true, "helmet": {"type": "bread"}}], + "leashHolder": {"type": "minecraft:bat", "attributes": [{"attribute": "max_health", "name": "tiny", "minAmount": 1, "maxAmount": 3}]}, + "spawnEffect": {"sound": "entity.zombie.ambient", "particleEffect": "SMOKE", "particleCount": 3, "interval": 0, "chance": 1}, + "spawnEffectRiseOutOfGround": true, + "rawCommands": [{"commands": ["say hello {x}"], "delay": 5, "repeat": true, "repeatDelay": 40}]} + """; + + @Test + public void anEntityResolvesToThePinnedSpec() { + ItemRegistry registry = mock(ItemRegistry.class); + when(registry.maxDurability(anyString())).thenReturn(OptionalInt.of(0)); + when(registry.maxDurability("iron_helmet")).thenReturn(OptionalInt.of(165)); + when(registry.maxDurability("diamond_sword")).thenReturn(OptionalInt.of(1561)); + PlatformWorld world = mock(PlatformWorld.class); + IrisEntity entity = new Gson().fromJson(ENTITY, IrisEntity.class); + + EntitySpec spec = new EntityResolution(new LootItems(registry, false), world).resolve(entity, new RNG(STREAM_SEED)); + + assertEquals(1726532922, spec.toString().hashCode()); + } +} From fac06c3beb1066e03057b8bd8a8745eb50e21bfc Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 08:27:45 +0200 Subject: [PATCH 03/10] Tests for the ore settings: resolved ores pinned against the deleted IrisOreGenerator, warm-up order, terrain ore order, decoding of the old keys --- .../modules/DecorantSettingsDecodingTest.java | 3 +- .../modules/DepositSettingsDecodingTest.java | 3 +- .../core/modules/OreSettingsDecodingTest.java | 183 ++++++++++++++++++ .../iris/engine/actuator/OreWarmUpTest.java | 55 +++--- .../iris/engine/actuator/ResolvedOreTest.java | 166 ++++++++++++++++ .../engine/actuator/TerrainModuleTest.java | 54 +++++- .../engine/modifier/ResolvedDepositTest.java | 8 +- .../modifier/ResolvedDepositVariantTest.java | 75 +++++++ 8 files changed, 508 insertions(+), 39 deletions(-) create mode 100644 core/src/test/java/art/arcane/iris/core/modules/OreSettingsDecodingTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/actuator/ResolvedOreTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/modifier/ResolvedDepositVariantTest.java diff --git a/core/src/test/java/art/arcane/iris/core/modules/DecorantSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/DecorantSettingsDecodingTest.java index f84b1f653..647016d36 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/DecorantSettingsDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/DecorantSettingsDecodingTest.java @@ -137,7 +137,8 @@ public class DecorantSettingsDecodingTest { JSONObject byId = new JSONObject("{\"iris:decorant\": [{\"chance\": 1}]}"); assertSame(ModuleSettings.NONE, decoder.decode(Target.BIOME, byId, "biome meadow")); - assertEquals(Set.of("decorators", "deposits"), decoder.keys(Target.BIOME)); + assertTrue(decoder.keys(Target.BIOME).containsAll(Set.of("decorators", "deposits"))); + assertFalse(decoder.keys(Target.BIOME).contains("iris:decorant")); } @Test diff --git a/core/src/test/java/art/arcane/iris/core/modules/DepositSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/DepositSettingsDecodingTest.java index fb91ac9f9..62b56e3b1 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/DepositSettingsDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/DepositSettingsDecodingTest.java @@ -147,7 +147,8 @@ public class DepositSettingsDecodingTest { JSONObject byId = new JSONObject("{\"iris:deposit\": [{\"maxHeight\": 16}]}"); assertSame(ModuleSettings.NONE, decoder.decode(Target.REGION, byId, "region forests")); - assertEquals(Set.of("deposits"), decoder.keys(Target.REGION)); + assertTrue(decoder.keys(Target.REGION).contains("deposits")); + assertFalse(decoder.keys(Target.REGION).contains("iris:deposit")); } @Test diff --git a/core/src/test/java/art/arcane/iris/core/modules/OreSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/OreSettingsDecodingTest.java new file mode 100644 index 000000000..7a162afa2 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/modules/OreSettingsDecodingTest.java @@ -0,0 +1,183 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.modules; + +import art.arcane.iris.builtin.deposit.DepositVariant; +import art.arcane.iris.builtin.deposit.DepositVariantSettings; +import art.arcane.iris.builtin.deposit.OreFrequencySettings; +import art.arcane.iris.builtin.deposit.OreSizeSettings; +import art.arcane.iris.builtin.terrain.HideOresSettings; +import art.arcane.iris.builtin.terrain.OreGenerator; +import art.arcane.iris.builtin.terrain.OreSettings; +import art.arcane.volmlib.util.json.JSONObject; +import com.google.gson.Gson; +import com.volmit.FeatureAttachment.Target; +import com.volmit.block.BlockSpec; +import com.volmit.host.LoadedPack; +import com.volmit.host.ModuleHost; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * The ore settings packs have always written, read by the terrain and deposit modules under their old keys: {@code ores} (a + * list at a dimension, region or biome), {@code hideOresForHiddenOre} (a boolean at a dimension), {@code depositVariants} (a list) + * and the two ore deposit multipliers (numbers at a biome). The dimension is the overworld file as it was before the port. + */ +public class OreSettingsDecodingTest { + private static final String PACK = "/art/arcane/iris/core/modules/pack-before-the-port"; + + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + + private Path packFolder; + private LoadedPack pack; + private ModuleSettingsDecoder decoder; + + @Before + public void loadBuiltIns() throws IOException, URISyntaxException { + packFolder = Path.of(OreSettingsDecodingTest.class.getResource(PACK).toURI()); + pack = LoadedPack.load(packFolder, ModuleHost.of(IrisModuleHost.builtInModules()) + .reservingFields(ModuleTargets.reservedFields()) + .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGE).copyingJarsTo(folder.newFolder("copies").toPath())); + decoder = new ModuleSettingsDecoder(pack.catalog(), packFolder, Gson::new); + } + + @After + public void closePack() { + pack.close(); + } + + @Test + public void theOverworldReadsItsOresInTheOrderTheFileListsThem() throws IOException { + JSONObject dimension = new JSONObject(Files.readString(packFolder.resolve("dimensions/overworld.json"))); + + List ores = decoder.decode(Target.DIMENSION, dimension, "dimension overworld") + .find(OreSettings.class).orElseThrow().generators(); + + assertEquals(dimension.getJSONArray("ores").length(), ores.size()); + assertEquals(11, ores.size()); + OreGenerator firstBedrock = ores.getFirst(); + assertEquals(1, firstBedrock.threshold(), 0); + assertEquals(0, firstBedrock.range().min(), 0); + assertEquals(0, firstBedrock.range().max(), 0); + assertEquals(List.of(BlockSpec.of("minecraft:bedrock")), firstBedrock.palette().palette()); + assertEquals("FLAT", firstBedrock.chanceStyle().style()); + assertFalse(firstBedrock.generateSurface()); + OreGenerator secondBedrock = ores.get(1); + assertEquals(0.625, secondBedrock.threshold(), 0); + assertEquals("a snippet reference reads the snippet's style", "STATIC", secondBedrock.chanceStyle().style()); + OreGenerator lastDeepslate = ores.getLast(); + assertEquals(0.125, lastDeepslate.threshold(), 0); + assertEquals(64, lastDeepslate.range().min(), 0); + assertEquals(List.of(BlockSpec.of("minecraft:deepslate")), lastDeepslate.palette().palette()); + } + + @Test + public void oresOfARegionAndABiomeReadSurfaceFlagsStylesAndPalettes() { + JSONObject ores = new JSONObject(""" + {"ores": [ + {"generateSurface": true, "threshold": 0.3, "range": {"min": 50, "max": 90}, + "chanceStyle": {"style": "SIMPLEX", "zoom": 4}, + "palette": {"zoom": 2, "palette": [{"block": "minecraft:gold_ore"}, {"block": "minecraft:gold_block", "weight": 3}]}}, + {} + ]} + """); + + for (Target target : List.of(Target.REGION, Target.BIOME)) { + List read = decoder.decode(target, ores, "test").find(OreSettings.class).orElseThrow().generators(); + + assertEquals(2, read.size()); + assertTrue(read.getFirst().generateSurface()); + assertEquals(0.3, read.getFirst().threshold(), 0); + assertEquals("SIMPLEX", read.getFirst().chanceStyle().style()); + assertEquals(4, read.getFirst().chanceStyle().zoom(), 0); + assertEquals(2, read.getFirst().palette().zoom(), 0); + assertEquals(List.of(BlockSpec.of("minecraft:gold_ore"), BlockSpec.of("minecraft:gold_block").withWeight(3)), read.getFirst().palette().palette()); + assertEquals("an empty generator keeps Iris's defaults", 0.5, read.get(1).threshold(), 0); + assertEquals(List.of(), read.get(1).palette().palette()); + } + } + + @Test + public void hideOresForHiddenOreIsABooleanOnTheDimension() { + ModuleSettings hidden = decoder.decode(Target.DIMENSION, new JSONObject("{\"hideOresForHiddenOre\": true}"), "dimension test"); + ModuleSettings shown = decoder.decode(Target.DIMENSION, new JSONObject("{\"hideOresForHiddenOre\": false}"), "dimension test"); + + assertTrue(hidden.find(HideOresSettings.class).orElseThrow().hide()); + assertFalse(shown.find(HideOresSettings.class).orElseThrow().hide()); + assertTrue("a dimension that does not write it declares nothing", decoder.decode(Target.DIMENSION, new JSONObject("{}"), "dimension test").isEmpty()); + } + + @Test + public void depositVariantsAreAListAtEveryLevel() { + JSONObject json = new JSONObject(""" + {"depositVariants": [ + {"minHeight": -64, "maxHeight": 0, "remap": {"minecraft:iron_ore": "minecraft:deepslate_iron_ore", "minecraft:coal_ore": "minecraft:deepslate_coal_ore"}}, + {"maxHeight": 10} + ]} + """); + + for (Target target : List.of(Target.DIMENSION, Target.REGION, Target.BIOME)) { + List variants = decoder.decode(target, json, "test").find(DepositVariantSettings.class).orElseThrow().variants(); + + assertEquals(2, variants.size()); + assertEquals(-64, variants.getFirst().minHeight()); + assertEquals(0, variants.getFirst().maxHeight()); + assertEquals(Map.of("minecraft:iron_ore", "minecraft:deepslate_iron_ore", "minecraft:coal_ore", "minecraft:deepslate_coal_ore"), + variants.getFirst().remap()); + assertEquals(0, variants.get(1).minHeight()); + assertEquals(10, variants.get(1).maxHeight()); + assertEquals(Map.of(), variants.get(1).remap()); + } + } + + @Test + public void theTwoOreDepositMultipliersAreNumbersOnTheBiome() { + ModuleSettings tuned = decoder.decode(Target.BIOME, new JSONObject("{\"oreDepositFrequencyMultiplier\": 0.4, \"oreDepositSizeMultiplier\": 2}"), "biome test"); + ModuleSettings plain = decoder.decode(Target.BIOME, new JSONObject("{}"), "biome test"); + + assertEquals(0.4, tuned.find(OreFrequencySettings.class).orElseThrow().multiplier(), 0); + assertEquals(2, tuned.find(OreSizeSettings.class).orElseThrow().multiplier(), 0); + assertTrue(plain.find(OreFrequencySettings.class).isEmpty()); + assertTrue(plain.find(OreSizeSettings.class).isEmpty()); + } + + @Test + public void everyKeyIsOnlyReadAtTheLevelsTheOldFieldExistedAt() { + assertTrue(decoder.keys(Target.DIMENSION).containsAll(List.of("ores", "hideOresForHiddenOre", "depositVariants"))); + assertTrue(decoder.keys(Target.REGION).containsAll(List.of("ores", "depositVariants"))); + assertFalse(decoder.keys(Target.REGION).contains("hideOresForHiddenOre")); + assertTrue(decoder.keys(Target.BIOME).containsAll(List.of("ores", "depositVariants", "oreDepositFrequencyMultiplier", "oreDepositSizeMultiplier"))); + assertFalse(decoder.keys(Target.DIMENSION).contains("oreDepositFrequencyMultiplier")); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/actuator/OreWarmUpTest.java b/core/src/test/java/art/arcane/iris/engine/actuator/OreWarmUpTest.java index 76a76f332..f52cda083 100644 --- a/core/src/test/java/art/arcane/iris/engine/actuator/OreWarmUpTest.java +++ b/core/src/test/java/art/arcane/iris/engine/actuator/OreWarmUpTest.java @@ -1,26 +1,23 @@ package art.arcane.iris.engine.actuator; -import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.SeedManager; -import art.arcane.iris.engine.object.terrain.deposit.IrisOreGenerator; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -/** Ore generators keep the noise of the first random they are warmed with, so the order and the randoms of the warm-up are pinned. */ +/** Ore generators keep the noise of the first seed they are warmed with, so the order and the seeds of the warm-up are pinned. */ public class OreWarmUpTest { private static final long COMPONENT_SEED = 100L; private static final long ROOT_SEED = COMPONENT_SEED + 7777L; @@ -28,54 +25,52 @@ public class OreWarmUpTest { private final List warmed = new ArrayList<>(); @Test - public void biomesByKeyThenRegionsByKeyThenTheDimensionWarmWithConsecutiveRandomsOfTheWorld() { + public void biomesByKeyThenRegionsByKeyThenTheDimensionWarmWithConsecutiveSeedsOfTheWorld() { SeedManager seeds = mock(SeedManager.class); when(seeds.getComponent()).thenReturn(COMPONENT_SEED); IrisDimension dimension = mock(IrisDimension.class); Engine engine = mock(Engine.class); when(engine.getSeedManager()).thenReturn(seeds); - when(engine.getData()).thenReturn(mock(IrisData.class)); when(engine.getDimension()).thenReturn(dimension); - IrisBiome biomeB = biome("b", ore("b0"), null, ore("b1")); - IrisBiome biomeA = biome("a", ore("a0")); - IrisRegion regionY = region("y", ore("y0")); - IrisRegion regionX = region("x", ore("x0"), ore("x1")); - KList dimensionOres = list(ore("d0")); + TerrainOres ores = mock(TerrainOres.class); + IrisBiome biomeB = biome("b", ores, "b0", "b1"); + IrisBiome biomeA = biome("a", ores, "a0"); + IrisRegion regionY = region("y", ores, "y0"); + IrisRegion regionX = region("x", ores, "x0", "x1"); + ResolvedOres dimensionOres = resolved("d0"); + when(ores.of(dimension)).thenReturn(dimensionOres); when(engine.getAllBiomes()).thenReturn(new KList<>(List.of(biomeB, biomeA))); when(dimension.getAllRegions(engine)).thenReturn(new KList<>(List.of(regionY, regionX))); - when(dimension.getOres()).thenReturn(dimensionOres); - new OreWarmUp(engine).warm(); + new OreWarmUp(engine, ores).warm(); assertEquals(List.of("a0@" + ROOT_SEED, "b0@" + (ROOT_SEED + 1), "b1@" + (ROOT_SEED + 2), "x0@" + (ROOT_SEED + 3), "x1@" + (ROOT_SEED + 4), "y0@" + (ROOT_SEED + 5), "d0@" + (ROOT_SEED + 6)), warmed); } - private IrisOreGenerator ore(String name) { - IrisOreGenerator ore = mock(IrisOreGenerator.class); - doAnswer(call -> warmed.add(name + "@" + call.getArgument(0).getSeed())).when(ore).warm(any(RNG.class), any()); - return ore; + private ResolvedOres resolved(String... names) { + List ores = new ArrayList<>(); + for (String name : names) { + ResolvedOre ore = mock(ResolvedOre.class); + doAnswer(call -> warmed.add(name + "@" + call.getArgument(0))).when(ore).warm(anyLong()); + ores.add(ore); + } + return new ResolvedOres(ores); } - private static IrisBiome biome(String key, IrisOreGenerator... ores) { + private IrisBiome biome(String key, TerrainOres ores, String... oreNames) { IrisBiome biome = mock(IrisBiome.class); when(biome.getLoadKey()).thenReturn(key); - when(biome.getOres()).thenReturn(list(ores)); + ResolvedOres declared = resolved(oreNames); + when(ores.of(biome)).thenReturn(declared); return biome; } - private static IrisRegion region(String key, IrisOreGenerator... ores) { + private IrisRegion region(String key, TerrainOres ores, String... oreNames) { IrisRegion region = mock(IrisRegion.class); when(region.getLoadKey()).thenReturn(key); - when(region.getOres()).thenReturn(list(ores)); + ResolvedOres declared = resolved(oreNames); + when(ores.of(region)).thenReturn(declared); return region; } - - private static KList list(IrisOreGenerator... ores) { - KList list = new KList<>(); - for (IrisOreGenerator ore : ores) { - list.add(ore); - } - return list; - } } diff --git a/core/src/test/java/art/arcane/iris/engine/actuator/ResolvedOreTest.java b/core/src/test/java/art/arcane/iris/engine/actuator/ResolvedOreTest.java new file mode 100644 index 000000000..c6ebf2226 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/actuator/ResolvedOreTest.java @@ -0,0 +1,166 @@ +package art.arcane.iris.engine.actuator; + +import art.arcane.iris.builtin.terrain.OreGenerator; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.loader.ResourceLoader; +import art.arcane.iris.core.modules.IrisPackResources; +import art.arcane.iris.engine.UsableBlockPlatform; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.SeedManager; +import art.arcane.iris.engine.object.material.IrisBlockData; +import art.arcane.iris.spi.PlatformBlockState; +import com.google.gson.Gson; +import com.volmit.noise.NoiseSampler; +import org.junit.After; +import org.junit.Test; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ResolvedOreTest { + private static final long TERRAIN_SEED = 1337L; + private static final long WARM_SEED = 99L; + /** Taken from {@code IrisOreGenerator} (now deleted) generating the same ores with the same seeds, before ores moved into the terrain module. */ + private static final int TRANSCRIPT_LENGTH = 128237; + private static final int TRANSCRIPT_HASH = -1665706847; + private static final String[] ORES = { + "{\"palette\":{\"palette\":[{\"block\":\"coal_ore\"}]},\"chanceStyle\":{\"style\":\"STATIC\"},\"threshold\":0.2,\"range\":{\"min\":0,\"max\":64}}", + "{\"palette\":{\"palette\":[{\"block\":\"iron_ore\"},{\"block\":\"deepslate_iron_ore\"}]},\"chanceStyle\":{\"style\":\"SIMPLEX\",\"zoom\":4}," + + "\"threshold\":0.5,\"range\":{\"min\":-16,\"max\":40}}", + "{\"palette\":{\"palette\":[{\"block\":\"gold_ore\"},{\"block\":\"gold_block\"},{\"block\":\"raw_gold_block\"}]},\"chanceStyle\":{\"style\":\"PERLIN\",\"zoom\":2}," + + "\"threshold\":0.35,\"range\":{\"min\":10,\"max\":20}}", + "{\"palette\":{\"palette\":[]},\"chanceStyle\":{\"style\":\"STATIC\"},\"threshold\":1,\"range\":{\"min\":0,\"max\":100}}", + "{\"palette\":{\"palette\":[{\"block\":\"bedrock\"}]},\"chanceStyle\":{\"style\":\"FLAT\"},\"threshold\":1,\"range\":{\"min\":0,\"max\":3}}", + }; + + @After + public void unbindPlatform() { + UsableBlockPlatform.unbind(); + } + + @Test + public void everyOreGeneratesAsIrisOreGeneratorDid() { + UsableBlockPlatform.bind(); + Engine engine = engine(); + StringBuilder transcript = new StringBuilder(); + for (String json : ORES) { + ResolvedOre ore = ResolvedOre.of(new Gson().fromJson(json, OreGenerator.class), engine); + ore.warm(WARM_SEED); + for (int x = -30; x < 30; x += 3) { + for (int z = -30; z < 30; z += 4) { + for (int y = -20; y < 70; y += 5) { + PlatformBlockState state = ore.generate(x, y, z); + transcript.append(state == null ? "-" : state.key()).append(';'); + } + } + } + } + assertTrue("the palettes' blocks are placed", transcript.indexOf("minecraft:deepslate_iron_ore") >= 0 + && transcript.indexOf("minecraft:iron_ore") >= 0 && transcript.indexOf("minecraft:coal_ore") >= 0 && transcript.indexOf("minecraft:bedrock") >= 0); + assertTrue("positions without ore occur", transcript.indexOf("-") >= 0); + assertEquals(TRANSCRIPT_LENGTH, transcript.length()); + assertEquals(TRANSCRIPT_HASH, transcript.toString().hashCode()); + } + + @Test + public void theNoiseKeepsTheFirstSeedItIsBuiltFrom() { + UsableBlockPlatform.bind(); + OreGenerator settings = new Gson().fromJson(ORES[1], OreGenerator.class); + List seeds = new ArrayList<>(); + ResolvedOre ore = new ResolvedOre(settings, (style, seed) -> { + seeds.add(seed); + return constant(0); + }, null, TERRAIN_SEED, List.of(UsableBlockPlatform.block("iron_ore"))); + + ore.warm(WARM_SEED); + ore.warm(WARM_SEED + 1); + ore.generate(0, 0, 0); + + assertEquals(List.of(WARM_SEED), seeds); + } + + @Test + public void anOreNothingWarmedBuildsItsNoiseFromTheTerrainSeed() { + UsableBlockPlatform.bind(); + OreGenerator settings = new Gson().fromJson(ORES[1], OreGenerator.class); + List seeds = new ArrayList<>(); + ResolvedOre ore = new ResolvedOre(settings, (style, seed) -> { + seeds.add(seed); + return constant(0); + }, null, TERRAIN_SEED, List.of(UsableBlockPlatform.block("iron_ore"))); + + ore.generate(0, 0, 0); + ore.generate(1, 1, 1); + + assertEquals(List.of(TERRAIN_SEED), seeds); + } + + @Test + public void nothingGeneratesOutsideTheBandOrWithAnEmptyPaletteOrAboveTheThreshold() { + UsableBlockPlatform.bind(); + PlatformBlockState iron = UsableBlockPlatform.block("iron_ore"); + OreGenerator settings = new Gson().fromJson(ORES[1], OreGenerator.class); + ResolvedOre atThreshold = new ResolvedOre(settings, (style, seed) -> constant(0.5), null, TERRAIN_SEED, List.of(iron)); + ResolvedOre aboveThreshold = new ResolvedOre(settings, (style, seed) -> constant(0.51), null, TERRAIN_SEED, List.of(iron)); + ResolvedOre noBlocks = new ResolvedOre(settings, (style, seed) -> constant(0), null, TERRAIN_SEED, List.of()); + OreGenerator emptyPalette = new Gson().fromJson(ORES[3], OreGenerator.class); + ResolvedOre empty = new ResolvedOre(emptyPalette, (style, seed) -> constant(0), null, TERRAIN_SEED, List.of()); + + assertEquals("noise at the threshold becomes ore", iron, atThreshold.generate(0, 0, 0)); + assertNull(aboveThreshold.generate(0, 0, 0)); + assertNull("below the band", atThreshold.generate(0, -17, 0)); + assertNull("above the band", atThreshold.generate(0, 41, 0)); + assertEquals("the band's ends are in it", iron, atThreshold.generate(0, 40, 0)); + assertNull(noBlocks.generate(0, 0, 0)); + assertNull(empty.generate(0, 50, 0)); + } + + @Test + public void oresDefaultToNoBlocksSurfaceOffAndTheDocumentedBand() { + OreGenerator ore = new Gson().fromJson("{}", OreGenerator.class); + + assertEquals(List.of(), ore.palette().palette()); + assertEquals("STATIC", ore.chanceStyle().style()); + assertEquals(false, ore.generateSurface()); + assertEquals(0.5, ore.threshold(), 0); + assertEquals(30, ore.range().min(), 0); + assertEquals(80, ore.range().max(), 0); + } + + private static NoiseSampler constant(double value) { + return new NoiseSampler() { + @Override + public double sample(double worldX, double worldZ) { + return value; + } + + @Override + public double sample(double worldX, double y, double worldZ) { + return value; + } + }; + } + + private static Engine engine() { + IrisData data = mock(IrisData.class); + @SuppressWarnings("unchecked") + ResourceLoader blocks = mock(ResourceLoader.class); + when(data.getBlockLoader()).thenReturn(blocks); + when(data.getDataFolder()).thenReturn(new File("pack")); + IrisPackResources resources = new IrisPackResources(data); + when(data.getPackResources()).thenReturn(resources); + SeedManager seeds = mock(SeedManager.class); + when(seeds.getTerrain()).thenReturn(TERRAIN_SEED); + Engine engine = mock(Engine.class); + when(engine.getData()).thenReturn(data); + when(engine.getSeedManager()).thenReturn(seeds); + return engine; + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/actuator/TerrainModuleTest.java b/core/src/test/java/art/arcane/iris/engine/actuator/TerrainModuleTest.java index 0e9d5ba07..d07d5df13 100644 --- a/core/src/test/java/art/arcane/iris/engine/actuator/TerrainModuleTest.java +++ b/core/src/test/java/art/arcane/iris/engine/actuator/TerrainModuleTest.java @@ -15,9 +15,13 @@ import art.arcane.iris.util.project.context.ChunkedDataCache; import art.arcane.iris.util.project.hunk.Hunk; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; +import art.arcane.iris.builtin.terrain.HideOresSettings; +import art.arcane.iris.core.modules.BuiltInPack; import org.junit.After; import org.junit.Test; +import java.util.List; + import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; @@ -26,6 +30,7 @@ import static org.junit.Assert.assertSame; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyDouble; import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -48,7 +53,7 @@ public class TerrainModuleTest { @SuppressWarnings("unchecked") public void aColumnIsBedrockThenRockThenLayersThenFluid() { UsableBlockPlatform.bind(); - TerrainModule.TerrainShaper shaper = new TerrainModule.TerrainShaper(engine()); + TerrainModule.TerrainShaper shaper = new TerrainModule.TerrainShaper(engine(true), mock(TerrainOres.class)); Hunk blocks = Hunk.newArrayHunk(16, 64, 16); IrisBiome biome = mock(IrisBiome.class); KList layers = new KList<>(); @@ -69,6 +74,49 @@ public class TerrainModuleTest { assertNull("nothing above the fluid", blocks.get(3, FLUID_HEIGHT + 1, 4)); } + @Test + @SuppressWarnings("unchecked") + public void oresOfTheBiomeThenTheRegionThenTheDimensionReplaceTheBlocksTheirBandsReach() { + UsableBlockPlatform.bind(); + Engine engine = engine(false); + IrisDimension dimension = engine.getDimension(); + IrisBiome biome = mock(IrisBiome.class); + when(biome.generateLayers(any(), anyDouble(), anyDouble(), any(RNG.class), anyInt(), anyInt(), any(), any())).thenReturn(new KList<>()); + when(biome.generateSeaLayers(anyDouble(), anyDouble(), any(RNG.class), anyInt(), any())).thenReturn(new KList<>()); + ChunkContext context = context(biome); + IrisRegion region = context.getRegion().get(0, 0); + PlatformBlockState biomeOre = mock(PlatformBlockState.class); + PlatformBlockState regionOre = mock(PlatformBlockState.class); + PlatformBlockState dimensionOre = mock(PlatformBlockState.class); + TerrainOres ores = mock(TerrainOres.class); + ResolvedOres biomeOres = oresAt(2, biomeOre); + ResolvedOres regionOres = oresAt(2, regionOre, 3, regionOre); + ResolvedOres dimensionOres = oresAt(2, dimensionOre, 3, dimensionOre, 4, dimensionOre); + when(ores.of(biome)).thenReturn(biomeOres); + when(ores.of(region)).thenReturn(regionOres); + when(ores.of(dimension)).thenReturn(dimensionOres); + Hunk blocks = Hunk.newArrayHunk(16, 64, 16); + + new TerrainModule.TerrainShaper(engine, ores).shape(0, 0, blocks, context); + + assertSame("the biome's ore comes first", biomeOre, blocks.get(3, 2, 4)); + assertSame("then the region's", regionOre, blocks.get(3, 3, 4)); + assertSame("then the dimension's", dimensionOre, blocks.get(3, 4, 4)); + assertSame("rock where no ore reaches", rock, blocks.get(3, 5, 4)); + } + + /** Underground ores that give {@code block} at each listed height and nothing elsewhere. */ + private static ResolvedOres oresAt(Object... heightsAndBlocks) { + ResolvedOre ore = mock(ResolvedOre.class); + when(ore.generatesSurface()).thenReturn(false); + when(ore.minY()).thenReturn(0D); + when(ore.maxY()).thenReturn(10D); + for (int index = 0; index < heightsAndBlocks.length; index += 2) { + when(ore.generate(anyInt(), eq((int) heightsAndBlocks[index]), anyInt())).thenReturn((PlatformBlockState) heightsAndBlocks[index + 1]); + } + return new ResolvedOres(List.of(ore)); + } + @SuppressWarnings("unchecked") private ChunkContext context(IrisBiome biome) { ChunkedDataCache biomes = mock(ChunkedDataCache.class); @@ -88,11 +136,11 @@ public class TerrainModuleTest { return context; } - private Engine engine() { + private Engine engine(boolean hidesOres) { IrisDimension dimension = mock(IrisDimension.class); when(dimension.getFluidHeight()).thenReturn(FLUID_HEIGHT); when(dimension.isBedrock()).thenReturn(true); - when(dimension.isHideOresForHiddenOre()).thenReturn(true); + when(dimension.getModuleSettings()).thenReturn(BuiltInPack.settings(new HideOresSettings(hidesOres))); IrisComplex complex = mock(IrisComplex.class); when(complex.getImageMapRuntime()).thenReturn(mock(IrisImageMapRuntime.class)); SeedManager seeds = mock(SeedManager.class); diff --git a/core/src/test/java/art/arcane/iris/engine/modifier/ResolvedDepositTest.java b/core/src/test/java/art/arcane/iris/engine/modifier/ResolvedDepositTest.java index 25f45dc81..e88266f97 100644 --- a/core/src/test/java/art/arcane/iris/engine/modifier/ResolvedDepositTest.java +++ b/core/src/test/java/art/arcane/iris/engine/modifier/ResolvedDepositTest.java @@ -1,6 +1,8 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.deposit.DepositGenerator; +import art.arcane.iris.builtin.deposit.OreFrequencySettings; +import art.arcane.iris.builtin.deposit.OreSizeSettings; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.ResourceLoader; import art.arcane.iris.core.modules.PackResourceFixture; @@ -91,10 +93,8 @@ public class ResolvedDepositTest { @Test public void biomeOreTuningDefaultsPreserveExistingGeneration() { - IrisBiome biome = new IrisBiome(); - - assertEquals(1D, biome.getOreDepositFrequencyMultiplier(), 0D); - assertEquals(1D, biome.getOreDepositSizeMultiplier(), 0D); + assertEquals(1D, new OreFrequencySettings().multiplier(), 0D); + assertEquals(1D, new OreSizeSettings().multiplier(), 0D); } @Test diff --git a/core/src/test/java/art/arcane/iris/engine/modifier/ResolvedDepositVariantTest.java b/core/src/test/java/art/arcane/iris/engine/modifier/ResolvedDepositVariantTest.java new file mode 100644 index 000000000..a4ed1db2c --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/modifier/ResolvedDepositVariantTest.java @@ -0,0 +1,75 @@ +package art.arcane.iris.engine.modifier; + +import art.arcane.iris.builtin.deposit.DepositVariant; +import art.arcane.iris.engine.UsableBlockPlatform; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.PlatformBlockState; +import com.google.gson.Gson; +import org.junit.After; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +public class ResolvedDepositVariantTest { + private static final String DEEP_IRON = """ + {"minHeight": -64, "maxHeight": 0, "remap": {"minecraft:iron_ore": "minecraft:deepslate_iron_ore", "unknown_block": "minecraft:stone"}} + """; + + private static void knowEveryBlockButTheUnknownOne() { + UsableBlockPlatform.bind(); + when(IrisPlatforms.get().registries().blockOrNull(anyString(), anyBoolean())).thenAnswer(call -> { + String name = call.getArgument(0); + return name.equals("unknown_block") ? null : UsableBlockPlatform.block(name); + }); + } + + @After + public void unbindPlatform() { + UsableBlockPlatform.unbind(); + } + + @Test + public void aVariantAppliesWithinItsInclusiveBand() { + ResolvedDepositVariant variant = new ResolvedDepositVariant(new Gson().fromJson(DEEP_IRON, DepositVariant.class)); + + assertTrue(variant.appliesAt(-64)); + assertTrue(variant.appliesAt(0)); + assertFalse(variant.appliesAt(-65)); + assertFalse(variant.appliesAt(1)); + } + + @Test + public void anOreIsRemappedByItsMaterialAndOtherBlocksAreNot() { + knowEveryBlockButTheUnknownOne(); + ResolvedDepositVariant variant = new ResolvedDepositVariant(new Gson().fromJson(DEEP_IRON, DepositVariant.class)); + PlatformBlockState iron = UsableBlockPlatform.block("iron_ore"); + + PlatformBlockState remapped = variant.remapOrNull(iron); + + assertEquals("minecraft:deepslate_iron_ore", remapped.key()); + assertNull(variant.remapOrNull(UsableBlockPlatform.block("coal_ore"))); + assertNull(variant.remapOrNull(null)); + } + + @Test + public void aRuleWhoseSourceTheServerDoesNotKnowRemapsNothing() { + knowEveryBlockButTheUnknownOne(); + DepositVariant unknown = new Gson().fromJson("{\"remap\": {\"unknown_block\": \"minecraft:stone\"}}", DepositVariant.class); + + assertNull(new ResolvedDepositVariant(unknown).remapOrNull(UsableBlockPlatform.block("unknown_block"))); + } + + @Test + public void aVariantWithoutRemapsChangesNothing() { + UsableBlockPlatform.bind(); + ResolvedDepositVariant variant = new ResolvedDepositVariant(new Gson().fromJson("{\"maxHeight\": 5}", DepositVariant.class)); + + assertNull(variant.remapOrNull(UsableBlockPlatform.block("iron_ore"))); + } +} From ee2818514f8a13f1a529698ae292f8039b94ec08 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 08:29:05 +0200 Subject: [PATCH 04/10] Entity resolution pin: an interval that always elapses, so the spawn effect is part of the pinned spec --- .../art/arcane/iris/engine/spawn/EntityResolutionPinTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/src/test/java/art/arcane/iris/engine/spawn/EntityResolutionPinTest.java b/core/src/test/java/art/arcane/iris/engine/spawn/EntityResolutionPinTest.java index fe872f7d2..616a1d096 100644 --- a/core/src/test/java/art/arcane/iris/engine/spawn/EntityResolutionPinTest.java +++ b/core/src/test/java/art/arcane/iris/engine/spawn/EntityResolutionPinTest.java @@ -52,7 +52,7 @@ public class EntityResolutionPinTest { "loot": {"tables": ["zombie/drops", "zombie/rare"]}, "passengers": [{"type": "minecraft:chicken", "baby": true, "helmet": {"type": "bread"}}], "leashHolder": {"type": "minecraft:bat", "attributes": [{"attribute": "max_health", "name": "tiny", "minAmount": 1, "maxAmount": 3}]}, - "spawnEffect": {"sound": "entity.zombie.ambient", "particleEffect": "SMOKE", "particleCount": 3, "interval": 0, "chance": 1}, + "spawnEffect": {"sound": "entity.zombie.ambient", "particleEffect": "SMOKE", "particleCount": 3, "interval": 1, "chance": 1}, "spawnEffectRiseOutOfGround": true, "rawCommands": [{"commands": ["say hello {x}"], "delay": 5, "repeat": true, "repeatDelay": 40}]} """; @@ -68,6 +68,6 @@ public class EntityResolutionPinTest { EntitySpec spec = new EntityResolution(new LootItems(registry, false), world).resolve(entity, new RNG(STREAM_SEED)); - assertEquals(1726532922, spec.toString().hashCode()); + assertEquals(-819231818, spec.toString().hashCode()); } } From f7872685cef9f3f89cffe6554f6b7b0c6c4edf12 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 08:37:08 +0200 Subject: [PATCH 05/10] Core stops reading biome layers, slab, wall and the dimension's rock, fluid and post processing fields IrisComplex, UpperDimensionContext and ChunkContext lose the rock and fluid streams, the engine loses the layer density, studio's style timings read the terrain module. Pins of layers and palettes now run through the module classes; tests for the settings of the new keys read real pack files. --- .../iris/core/commands/CommandStudio.java | 8 +- .../art/arcane/iris/engine/EngineRuntime.java | 2 +- .../iris/engine/EngineRuntimeBuilder.java | 11 +- .../art/arcane/iris/engine/IrisComplex.java | 7 - .../art/arcane/iris/engine/IrisEngine.java | 6 - .../iris/engine/UpperDimensionContext.java | 13 - .../arcane/iris/engine/framework/Engine.java | 2 - .../util/project/context/ChunkContext.java | 33 +-- .../modules/DecorantSettingsDecodingTest.java | 2 +- .../modules/TerrainSettingsDecodingTest.java | 278 ++++++++++++++++++ .../core/project/SchemaBuilderParityTest.java | 24 ++ .../engine/actuator/TerrainLayersPinTest.java | 43 ++- .../engine/actuator/TerrainModuleTest.java | 33 ++- .../actuator/TerrainPalettesPinTest.java | 78 +++-- .../IrisCaveCarver3DNearParityTest.java | 5 +- .../CaveApplyingInferenceIsolationTest.java | 6 +- .../engine/modifier/SurfaceSmoothingTest.java | 11 +- .../FloatingChildBiomeDecodingTest.java | 2 +- .../biome/IrisBiomeCeilingLayerGuardTest.java | 58 ---- .../IrisBiomeInferenceIsolationTest.java | 21 ++ .../terrain/BiomeLayersCeilingGuardTest.java | 74 +++++ .../engine/terrain/TerrainTestSettings.java | 64 ++++ .../context/ChunkContextPrefillPlanTest.java | 35 --- .../biomes/carving/polarity-grotto.json | 178 +++++++++++ .../pack-terrain/biomes/frozen/sea/river.json | 71 +++++ .../pack-terrain/biomes/mesa/yellow.json | 113 +++++++ .../biomes/mountain/shore/beach.json | 48 +++ .../snippet/decorator/dry_grass.json | 37 +++ 28 files changed, 1049 insertions(+), 214 deletions(-) create mode 100644 core/src/test/java/art/arcane/iris/core/modules/TerrainSettingsDecodingTest.java delete mode 100644 core/src/test/java/art/arcane/iris/engine/object/world/biome/IrisBiomeCeilingLayerGuardTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/terrain/BiomeLayersCeilingGuardTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/terrain/TerrainTestSettings.java create mode 100644 core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/biomes/carving/polarity-grotto.json create mode 100644 core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/biomes/frozen/sea/river.json create mode 100644 core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/biomes/mesa/yellow.json create mode 100644 core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/biomes/mountain/shore/beach.json create mode 100644 core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/snippet/decorator/dry_grass.json diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandStudio.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandStudio.java index a034cb182..acc78470f 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandStudio.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandStudio.java @@ -38,7 +38,7 @@ import art.arcane.iris.core.tools.IrisToolbelt; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.loot.InventorySlotType; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.terrain.IrisBiomePaletteLayer; +import art.arcane.iris.engine.terrain.BiomeLayers; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.entity.IrisEntity; import art.arcane.iris.engine.platform.BukkitEntitySpawner; @@ -556,10 +556,10 @@ public class CommandStudio implements DirectorExecutor { double score = 0; int m = 0; - for (IrisBiomePaletteLayer j : b.getLayers()) { + for (NoiseStyle layerStyle : BiomeLayers.layerStyles(b)) { m++; - score += styleTimings.get(j.getStyle().getStyle()); - vv.add("Palette Layer " + m + ": " + styleTimings.get(j.getStyle().getStyle())); + score += styleTimings.get(layerStyle); + vv.add("Palette Layer " + m + ": " + styleTimings.get(layerStyle)); } score += styleTimings.get(b.getBiomeStyle().getStyle()); diff --git a/core/src/main/java/art/arcane/iris/engine/EngineRuntime.java b/core/src/main/java/art/arcane/iris/engine/EngineRuntime.java index 051d7a161..04fd257a3 100644 --- a/core/src/main/java/art/arcane/iris/engine/EngineRuntime.java +++ b/core/src/main/java/art/arcane/iris/engine/EngineRuntime.java @@ -58,6 +58,6 @@ record EngineRuntime( nextBiomeMaxes); } - record BiomeMaxes(double objectDensity, double layerDensity) { + record BiomeMaxes(double objectDensity) { } } diff --git a/core/src/main/java/art/arcane/iris/engine/EngineRuntimeBuilder.java b/core/src/main/java/art/arcane/iris/engine/EngineRuntimeBuilder.java index f1295ff41..d2124da2e 100644 --- a/core/src/main/java/art/arcane/iris/engine/EngineRuntimeBuilder.java +++ b/core/src/main/java/art/arcane/iris/engine/EngineRuntimeBuilder.java @@ -29,7 +29,6 @@ import art.arcane.iris.engine.framework.EngineTarget; import art.arcane.iris.engine.framework.EngineWorldManager; import art.arcane.iris.engine.framework.EngineWorldManagerProvider; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.terrain.IrisBiomePaletteLayer; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisServices; @@ -197,7 +196,6 @@ final class EngineRuntimeBuilder { BiomeMaxes computeBiomeMaxes() { double objectDensity = 0D; - double layerDensity = 0D; for (IrisBiome i : engine.getDimension().getReachableBiomes(engine)) { double density = 0; @@ -206,15 +204,8 @@ final class EngineRuntimeBuilder { } objectDensity = Math.max(objectDensity, density); - density = 0; - - for (IrisBiomePaletteLayer j : i.getLayers()) { - density++; - } - - layerDensity = Math.max(layerDensity, density); } - return new BiomeMaxes(objectDensity, layerDensity); + return new BiomeMaxes(objectDensity); } void restoreRuntimeAfterFailedTransition(EngineRuntime previous) { diff --git a/core/src/main/java/art/arcane/iris/engine/IrisComplex.java b/core/src/main/java/art/arcane/iris/engine/IrisComplex.java index 1486d6986..164198311 100644 --- a/core/src/main/java/art/arcane/iris/engine/IrisComplex.java +++ b/core/src/main/java/art/arcane/iris/engine/IrisComplex.java @@ -32,7 +32,6 @@ import art.arcane.iris.engine.object.noise.IrisShapedGeneratorStyle; import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.PlatformBiome; -import art.arcane.iris.spi.PlatformBlockState; import art.arcane.volmlib.util.collection.KList; import art.arcane.iris.util.common.data.DataProvider; import art.arcane.volmlib.util.math.M; @@ -116,8 +115,6 @@ public class IrisComplex implements DataProvider { private ProceduralStream heightFluidStream; private ProceduralStream slopeStream; private ProceduralStream topSurfaceStream; - private ProceduralStream rockStream; - private ProceduralStream fluidStream; private IrisBiome focusBiome; private IrisRegion focusRegion; private Map> generatorBounds; @@ -198,10 +195,6 @@ public class IrisComplex implements DataProvider { return value; }); - rockStream = engine.getDimension().getRockPalette().getLayerGenerator(rng.nextParallelRNG(45), data).stream() - .select(engine.getDimension().getRockPalette().getBlockData(data)); - fluidStream = engine.getDimension().getFluidPalette().getLayerGenerator(rng.nextParallelRNG(78), data).stream() - .select(engine.getDimension().getFluidPalette().getBlockData(data)); regionStyleStream = engine.getDimension().getRegionStyle().create(rng.nextParallelRNG(883), getData()).stream() .zoom(engine.getDimension().getRegionZoom()); regionIdentityStream = regionStyleStream.fit(Integer.MIN_VALUE, Integer.MAX_VALUE); diff --git a/core/src/main/java/art/arcane/iris/engine/IrisEngine.java b/core/src/main/java/art/arcane/iris/engine/IrisEngine.java index c23a2239a..1cb403e8b 100644 --- a/core/src/main/java/art/arcane/iris/engine/IrisEngine.java +++ b/core/src/main/java/art/arcane/iris/engine/IrisEngine.java @@ -595,12 +595,6 @@ public class IrisEngine implements Engine { return current == null ? 0D : current.biomeMaxes().objectDensity(); } - @Override - public double getMaxBiomeLayerDensity() { - EngineRuntime current = runtime; - return current == null ? 0D : current.biomeMaxes().layerDensity(); - } - @Override public boolean isClosed() { return closed; diff --git a/core/src/main/java/art/arcane/iris/engine/UpperDimensionContext.java b/core/src/main/java/art/arcane/iris/engine/UpperDimensionContext.java index 84cac453b..0d8b66941 100644 --- a/core/src/main/java/art/arcane/iris/engine/UpperDimensionContext.java +++ b/core/src/main/java/art/arcane/iris/engine/UpperDimensionContext.java @@ -35,7 +35,6 @@ public class UpperDimensionContext implements DataProvider { private final ProceduralStream heightStream; private final ProceduralStream biomeStream; private final ProceduralStream regionStream; - private final ProceduralStream rockStream; private final IrisImageMapRuntime imageMapRuntime; private final boolean selfReferencing; @@ -46,7 +45,6 @@ public class UpperDimensionContext implements DataProvider { this.heightStream = state.heightStream(); this.biomeStream = state.biomeStream(); this.regionStream = state.regionStream(); - this.rockStream = state.rockStream(); this.imageMapRuntime = state.imageMapRuntime(); this.selfReferencing = state.selfReferencing(); } @@ -69,7 +67,6 @@ public class UpperDimensionContext implements DataProvider { complex.getHeightStream(), complex.getTrueBiomeStream(), complex.getRegionStream(), - complex.getRockStream(), complex.getImageMapRuntime(), true )); @@ -276,10 +273,6 @@ public class UpperDimensionContext implements DataProvider { : implode(resolved, x, z, rng, dataProvider, childSelectionPlans, 3); }).cache2D("upperImageMappedFinalBiomeStream", engine, cacheSize); - ProceduralStream rockStream = upperDim.getRockPalette() - .getLayerGenerator(rng.nextParallelRNG(45), upperData).stream() - .select(upperDim.getRockPalette().getBlockData(upperData)); - return new UpperDimensionContext(new ContextState( upperDim, upperData, @@ -287,7 +280,6 @@ public class UpperDimensionContext implements DataProvider { heightStream, finalBiomeStream, regionStream, - rockStream, imageMapRuntime, false )); @@ -414,10 +406,6 @@ public class UpperDimensionContext implements DataProvider { return regionStream == null ? null : regionStream.get((double) x, (double) z); } - public PlatformBlockState getRockBlock(int x, int z) { - return rockStream.get((double) x, (double) z); - } - public PlatformBlockState getSurfaceBlock(int x, int z) { return imageMapRuntime.sampleSurfaceBlock(x, z); } @@ -442,7 +430,6 @@ public class UpperDimensionContext implements DataProvider { ProceduralStream heightStream, ProceduralStream biomeStream, ProceduralStream regionStream, - ProceduralStream rockStream, IrisImageMapRuntime imageMapRuntime, boolean selfReferencing ) { diff --git a/core/src/main/java/art/arcane/iris/engine/framework/Engine.java b/core/src/main/java/art/arcane/iris/engine/framework/Engine.java index 5360568fc..1c2aa4801 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/Engine.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/Engine.java @@ -129,8 +129,6 @@ public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer, double getMaxBiomeObjectDensity(); - double getMaxBiomeLayerDensity(); - boolean isClosed(); default GenerationSessionManager getGenerationSessions() { diff --git a/core/src/main/java/art/arcane/iris/util/project/context/ChunkContext.java b/core/src/main/java/art/arcane/iris/util/project/context/ChunkContext.java index 4647e0972..7e9799ac1 100644 --- a/core/src/main/java/art/arcane/iris/util/project/context/ChunkContext.java +++ b/core/src/main/java/art/arcane/iris/util/project/context/ChunkContext.java @@ -6,7 +6,6 @@ import art.arcane.iris.engine.framework.EngineMetrics; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.parallel.MultiBurst; import java.util.ArrayList; @@ -22,8 +21,6 @@ public class ChunkContext { private final int[] roundedHeight; private final ChunkedDataCache biome; private final ChunkedDataCache cave; - private final ChunkedDataCache rock; - private final ChunkedDataCache fluid; private final ChunkedDataCache region; private final FloatingIslandBoundarySampler floatingIslandBoundarySampler; @@ -52,8 +49,6 @@ public class ChunkContext { this.roundedHeight = new int[cache ? 256 : 0]; this.biome = new ChunkedDataCache<>(complex.getTrueBiomeStream(), x, z, cache); this.cave = new ChunkedDataCache<>(complex.getCaveBiomeStream(), x, z, cache); - this.rock = new ChunkedDataCache<>(complex.getRockStream(), x, z, cache); - this.fluid = new ChunkedDataCache<>(complex.getFluidStream(), x, z, cache); this.region = new ChunkedDataCache<>(complex.getRegionStream(), x, z, cache); this.floatingIslandBoundarySampler = new FloatingIslandBoundarySampler((wx, wz) -> complex.getTrueBiomeStream().get(wx, wz)); @@ -61,19 +56,13 @@ public class ChunkContext { PrefillPlan resolvedPlan = prefillPlan == null ? PrefillPlan.NO_CAVE : prefillPlan; boolean capturePrefillMetric = metrics != null; long totalStartNanos = capturePrefillMetric ? System.nanoTime() : 0L; - List fillTasks = new ArrayList<>(6); + List fillTasks = new ArrayList<>(4); if (resolvedPlan.height) { fillTasks.add(() -> height.fillRounded(roundedHeight)); } if (resolvedPlan.biome) { fillTasks.add(new PrefillFillTask(biome)); } - if (resolvedPlan.rock) { - fillTasks.add(new PrefillFillTask(rock)); - } - if (resolvedPlan.fluid) { - fillTasks.add(new PrefillFillTask(fluid)); - } if (resolvedPlan.region) { fillTasks.add(new PrefillFillTask(region)); } @@ -148,36 +137,24 @@ public class ChunkContext { return cave; } - public ChunkedDataCache getRock() { - return rock; - } - - public ChunkedDataCache getFluid() { - return fluid; - } - public ChunkedDataCache getRegion() { return region; } public enum PrefillPlan { - ALL(true, true, true, true, true, true), - NO_CAVE(true, true, false, true, true, true), - NONE(false, false, false, false, false, false); + ALL(true, true, true, true), + NO_CAVE(true, true, false, true), + NONE(false, false, false, false); private final boolean height; private final boolean biome; private final boolean cave; - private final boolean rock; - private final boolean fluid; private final boolean region; - PrefillPlan(boolean height, boolean biome, boolean cave, boolean rock, boolean fluid, boolean region) { + PrefillPlan(boolean height, boolean biome, boolean cave, boolean region) { this.height = height; this.biome = biome; this.cave = cave; - this.rock = rock; - this.fluid = fluid; this.region = region; } } diff --git a/core/src/test/java/art/arcane/iris/core/modules/DecorantSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/DecorantSettingsDecodingTest.java index f84b1f653..d58a93675 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/DecorantSettingsDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/DecorantSettingsDecodingTest.java @@ -137,7 +137,7 @@ public class DecorantSettingsDecodingTest { JSONObject byId = new JSONObject("{\"iris:decorant\": [{\"chance\": 1}]}"); assertSame(ModuleSettings.NONE, decoder.decode(Target.BIOME, byId, "biome meadow")); - assertEquals(Set.of("decorators", "deposits"), decoder.keys(Target.BIOME)); + assertTrue(decoder.keys(Target.BIOME).containsAll(Set.of("decorators", "deposits"))); } @Test diff --git a/core/src/test/java/art/arcane/iris/core/modules/TerrainSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/TerrainSettingsDecodingTest.java new file mode 100644 index 000000000..64b2c100a --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/modules/TerrainSettingsDecodingTest.java @@ -0,0 +1,278 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.modules; + +import art.arcane.iris.builtin.post.PostProcessingSettings; +import art.arcane.iris.builtin.post.PostProcessingSlabsSettings; +import art.arcane.iris.builtin.post.PostProcessingWallsSettings; +import art.arcane.iris.builtin.terrain.CaveCeilingLayersSettings; +import art.arcane.iris.builtin.terrain.FluidPaletteSettings; +import art.arcane.iris.builtin.terrain.LayersSettings; +import art.arcane.iris.builtin.terrain.LockLayersMaxSettings; +import art.arcane.iris.builtin.terrain.LockLayersSettings; +import art.arcane.iris.builtin.terrain.PaletteLayer; +import art.arcane.iris.builtin.terrain.RockPaletteSettings; +import art.arcane.iris.builtin.terrain.SeaLayersSettings; +import art.arcane.iris.builtin.terrain.SlabSettings; +import art.arcane.iris.builtin.terrain.WallSettings; +import art.arcane.volmlib.util.json.JSONObject; +import com.google.gson.Gson; +import com.volmit.FeatureAttachment.Target; +import com.volmit.block.BlockSpec; +import com.volmit.host.LoadedPack; +import com.volmit.host.ModuleHost; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +/** + * The layers, slab, wall, sea layers, cave ceiling layers and locked layers of a biome, the rock and fluid palettes of a + * dimension and its post processing switches, as packs have always written them (files of the overworld pack as it was + * before the port, copied from the pack backup), read into the settings of the terrain and post modules. The dimension + * keys and {@code lockLayersMax} are in no file of that pack, so they are written here. + */ +public class TerrainSettingsDecodingTest { + private static final String PACK = "/art/arcane/iris/core/modules/pack-terrain"; + + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + + private Path packFolder; + private LoadedPack pack; + private ModuleSettingsDecoder decoder; + + @Before + public void loadBuiltIns() throws IOException, URISyntaxException { + packFolder = Path.of(TerrainSettingsDecodingTest.class.getResource(PACK).toURI()); + pack = LoadedPack.load(packFolder, ModuleHost.of(IrisModuleHost.builtInModules()) + .reservingFields(ModuleTargets.reservedFields()) + .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGE).copyingJarsTo(folder.newFolder("copies").toPath())); + decoder = new ModuleSettingsDecoder(pack.catalog(), packFolder, Gson::new); + } + + @After + public void closePack() { + pack.close(); + } + + @Test + public void aLockedBiomeReadsItsLayersAndWall() throws IOException { + JSONObject biome = file("biomes/mesa/yellow.json"); + + ModuleSettings settings = decoder.decode(Target.BIOME, biome, "biome mesa/yellow"); + + List layers = settings.find(LayersSettings.class).orElseThrow().layers(); + assertEquals(biome.getJSONArray("layers").length(), layers.size()); + PaletteLayer first = layers.getFirst(); + assertEquals(2, first.minHeight()); + assertEquals(3, first.maxHeight()); + assertEquals("STATIC", first.style().style()); + assertEquals(List.of(BlockSpec.of("minecraft:terracotta")), first.palette()); + assertEquals(5, first.zoom(), 0); + assertTrue(first.slopeCondition().isDefault()); + assertTrue(settings.find(LockLayersSettings.class).orElseThrow().locked()); + assertTrue("lockLayersMax is not written in this file", settings.find(LockLayersMaxSettings.class).isEmpty()); + + PaletteLayer wall = settings.find(WallSettings.class).orElseThrow().layer(); + assertEquals("NOWHERE", wall.style().style()); + assertEquals(List.of(BlockSpec.of("minecraft:red_terracotta"), BlockSpec.of("minecraft:gray_terracotta"), BlockSpec.of("minecraft:yellow_terracotta")), + wall.palette()); + assertTrue(settings.find(SlabSettings.class).isEmpty()); + } + + @Test + public void aSlabIsOneLayerWithIrisDefaults() throws IOException { + ModuleSettings settings = decoder.decode(Target.BIOME, file("biomes/mountain/shore/beach.json"), "biome mountain/shore/beach"); + + PaletteLayer slab = settings.find(SlabSettings.class).orElseThrow().layer(); + + assertEquals("STATIC", slab.style().style()); + assertEquals(List.of(BlockSpec.of("minecraft:stone_slab"), BlockSpec.of("minecraft:air")), slab.palette()); + assertEquals(1, slab.minHeight()); + assertEquals(1, slab.maxHeight()); + assertEquals(5, slab.zoom(), 0); + assertEquals(2, settings.find(LayersSettings.class).orElseThrow().layers().size()); + assertEquals(List.of(BlockSpec.of("minecraft:stone"), BlockSpec.of("minecraft:andesite")), settings.find(LayersSettings.class).orElseThrow().layers().getFirst().palette()); + assertTrue(settings.find(WallSettings.class).isEmpty()); + } + + @Test + public void seaLayersKeepTheirNoiseAndWeights() throws IOException { + JSONObject biome = file("biomes/frozen/sea/river.json"); + + List seaLayers = decoder.decode(Target.BIOME, biome, "biome frozen/sea/river").find(SeaLayersSettings.class).orElseThrow().layers(); + + assertEquals(biome.getJSONArray("seaLayers").length(), seaLayers.size()); + PaletteLayer first = seaLayers.getFirst(); + assertEquals(3, first.minHeight()); + assertEquals(6, first.maxHeight()); + assertEquals("NOWHERE", first.style().style()); + assertEquals(1.16, first.zoom(), 0); + assertEquals(5, first.palette().size()); + assertEquals(2, first.palette().getFirst().weight()); + assertEquals("minecraft:ice", first.palette().getFirst().block()); + assertEquals(1, first.palette().get(2).weight()); + } + + @Test + public void caveCeilingLayersAreAListOfLayers() throws IOException { + JSONObject biome = file("biomes/carving/polarity-grotto.json"); + + List ceiling = decoder.decode(Target.BIOME, biome, "biome carving/polarity-grotto") + .find(CaveCeilingLayersSettings.class).orElseThrow().layers(); + + assertEquals(1, ceiling.size()); + assertEquals(1, ceiling.getFirst().minHeight()); + assertEquals(2, ceiling.getFirst().maxHeight()); + assertEquals(List.of(BlockSpec.of("minecraft:tuff").withWeight(4), BlockSpec.of("minecraft:moss_block").withWeight(3), + BlockSpec.of("minecraft:andesite").withWeight(3)), ceiling.getFirst().palette()); + } + + @Test + public void lockLayersMaxIsANumberAndLockLayersABoolean() { + ModuleSettings settings = decoder.decode(Target.BIOME, new JSONObject("{\"lockLayers\": false, \"lockLayersMax\": 4}"), "biome mesa"); + + assertFalse(settings.find(LockLayersSettings.class).orElseThrow().locked()); + assertEquals(4, settings.find(LockLayersMaxSettings.class).orElseThrow().layers()); + assertEquals(7, new LockLayersMaxSettings().layers()); + } + + @Test + public void aLayerWrittenWithoutOptionsHasIrisDefaults() { + ModuleSettings settings = decoder.decode(Target.BIOME, new JSONObject("{\"layers\": [{}], \"slab\": {}}"), "biome plain"); + + PaletteLayer layer = settings.find(LayersSettings.class).orElseThrow().layers().getFirst(); + assertEquals(List.of(BlockSpec.of("grass_block")), layer.palette()); + assertEquals(1, layer.minHeight()); + assertEquals(1, layer.maxHeight()); + assertEquals(5, layer.zoom(), 0); + assertEquals("a slab written as {} is a layer like any other", List.of(BlockSpec.of("grass_block")), + settings.find(SlabSettings.class).orElseThrow().layer().palette()); + assertTrue("a biome that writes nothing has the one grass layer", new LayersSettings().layers().size() == 1); + assertTrue(new SlabSettings().layer().palette().isEmpty()); + assertTrue(new WallSettings().layer().palette().isEmpty()); + } + + @Test + public void aLayerMayBeASnippet() throws IOException { + Path snippets = Files.createDirectories(folder.newFolder("snippet-pack").toPath().resolve("snippet/biome-palette")); + Files.writeString(snippets.resolve("sandy.json"), "{\"minHeight\": 2, \"maxHeight\": 4, \"palette\": [{\"block\": \"sand\"}]}"); + ModuleSettingsDecoder snippetDecoder = new ModuleSettingsDecoder(pack.catalog(), snippets.getParent().getParent(), Gson::new); + + PaletteLayer layer = snippetDecoder.decode(Target.BIOME, new JSONObject("{\"layers\": [\"snippet/biome-palette/sandy\", \"snippet/sandy\"]}"), "biome dunes") + .find(LayersSettings.class).orElseThrow().layers().getFirst(); + + assertEquals(4, layer.maxHeight()); + assertEquals(List.of(BlockSpec.of("sand")), layer.palette()); + } + + @Test + public void theDimensionReadsItsPalettesAndPostProcessingSwitches() { + ModuleSettings settings = decoder.decode(Target.DIMENSION, new JSONObject(""" + {"rockPalette": {"style": {"style": "SIMPLEX", "zoom": 2}, "zoom": 9, + "palette": [{"block": "minecraft:stone", "weight": 3}, {"block": "minecraft:granite"}]}, + "fluidPalette": {"palette": [{"block": "minecraft:lava"}]}, + "postProcessing": false, "postProcessingSlabs": false, "postProcessingWalls": true} + """), "dimension nether"); + + var rock = settings.find(RockPaletteSettings.class).orElseThrow().palette(); + assertEquals("SIMPLEX", rock.style().style()); + assertEquals(2, rock.style().zoom(), 0); + assertEquals(9, rock.zoom(), 0); + assertEquals(List.of(BlockSpec.of("minecraft:stone").withWeight(3), BlockSpec.of("minecraft:granite")), rock.palette()); + assertEquals(List.of(BlockSpec.of("minecraft:lava")), settings.find(FluidPaletteSettings.class).orElseThrow().palette().palette()); + assertFalse(settings.find(PostProcessingSettings.class).orElseThrow().enabled()); + assertFalse(settings.find(PostProcessingSlabsSettings.class).orElseThrow().enabled()); + assertTrue(settings.find(PostProcessingWallsSettings.class).orElseThrow().enabled()); + } + + @Test + public void aDimensionThatWritesNothingIsStoneAndWaterWithPostProcessingOn() { + ModuleSettings settings = decoder.decode(Target.DIMENSION, new JSONObject("{}"), "dimension overworld"); + + assertTrue(settings.find(RockPaletteSettings.class).isEmpty()); + assertEquals(List.of(BlockSpec.of("stone")), new RockPaletteSettings().palette().palette()); + assertEquals(List.of(BlockSpec.of("water")), new FluidPaletteSettings().palette().palette()); + assertTrue(new PostProcessingSettings().enabled()); + assertTrue(new PostProcessingSlabsSettings().enabled()); + assertTrue(new PostProcessingWallsSettings().enabled()); + } + + @Test + public void aBooleanWrittenAsAnObjectIsRefused() { + IllegalArgumentException refused = assertThrows(IllegalArgumentException.class, + () -> decoder.decode(Target.BIOME, new JSONObject("{\"lockLayers\": {\"locked\": true}}"), "biome mesa")); + + assertTrue(refused.getMessage(), refused.getMessage().startsWith("Cannot read settings iris:terrain/lock-layers under \"lockLayers\" in biome mesa:")); + } + + @Test + public void layersWrittenAsAnObjectOfOptionsAreRefused() { + IllegalArgumentException refused = assertThrows(IllegalArgumentException.class, + () -> decoder.decode(Target.BIOME, new JSONObject("{\"layers\": {\"layers\": []}}"), "biome mesa")); + + assertEquals("Cannot read settings iris:terrain/layers under \"layers\" in biome mesa: write a list, [...], of the layers, not an object of options", + refused.getMessage()); + } + + @Test + public void theTerrainAndPostKeysAreModuleKeysAndNoLongerFieldsOfIris() { + assertTrue(decoder.keys(Target.BIOME).containsAll(Set.of("layers", "seaLayers", "caveCeilingLayers", "slab", "wall", "lockLayers", "lockLayersMax"))); + assertTrue(decoder.keys(Target.DIMENSION).containsAll(Set.of("rockPalette", "fluidPalette", "postProcessing", "postProcessingSlabs", "postProcessingWalls"))); + for (String key : Set.of("layers", "seaLayers", "caveCeilingLayers", "slab", "wall", "lockLayers", "lockLayersMax")) { + assertFalse(key, ModuleTargets.reservedFields().get(Target.BIOME).contains(key)); + } + for (String key : Set.of("rockPalette", "fluidPalette", "postProcessing", "postProcessingSlabs", "postProcessingWalls")) { + assertFalse(key, ModuleTargets.reservedFields().get(Target.DIMENSION).contains(key)); + } + } + + @Test + public void everyTopLevelKeyOfTheseFilesIsAFieldOfIrisOrAKeyOfAModule() throws IOException { + Map files = Map.of("biomes/mesa/yellow.json", Target.BIOME, "biomes/mountain/shore/beach.json", Target.BIOME, + "biomes/frozen/sea/river.json", Target.BIOME, "biomes/carving/polarity-grotto.json", Target.BIOME); + + for (Map.Entry file : files.entrySet()) { + Set unknown = new TreeSet<>(file(file.getKey()).keySet()); + unknown.removeAll(ModuleTargets.reservedFields().get(file.getValue())); + unknown.removeAll(decoder.keys(file.getValue())); + assertEquals(file.getKey(), Set.of(), unknown); + } + } + + private JSONObject file(String name) throws IOException { + return new JSONObject(Files.readString(packFolder.resolve(name))); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/project/SchemaBuilderParityTest.java b/core/src/test/java/art/arcane/iris/core/project/SchemaBuilderParityTest.java index b887519c9..54af73016 100644 --- a/core/src/test/java/art/arcane/iris/core/project/SchemaBuilderParityTest.java +++ b/core/src/test/java/art/arcane/iris/core/project/SchemaBuilderParityTest.java @@ -232,6 +232,30 @@ public class SchemaBuilderParityTest { assertFalse("the feature ids are not keys", properties.has("iris:decorant")); } + @Test + public void terrainSettingsRenderTheirOneValueUnderTheOldKeys() throws IOException { + JSONObject biome = rootProperties(new SchemaBuilder(IrisBiome.class, structureSchemaData()).construct()); + JSONObject dimension = rootProperties(new SchemaBuilder(IrisDimension.class, structureSchemaData()).construct()); + + JSONObject layers = biome.getJSONObject("layers"); + assertEquals("array", layers.getString("type")); + assertEquals("module-art-arcane-iris-builtin-terrain-palettelayer", definitionKey(layers.getJSONObject("items"))); + assertEquals("a slab is one layer", "module-art-arcane-iris-builtin-terrain-palettelayer", definitionKey(biome.getJSONObject("slab"))); + assertEquals("module-art-arcane-iris-builtin-terrain-palettelayer", definitionKey(biome.getJSONObject("wall"))); + assertEquals("array", biome.getJSONObject("seaLayers").getString("type")); + assertEquals("array", biome.getJSONObject("caveCeilingLayers").getString("type")); + assertEquals("boolean", biome.getJSONObject("lockLayers").getString("type")); + assertEquals("integer", biome.getJSONObject("lockLayersMax").getString("type")); + assertEquals("module-com-volmit-block-palettespec", definitionKey(dimension.getJSONObject("rockPalette"))); + assertEquals("module-com-volmit-block-palettespec", definitionKey(dimension.getJSONObject("fluidPalette"))); + for (String key : List.of("postProcessing", "postProcessingSlabs", "postProcessingWalls")) { + assertEquals(key, "boolean", dimension.getJSONObject(key).getString("type")); + } + for (String id : List.of("iris:terrain/layers", "iris:terrain/slab", "iris:terrain/lock-layers")) { + assertFalse("the feature ids are not keys", biome.has(id)); + } + } + /** A native structure's jigsaw start pool names one of the platform's template pools, and studio lists them. */ @Test public void jigsawStartPoolsCompleteThePlatformsTemplatePools() { diff --git a/core/src/test/java/art/arcane/iris/engine/actuator/TerrainLayersPinTest.java b/core/src/test/java/art/arcane/iris/engine/actuator/TerrainLayersPinTest.java index 9fe8e2e97..f2369c028 100644 --- a/core/src/test/java/art/arcane/iris/engine/actuator/TerrainLayersPinTest.java +++ b/core/src/test/java/art/arcane/iris/engine/actuator/TerrainLayersPinTest.java @@ -8,11 +8,13 @@ import art.arcane.iris.engine.UsableBlockPlatform; import art.arcane.iris.engine.object.material.IrisBlockData; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.engine.terrain.BiomeLayers; +import art.arcane.iris.engine.terrain.ResolvedLayer; +import art.arcane.iris.engine.terrain.TerrainTestSettings; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.project.stream.ProceduralStream; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; -import com.google.gson.Gson; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -29,12 +31,13 @@ import static org.mockito.Mockito.when; * Pins what biome layers, sea layers, cave ceiling layers, locked layers, slabs and walls pick for a spread of columns * with a fixed terrain RNG, so they can move out of {@code IrisBiome} and into the terrain module without changing what * a world generates. The transcript hash was taken from {@code IrisBiome.generateLayers} and friends and from - * {@code IrisBiomePaletteLayer.get} before they moved. + * {@code IrisBiomePaletteLayer.get} before they moved; block keys list their properties in name order, because + * the old classes listed them in the order of a hash map and the platform does not tell the two apart. */ public class TerrainLayersPinTest { private static final long TERRAIN_SEED = 1337L; private static final int TRANSCRIPT_LENGTH = 143080; - private static final int TRANSCRIPT_HASH = -1399100638; + private static final int TRANSCRIPT_HASH = 1726319394; private static final int COLUMN_STEP_X = 61; private static final int COLUMN_STEP_Z = 67; private static final int COLUMN_RANGE = 400; @@ -109,7 +112,6 @@ public class TerrainLayersPinTest { } } - try { java.nio.file.Files.writeString(java.nio.file.Path.of("/tmp/iris-wt/3t/transcript.txt"), transcript.toString().replace("|", "\n")); } catch (java.io.IOException e) { throw new RuntimeException(e); } for (String picked : List.of("terracotta", "prismarine", "moss_block", "cobblestone_slab", "andesite", "barrier")) { assertTrue(picked + " is picked: " + transcript.length(), transcript.indexOf(picked) >= 0); } @@ -122,23 +124,27 @@ public class TerrainLayersPinTest { dimension.setExplodeBiomePalettes(exploded); dimension.setExplodeBiomePaletteSize(2); RNG rng = new RNG(TERRAIN_SEED); - IrisBiome biome = new Gson().fromJson(biomeJson, IrisBiome.class); + IrisBiome biome = new IrisBiome(); + biome.setModuleSettings(TerrainTestSettings.of(biomeJson)); + BiomeLayers layers = new BiomeLayers(); for (int x = -COLUMN_RANGE; x < COLUMN_RANGE; x += COLUMN_STEP_X) { for (int z = -COLUMN_RANGE; z < COLUMN_RANGE; z += COLUMN_STEP_Z) { - transcript.append('|').append(keys(biome.generateLayers(dimension, x, z, rng, 14, 70 + Math.floorMod(x + z, 9), data, complex))); - transcript.append('|').append(keys(biome.generateCeilingLayers(dimension, x, z, rng, 12, 40, data, complex))); - transcript.append('|').append(keys(biome.generateSeaLayers(x, z, rng, 7, data))); - transcript.append('|').append(smoothing(biome, rng, x, z)); + transcript.append('|').append(keys(layers.generateLayers(biome, dimension, x, z, rng, 14, 70 + Math.floorMod(x + z, 9), data, complex))); + transcript.append('|').append(keys(layers.generateCeilingLayers(biome, dimension, x, z, rng, 12, 40, data, complex))); + transcript.append('|').append(keys(layers.generateSeaLayers(biome, x, z, rng, 7, data))); + transcript.append('|').append(smoothing(layers, biome, rng, x, z)); } } } /** The block a slab and a wall place in post processing at the column, as the smoothing stage asks the biome. */ - private String smoothing(IrisBiome biome, RNG rng, int x, int z) { + private String smoothing(BiomeLayers layers, IrisBiome biome, RNG rng, int x, int z) { int height = 60 + Math.floorMod(x - z, 7); double slope = complex.getSlopeStream().get(x, z); - String slab = biome.getSlab().getSlopeCondition().isValid(slope) ? key(biome.getSlab().get(rng, x, height, z, data)) : "-"; - String wall = biome.getWall().getPalette().isEmpty() ? "-" : key(biome.getWall().get(rng, x + height, height + height, z + height, data)); + ResolvedLayer slabLayer = layers.slab(biome, data); + ResolvedLayer wallLayer = layers.wall(biome, data); + String slab = slabLayer.slopeCondition().isValid(slope) ? key(slabLayer.get(rng, x, height, z)) : "-"; + String wall = !wallLayer.hasPalette() ? "-" : key(wallLayer.get(rng, x + height, height + height, z + height)); return slab + "," + wall; } @@ -150,7 +156,18 @@ public class TerrainLayersPinTest { return keys.toString(); } + /** The block's key without its namespace and with its properties in name order, which is how the platform identifies a state whatever order a pack lists them in. */ private static String key(PlatformBlockState state) { - return state == null ? "null" : state.key().replace("minecraft:", ""); + if (state == null) { + return "null"; + } + String key = state.key().replace("minecraft:", ""); + int properties = key.indexOf('['); + if (properties < 0) { + return key; + } + String[] sorted = key.substring(properties + 1, key.length() - 1).split(","); + java.util.Arrays.sort(sorted); + return key.substring(0, properties) + "[" + String.join(",", sorted) + "]"; } } diff --git a/core/src/test/java/art/arcane/iris/engine/actuator/TerrainModuleTest.java b/core/src/test/java/art/arcane/iris/engine/actuator/TerrainModuleTest.java index 0e9d5ba07..fc7a15dca 100644 --- a/core/src/test/java/art/arcane/iris/engine/actuator/TerrainModuleTest.java +++ b/core/src/test/java/art/arcane/iris/engine/actuator/TerrainModuleTest.java @@ -9,6 +9,8 @@ import art.arcane.iris.engine.image.IrisImageMapRuntime; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.engine.terrain.BiomeLayers; +import art.arcane.iris.engine.terrain.TerrainPalettes; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.project.context.ChunkContext; import art.arcane.iris.util.project.context.ChunkedDataCache; @@ -26,6 +28,7 @@ import static org.junit.Assert.assertSame; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyDouble; import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -48,13 +51,9 @@ public class TerrainModuleTest { @SuppressWarnings("unchecked") public void aColumnIsBedrockThenRockThenLayersThenFluid() { UsableBlockPlatform.bind(); - TerrainModule.TerrainShaper shaper = new TerrainModule.TerrainShaper(engine()); - Hunk blocks = Hunk.newArrayHunk(16, 64, 16); IrisBiome biome = mock(IrisBiome.class); - KList layers = new KList<>(); - layers.add(grass, dirt); - when(biome.generateLayers(any(), anyDouble(), anyDouble(), any(RNG.class), anyInt(), anyInt(), any(), any())).thenReturn(layers); - when(biome.generateSeaLayers(anyDouble(), anyDouble(), any(RNG.class), anyInt(), any())).thenReturn(new KList<>()); + TerrainModule.TerrainShaper shaper = new TerrainModule.TerrainShaper(engine(), palettes(), layersOf(biome)); + Hunk blocks = Hunk.newArrayHunk(16, 64, 16); shaper.shape(0, 0, blocks, context(biome)); @@ -75,19 +74,29 @@ public class TerrainModuleTest { when(biomes.get(anyInt(), anyInt())).thenReturn(biome); ChunkedDataCache regions = mock(ChunkedDataCache.class); when(regions.get(anyInt(), anyInt())).thenReturn(mock(IrisRegion.class)); - ChunkedDataCache fluids = mock(ChunkedDataCache.class); - when(fluids.get(anyInt(), anyInt())).thenReturn(water); - ChunkedDataCache rocks = mock(ChunkedDataCache.class); - when(rocks.get(anyInt(), anyInt())).thenReturn(rock); ChunkContext context = mock(ChunkContext.class); when(context.getBiome()).thenReturn(biomes); when(context.getRegion()).thenReturn(regions); - when(context.getFluid()).thenReturn(fluids); - when(context.getRock()).thenReturn(rocks); when(context.getRoundedHeight(anyInt(), anyInt())).thenReturn(HEIGHT); return context; } + private TerrainPalettes palettes() { + TerrainPalettes palettes = mock(TerrainPalettes.class); + when(palettes.rockAt(anyDouble(), anyDouble())).thenReturn(rock); + when(palettes.fluidAt(anyDouble(), anyDouble())).thenReturn(water); + return palettes; + } + + private BiomeLayers layersOf(IrisBiome biome) { + KList layers = new KList<>(); + layers.add(grass, dirt); + BiomeLayers biomeLayers = mock(BiomeLayers.class); + when(biomeLayers.generateLayers(eq(biome), any(), anyDouble(), anyDouble(), any(RNG.class), anyInt(), anyInt(), any(), any())).thenReturn(layers); + when(biomeLayers.generateSeaLayers(eq(biome), anyDouble(), anyDouble(), any(RNG.class), anyInt(), any())).thenReturn(new KList<>()); + return biomeLayers; + } + private Engine engine() { IrisDimension dimension = mock(IrisDimension.class); when(dimension.getFluidHeight()).thenReturn(FLUID_HEIGHT); diff --git a/core/src/test/java/art/arcane/iris/engine/actuator/TerrainPalettesPinTest.java b/core/src/test/java/art/arcane/iris/engine/actuator/TerrainPalettesPinTest.java index 2f36fd219..e3a178c32 100644 --- a/core/src/test/java/art/arcane/iris/engine/actuator/TerrainPalettesPinTest.java +++ b/core/src/test/java/art/arcane/iris/engine/actuator/TerrainPalettesPinTest.java @@ -3,13 +3,15 @@ package art.arcane.iris.engine.actuator; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.ResourceLoader; import art.arcane.iris.core.modules.IrisPackResources; +import art.arcane.iris.engine.UpperDimensionContext; import art.arcane.iris.engine.UsableBlockPlatform; +import art.arcane.iris.engine.decorator.DecoratorTestEngines; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.SeedManager; import art.arcane.iris.engine.object.material.IrisBlockData; import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.project.stream.ProceduralStream; -import art.arcane.volmlib.util.math.RNG; -import com.google.gson.Gson; +import art.arcane.iris.engine.terrain.TerrainPalettes; +import art.arcane.iris.engine.terrain.TerrainTestSettings; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -23,13 +25,15 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** - * Pins the blocks the dimension's rock and fluid palettes pick for a spread of columns, so they can move out of + * Pins the blocks the dimension's rock and fluid palettes pick for a spread of columns, so they could move out of * {@code IrisComplex} into the terrain module without changing what a world generates. The hash was taken from the streams - * {@code IrisComplex} built from {@code IrisDimension.getRockPalette()} and {@code getFluidPalette()} before they moved. + * {@code IrisComplex} built from {@code IrisDimension.getRockPalette()} and {@code getFluidPalette()} before they moved, + * for the world's complex seed and for the seed an upper dimension derives from it. */ public class TerrainPalettesPinTest { private static final long COMPLEX_SEED = 424242L; - private static final long UPPER_DIMENSION_SEED_OFFSET = "upper".hashCode(); + private static final String UPPER_DIMENSION_KEY = "upper"; + private static final long UPPER_DIMENSION_SEED = COMPLEX_SEED ^ UPPER_DIMENSION_KEY.hashCode(); private static final int TRANSCRIPT_LENGTH = 154196; private static final int TRANSCRIPT_HASH = 1568450945; private static final int COLUMN_RANGE = 1200; @@ -68,9 +72,9 @@ public class TerrainPalettesPinTest { public void rockAndFluidPickAsTheyDidInTheComplex() { StringBuilder transcript = new StringBuilder(); for (String json : List.of(STYLED, DEFAULTS, SINGLE)) { - IrisDimension dimension = new Gson().fromJson(json, IrisDimension.class); - record(transcript, dimension, new RNG(COMPLEX_SEED)); - record(transcript, dimension, new RNG(COMPLEX_SEED ^ UPPER_DIMENSION_SEED_OFFSET)); + IrisDimension dimension = dimension(json); + record(transcript, TerrainPalettes.of(engine(dimension, COMPLEX_SEED))); + record(transcript, TerrainPalettes.of(engine(dimension, UPPER_DIMENSION_SEED))); } for (String picked : List.of("granite", "andesite", "diorite", "tuff", "lava", "packed_ice", "netherrack")) { @@ -80,15 +84,55 @@ public class TerrainPalettesPinTest { assertEquals(TRANSCRIPT_HASH, transcript.toString().hashCode()); } - private void record(StringBuilder transcript, IrisDimension dimension, RNG complexRng) { - ProceduralStream rock = dimension.getRockPalette().getLayerGenerator(complexRng.nextParallelRNG(45), data).stream() - .select(dimension.getRockPalette().getBlockData(data)); - ProceduralStream fluid = dimension.getFluidPalette().getLayerGenerator(complexRng.nextParallelRNG(78), data).stream() - .select(dimension.getFluidPalette().getBlockData(data)); + @Test + public void anUpperDimensionPicksItsRockFromTheSeedItDerivesFromTheWorldsAndItsOwnKey() { + IrisDimension upperDimension = dimension(STYLED); + upperDimension.setLoadKey(UPPER_DIMENSION_KEY); + UpperDimensionContext upper = mock(UpperDimensionContext.class); + when(upper.isSelfReferencing()).thenReturn(false); + when(upper.getDimension()).thenReturn(upperDimension); + when(upper.getData()).thenReturn(data); + TerrainPalettes world = TerrainPalettes.of(engine(dimension(DEFAULTS), COMPLEX_SEED)); + TerrainPalettes derived = TerrainPalettes.of(engine(upperDimension, UPPER_DIMENSION_SEED)); + for (int x = -COLUMN_RANGE; x < COLUMN_RANGE; x += COLUMN_STEP_X) { for (int z = -COLUMN_RANGE; z < COLUMN_RANGE; z += COLUMN_STEP_Z) { - transcript.append(rock.get(x, z).key().replace("minecraft:", "")).append(',') - .append(fluid.get(x, z).key().replace("minecraft:", "")).append(' '); + assertEquals(derived.rockAt(x, z).key(), world.upperRockAt(upper, x, z).key()); + } + } + } + + @Test + public void aDimensionThatIsItsOwnUpperDimensionSharesItsRock() { + TerrainPalettes world = TerrainPalettes.of(engine(dimension(STYLED), COMPLEX_SEED)); + UpperDimensionContext upper = mock(UpperDimensionContext.class); + when(upper.isSelfReferencing()).thenReturn(true); + + assertEquals(world.rockAt(17, -90).key(), world.upperRockAt(upper, 17, -90).key()); + } + + private IrisDimension dimension(String json) { + IrisDimension dimension = new IrisDimension(); + dimension.setModuleSettings(TerrainTestSettings.of(json)); + return dimension; + } + + private Engine engine(IrisDimension dimension, long complexSeed) { + SeedManager seeds = mock(SeedManager.class); + when(seeds.getComplex()).thenReturn(complexSeed); + Engine engine = mock(Engine.class); + when(engine.getDimension()).thenReturn(dimension); + when(engine.getData()).thenReturn(data); + when(engine.getSeedManager()).thenReturn(seeds); + DecoratorTestEngines.withGeneration(engine); + return engine; + } + + private static void record(StringBuilder transcript, TerrainPalettes palettes) { + for (int x = -COLUMN_RANGE; x < COLUMN_RANGE; x += COLUMN_STEP_X) { + for (int z = -COLUMN_RANGE; z < COLUMN_RANGE; z += COLUMN_STEP_Z) { + transcript.append(palettes.rockAt(x, z).key().replace("minecraft:", "")).append(',') + .append(palettes.fluidAt(x, z).key().replace("minecraft:", "")).append(' '); } } } diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3DNearParityTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3DNearParityTest.java index d838dd6c0..7b548e9e4 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3DNearParityTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3DNearParityTest.java @@ -5,6 +5,7 @@ import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.engine.object.TestSettings; import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.builtin.terrain.FluidPaletteSettings; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.EngineMetrics; import art.arcane.iris.engine.framework.SeedManager; @@ -91,12 +92,10 @@ public class IrisCaveCarver3DNearParityTest { @Test public void genericFluidContractKeepsOverworldDefaults() { CaveProfile profile = new CaveProfile(); - IrisDimension dimension = new IrisDimension(); - assertTrue(profile.allowFluid()); assertEquals(12, profile.fluidMinDepthBelowSurface()); assertTrue(profile.fluidRequiresFloor()); - assertEquals("water", dimension.getFluidPalette().getPalette().get(0).getBlock()); + assertEquals("water", new FluidPaletteSettings().palette().palette().get(0).block()); } @Test diff --git a/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingInferenceIsolationTest.java b/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingInferenceIsolationTest.java index 18a30c614..d600195a5 100644 --- a/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingInferenceIsolationTest.java +++ b/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingInferenceIsolationTest.java @@ -1,6 +1,8 @@ package art.arcane.iris.engine.modifier; +import art.arcane.iris.builtin.terrain.LayersSettings; import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.BuiltInPack; import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.decorator.DecoratorTestEngines; import art.arcane.iris.engine.framework.Engine; @@ -18,6 +20,7 @@ import art.arcane.iris.spi.PlatformRegistries; import art.arcane.iris.util.project.hunk.Hunk; import art.arcane.iris.util.project.stream.ProceduralStream; import art.arcane.volmlib.util.matter.MatterCavern; +import com.google.gson.Gson; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import org.junit.AfterClass; import org.junit.BeforeClass; @@ -57,8 +60,7 @@ public class CaveApplyingInferenceIsolationTest { @SuppressWarnings("unchecked") public void cavePaintingDoesNotMutateSharedBiomeInference() throws Exception { IrisBiome biome = new IrisBiome().setInferredType(InferredType.LAND); - biome.getLayers().clear(); - biome.getCaveCeilingLayers().clear(); + biome.setModuleSettings(BuiltInPack.settings(new Gson().fromJson("{\"layers\": []}", LayersSettings.class))); Engine engine = mock(Engine.class); doReturn(mock(IrisData.class)).when(engine).getData(); diff --git a/core/src/test/java/art/arcane/iris/engine/modifier/SurfaceSmoothingTest.java b/core/src/test/java/art/arcane/iris/engine/modifier/SurfaceSmoothingTest.java index dc47f178a..82a86febb 100644 --- a/core/src/test/java/art/arcane/iris/engine/modifier/SurfaceSmoothingTest.java +++ b/core/src/test/java/art/arcane/iris/engine/modifier/SurfaceSmoothingTest.java @@ -1,6 +1,11 @@ package art.arcane.iris.engine.modifier; +import art.arcane.iris.builtin.post.PostProcessingSlabsSettings; +import art.arcane.iris.builtin.post.PostProcessingWallsSettings; +import art.arcane.iris.core.modules.BuiltInPack; import art.arcane.iris.engine.UsableBlockPlatform; +import art.arcane.iris.engine.decorator.DecoratorTestEngines; +import art.arcane.iris.engine.object.TestSettings; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.EngineMetrics; import art.arcane.iris.engine.framework.SeedManager; @@ -21,7 +26,7 @@ import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -/** Smoothing the surface removes a nib that floats above columns two blocks lower and leaves a flat surface alone. */ +/** Smoothing the surface (here without slabs and walls, which post processing switches off per dimension) removes a nib that floats above columns two blocks lower and leaves a flat surface alone. */ public class SurfaceSmoothingTest { private static final int NIB_X = 5; private static final int NIB_Z = 5; @@ -68,12 +73,16 @@ public class SurfaceSmoothingTest { when(mantle.trueHeight(anyInt(), anyInt())).thenAnswer(invocation -> (int) invocation.getArgument(0) == nibX && (int) invocation.getArgument(1) == nibZ ? nibHeight : NEIGHBOUR_HEIGHT); IrisDimension dimension = mock(IrisDimension.class); + when(dimension.getModuleSettings()).thenReturn(BuiltInPack.settings( + TestSettings.of(PostProcessingWallsSettings.class, "{\"enabled\": false}"), + TestSettings.of(PostProcessingSlabsSettings.class, "{\"enabled\": false}"))); SeedManager seeds = mock(SeedManager.class); Engine engine = mock(Engine.class); when(engine.getMantle()).thenReturn(mantle); when(engine.getDimension()).thenReturn(dimension); when(engine.getSeedManager()).thenReturn(seeds); when(engine.getMetrics()).thenReturn(new EngineMetrics(16)); + DecoratorTestEngines.withGeneration(engine); return engine; } diff --git a/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/FloatingChildBiomeDecodingTest.java b/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/FloatingChildBiomeDecodingTest.java index 76ef7d2af..db0ec3c04 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/FloatingChildBiomeDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/FloatingChildBiomeDecodingTest.java @@ -92,7 +92,7 @@ public class FloatingChildBiomeDecodingTest { assertEquals(4, child.edgeTaperVariationAmplitude(), 0); assertEquals(FloatingBottomPaletteMode.CUSTOM, child.bottomPaletteMode()); assertEquals(1, child.bottomPalette().size()); - assertEquals(5, child.bottomPalette().get(0).getMaxHeight()); + assertEquals(5, child.bottomPalette().get(0).maxHeight()); assertEquals("SIMPLEX", child.wallWarpStyle().orElseThrow().style()); assertEquals(5, child.wallWarpAmplitude(), 0); assertEquals("carving/sand-hollows-child", child.carving()); diff --git a/core/src/test/java/art/arcane/iris/engine/object/world/biome/IrisBiomeCeilingLayerGuardTest.java b/core/src/test/java/art/arcane/iris/engine/object/world/biome/IrisBiomeCeilingLayerGuardTest.java deleted file mode 100644 index 9f75dc371..000000000 --- a/core/src/test/java/art/arcane/iris/engine/object/world/biome/IrisBiomeCeilingLayerGuardTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package art.arcane.iris.engine.object.world.biome; - -import art.arcane.iris.engine.object.terrain.IrisBiomePaletteLayer; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; -import org.junit.Test; - -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; - -public class IrisBiomeCeilingLayerGuardTest { - private static IrisBiome biome(int layers, int ceilingLayers) { - IrisBiome biome = new IrisBiome(); - KList surface = new KList<>(); - for (int i = 0; i < layers; i++) { - surface.add(new IrisBiomePaletteLayer().zero()); - } - KList ceiling = new KList<>(); - for (int i = 0; i < ceilingLayers; i++) { - IrisBiomePaletteLayer layer = new IrisBiomePaletteLayer().zero(); - layer.setMinHeight(0); - layer.setMaxHeight(0); - ceiling.add(layer); - } - biome.setLayers(surface); - biome.setCaveCeilingLayers(ceiling); - return biome; - } - - @Test - public void moreCeilingLayersThanLayersMustNotThrow() { - IrisBiome biome = biome(1, 3); - - KList result = biome.generateCeilingLayers( - new IrisDimension(), 0, 0, new RNG(1), 8, 64, mock(IrisData.class), null); - - assertTrue("extra ceiling layers are skipped, not crashed on", result.isEmpty()); - } - - @Test - public void inRangeCeilingLayersKeepWorking() { - IrisBiome biome = biome(3, 2); - - KList result = biome.generateCeilingLayers( - new IrisDimension(), 0, 0, new RNG(1), 8, 64, mock(IrisData.class), null); - - assertTrue("zeroed palettes with zero heights produce no blocks", result.isEmpty()); - } - - @Test - public void omittedCeilingLayersLeaveCavesUnchanged() { - assertTrue(new IrisBiome().getCaveCeilingLayers().isEmpty()); - } -} diff --git a/core/src/test/java/art/arcane/iris/engine/object/world/biome/IrisBiomeInferenceIsolationTest.java b/core/src/test/java/art/arcane/iris/engine/object/world/biome/IrisBiomeInferenceIsolationTest.java index 300670488..ce3d02b3b 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/world/biome/IrisBiomeInferenceIsolationTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/world/biome/IrisBiomeInferenceIsolationTest.java @@ -2,13 +2,17 @@ package art.arcane.iris.engine.object.world.biome; import art.arcane.iris.engine.object.world.biome.InferredType; import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.builtin.terrain.LayersSettings; import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.BuiltInPack; +import art.arcane.iris.engine.object.TestSettings; import com.google.gson.Gson; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -31,4 +35,21 @@ public class IrisBiomeInferenceIsolationTest { assertEquals(InferredType.LAND, land.getInferredType()); assertEquals(InferredType.SEA, sea.getInferredType()); } + + @Test + public void aVariantKeepsTheModuleSettingsOfItsBiome() { + Gson gson = new Gson(); + IrisData data = mock(IrisData.class); + when(data.getGson()).thenReturn(gson); + IrisBiome biome = gson.fromJson("{\"name\":\"Shared\"}", IrisBiome.class); + biome.setLoader(data); + biome.setLoadKey("shared"); + biome.setModuleSettings(BuiltInPack.settings(TestSettings.of(LayersSettings.class, "{\"layers\": []}"))); + + biome.withInferredType(InferredType.LAND); + IrisBiome sea = biome.withInferredType(InferredType.SEA); + + assertSame(biome.getModuleSettings(), sea.getModuleSettings()); + assertTrue(sea.getModuleSettings().find(LayersSettings.class).orElseThrow().layers().isEmpty()); + } } diff --git a/core/src/test/java/art/arcane/iris/engine/terrain/BiomeLayersCeilingGuardTest.java b/core/src/test/java/art/arcane/iris/engine/terrain/BiomeLayersCeilingGuardTest.java new file mode 100644 index 000000000..377f25644 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/terrain/BiomeLayersCeilingGuardTest.java @@ -0,0 +1,74 @@ +package art.arcane.iris.engine.terrain; + +import art.arcane.iris.builtin.terrain.CaveCeilingLayersSettings; +import art.arcane.iris.builtin.terrain.LayersSettings; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.BuiltInPack; +import art.arcane.iris.core.modules.IrisPackResources; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import com.google.gson.Gson; +import org.junit.Test; + +import java.io.File; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class BiomeLayersCeilingGuardTest { + private static final String EMPTY_LAYER = "{\"palette\": []}"; + private static final String EMPTY_CEILING_LAYER = "{\"palette\": [], \"minHeight\": 0, \"maxHeight\": 0}"; + + private static IrisBiome biome(int layers, int ceilingLayers) { + Gson gson = new Gson(); + IrisBiome biome = new IrisBiome(); + biome.setModuleSettings(BuiltInPack.settings( + gson.fromJson("{\"layers\": " + layerList(EMPTY_LAYER, layers) + "}", LayersSettings.class), + gson.fromJson("{\"layers\": " + layerList(EMPTY_CEILING_LAYER, ceilingLayers) + "}", CaveCeilingLayersSettings.class))); + return biome; + } + + private static String layerList(String layer, int count) { + return "[" + String.join(",", java.util.Collections.nCopies(count, layer)) + "]"; + } + + private static IrisData data() { + IrisData data = mock(IrisData.class); + when(data.getDataFolder()).thenReturn(new File("pack")); + IrisPackResources resources = new IrisPackResources(data); + when(data.getPackResources()).thenReturn(resources); + return data; + } + + @Test + public void moreCeilingLayersThanLayersMustNotThrow() { + IrisBiome biome = biome(1, 3); + + KList result = new BiomeLayers().generateCeilingLayers( + biome, new IrisDimension(), 0, 0, new RNG(1), 8, 64, data(), null); + + assertTrue("extra ceiling layers are skipped, not crashed on", result.isEmpty()); + } + + @Test + public void inRangeCeilingLayersKeepWorking() { + IrisBiome biome = biome(3, 2); + + KList result = new BiomeLayers().generateCeilingLayers( + biome, new IrisDimension(), 0, 0, new RNG(1), 8, 64, data(), null); + + assertTrue("zeroed palettes with zero heights produce no blocks", result.isEmpty()); + } + + @Test + public void omittedCeilingLayersLeaveCavesUnchanged() { + KList result = new BiomeLayers().generateCeilingLayers( + new IrisBiome(), new IrisDimension(), 0, 0, new RNG(1), 8, 64, data(), null); + + assertTrue(result.isEmpty()); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/terrain/TerrainTestSettings.java b/core/src/test/java/art/arcane/iris/engine/terrain/TerrainTestSettings.java new file mode 100644 index 000000000..a5201f70b --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/terrain/TerrainTestSettings.java @@ -0,0 +1,64 @@ +package art.arcane.iris.engine.terrain; + +import art.arcane.iris.builtin.post.PostProcessingSettings; +import art.arcane.iris.builtin.post.PostProcessingSlabsSettings; +import art.arcane.iris.builtin.post.PostProcessingWallsSettings; +import art.arcane.iris.builtin.terrain.CaveCeilingLayersSettings; +import art.arcane.iris.builtin.terrain.FluidPaletteSettings; +import art.arcane.iris.builtin.terrain.LayersSettings; +import art.arcane.iris.builtin.terrain.LockLayersMaxSettings; +import art.arcane.iris.builtin.terrain.LockLayersSettings; +import art.arcane.iris.builtin.terrain.RockPaletteSettings; +import art.arcane.iris.builtin.terrain.SeaLayersSettings; +import art.arcane.iris.builtin.terrain.SlabSettings; +import art.arcane.iris.builtin.terrain.WallSettings; +import art.arcane.iris.core.modules.BuiltInPack; +import art.arcane.iris.core.modules.ModuleSettings; +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.volmit.IrisFeature; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * Pack JSON as the module settings the decoder reads it into: each key a terrain or post feature declares, under its root + * option, without loading the module host. {@code ModuleSettingsDecoder} reads the same shapes (see the settings decoding tests). + */ +public final class TerrainTestSettings { + private static final Gson GSON = new Gson(); + private static final Map FEATURES = Map.ofEntries( + Map.entry("layers", new Object[]{LayersSettings.class, "layers"}), + Map.entry("seaLayers", new Object[]{SeaLayersSettings.class, "layers"}), + Map.entry("caveCeilingLayers", new Object[]{CaveCeilingLayersSettings.class, "layers"}), + Map.entry("slab", new Object[]{SlabSettings.class, "layer"}), + Map.entry("wall", new Object[]{WallSettings.class, "layer"}), + Map.entry("lockLayers", new Object[]{LockLayersSettings.class, "locked"}), + Map.entry("lockLayersMax", new Object[]{LockLayersMaxSettings.class, "layers"}), + Map.entry("rockPalette", new Object[]{RockPaletteSettings.class, "palette"}), + Map.entry("fluidPalette", new Object[]{FluidPaletteSettings.class, "palette"}), + Map.entry("postProcessing", new Object[]{PostProcessingSettings.class, "enabled"}), + Map.entry("postProcessingSlabs", new Object[]{PostProcessingSlabsSettings.class, "enabled"}), + Map.entry("postProcessingWalls", new Object[]{PostProcessingWallsSettings.class, "enabled"})); + + private TerrainTestSettings() { + } + + /** The settings a biome or dimension file holds, of the terrain and post keys it writes. */ + @SuppressWarnings("unchecked") + public static ModuleSettings of(String json) { + List settings = new ArrayList<>(); + for (Map.Entry entry : GSON.fromJson(json, JsonObject.class).entrySet()) { + Object[] feature = FEATURES.get(entry.getKey()); + if (feature == null) { + continue; + } + JsonObject wrapped = new JsonObject(); + wrapped.add((String) feature[1], entry.getValue()); + settings.add(GSON.fromJson(wrapped, (Class) feature[0])); + } + return BuiltInPack.settings(settings.toArray(new IrisFeature[0])); + } +} diff --git a/core/src/test/java/art/arcane/iris/util/project/context/ChunkContextPrefillPlanTest.java b/core/src/test/java/art/arcane/iris/util/project/context/ChunkContextPrefillPlanTest.java index 2758385d3..615254641 100644 --- a/core/src/test/java/art/arcane/iris/util/project/context/ChunkContextPrefillPlanTest.java +++ b/core/src/test/java/art/arcane/iris/util/project/context/ChunkContextPrefillPlanTest.java @@ -4,7 +4,6 @@ import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.util.project.stream.ProceduralStream; -import org.bukkit.block.data.BlockData; import org.junit.Test; import java.util.concurrent.atomic.AtomicInteger; @@ -22,23 +21,17 @@ public class ChunkContextPrefillPlanTest { AtomicInteger caveCalls = new AtomicInteger(); AtomicInteger heightCalls = new AtomicInteger(); AtomicInteger biomeCalls = new AtomicInteger(); - AtomicInteger rockCalls = new AtomicInteger(); - AtomicInteger fluidCalls = new AtomicInteger(); AtomicInteger regionCalls = new AtomicInteger(); ChunkContext context = createContext( ChunkContext.PrefillPlan.NO_CAVE, caveCalls, heightCalls, biomeCalls, - rockCalls, - fluidCalls, regionCalls ); assertEquals(256, heightCalls.get()); assertEquals(256, biomeCalls.get()); - assertEquals(256, rockCalls.get()); - assertEquals(256, fluidCalls.get()); assertEquals(256, regionCalls.get()); assertEquals(0, caveCalls.get()); @@ -53,23 +46,17 @@ public class ChunkContextPrefillPlanTest { AtomicInteger caveCalls = new AtomicInteger(); AtomicInteger heightCalls = new AtomicInteger(); AtomicInteger biomeCalls = new AtomicInteger(); - AtomicInteger rockCalls = new AtomicInteger(); - AtomicInteger fluidCalls = new AtomicInteger(); AtomicInteger regionCalls = new AtomicInteger(); ChunkContext context = createContext( ChunkContext.PrefillPlan.ALL, caveCalls, heightCalls, biomeCalls, - rockCalls, - fluidCalls, regionCalls ); assertEquals(256, heightCalls.get()); assertEquals(256, biomeCalls.get()); - assertEquals(256, rockCalls.get()); - assertEquals(256, fluidCalls.get()); assertEquals(256, regionCalls.get()); assertEquals(256, caveCalls.get()); @@ -88,8 +75,6 @@ public class ChunkContextPrefillPlanTest { AtomicInteger caveCalls, AtomicInteger heightCalls, AtomicInteger biomeCalls, - AtomicInteger rockCalls, - AtomicInteger fluidCalls, AtomicInteger regionCalls ) { IrisComplex complex = mock(IrisComplex.class); @@ -119,24 +104,6 @@ public class ChunkContextPrefillPlanTest { return caveBiome; }).when(caveStream).get(anyDouble(), anyDouble()); - @SuppressWarnings("unchecked") - ProceduralStream rockStream = mock(ProceduralStream.class); - BlockData rock = mock(BlockData.class); - doReturn("minecraft:stone").when(rock).getAsString(); - doAnswer(invocation -> { - rockCalls.incrementAndGet(); - return rock; - }).when(rockStream).get(anyDouble(), anyDouble()); - - @SuppressWarnings("unchecked") - ProceduralStream fluidStream = mock(ProceduralStream.class); - BlockData fluid = mock(BlockData.class); - doReturn("minecraft:water").when(fluid).getAsString(); - doAnswer(invocation -> { - fluidCalls.incrementAndGet(); - return fluid; - }).when(fluidStream).get(anyDouble(), anyDouble()); - @SuppressWarnings("unchecked") ProceduralStream regionStream = mock(ProceduralStream.class); IrisRegion region = mock(IrisRegion.class); @@ -148,8 +115,6 @@ public class ChunkContextPrefillPlanTest { doReturn(heightStream).when(complex).getHeightStream(); doReturn(biomeStream).when(complex).getTrueBiomeStream(); doReturn(caveStream).when(complex).getCaveBiomeStream(); - doReturn(rockStream).when(complex).getRockStream(); - doReturn(fluidStream).when(complex).getFluidStream(); doReturn(regionStream).when(complex).getRegionStream(); return new ChunkContext(32, 48, complex, true, prefillPlan, null); diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/biomes/carving/polarity-grotto.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/biomes/carving/polarity-grotto.json new file mode 100644 index 000000000..dd238072e --- /dev/null +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/biomes/carving/polarity-grotto.json @@ -0,0 +1,178 @@ +{ + "name": "Polarity Grotto", + "derivative": "minecraft:lush_caves", + "vanillaDerivative": "minecraft:lush_caves", + "caveMinDepthBelowSurface": 9, + "caveProfile": { + "enabled": true, + "verticalRange": { + "min": 6, + "max": 700 + }, + "baseDensityStyle": { + "style": "SIMPLEX_VASCULAR", + "zoom": 0.88 + }, + "detailDensityStyle": { + "style": "FRACTAL_BILLOW_SIMPLEX", + "zoom": 0.42 + }, + "warpStyle": { + "style": "SIMPLEX", + "zoom": 0.28 + }, + "baseWeight": 0.9, + "detailWeight": 0.12, + "warpStrength": 0.38, + "densityThreshold": { + "min": -0.13, + "max": -0.035, + "style": { + "style": "SIMPLEX", + "zoom": 0.66 + } + }, + "thresholdBias": 0.08, + "sampleStep": 2, + "surfaceClearance": 9, + "allowSurfaceBreak": false, + "objectMinDepthBelowSurface": 13, + "defaultObjectAnchor": "FLOOR", + "defaultObjectPlaceMode": "ORGANIC_STILT", + "anchorScanStep": 1, + "anchorSearchAttempts": 16, + "allowFluid": true, + "fluidMinDepthBelowSurface": 18, + "fluidRequiresFloor": true, + "allowLava": true, + "modules": [ + { + "style": { + "style": "FRACTAL_BILLOW_SIMPLEX", + "zoom": 0.34 + }, + "weight": 0.06, + "threshold": 0.06, + "verticalRange": { + "min": 12, + "max": 420 + }, + "invert": true + } + ], + "verticalEdgeFade": 22, + "verticalEdgeFadeStrength": 0.15, + "minCarveCells": 20, + "recoveryThresholdBoost": 0.06 + }, + "wall": { + "style": { + "style": "SIMPLEX", + "zoom": 0.52 + }, + "palette": [ + { + "block": "minecraft:tuff", + "weight": 5 + }, + { + "block": "minecraft:andesite", + "weight": 4 + }, + { + "block": "minecraft:mossy_cobblestone", + "weight": 2 + }, + { + "block": "minecraft:stone", + "weight": 3 + } + ] + }, + "layers": [ + { + "minHeight": 1, + "maxHeight": 2, + "palette": [ + { + "block": "minecraft:moss_block", + "weight": 5 + }, + { + "block": "minecraft:rooted_dirt", + "weight": 2 + }, + { + "block": "minecraft:andesite", + "weight": 3 + } + ] + } + ], + "caveCeilingLayers": [ + { + "minHeight": 1, + "maxHeight": 2, + "palette": [ + { + "block": "minecraft:tuff", + "weight": 4 + }, + { + "block": "minecraft:moss_block", + "weight": 3 + }, + { + "block": "minecraft:andesite", + "weight": 3 + } + ] + } + ], + "objects": [ + { + "chance": 0.15, + "density": 2, + "carvingSupport": "CARVING_ONLY", + "caveAnchorMode": "PROFILE_DEFAULT", + "translate": { + "y": -1 + }, + "place": [ + "clutter/shrub1", + "clutter/shrub2", + "clutter/shrub3", + "clutter/oakshrub1", + "clutter/oakshrub2", + "clutter/oakshrub3" + ], + "bottom": true, + "force": true, + "scale": { + "size": 0.6 + } + }, + { + "chance": 0.1, + "density": 2, + "carvingSupport": "CARVING_ONLY", + "caveAnchorMode": "PROFILE_DEFAULT", + "translate": { + "y": -1 + }, + "place": [ + "clutter/rock1", + "clutter/rock2", + "clutter/rock3", + "clutter/stoneclutt1", + "clutter/stoneclutt2", + "clutter/stoneclutt3" + ], + "bottom": true, + "force": true, + "scale": { + "size": 0.6 + } + } + ] +} diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/biomes/frozen/sea/river.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/biomes/frozen/sea/river.json new file mode 100644 index 000000000..2123b378b --- /dev/null +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/biomes/frozen/sea/river.json @@ -0,0 +1,71 @@ +{ + "proceduralObjects": "snippet/procedural-objects/frozen/magical-ice-spikes-surface", + "name": "Frozen River", + "color": "#3DB9F5", + "derivative": "minecraft:frozen_river", + "vanillaDerivative": "minecraft:frozen_river", + "generators": [{ + "min": -32, + "max": -10, + "generator": "mountain" + }], + "layers": [ + {"palette": [ + {"block": "minecraft:dirt"}, + {"block": "minecraft:gravel"}, + {"block": "minecraft:stone"} + ]}, + { + "minHeight": 2, + "maxHeight": 3, + "style": {"style": "STATIC"}, + "palette": [ + {"block": "minecraft:sand"}, + {"block": "minecraft:clay"}, + {"block": "minecraft:sand"}, + {"block": "minecraft:gravel"}, + {"block": "minecraft:sand"}, + {"block": "minecraft:dirt"}, + { + "weight": 2, + "block": "minecraft:sand" + } + ] + } + ], + "objects": [ + + ], + "seaLayers": [ + { + "minHeight": 3, + "maxHeight": 6, + "style": {"style": "NOWHERE"}, + "zoom": 1.16, + "palette": [ + { + "weight": 2, + "block": "minecraft:ice" + }, + { + "weight": 3, + "block": "minecraft:packed_ice" + }, + {"block": "minecraft:blue_ice"}, + { + "weight": 3, + "block": "minecraft:packed_ice" + }, + { + "weight": 2, + "block": "minecraft:ice" + } + ] + }, + { + "minHeight": 1, + "maxHeight": 2, + "palette": [{"block": "minecraft:packed_ice"}] + } + ] +} diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/biomes/mesa/yellow.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/biomes/mesa/yellow.json new file mode 100644 index 000000000..f675f0691 --- /dev/null +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/biomes/mesa/yellow.json @@ -0,0 +1,113 @@ +{ + "name": "Mesa Yellow", + "color": "#83300B", + "rarity": 1, + "derivative": "minecraft:windswept_savanna", + "vanillaDerivative": "minecraft:badlands", + "children": ["mesa/dark"], + "generators": [ + { + "min": 50, + "max": 70, + "generator": "highplains" + }, + { + "min": 70, + "max": 110, + "generator": "mountain" + } + ], + "wall": { + "style": {"style": "NOWHERE"}, + "palette": [ + {"block": "minecraft:red_terracotta"}, + {"block": "minecraft:gray_terracotta"}, + {"block": "minecraft:yellow_terracotta"} + ] + }, + "layers": [ + { + "minHeight": 2, + "maxHeight": 3, + "style": {"style": "STATIC"}, + "palette": [{"block": "minecraft:terracotta"}] + }, + { + "minHeight": 2, + "maxHeight": 3, + "style": {"style": "STATIC"}, + "palette": [{"block": "minecraft:white_terracotta"}] + }, + { + "minHeight": 2, + "maxHeight": 3, + "style": {"style": "STATIC"}, + "palette": [{"block": "minecraft:terracotta"}] + }, + { + "minHeight": 2, + "maxHeight": 3, + "style": {"style": "STATIC"}, + "palette": [{"block": "minecraft:red_terracotta"}] + }, + { + "minHeight": 4, + "maxHeight": 4, + "style": {"style": "STATIC"}, + "palette": [{"block": "minecraft:terracotta"}] + }, + { + "minHeight": 2, + "maxHeight": 3, + "style": {"style": "STATIC"}, + "palette": [{"block": "minecraft:yellow_terracotta"}] + }, + { + "minHeight": 2, + "maxHeight": 3, + "style": {"style": "STATIC"}, + "palette": [{"block": "minecraft:terracotta"}] + }, + { + "minHeight": 2, + "maxHeight": 3, + "style": {"style": "STATIC"}, + "palette": [{"block": "minecraft:brown_terracotta"}] + } + ], + "decorators": [ + { + "chance": 0.009, + "variance": {"style": "STATIC"}, + "zoom": 0.3, + "palette": [ + { + "data": { + "face": "floor", + "powered": false, + "facing": "east" + }, + "block": "minecraft:stone_button" + }, + { + "data": { + "face": "floor", + "powered": false, + "facing": "south" + }, + "block": "minecraft:stone_button" + } + ], + "style": {"style": "STATIC"} + }, + { + "chance": 0.01, + "variance": {"style": "STATIC"}, + "zoom": 0.3, + "palette": [{"block": "minecraft:dead_bush"}], + "style": {"style": "STATIC"} + }, + "snippet/decorator/dry_grass" + ], + "lockLayers": true +} diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/biomes/mountain/shore/beach.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/biomes/mountain/shore/beach.json new file mode 100644 index 000000000..32b137d08 --- /dev/null +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/biomes/mountain/shore/beach.json @@ -0,0 +1,48 @@ +{ + "name": "Mountain Beach", + "color": "#365B8F", + "rarity": 1, + "derivative": "minecraft:old_growth_spruce_taiga", + "vanillaDerivative": "minecraft:old_growth_spruce_taiga", + "generators": [{ + "min": 0, + "max": 2, + "generator": "plain" + }], + "layers": [ + { + "minHeight": 1, + "maxHeight": 1, + "palette": [ + {"block": "minecraft:stone"}, + {"block": "minecraft:andesite"} + ] + }, + { + "minHeight": 1, + "maxHeight": 6, + "palette": [{"block": "minecraft:stone"}] + } + ], + "objects": [{ + "mode": "PAINT", + "chance": 0.0025, + "rotation": { + "yAxis": { + "min": 0, + "max": 270, + "interval": 90, + "enabled": true + }, + "enabled": true + }, + "place": ["clutter/bincluster1"] + }], + "slab": { + "style": {"style": "STATIC"}, + "palette": [ + {"block": "minecraft:stone_slab"}, + {"block": "minecraft:air"} + ] + } +} diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/snippet/decorator/dry_grass.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/snippet/decorator/dry_grass.json new file mode 100644 index 000000000..78b60d7e0 --- /dev/null +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-terrain/snippet/decorator/dry_grass.json @@ -0,0 +1,37 @@ +{ + "chance": 0.01, + "style": { + "style": "CELLULAR", + "zoom": 0.3, + "exponent": 1.5, + "axialFracturing": true, + "fracture": { + "multiplier": 55, + "axialFracturing": true, + "style": "NOWHERE", + "zoom": 0.15, + "fracture": { + "axialFracturing": true, + "style": "STATIC", + "multiplier": 18 + } + } + }, + "slopeCondition":{ + "maximumSlope": 5 + }, + "palette": [ + { + "block": "minecraft:tall_dry_grass", + "weight": 1 + }, + { + "block": "minecraft:short_dry_grass", + "weight": 1 + }, + { + "block": "minecraft:air", + "weight": 3 + } + ] +} \ No newline at end of file From f404dec7d71d99e023edf7c33d352d44f8636cbc Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 08:46:33 +0200 Subject: [PATCH 06/10] Core stops reading loot, spawn and effect classes: services, resource closure for exports, key handler for entities --- .../iris/core/commands/CommandStudio.java | 10 +- core/purity-allowlist.txt | 7 +- .../iris/core/events/InventorySlotType.java | 33 + .../iris/core/events/IrisLootEvent.java | 5 +- .../iris/core/modules/ModuleServices.java | 12 + .../core/modules/ModuleSettingsDecoder.java | 20 + .../iris/core/pack/ModuleResourceClosure.java | 211 ++++ .../iris/core/pack/PackExportClosure.java | 20 - .../core/project/IrisPackageCompiler.java | 80 +- .../iris/engine/framework/EnginePlayer.java | 37 +- .../framework/placer/WorldObjectPlacer.java | 3 +- .../iris/engine/platform/EngineBukkitOps.java | 3 +- .../platform/bukkit/BukkitAmbientEffects.java | 144 +++ .../platform/bukkit/PotionEffectTypes.java | 98 ++ .../director/handlers/EntityHandler.java | 49 - .../specialhandlers/EntityKeyHandler.java | 77 ++ .../project/matter/IrisMatterSupport.java | 2 - .../project/matter/slices/RegistryMatter.java | 53 - .../project/matter/slices/SpawnerMatter.java | 40 - .../modules/DecorantSettingsDecodingTest.java | 3 +- .../modules/DepositSettingsDecodingTest.java | 3 +- .../modules/LootAndSpawnPackDecodingTest.java | 276 +++++ .../iris/core/pack/PackExportClosureTest.java | 27 +- .../IrisProjectEntityDependencyTest.java | 33 - .../iris/engine/loot/LootDrawPinTest.java | 6 +- .../engine/loot/LootEnvironmentPinTest.java | 27 +- .../iris/engine/loot/LootItemsTest.java | 43 +- .../iris/engine/loot/LootResolverTest.java | 80 +- .../iris/engine/loot/LootResourcesTest.java | 15 +- .../engine/loot/LootTablesClearModeTest.java | 8 +- .../iris/engine/loot/LootValidatorTest.java | 16 +- .../object/loot/IrisLootKeyAccessorTest.java | 51 - .../engine/object/value/IrisDurationTest.java | 39 - .../engine/spawn/EntityResolutionPinTest.java | 6 +- .../iris/engine/spawn/EntitySpawningTest.java | 33 +- .../iris/engine/spawn/SpawnDurationTest.java | 38 + .../iris/engine/spawn/SpawnResourcesTest.java | 25 +- .../purity/PackTypeBukkitPurityGateTest.java | 18 +- .../matter/RegistryMatterContextTest.java | 55 - .../biomes/tropical/volcanoes.json | 72 ++ .../dimensions/overworld.json | 946 ++++++++++++++++++ .../entities/standard/hostile/zombie.json | 1 + .../entities/standard/passive/mooshroom.json | 1 + .../loot/global-clutter.json | 115 +++ .../regions/hot.json | 138 +++ .../regions/mushroom.json | 266 +++++ .../regions/swamp.json | 126 +++ .../regions/terralost.json | 96 ++ .../spawners/mushroom/passive.json | 32 + .../spawners/tropical/water.json | 33 + 50 files changed, 2916 insertions(+), 616 deletions(-) create mode 100644 core/src/main/java/art/arcane/iris/core/events/InventorySlotType.java create mode 100644 core/src/main/java/art/arcane/iris/core/pack/ModuleResourceClosure.java create mode 100644 core/src/main/java/art/arcane/iris/platform/bukkit/BukkitAmbientEffects.java create mode 100644 core/src/main/java/art/arcane/iris/platform/bukkit/PotionEffectTypes.java delete mode 100644 core/src/main/java/art/arcane/iris/util/common/director/handlers/EntityHandler.java create mode 100644 core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/EntityKeyHandler.java delete mode 100644 core/src/main/java/art/arcane/iris/util/project/matter/slices/RegistryMatter.java delete mode 100644 core/src/main/java/art/arcane/iris/util/project/matter/slices/SpawnerMatter.java create mode 100644 core/src/test/java/art/arcane/iris/core/modules/LootAndSpawnPackDecodingTest.java delete mode 100644 core/src/test/java/art/arcane/iris/core/project/IrisProjectEntityDependencyTest.java delete mode 100644 core/src/test/java/art/arcane/iris/engine/object/loot/IrisLootKeyAccessorTest.java delete mode 100644 core/src/test/java/art/arcane/iris/engine/object/value/IrisDurationTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/spawn/SpawnDurationTest.java delete mode 100644 core/src/test/java/art/arcane/iris/util/project/matter/RegistryMatterContextTest.java create mode 100644 core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/biomes/tropical/volcanoes.json create mode 100644 core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/dimensions/overworld.json create mode 100644 core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/entities/standard/hostile/zombie.json create mode 100644 core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/entities/standard/passive/mooshroom.json create mode 100644 core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/loot/global-clutter.json create mode 100644 core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/hot.json create mode 100644 core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/mushroom.json create mode 100644 core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/swamp.json create mode 100644 core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/terralost.json create mode 100644 core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/spawners/mushroom/passive.json create mode 100644 core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/spawners/tropical/water.json diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandStudio.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandStudio.java index a034cb182..9c1ca8440 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandStudio.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandStudio.java @@ -36,15 +36,12 @@ import art.arcane.iris.core.structure.FeatureImporter; import art.arcane.iris.core.structure.StructureImporter; import art.arcane.iris.core.tools.IrisToolbelt; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.loot.InventorySlotType; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.terrain.IrisBiomePaletteLayer; import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.entity.IrisEntity; import art.arcane.iris.engine.platform.BukkitEntitySpawner; import art.arcane.iris.engine.object.terrain.IrisGenerator; import art.arcane.iris.engine.object.noise.IrisInterpolator; -import art.arcane.iris.engine.object.loot.IrisLootTable; import art.arcane.iris.engine.object.noise.IrisNoiseGenerator; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.world.region.IrisRegion; @@ -57,6 +54,7 @@ import art.arcane.volmlib.util.collection.KSet; import art.arcane.iris.util.common.director.DirectorExecutor; import art.arcane.iris.util.common.director.handlers.DimensionHandler; import art.arcane.iris.util.common.director.specialhandlers.NullableDimensionHandler; +import art.arcane.iris.util.common.director.specialhandlers.EntityKeyHandler; import art.arcane.volmlib.util.director.DirectorOrigin; import art.arcane.volmlib.util.director.annotations.Director; import art.arcane.volmlib.util.director.annotations.Param; @@ -648,8 +646,8 @@ public class CommandStudio implements DirectorExecutor { @Director(description = "Spawn an Iris entity", descriptionKey = "iris.director.commandstudio.director.spawn_iris_entity", aliases = "summon", origin = DirectorOrigin.PLAYER) public void spawn( - @Param(description = "The entity to spawn", descriptionKey = "iris.director.commandstudio.param.entity_spawn") - IrisEntity entity, + @Param(description = "The entity to spawn", descriptionKey = "iris.director.commandstudio.param.entity_spawn", customHandler = EntityKeyHandler.class) + String entity, @Param(description = "The location to spawn the entity at", descriptionKey = "iris.director.commandstudio.param.location_spawn_entity_at", contextual = true, contextualOverride = true) Vector location ) { @@ -662,7 +660,7 @@ public class CommandStudio implements DirectorExecutor { // Entity creation must run on the thread owning the destination chunk. Location at = new Location(world(), location.getX(), location.getY(), location.getZ()); - if (!J.runAt(at, () -> BukkitEntitySpawner.spawnByKey(spawnEngine, entity.getLoadKey(), at))) { + if (!J.runAt(at, () -> BukkitEntitySpawner.spawnByKey(spawnEngine, entity, at))) { Iris.warn("Could not schedule the entity spawn at " + at.getBlockX() + ", " + at.getBlockY() + ", " + at.getBlockZ() + "."); } } diff --git a/core/purity-allowlist.txt b/core/purity-allowlist.txt index 36b3c155c..47dc57bce 100644 --- a/core/purity-allowlist.txt +++ b/core/purity-allowlist.txt @@ -104,20 +104,15 @@ art/arcane/iris/engine/object/world/biome/IrisBiome.java art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomParticle.java art/arcane/iris/engine/object/world/biome/IrisBiomeDerivatives.java art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomSpawn.java -art/arcane/iris/engine/object/marker/IrisCommandRegistry.java art/arcane/iris/engine/object/compatibility/IrisCompat.java art/arcane/iris/engine/object/compatibility/IrisCompatabilityBlockFilter.java art/arcane/iris/engine/object/compatibility/IrisCompatabilityItemFilter.java art/arcane/iris/engine/object/value/IrisDirection.java -art/arcane/iris/engine/object/entity/IrisEffect.java art/arcane/iris/engine/object/prefab/IrisObject.java art/arcane/iris/engine/object/placement/IrisObjectPlacement.java art/arcane/iris/engine/object/prefab/IrisObjectRotation.java -art/arcane/iris/engine/object/entity/IrisPotionEffect.java art/arcane/iris/engine/object/placement/IrisTree.java -art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java art/arcane/iris/engine/object/prefab/LegacyTileData.java -art/arcane/iris/engine/object/entity/PotionEffectTypes.java art/arcane/iris/engine/object/prefab/TileData.java art/arcane/iris/engine/platform/BukkitChunkGenerator.java art/arcane/iris/engine/platform/DummyBiomeProvider.java @@ -182,3 +177,5 @@ art/arcane/iris/engine/platform/BukkitEntitySpawner.java art/arcane/iris/engine/platform/BukkitSurfaces.java art/arcane/iris/platform/bukkit/BukkitAttributes.java art/arcane/iris/platform/bukkit/BukkitItemStacks.java +art/arcane/iris/platform/bukkit/BukkitAmbientEffects.java +art/arcane/iris/platform/bukkit/PotionEffectTypes.java diff --git a/core/src/main/java/art/arcane/iris/core/events/InventorySlotType.java b/core/src/main/java/art/arcane/iris/core/events/InventorySlotType.java new file mode 100644 index 000000000..18590a487 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/events/InventorySlotType.java @@ -0,0 +1,33 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.events; + +/** The kind of slot of an inventory that loot fills. World generation only ever fills {@link #STORAGE}. */ +public enum InventorySlotType { + /** Most slots of an inventory. */ + STORAGE, + /** The fuel slot of furnaces, blast furnaces and smokers. */ + FUEL, + /** The cook slot of furnaces. */ + FURNACE, + /** The cook slot of blast furnaces. */ + BLAST_FURNACE, + /** The cook slot of smokers. */ + SMOKER +} diff --git a/core/src/main/java/art/arcane/iris/core/events/IrisLootEvent.java b/core/src/main/java/art/arcane/iris/core/events/IrisLootEvent.java index 87576d982..69446dee1 100644 --- a/core/src/main/java/art/arcane/iris/core/events/IrisLootEvent.java +++ b/core/src/main/java/art/arcane/iris/core/events/IrisLootEvent.java @@ -51,6 +51,7 @@ public class IrisLootEvent extends Event { private final Engine engine; private final Block block; + private final InventorySlotType slot; private final KList tables; /** @@ -58,11 +59,13 @@ public class IrisLootEvent extends Event { * * @param engine The engine instance. * @param block The block associated with the event. + * @param slot The inventory slot type the loot fills. * @param tables The loot tables the container draws from, as the pack's modules named them. (mutable*) */ - public IrisLootEvent(Engine engine, Block block, KList tables) { + public IrisLootEvent(Engine engine, Block block, InventorySlotType slot, KList tables) { this.engine = engine; this.block = block; + this.slot = slot; this.tables = tables; } diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleServices.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleServices.java index 0967cd1b9..453e624ad 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleServices.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleServices.java @@ -23,6 +23,7 @@ import art.arcane.iris.engine.framework.Engine; import com.volmit.host.FeatureCatalog; import com.volmit.entity.EntitySpec; import com.volmit.item.ItemDrop; +import com.volmit.service.AmbientEffects; import com.volmit.service.BlockDrops; import com.volmit.service.EntitySpawns; import com.volmit.service.LocateResult; @@ -30,6 +31,7 @@ import com.volmit.service.Loot; import com.volmit.service.ObjectsAt; import com.volmit.service.SaplingGrowth; import com.volmit.service.StructureLocator; +import com.volmit.world.BlockPosition; import com.volmit.world.PackWorld; import java.util.ArrayList; import java.util.LinkedHashSet; @@ -164,6 +166,16 @@ public final class ModuleServices { return Optional.empty(); } + /** The ambient effects every module says are due for a player standing at {@code at}, in module order. */ + public static List ambientEffects(Engine engine, BlockPosition at) { + PackWorld world = engine.getGeneration().world(); + List effects = new ArrayList<>(); + for (AmbientEffects provider : catalog(engine.getData()).services(AmbientEffects.class)) { + effects.addAll(provider.due(world, at)); + } + return effects; + } + /** A plan and the module that made it, which hears how many of its entities appeared. */ public record PlannedSpawn(EntitySpawns provider, PackWorld world, EntitySpawns.Plan plan) { public void spawned(int count) { diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleSettingsDecoder.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleSettingsDecoder.java index a192f7042..35b012ce6 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleSettingsDecoder.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleSettingsDecoder.java @@ -20,8 +20,10 @@ package art.arcane.iris.core.modules; import art.arcane.volmlib.util.json.JSONArray; import art.arcane.volmlib.util.json.JSONObject; +import art.arcane.volmlib.util.json.JSONTokener; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; @@ -129,6 +131,24 @@ public final class ModuleSettingsDecoder { return decoded; } + /** + * The JSON that declares {@code values} at {@code target}: each settings feature under its key, in the shape the + * feature is written in (a rooted feature as its root option's value), the inverse of {@link #decode}. + */ + public JSONObject encode(Target target, ModuleSettings values) { + JSONObject json = new JSONObject(); + for (FeatureDescriptor feature : settings.get(target)) { + values.find(feature.type()).ifPresent(value -> json.put(feature.key(), writtenShape(feature, value))); + } + return json; + } + + private Object writtenShape(FeatureDescriptor feature, IrisFeature value) { + JsonElement settingsTree = gson.toJsonTree(value, feature.type()); + JsonElement written = feature.root().map(root -> settingsTree.getAsJsonObject().get(root)).orElse(settingsTree); + return new JSONTokener(gson.toJson(written)).nextValue(); + } + private IrisFeature read(FeatureDescriptor feature, Object value, String resource) { try { requireShape(feature, value); diff --git a/core/src/main/java/art/arcane/iris/core/pack/ModuleResourceClosure.java b/core/src/main/java/art/arcane/iris/core/pack/ModuleResourceClosure.java new file mode 100644 index 000000000..1259ff6d3 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/pack/ModuleResourceClosure.java @@ -0,0 +1,211 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.pack; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.loader.IrisRegistrant; +import art.arcane.iris.core.modules.IrisPackResources; +import art.arcane.iris.engine.object.annotations.RegistryListResource; +import art.arcane.volmlib.util.io.IO; +import art.arcane.volmlib.util.json.JSONObject; +import com.google.gson.Gson; +import com.volmit.config.ResourceRef; +import com.volmit.host.ResourceKindRegistration; +import com.volmit.resource.ResourceKind; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +/** + * The resources of the pack's module resource kinds that a pack export has to carry: what the settings of the + * exported dimension, regions and biomes (and anything else handed to {@link #follow}) name by {@link ResourceRef} or + * {@link RegistryListResource}, and what those resources name in turn. Core does not know the kinds: it follows the + * references the modules declare on their classes. + */ +public final class ModuleResourceClosure { + private static final String JAVA_PACKAGE_PREFIX = "java."; + private static final String JSON_EXTENSION = ".json"; + private static final int PRETTY_INDENT = 4; + + private final IrisData data; + private final Map, ResourceKind> kindsByType = new HashMap<>(); + private final Map, Map> found = new LinkedHashMap<>(); + private final Set visited = java.util.Collections.newSetFromMap(new IdentityHashMap<>()); + + public ModuleResourceClosure(IrisData data) { + this.data = data; + for (ResourceKindRegistration registration : data.getModules().pack().catalog().resourceKinds()) { + kindsByType.put(registration.kind().type(), registration.kind()); + } + } + + /** Adds the resources that the module settings of {@code owner} reference, and those they reference. */ + public void followSettingsOf(IrisRegistrant owner) { + owner.getModuleSettings().values().forEach(this::follow); + } + + /** Adds the resources that {@code holder} references, and those they reference. */ + public void follow(Object holder) { + if (holder == null || !visited.add(holder)) { + return; + } + if (holder instanceof Collection collection) { + collection.forEach(this::follow); + return; + } + if (holder instanceof Map map) { + map.values().forEach(this::follow); + return; + } + if (holder instanceof Object[] array) { + for (Object element : array) { + follow(element); + } + return; + } + if (isLeaf(holder.getClass())) { + return; + } + for (Class type = holder.getClass(); type != null && type != Object.class; type = type.getSuperclass()) { + for (Field field : type.getDeclaredFields()) { + followField(holder, field); + } + } + } + + /** Whether nothing was found. */ + public boolean isEmpty() { + return found.isEmpty(); + } + + /** The keys of the resources found of the kind that reads into {@code type}, in key order. */ + public List keysOf(Class type) { + ResourceKind kind = kindsByType.get(type); + return kind == null || !found.containsKey(kind) ? List.of() : new ArrayList<>(new TreeMap<>(found.get(kind)).keySet()); + } + + /** + * Writes every resource found as {@code /.json} below {@code targetRoot}, kinds in folder + * order and keys in key order. + * + * @return the hashes of the files written, to put into the package's hash + */ + public String writeTo(File targetRoot, boolean minify) throws IOException { + StringBuilder hashes = new StringBuilder(); + List, Map>> kinds = new ArrayList<>(found.entrySet()); + kinds.sort(Comparator.comparing(entry -> entry.getKey().folder())); + for (Map.Entry, Map> kind : kinds) { + for (Map.Entry resource : new TreeMap<>(kind.getValue()).entrySet()) { + String json = new JSONObject(new Gson().toJson(resource.getValue())).toString(minify ? 0 : PRETTY_INDENT); + IO.writeAll(new File(targetRoot, kind.getKey().folder() + "/" + resource.getKey() + JSON_EXTENSION), json); + hashes.append(IO.hash(json)); + } + } + return hashes.toString(); + } + + private void followField(Object holder, Field field) { + if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers()) || field.getType().isPrimitive()) { + return; + } + Object value = valueOf(holder, field); + if (value == null) { + return; + } + Class referenced = referencedType(field); + if (referenced == null) { + follow(value); + return; + } + for (String key : keysIn(value)) { + add(referenced, key); + } + } + + /** The class of the resources the field names by key, or null when it names none. */ + private static Class referencedType(Field field) { + ResourceRef reference = field.getAnnotation(ResourceRef.class); + if (reference != null) { + return reference.value(); + } + RegistryListResource registry = field.getAnnotation(RegistryListResource.class); + return registry == null ? null : registry.value(); + } + + private static List keysIn(Object value) { + List keys = new ArrayList<>(); + if (value instanceof String key) { + keys.add(key); + } else if (value instanceof Collection collection) { + collection.stream().filter(String.class::isInstance).map(String.class::cast).forEach(keys::add); + } + return keys; + } + + private void add(Class type, String key) { + ResourceKind kind = kindsByType.get(type); + if (kind == null || key == null || key.isBlank()) { + return; + } + Map ofKind = found.computeIfAbsent(kind, ignored -> new LinkedHashMap<>()); + if (ofKind.containsKey(key)) { + return; + } + Object resource = lookup(kind, key); + if (resource == null) { + return; + } + ofKind.put(key, resource); + follow(resource); + } + + private Object lookup(ResourceKind kind, String key) { + IrisPackResources resources = data.getPackResources(); + try { + return resources.find(kind.key(resources.idOf(key))).orElse(null); + } catch (IllegalStateException failedToLoad) { + return null; + } + } + + private static boolean isLeaf(Class type) { + return type.isEnum() || type.getName().startsWith(JAVA_PACKAGE_PREFIX); + } + + private static Object valueOf(Object holder, Field field) { + try { + field.setAccessible(true); + return field.get(holder); + } catch (ReflectiveOperationException | RuntimeException inaccessible) { + return null; + } + } +} diff --git a/core/src/main/java/art/arcane/iris/core/pack/PackExportClosure.java b/core/src/main/java/art/arcane/iris/core/pack/PackExportClosure.java index 1af44db16..1f24f9b36 100644 --- a/core/src/main/java/art/arcane/iris/core/pack/PackExportClosure.java +++ b/core/src/main/java/art/arcane/iris/core/pack/PackExportClosure.java @@ -18,7 +18,6 @@ package art.arcane.iris.core.pack; -import art.arcane.iris.engine.object.marker.IrisObjectMarker; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.volmlib.util.collection.KSet; @@ -32,25 +31,6 @@ public final class PackExportClosure { private PackExportClosure() { } - public static KSet collectMarkerKeys(Iterable placements) { - KSet markerKeys = new KSet<>(); - if (placements == null) { - return markerKeys; - } - for (IrisObjectPlacement placement : placements) { - if (placement == null || placement.getMarkers() == null) { - continue; - } - for (IrisObjectMarker marker : placement.getMarkers()) { - if (marker == null || marker.getMarker() == null || marker.getMarker().isBlank()) { - continue; - } - markerKeys.add(marker.getMarker()); - } - } - return markerKeys; - } - public static KSet collectObjectKeys(Iterable placements) { KSet objectKeys = new KSet<>(); if (placements == null) { diff --git a/core/src/main/java/art/arcane/iris/core/project/IrisPackageCompiler.java b/core/src/main/java/art/arcane/iris/core/project/IrisPackageCompiler.java index 241f811e2..4c54f64ea 100644 --- a/core/src/main/java/art/arcane/iris/core/project/IrisPackageCompiler.java +++ b/core/src/main/java/art/arcane/iris/core/project/IrisPackageCompiler.java @@ -18,27 +18,22 @@ package art.arcane.iris.core.project; -import art.arcane.iris.engine.spawn.SpawnResources; -import art.arcane.iris.engine.loot.LootResources; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import com.google.gson.Gson; import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.loader.IrisRegistrant; import art.arcane.iris.core.localization.BukkitRuntimeMessages; import art.arcane.iris.core.localization.IrisLanguage; import art.arcane.iris.core.pack.ImageMapPackageClosure; +import art.arcane.iris.core.pack.ModuleResourceClosure; import art.arcane.iris.core.pack.PackValidationResult; import art.arcane.iris.core.pack.PackValidator; import art.arcane.iris.core.pack.StructurePackageClosure; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.material.IrisBlockData; import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.entity.IrisEntity; import art.arcane.iris.engine.object.terrain.IrisGenerator; -import art.arcane.iris.engine.object.loot.IrisLootTable; -import art.arcane.iris.core.pack.PackExportClosure; -import art.arcane.iris.engine.object.marker.IrisMarker; import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisPlatforms; @@ -52,11 +47,11 @@ import art.arcane.volmlib.util.localization.MessageArgument; import art.arcane.volmlib.util.math.M; import art.arcane.volmlib.util.scheduling.ChronoLatch; import art.arcane.volmlib.util.scheduling.O; +import com.volmit.FeatureAttachment.Target; import org.zeroturnaround.zip.ZipUtil; import java.io.File; import java.io.IOException; -import java.util.Comparator; import java.util.LinkedHashSet; import java.util.Set; import java.util.UUID; @@ -109,10 +104,8 @@ public class IrisPackageCompiler { IrisLogging.info("Packaging Dimension " + dimension.getName() + " " + (obfuscate ? "(Obfuscated)" : "")); KSet regions = new KSet<>(); KSet biomes = new KSet<>(); - KSet entities = new KSet<>(); - KSet spawners = new KSet<>(); KSet generators = new KSet<>(); - KSet loot = new KSet<>(); + ModuleResourceClosure moduleResources = new ModuleResourceClosure(dm); KSet blocks = new KSet<>(); // KSet is ConcurrentHashMap-backed: both add(null) and remove(null) throw NPE, so a @@ -122,29 +115,16 @@ public class IrisPackageCompiler { } dimension.getAllRegions(() -> dm).forEach((region) -> addIfPresent(regions, region)); - dimension.getLoot().getTables().forEach((i) -> addIfPresent(loot, LootResources.table(dm, i))); + moduleResources.followSettingsOf(dimension); regions.forEach((i) -> biomes.addAll(i.getAllBiomes(() -> dm))); dimension.getReachableBiomes(() -> dm).forEach((biome) -> addIfPresent(biomes, biome)); - regions.forEach((r) -> r.getLoot().getTables().forEach((i) -> addIfPresent(loot, LootResources.table(dm, i)))); - regions.forEach((r) -> r.getEntitySpawners().forEach((sp) -> addIfPresent(spawners, SpawnResources.spawner(dm, sp)))); - dimension.getEntitySpawners().forEach((sp) -> addIfPresent(spawners, SpawnResources.spawner(dm, sp))); + regions.forEach(moduleResources::followSettingsOf); biomes.forEach((i) -> i.getGenerators().forEach((j) -> addIfPresent(generators, j.getCachedGenerator(() -> dm)))); - biomes.forEach((r) -> r.getLoot().getTables().forEach((i) -> addIfPresent(loot, LootResources.table(dm, i)))); - biomes.forEach((r) -> r.getEntitySpawners().forEach((sp) -> addIfPresent(spawners, SpawnResources.spawner(dm, sp)))); + biomes.forEach(moduleResources::followSettingsOf); KList allPlacements = new KList<>(); regions.forEach((r) -> allPlacements.addAll(r.getObjects())); biomes.forEach((i) -> allPlacements.addAll(i.getObjects())); - KSet markers = new KSet<>(); - for (String markerKey : PackExportClosure.collectMarkerKeys(allPlacements)) { - IrisMarker marker = SpawnResources.marker(dm, markerKey); - if (marker == null) { - continue; - } - markers.add(marker); - marker.getSpawners().forEach((sp) -> addIfPresent(spawners, SpawnResources.spawner(dm, sp))); - } - collectSpawnerEntityKeys(spawners).forEach((i) -> addIfPresent(entities, SpawnResources.entity(dm, i))); - entities.forEach((e) -> e.getLoot().getTables().forEach((i) -> addIfPresent(loot, LootResources.table(dm, i)))); + moduleResources.follow(allPlacements); Set structureKeys = new LinkedHashSet<>(); collectStructureKeys(structureKeys, dimension.getStructures()); regions.forEach((region) -> collectStructureKeys(structureKeys, region.getStructures())); @@ -224,7 +204,7 @@ public class IrisPackageCompiler { } b.append(structureClosure.writeTo(folder, minify)); b.append(ImageMapPackageClosure.writeAll(dm, folder, minify)); - a = new JSONObject(new Gson().toJson(dimension)).toString(minify ? 0 : 4); + a = withModuleSettings(dimension, Target.DIMENSION, dm).toString(minify ? 0 : 4); IO.writeAll(new File(folder, "dimensions/" + dimension.getLoadKey() + ".json"), a); b.append(IO.hash(a)); @@ -238,7 +218,7 @@ public class IrisPackageCompiler { b = new StringBuilder(); for (IrisRegion i : regions) { - a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); + a = withModuleSettings(i, Target.REGION, dm).toString(minify ? 0 : 4); IO.writeAll(new File(folder, "regions/" + i.getLoadKey() + ".json"), a); b.append(IO.hash(a)); } @@ -250,35 +230,12 @@ public class IrisPackageCompiler { } for (IrisBiome i : biomes) { - a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); + a = withModuleSettings(i, Target.BIOME, dm).toString(minify ? 0 : 4); IO.writeAll(new File(folder, "biomes/" + i.getLoadKey() + ".json"), a); b.append(IO.hash(a)); } - for (IrisEntity i : entities) { - a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); - IO.writeAll(new File(folder, "entities/" + i.getLoadKey() + ".json"), a); - b.append(IO.hash(a)); - } - - for (IrisLootTable i : loot) { - a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); - IO.writeAll(new File(folder, "loot/" + i.getLoadKey() + ".json"), a); - b.append(IO.hash(a)); - } - - // Sorted so package.json.hash stays stable across runs. - for (IrisSpawner i : spawners.stream().sorted(Comparator.comparing(IrisSpawner::getLoadKey)).toList()) { - a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); - IO.writeAll(new File(folder, "spawners/" + i.getLoadKey() + ".json"), a); - b.append(IO.hash(a)); - } - - for (IrisMarker i : markers.stream().sorted(Comparator.comparing(IrisMarker::getLoadKey)).toList()) { - a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); - IO.writeAll(new File(folder, "markers/" + i.getLoadKey() + ".json"), a); - b.append(IO.hash(a)); - } + b.append(moduleResources.writeTo(folder, minify)); c.append(IO.hash(b.toString())); String finalHash = IO.hash(c.toString()); @@ -301,13 +258,12 @@ public class IrisPackageCompiler { return null; } - static KSet collectSpawnerEntityKeys(KSet spawners) { - KSet entityKeys = new KSet<>(); - for (IrisSpawner spawner : spawners) { - spawner.getSpawns().forEach((spawn) -> entityKeys.add(spawn.getEntity())); - spawner.getInitialSpawns().forEach((spawn) -> entityKeys.add(spawn.getEntity())); - } - return entityKeys; + /** The JSON of a dimension, region or biome with the settings its modules declare, which the resource itself does not hold. */ + private static JSONObject withModuleSettings(IrisRegistrant resource, Target target, IrisData data) { + JSONObject json = new JSONObject(new Gson().toJson(resource)); + JSONObject settings = data.getModules().settings().encode(target, resource.getModuleSettings()); + settings.keySet().forEach(key -> json.put(key, settings.get(key))); + return json; } private static void collectStructureKeys(Set keys, KList placements) { diff --git a/core/src/main/java/art/arcane/iris/engine/framework/EnginePlayer.java b/core/src/main/java/art/arcane/iris/engine/framework/EnginePlayer.java index 5bbf38f92..add9312c4 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/EnginePlayer.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/EnginePlayer.java @@ -19,14 +19,13 @@ package art.arcane.iris.engine.framework; import art.arcane.iris.core.IrisSettings; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.entity.IrisEffect; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.engine.platform.EngineBukkitOps; +import art.arcane.iris.core.modules.ModuleServices; +import art.arcane.iris.platform.bukkit.BukkitAmbientEffects; import art.arcane.iris.platform.bukkit.BukkitWorldBinding; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.util.common.scheduling.J; import art.arcane.volmlib.util.math.M; +import com.volmit.world.BlockPosition; import lombok.Data; import org.bukkit.Location; import org.bukkit.entity.Player; @@ -35,8 +34,7 @@ import org.bukkit.entity.Player; public class EnginePlayer { private final Engine engine; private final Player player; - private IrisBiome biome; - private IrisRegion region; + private BlockPosition sampledPosition; private Location lastLocation; private long lastSample; @@ -56,26 +54,14 @@ public class EnginePlayer { return; } - if (region != null) { - for (IrisEffect effect : region.getEffects()) { - try { - effect.apply(player, getEngine()); - } catch (Throwable e) { - IrisLogging.reportError(e); - - } - } + if (sampledPosition == null) { + return; } - if (biome != null) { - for (IrisEffect effect : biome.getEffects()) { - try { - effect.apply(player, getEngine()); - } catch (Throwable e) { - IrisLogging.reportError(e); - - } - } + try { + BukkitAmbientEffects.play(player, engine, ModuleServices.ambientEffects(engine, sampledPosition)); + } catch (Throwable e) { + IrisLogging.reportError(e); } } @@ -94,8 +80,7 @@ public class EnginePlayer { if (needsSample(sampled, ticksSinceLastSample(), distanceSquared)) { lastLocation = current; lastSample = M.ms(); - biome = EngineBukkitOps.getBiome(engine, current); - region = EngineBukkitOps.getRegion(engine, current); + sampledPosition = new BlockPosition(current.getBlockX(), current.getBlockY() - engine.getWorld().minHeight(), current.getBlockZ()); } return false; } catch (Throwable e) { diff --git a/core/src/main/java/art/arcane/iris/engine/framework/placer/WorldObjectPlacer.java b/core/src/main/java/art/arcane/iris/engine/framework/placer/WorldObjectPlacer.java index 2b9e0ba64..653463074 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/placer/WorldObjectPlacer.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/placer/WorldObjectPlacer.java @@ -5,6 +5,7 @@ import art.arcane.iris.platform.bukkit.BukkitBlockResolution; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.tools.IrisToolbelt; import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.core.events.InventorySlotType; import art.arcane.iris.core.events.IrisLootEvent; import art.arcane.iris.engine.mantle.EngineMantle; import art.arcane.iris.engine.platform.EngineBukkitOps; @@ -86,7 +87,7 @@ public class WorldObjectPlacer implements IObjectPlacer { KList tables = EngineBukkitOps.getLootTables(engine, block); try { - Bukkit.getPluginManager().callEvent(new IrisLootEvent(engine, block, tables)); + Bukkit.getPluginManager().callEvent(new IrisLootEvent(engine, block, InventorySlotType.STORAGE, tables)); if (tables.isEmpty()) { return; } diff --git a/core/src/main/java/art/arcane/iris/engine/platform/EngineBukkitOps.java b/core/src/main/java/art/arcane/iris/engine/platform/EngineBukkitOps.java index 53690d89b..04b649f9a 100644 --- a/core/src/main/java/art/arcane/iris/engine/platform/EngineBukkitOps.java +++ b/core/src/main/java/art/arcane/iris/engine/platform/EngineBukkitOps.java @@ -19,6 +19,7 @@ package art.arcane.iris.engine.platform; import art.arcane.iris.platform.bukkit.BukkitWorldBinding; +import art.arcane.iris.core.events.InventorySlotType; import art.arcane.iris.core.events.IrisLootEvent; import art.arcane.iris.core.link.Identifier; import art.arcane.iris.core.service.ExternalDataSVC; @@ -304,7 +305,7 @@ public final class EngineBukkitOps { KList tables = new KList<>(getLootTables(engine, block, hasNativeLootTable(block))); try { - Bukkit.getPluginManager().callEvent(new IrisLootEvent(engine, block, tables)); + Bukkit.getPluginManager().callEvent(new IrisLootEvent(engine, block, InventorySlotType.STORAGE, tables)); if (tables.isEmpty()) return; InventoryHolder m = (InventoryHolder) block.getState(); addItems(engine, false, m.getInventory(), tables, c.getWorld(), block.getX(), y, block.getZ()); diff --git a/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitAmbientEffects.java b/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitAmbientEffects.java new file mode 100644 index 000000000..c791f1e0c --- /dev/null +++ b/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitAmbientEffects.java @@ -0,0 +1,144 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.platform.bukkit; + +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.util.common.data.registry.RegistryUtil; +import art.arcane.iris.util.common.scheduling.ConsoleCommands; +import art.arcane.iris.util.common.scheduling.J; +import com.volmit.entity.EntitySpec; +import com.volmit.service.AmbientEffects; +import org.bukkit.Location; +import org.bukkit.NamespacedKey; +import org.bukkit.Particle; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.util.Vector; + +import java.util.List; + +/** + * Plays the ambient effects a module decided on to a Bukkit player: the sound, the particles, the commands and the + * potion effect of each, in that order. Everything random was decided by the module; what the platform lacks is skipped. + */ +public final class BukkitAmbientEffects { + private static final double QUARTER_TURN_RADIANS = Math.toRadians(90); + private static final int ABOVE_SURFACE_BLOCKS = 1; + + private BukkitAmbientEffects() { + } + + public static void play(Player player, Engine engine, List effects) { + for (AmbientEffects.Effect effect : effects) { + J.runEntity(player, () -> playOnEntityThread(player, engine, effect)); + } + } + + private static void playOnEntityThread(Player player, Engine engine, AmbientEffects.Effect effect) { + if (effect.sound() != null) { + playSound(player, effect.sound()); + } + if (effect.particles() != null) { + showParticles(player, engine, effect.particles()); + } + effect.commands().forEach(command -> runCommand(player, command)); + if (effect.potion() != null) { + givePotion(player, effect.potion()); + } + } + + private static void playSound(Player player, AmbientEffects.Sound sound) { + Sound type = lookup(Sound.class, sound.key()); + if (type == null) { + return; + } + Location at = player.getLocation().clone().add(sound.offsetX(), sound.offsetY(), sound.offsetZ()); + player.playSound(at, type, sound.volume(), sound.pitch()); + } + + private static void showParticles(Player player, Engine engine, AmbientEffects.Particles particles) { + Particle type = lookup(Particle.class, particles.key()); + if (type == null) { + return; + } + Location location = player.getLocation(); + Vector direction = location.getDirection(); + Location spot = location.clone() + .add(direction.clone().multiply(particles.forward())) + .add(direction.clone().rotateAroundY(QUARTER_TURN_RADIANS).multiply(particles.sideways())); + spot.setY(Math.round(engine.getHeight(spot.getBlockX(), spot.getBlockZ())) + ABOVE_SURFACE_BLOCKS); + spot.add(particles.jitterX(), 0, particles.jitterZ()); + double x = spot.getX(); + double y = spot.getY() + player.getWorld().getMinHeight() + particles.lift(); + double z = spot.getZ(); + if (particles.extra() != 0) { + player.spawnParticle(type, x, y, z, particles.count(), particles.altX(), particles.altY(), particles.altZ(), particles.extra()); + return; + } + player.spawnParticle(type, x, y, z, particles.count(), particles.altX(), particles.altY(), particles.altZ()); + } + + private static void runCommand(Player player, AmbientEffects.Command command) { + Location at = player.getLocation().clone().add(command.offsetX(), command.offsetY(), command.offsetZ()); + EntitySpec.Command run = command.command(); + ConsoleCommands.run(run.commands(), run.delay(), run.repeat(), run.repeatDelay(), at.getBlockX(), at.getBlockY(), at.getBlockZ()); + } + + private static void givePotion(Player player, AmbientEffects.Potion potion) { + PotionEffectType type = potionType(potion.key()); + PotionEffect current = player.getPotionEffect(type); + if (current != null) { + if (current.getAmplifier() > potion.strength()) { + return; + } + player.removePotionEffect(type); + } + + player.addPotionEffect(new PotionEffect(type, potion.ticks(), potion.strength(), true, false, false)); + } + + /** The potion effect type a pack names, or luck for a name the platform does not know, with a warning once. */ + private static PotionEffectType potionType(String name) { + if (name == null || name.isEmpty()) { + return PotionEffectType.LUCK; + } + + try { + PotionEffectType resolved = PotionEffectTypes.resolve(name); + if (resolved != null) { + return resolved; + } + } catch (Throwable e) { + IrisLogging.reportError(e); + } + + if (PotionEffectTypes.shouldWarn(name)) { + IrisLogging.warn("Unknown Potion Effect Type: \"" + name + "\". Valid types: " + PotionEffectTypes.knownTypesList()); + } + return PotionEffectType.LUCK; + } + + private static T lookup(Class type, String key) { + NamespacedKey namespacedKey = NamespacedKey.fromString(key); + return namespacedKey == null ? null : RegistryUtil.lookup(type).get(namespacedKey); + } +} diff --git a/core/src/main/java/art/arcane/iris/platform/bukkit/PotionEffectTypes.java b/core/src/main/java/art/arcane/iris/platform/bukkit/PotionEffectTypes.java new file mode 100644 index 000000000..7c09c0f65 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/platform/bukkit/PotionEffectTypes.java @@ -0,0 +1,98 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.platform.bukkit; + +import art.arcane.iris.util.common.reflect.KeyedType; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; +import org.bukkit.potion.PotionEffectType; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentHashMap; + +public final class PotionEffectTypes { + private static final Map LEGACY_ALIASES; + private static final Set MISSING_WARNED = ConcurrentHashMap.newKeySet(); + + static { + Map m = new HashMap<>(); + m.put("SLOW", "SLOWNESS"); + m.put("FAST_DIGGING", "HASTE"); + m.put("SLOW_DIGGING", "MINING_FATIGUE"); + m.put("INCREASE_DAMAGE", "STRENGTH"); + m.put("HEAL", "INSTANT_HEALTH"); + m.put("HARM", "INSTANT_DAMAGE"); + m.put("JUMP", "JUMP_BOOST"); + m.put("CONFUSION", "NAUSEA"); + m.put("DAMAGE_RESISTANCE", "RESISTANCE"); + LEGACY_ALIASES = Collections.unmodifiableMap(m); + } + + private PotionEffectTypes() { + } + + public static String normalize(String input) { + if (input == null) { + return ""; + } + String upper = input.trim().toUpperCase(Locale.ROOT).replace(' ', '_'); + if (upper.contains(":")) { + upper = upper.substring(upper.indexOf(':') + 1); + } + return LEGACY_ALIASES.getOrDefault(upper, upper); + } + + public static PotionEffectType resolve(String rawName) { + if (rawName == null || rawName.trim().isEmpty()) { + return null; + } + String wanted = normalize(rawName); + for (PotionEffectType i : Registry.EFFECT) { + NamespacedKey key = KeyedType.getKey(i); + if (key == null) { + continue; + } + String candidate = key.getKey().toUpperCase(Locale.ROOT).replace(' ', '_'); + if (candidate.equals(wanted)) { + return i; + } + } + return null; + } + + public static String knownTypesList() { + TreeSet names = new TreeSet<>(); + for (PotionEffectType i : Registry.EFFECT) { + NamespacedKey key = KeyedType.getKey(i); + if (key != null) { + names.add(key.getKey().toUpperCase(Locale.ROOT).replace(' ', '_')); + } + } + return String.join(", ", names); + } + + public static boolean shouldWarn(String rawName) { + return MISSING_WARNED.add(normalize(rawName)); + } +} diff --git a/core/src/main/java/art/arcane/iris/util/common/director/handlers/EntityHandler.java b/core/src/main/java/art/arcane/iris/util/common/director/handlers/EntityHandler.java deleted file mode 100644 index 1844516e5..000000000 --- a/core/src/main/java/art/arcane/iris/util/common/director/handlers/EntityHandler.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.util.common.director.handlers; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.entity.IrisEntity; -import art.arcane.iris.engine.spawn.SpawnResources; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.iris.util.common.director.specialhandlers.RegistrantHandler; - -public class EntityHandler extends RegistrantHandler { - - public EntityHandler() { - super(IrisEntity.class, false); - } - - @Override - protected KList loadAll(IrisData data) { - KList entities = new KList<>(); - for (String key : SpawnResources.entityKeys(data)) { - IrisEntity entity = SpawnResources.entity(data, key); - if (entity != null) { - entities.add(entity); - } - } - return entities; - } - - @Override - public String getRandomDefault() { - return "entity"; - } -} diff --git a/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/EntityKeyHandler.java b/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/EntityKeyHandler.java new file mode 100644 index 000000000..3871ae1b9 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/EntityKeyHandler.java @@ -0,0 +1,77 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.util.common.director.specialhandlers; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.PackModulesException; +import art.arcane.iris.core.pack.PackDirectoryResolver; +import art.arcane.iris.engine.spawn.SpawnResources; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.util.common.director.DirectorParameterHandler; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.director.exceptions.DirectorParsingException; + +import java.io.File; +import java.util.LinkedHashSet; +import java.util.Set; + +/** The key of an entity of a pack: the open pack's, then those of the packs in the packs folder. */ +public final class EntityKeyHandler implements DirectorParameterHandler { + @Override + public KList getPossibilities() { + Set keys = new LinkedHashSet<>(); + IrisData activeData = data(); + if (activeData != null) { + addEntityKeys(keys, activeData); + } + for (File pack : PackDirectoryResolver.listVisiblePackDirectories( + IrisPlatforms.get().packsFolder())) { + addEntityKeys(keys, IrisData.get(pack)); + } + return new KList<>(keys); + } + + @Override + public String toString(String value) { + return value == null ? "" : value; + } + + @Override + public String parse(String input, boolean force) throws DirectorParsingException { + for (String option : getPossibilities(input)) { + if (option.equalsIgnoreCase(input)) { + return option; + } + } + throw new DirectorParsingException("Unable to find Entity \"" + input + "\""); + } + + @Override + public boolean supports(Class type) { + return type == String.class; + } + + /** A pack whose modules fail to load has no entities to offer; its failure was reported when it loaded. */ + private static void addEntityKeys(Set keys, IrisData data) { + try { + keys.addAll(SpawnResources.entityKeys(data)); + } catch (PackModulesException ignored) { + } + } +} diff --git a/core/src/main/java/art/arcane/iris/util/project/matter/IrisMatterSupport.java b/core/src/main/java/art/arcane/iris/util/project/matter/IrisMatterSupport.java index 99a7c0a04..f29a9eb9e 100644 --- a/core/src/main/java/art/arcane/iris/util/project/matter/IrisMatterSupport.java +++ b/core/src/main/java/art/arcane/iris/util/project/matter/IrisMatterSupport.java @@ -26,7 +26,6 @@ import art.arcane.iris.util.project.matter.slices.IdentifierMatter; import art.arcane.iris.util.project.matter.slices.ModuleLayerMatter; import art.arcane.iris.util.project.matter.slices.NativeStructureOwnershipMatter; import art.arcane.iris.util.project.matter.slices.PlatformBlockMatter; -import art.arcane.iris.util.project.matter.slices.SpawnerMatter; import art.arcane.iris.util.project.matter.slices.TileMatter; import art.arcane.iris.util.project.matter.slices.TreeBlockMaterialMatter; import art.arcane.volmlib.util.matter.IrisMatter; @@ -52,7 +51,6 @@ public final class IrisMatterSupport { IrisMatter.registerSliceType(new ModuleLayerMatter()); IrisMatter.registerSliceType(new NativeStructureOwnershipMatter()); IrisMatter.registerSliceType(new PlatformBlockMatter()); - IrisMatter.registerSliceType(new SpawnerMatter()); IrisMatter.registerSliceType(new TileMatter()); IrisMatter.registerSliceType(new TreeBlockMaterialMatter()); registered = true; diff --git a/core/src/main/java/art/arcane/iris/util/project/matter/slices/RegistryMatter.java b/core/src/main/java/art/arcane/iris/util/project/matter/slices/RegistryMatter.java deleted file mode 100644 index 229e1f11b..000000000 --- a/core/src/main/java/art/arcane/iris/util/project/matter/slices/RegistryMatter.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.util.project.matter.slices; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.util.project.matter.IrisMatterContext; -import art.arcane.volmlib.util.data.palette.Palette; -import art.arcane.volmlib.util.matter.slices.RawMatter; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -public abstract class RegistryMatter extends RawMatter { - public RegistryMatter(int width, int height, int depth, Class c, T e) { - super(width, height, depth, c); - } - - @Override - public Palette getGlobalPalette() { - return null; - } - - @Override - public void writeNode(T b, DataOutputStream dos) throws IOException { - dos.writeUTF(b.getLoadKey()); - } - - @Override - public T readNode(DataInputStream din) throws IOException { - return load(IrisMatterContext.require(), din.readUTF()); - } - - /** The resource of the pack {@code data} named by {@code key}, or null when the pack has none. */ - protected abstract T load(IrisData data, String key); -} diff --git a/core/src/main/java/art/arcane/iris/util/project/matter/slices/SpawnerMatter.java b/core/src/main/java/art/arcane/iris/util/project/matter/slices/SpawnerMatter.java deleted file mode 100644 index 0cd4eb21b..000000000 --- a/core/src/main/java/art/arcane/iris/util/project/matter/slices/SpawnerMatter.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.util.project.matter.slices; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; -import art.arcane.iris.engine.spawn.SpawnResources; -import art.arcane.volmlib.util.matter.Sliced; - -@Sliced -public class SpawnerMatter extends RegistryMatter { - public SpawnerMatter() { - this(1, 1, 1); - } - - public SpawnerMatter(int width, int height, int depth) { - super(width, height, depth, IrisSpawner.class, new IrisSpawner()); - } - - @Override - protected IrisSpawner load(IrisData data, String key) { - return SpawnResources.spawner(data, key); - } -} diff --git a/core/src/test/java/art/arcane/iris/core/modules/DecorantSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/DecorantSettingsDecodingTest.java index f84b1f653..647016d36 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/DecorantSettingsDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/DecorantSettingsDecodingTest.java @@ -137,7 +137,8 @@ public class DecorantSettingsDecodingTest { JSONObject byId = new JSONObject("{\"iris:decorant\": [{\"chance\": 1}]}"); assertSame(ModuleSettings.NONE, decoder.decode(Target.BIOME, byId, "biome meadow")); - assertEquals(Set.of("decorators", "deposits"), decoder.keys(Target.BIOME)); + assertTrue(decoder.keys(Target.BIOME).containsAll(Set.of("decorators", "deposits"))); + assertFalse(decoder.keys(Target.BIOME).contains("iris:decorant")); } @Test diff --git a/core/src/test/java/art/arcane/iris/core/modules/DepositSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/DepositSettingsDecodingTest.java index fb91ac9f9..62b56e3b1 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/DepositSettingsDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/DepositSettingsDecodingTest.java @@ -147,7 +147,8 @@ public class DepositSettingsDecodingTest { JSONObject byId = new JSONObject("{\"iris:deposit\": [{\"maxHeight\": 16}]}"); assertSame(ModuleSettings.NONE, decoder.decode(Target.REGION, byId, "region forests")); - assertEquals(Set.of("deposits"), decoder.keys(Target.REGION)); + assertTrue(decoder.keys(Target.REGION).contains("deposits")); + assertFalse(decoder.keys(Target.REGION).contains("iris:deposit")); } @Test diff --git a/core/src/test/java/art/arcane/iris/core/modules/LootAndSpawnPackDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/LootAndSpawnPackDecodingTest.java new file mode 100644 index 000000000..546d170cd --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/modules/LootAndSpawnPackDecodingTest.java @@ -0,0 +1,276 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.modules; + +import art.arcane.iris.builtin.loot.BlockDrop; +import art.arcane.iris.builtin.loot.BlockDropSettings; +import art.arcane.iris.builtin.loot.LootMode; +import art.arcane.iris.builtin.loot.LootSettings; +import art.arcane.iris.builtin.loot.LootSlot; +import art.arcane.iris.builtin.loot.LootTable; +import art.arcane.iris.builtin.spawn.AmbientEffect; +import art.arcane.iris.builtin.spawn.EffectSettings; +import art.arcane.iris.builtin.spawn.EntityDefinition; +import art.arcane.iris.builtin.spawn.SpawnGroup; +import art.arcane.iris.builtin.spawn.SpawnWeather; +import art.arcane.iris.builtin.spawn.Spawner; +import art.arcane.iris.builtin.spawn.SpawnerSettings; +import art.arcane.volmlib.util.json.JSONObject; +import com.google.gson.Gson; +import com.volmit.FeatureAttachment.Target; +import com.volmit.block.BlockSpec; +import com.volmit.host.LoadedPack; +import com.volmit.host.ModuleHost; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +/** + * Files of the overworld pack exactly as they were before the loot and spawn fields became module settings (copied from + * the pack backup), decoded by the built-in modules: {@code loot} is an object, {@code blockDrops}, {@code entitySpawners} + * and {@code effects} are lists, the loot tables, spawners and entities are the pack's own files. + */ +public class LootAndSpawnPackDecodingTest { + private static final String PACK = "/art/arcane/iris/core/modules/pack-before-loot-and-spawn"; + + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + + private Path packFolder; + private LoadedPack pack; + private ModuleSettingsDecoder decoder; + + @Before + public void loadBuiltIns() throws IOException, URISyntaxException { + packFolder = Path.of(LootAndSpawnPackDecodingTest.class.getResource(PACK).toURI()); + pack = LoadedPack.load(packFolder, ModuleHost.of(IrisModuleHost.builtInModules()) + .reservingFields(ModuleTargets.reservedFields()) + .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGE).copyingJarsTo(folder.newFolder("copies").toPath())); + decoder = new ModuleSettingsDecoder(pack.catalog(), packFolder, Gson::new); + } + + @After + public void closePack() { + pack.close(); + } + + @Test + public void theDimensionReadsItsLootReference() throws IOException { + ModuleSettings settings = decoder.decode(Target.DIMENSION, file("dimensions/overworld.json"), "dimension overworld"); + + LootSettings loot = settings.find(LootSettings.class).orElseThrow(); + assertEquals(LootMode.FALLBACK, loot.mode()); + assertEquals(List.of("global-clutter"), loot.tables()); + assertEquals(1D, loot.multiplier(), 0); + assertTrue(settings.find(BlockDropSettings.class).isEmpty()); + assertTrue(settings.find(SpawnerSettings.class).isEmpty()); + } + + @Test + public void aRegionReadsItsLootAndItsSpawners() throws IOException { + ModuleSettings settings = decoder.decode(Target.REGION, file("regions/terralost.json"), "region terralost"); + + LootSettings loot = settings.find(LootSettings.class).orElseThrow(); + assertEquals(LootMode.FALLBACK, loot.mode()); + assertEquals(0.5, loot.multiplier(), 0); + assertEquals(List.of("tropical/food", "cave/clutter"), loot.tables()); + assertEquals(List.of("temperate/cave", "temperate/hostile", "temperate/passive", "temperate/water"), + settings.find(SpawnerSettings.class).orElseThrow().spawners()); + } + + @Test + public void aRegionReadsItsBlockDrops() throws IOException { + ModuleSettings settings = decoder.decode(Target.REGION, file("regions/swamp.json"), "region swamp"); + + List drops = settings.find(BlockDropSettings.class).orElseThrow().drops(); + assertEquals(1, drops.size()); + assertEquals(List.of(BlockSpec.of("minecraft:grass_block"), BlockSpec.of("minecraft:dark_oak_leaves"), + BlockSpec.of("minecraft:short_grass"), BlockSpec.of("minecraft:tall_grass")), drops.getFirst().blocks()); + assertEquals("slime_ball", drops.getFirst().drops().getFirst().type()); + assertEquals(24, drops.getFirst().drops().getFirst().rarity()); + assertFalse(drops.getFirst().exactBlocks()); + assertFalse(drops.getFirst().skipParents()); + assertFalse(drops.getFirst().replaceVanillaDrops()); + assertEquals(LootSlot.STORAGE, drops.getFirst().drops().getFirst().slotTypes()); + } + + @Test + public void aRegionReadsItsEffectsLootAndBlockDropsTogether() throws IOException { + JSONObject region = file("regions/mushroom.json"); + + ModuleSettings settings = decoder.decode(Target.REGION, region, "region mushroom"); + + List effects = settings.find(EffectSettings.class).orElseThrow().effects(); + assertEquals(region.getJSONArray("effects").length(), effects.size()); + assertEquals("CRIMSON_SPORE", effects.getFirst().particleEffect()); + assertEquals(1e-05, effects.getFirst().particleAltX(), 0); + assertEquals(1, effects.getFirst().particleAway()); + assertEquals(5, effects.getFirst().particleDistance()); + assertEquals(2, effects.getFirst().particleOffset()); + assertEquals(50, effects.getFirst().interval()); + assertEquals(3, effects.getFirst().chance()); + assertNull(effects.getFirst().sound()); + AmbientEffect sound = effects.get(1); + assertEquals("AMBIENT.WARPED_FOREST.ADDITIONS", sound.sound()); + assertEquals(6.2, sound.volume(), 0); + assertEquals(0.2, sound.minPitch(), 0); + assertEquals(0.3, sound.maxPitch(), 0); + assertEquals(3, sound.soundDistance()); + assertEquals(60000, sound.interval()); + assertEquals(8, sound.chance()); + assertEquals(2, settings.find(BlockDropSettings.class).orElseThrow().drops().getFirst().drops().size()); + assertEquals(List.of("mushroom/clutter", "mushroom/food"), settings.find(LootSettings.class).orElseThrow().tables()); + assertEquals(4, settings.find(SpawnerSettings.class).orElseThrow().spawners().size()); + } + + @Test + public void aRegionsPotionEffectKeepsItsStrengthAndTicks() throws IOException { + ModuleSettings settings = decoder.decode(Target.REGION, file("regions/hot.json"), "region hot"); + + AmbientEffect potion = settings.find(EffectSettings.class).orElseThrow().effects().getFirst(); + assertEquals("CONFUSION", potion.potionEffect()); + assertEquals(0, potion.potionStrength()); + assertEquals(87, potion.potionTicksMin()); + assertEquals(67, potion.potionTicksMax()); + assertEquals(1200, potion.chance()); + assertEquals(500, potion.interval()); + } + + @Test + public void aBiomeReadsItsEffects() throws IOException { + ModuleSettings settings = decoder.decode(Target.BIOME, file("biomes/tropical/volcanoes.json"), "biome tropical/volcanoes"); + + AmbientEffect smoke = settings.find(EffectSettings.class).orElseThrow().effects().getFirst(); + assertEquals("CAMPFIRE_SIGNAL_SMOKE", smoke.particleEffect()); + assertEquals(0.13885, smoke.particleAltY(), 0); + assertEquals(300, smoke.interval()); + assertEquals(1, smoke.chance()); + assertEquals(0, smoke.particleCount()); + assertTrue(smoke.randomAltX()); + assertFalse(smoke.randomAltY()); + } + + @Test + public void aDimensionHasNoEffects() throws IOException { + JSONObject dimension = new JSONObject("{\"effects\": [{\"chance\": 1}], \"loot\": {}}"); + + ModuleSettings settings = decoder.decode(Target.DIMENSION, dimension, "dimension overworld"); + + assertTrue(settings.find(EffectSettings.class).isEmpty()); + assertFalse(decoder.keys(Target.DIMENSION).contains("effects")); + assertTrue(decoder.keys(Target.REGION).contains("effects")); + assertTrue(decoder.keys(Target.BIOME).containsAll(Set.of("loot", "blockDrops", "entitySpawners", "effects"))); + } + + @Test + public void thePacksSpawnersLootTablesAndEntitiesReadTheirOwnFiles() throws IOException { + Spawner spawner = decoder.decodeResource(Spawner.class, Files.readString(packFolder.resolve("spawners/mushroom/passive.json"))); + + assertEquals(SpawnGroup.NORMAL, spawner.group()); + assertEquals(2, spawner.maxEntitiesPerChunk()); + assertEquals(SpawnWeather.NONE, spawner.weather()); + assertEquals(2_000L, spawner.maximumRate().interval()); + assertFalse(spawner.maximumRate().isInfinite()); + assertTrue(spawner.maximumRatePerChunk().isInfinite()); + assertTrue(spawner.timeBlock().contains(12)); + assertFalse(spawner.timeBlock().contains(2)); + assertEquals(0, spawner.allowedLightLevels().min(), 0); + assertEquals(15, spawner.allowedLightLevels().max(), 0); + assertEquals(3, spawner.spawns().size()); + assertEquals("standard/passive/mooshroom", spawner.spawns().getFirst().entity()); + assertEquals(3, spawner.spawns().getFirst().maxSpawns()); + assertEquals(3, spawner.spawns().get(1).rarity()); + assertEquals(1, spawner.spawns().get(1).minSpawns()); + assertTrue(spawner.initialSpawns().isEmpty()); + + LootTable table = decoder.decodeResource(LootTable.class, Files.readString(packFolder.resolve("loot/global-clutter.json"))); + assertEquals("Global Clutter", table.name()); + assertEquals(20, table.maxTries()); + assertEquals(2, table.maxPicked()); + assertEquals("stone", table.loot().getFirst().type()); + assertEquals(8, table.loot().getFirst().maxAmount()); + assertEquals(LootSlot.STORAGE, table.loot().getFirst().slotTypes()); + + EntityDefinition entity = decoder.decodeResource(EntityDefinition.class, Files.readString(packFolder.resolve("entities/standard/passive/mooshroom.json"))); + assertEquals("MOOSHROOM", entity.type()); + assertTrue(entity.aware()); + assertTrue(entity.ai()); + assertTrue(entity.gravity()); + assertTrue(entity.loot().tables().isEmpty()); + assertEquals(LootMode.ADD, entity.loot().mode()); + } + + @Test + public void theFeatureIdsAreNotKeys() { + JSONObject byId = new JSONObject("{\"iris:loot\": {\"tables\": [\"a\"]}, \"iris:spawn\": [\"a\"]}"); + + assertSame(ModuleSettings.NONE, decoder.decode(Target.REGION, byId, "region forests")); + } + + @Test + public void aWrongShapeNamesTheKeyAndTheFile() { + IllegalArgumentException list = assertThrows(IllegalArgumentException.class, + () -> decoder.decode(Target.REGION, new JSONObject("{\"entitySpawners\": {\"spawners\": [\"a\"]}}"), "region forests")); + IllegalArgumentException object = assertThrows(IllegalArgumentException.class, + () -> decoder.decode(Target.REGION, new JSONObject("{\"loot\": [\"a\"]}"), "region forests")); + + assertTrue(list.getMessage(), list.getMessage().contains("under \"entitySpawners\" in region forests")); + assertTrue(object.getMessage(), object.getMessage().contains("under \"loot\" in region forests")); + } + + @Test + public void settingsEncodeBackToTheJsonThePackWrote() throws IOException { + for (String file : List.of("regions/terralost.json", "regions/swamp.json", "regions/mushroom.json", "regions/hot.json")) { + JSONObject region = this.file(file); + ModuleSettings settings = decoder.decode(Target.REGION, region, "region " + file); + + JSONObject written = decoder.encode(Target.REGION, settings); + + for (String key : List.of("loot", "blockDrops", "entitySpawners", "effects")) { + assertEquals(file + " " + key, region.has(key), written.has(key)); + } + if (region.has("entitySpawners")) { + assertEquals(region.getJSONArray("entitySpawners").toString(), written.getJSONArray("entitySpawners").toString()); + } + if (region.has("effects")) { + assertEquals(region.getJSONArray("effects").length(), written.getJSONArray("effects").length()); + } + } + } + + private JSONObject file(String relative) throws IOException { + return new JSONObject(Files.readString(packFolder.resolve(relative))); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/pack/PackExportClosureTest.java b/core/src/test/java/art/arcane/iris/core/pack/PackExportClosureTest.java index 397a4ec1b..b5b58bc89 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/PackExportClosureTest.java +++ b/core/src/test/java/art/arcane/iris/core/pack/PackExportClosureTest.java @@ -1,6 +1,5 @@ package art.arcane.iris.core.pack; -import art.arcane.iris.engine.object.marker.IrisObjectMarker; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.volmlib.util.collection.KList; import org.junit.Test; @@ -13,28 +12,19 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class PackExportClosureTest { - private static IrisObjectPlacement placement(String objectKey, String... markerKeys) { + private static IrisObjectPlacement placement(String objectKey) { IrisObjectPlacement placement = new IrisObjectPlacement(); placement.setPlace(new KList<>(objectKey)); - KList markers = new KList<>(); - for (String markerKey : markerKeys) { - IrisObjectMarker marker = new IrisObjectMarker(); - marker.setMarker(markerKey); - markers.add(marker); - } - placement.setMarkers(markers); return placement; } @Test - public void collectsMarkerAndObjectKeysFromPlacements() { + public void collectsObjectKeysFromPlacements() { List placements = List.of( - placement("houses/hut", "spawn-point", "loot-marker"), + placement("houses/hut"), placement("trees/oak"), - placement("houses/hut", "spawn-point")); + placement("houses/hut")); - assertEquals(List.of("loot-marker", "spawn-point"), - PackExportClosure.collectMarkerKeys(placements).stream().sorted().toList()); assertEquals(List.of("houses/hut", "trees/oak"), PackExportClosure.collectObjectKeys(placements).stream().sorted().toList()); } @@ -42,10 +32,9 @@ public class PackExportClosureTest { @Test public void toleratesNullPlacementsAndBlankKeys() { KList placements = new KList<>(); - placements.add(placement("", "")); + placements.add(placement("")); placements.add((IrisObjectPlacement) null); - assertTrue(PackExportClosure.collectMarkerKeys(placements).isEmpty()); assertTrue(PackExportClosure.collectObjectKeys(placements).isEmpty()); } @@ -57,11 +46,11 @@ public class PackExportClosureTest { public void bothPackagersExportSpawnersMarkersAndTheFullEntityGraph() throws Exception { String bukkit = Files.readString(Path.of( "src/main/java/art/arcane/iris/core/project/IrisPackageCompiler.java")).replace("\r\n", "\n"); - assertTrue("Bukkit packager must write spawners/", bukkit.contains("\"spawners/\"")); - assertTrue("Bukkit packager must write markers/", bukkit.contains("\"markers/\"")); assertTrue("Bukkit packager must export region objects alongside biome objects", bukkit.contains("regions.forEach((r) -> allPlacements.addAll(r.getObjects()))")); - assertTrue("Bukkit packager must export entity loot tables", bukkit.contains("getLoot().getTables()")); + assertTrue("Bukkit packager must export the spawn and loot resources the settings reference", + bukkit.contains("moduleResources.writeTo(folder, minify)")); + assertTrue("Bukkit packager must export the placements' references", bukkit.contains("moduleResources.follow(allPlacements)")); int bukkitValidation = bukkit.indexOf("PackValidator.validateForPackaging(project.getPath())"); assertTrue("Bukkit packager must validate before opening or mutating package state", bukkitValidation >= 0 diff --git a/core/src/test/java/art/arcane/iris/core/project/IrisProjectEntityDependencyTest.java b/core/src/test/java/art/arcane/iris/core/project/IrisProjectEntityDependencyTest.java deleted file mode 100644 index eb1fceab1..000000000 --- a/core/src/test/java/art/arcane/iris/core/project/IrisProjectEntityDependencyTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package art.arcane.iris.core.project; - -import art.arcane.iris.engine.object.entity.IrisEntitySpawn; -import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; -import art.arcane.volmlib.util.collection.KSet; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class IrisProjectEntityDependencyTest { - @Test - public void collectsInitialOnlyEntityAlongsideNormalSpawnEntityForExport() { - IrisSpawner spawner = new IrisSpawner(); - spawner.getSpawns().add(new IrisEntitySpawn().setEntity("standard/passive/cow")); - spawner.getInitialSpawns().add(new IrisEntitySpawn().setEntity("beta/sentinel")); - KSet spawners = new KSet<>(); - spawners.add(spawner); - - KSet entityKeys = IrisPackageCompiler.collectSpawnerEntityKeys(spawners); - - assertEquals(2, entityKeys.size()); - assertTrue(entityKeys.contains("standard/passive/cow")); - assertTrue(entityKeys.contains("beta/sentinel")); - } - - @Test - public void returnsNoEntityDependenciesForEmptySpawnerSet() { - KSet entityKeys = IrisPackageCompiler.collectSpawnerEntityKeys(new KSet<>()); - - assertTrue(entityKeys.isEmpty()); - } -} diff --git a/core/src/test/java/art/arcane/iris/engine/loot/LootDrawPinTest.java b/core/src/test/java/art/arcane/iris/engine/loot/LootDrawPinTest.java index 80acfa1f1..81c6a36c1 100644 --- a/core/src/test/java/art/arcane/iris/engine/loot/LootDrawPinTest.java +++ b/core/src/test/java/art/arcane/iris/engine/loot/LootDrawPinTest.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.loot; -import art.arcane.iris.engine.object.loot.IrisLootTable; +import art.arcane.iris.builtin.loot.LootTable; import com.google.gson.Gson; import com.volmit.item.ItemDrop; import com.volmit.item.ItemRegistry; @@ -69,12 +69,12 @@ public class LootDrawPinTest { @Test public void aTableGivesThePinnedItemsAtEachSpot() { - IrisLootTable table = new Gson().fromJson(TABLE, IrisLootTable.class); + LootTable table = new Gson().fromJson(TABLE, LootTable.class); LootItems items = new LootItems(registry, false); List hashes = new ArrayList<>(); for (int[] spot : SPOTS) { - List drops = items.draw(table, LOOT_SEED, spot[0], spot[1], spot[2]); + List drops = items.draw("Pin table", table, LOOT_SEED, spot[0], spot[1], spot[2]); hashes.add(drops.toString().hashCode()); } diff --git a/core/src/test/java/art/arcane/iris/engine/loot/LootEnvironmentPinTest.java b/core/src/test/java/art/arcane/iris/engine/loot/LootEnvironmentPinTest.java index c88a3b7f7..f9d94e3c5 100644 --- a/core/src/test/java/art/arcane/iris/engine/loot/LootEnvironmentPinTest.java +++ b/core/src/test/java/art/arcane/iris/engine/loot/LootEnvironmentPinTest.java @@ -19,11 +19,12 @@ package art.arcane.iris.engine.loot; import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.BuiltInPack; import art.arcane.iris.core.modules.ModuleResourceFixture; import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.loot.IrisLootReference; -import art.arcane.iris.engine.object.loot.IrisLootTable; +import art.arcane.iris.builtin.loot.LootSettings; +import art.arcane.iris.builtin.loot.LootTable; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.world.region.IrisRegion; @@ -65,7 +66,7 @@ public class LootEnvironmentPinTest { fixture.resource(LootResources.TABLES, key, table(key)); } IrisComplex complex = engine.getComplex(); - when(complex.getData()).thenReturn(data); + when(engine.getData()).thenReturn(data); dimension = mock(IrisDimension.class); region = mock(IrisRegion.class); surface = biome("surface"); @@ -111,19 +112,19 @@ public class LootEnvironmentPinTest { private List identities(boolean objectLootDefined, int y) { List sources = new ArrayList<>(); - LootTables.resolveEnvironmentSources(sources, engine, new RNG(19L), X, y, Z, objectLootDefined, LootTables::identity); + LootTables.resolveEnvironmentSources(sources, engine, new RNG(19L), X, y, Z, objectLootDefined, key -> key); return sources; } private void references(String dimensionJson, String regionJson, String surfaceJson, String caveJson) { - when(dimension.getLoot()).thenReturn(reference(dimensionJson)); - when(region.getLoot()).thenReturn(reference(regionJson)); - when(surface.getLoot()).thenReturn(reference(surfaceJson)); - when(cave.getLoot()).thenReturn(reference(caveJson)); + when(dimension.getModuleSettings()).thenReturn(BuiltInPack.settings(loot(dimensionJson))); + when(region.getModuleSettings()).thenReturn(BuiltInPack.settings(loot(regionJson))); + when(surface.getModuleSettings()).thenReturn(BuiltInPack.settings(loot(surfaceJson))); + when(cave.getModuleSettings()).thenReturn(BuiltInPack.settings(loot(caveJson))); } - private static IrisLootReference reference(String json) { - return new Gson().fromJson(json, IrisLootReference.class); + private static LootSettings loot(String json) { + return new Gson().fromJson(json, LootSettings.class); } private static IrisBiome biome(String key) { @@ -132,9 +133,7 @@ public class LootEnvironmentPinTest { return biome; } - private static IrisLootTable table(String key) { - IrisLootTable table = new IrisLootTable().setName(key); - table.setLoadKey(key); - return table; + private static LootTable table(String key) { + return new Gson().fromJson("{\"name\": \"" + key + "\"}", LootTable.class); } } diff --git a/core/src/test/java/art/arcane/iris/engine/loot/LootItemsTest.java b/core/src/test/java/art/arcane/iris/engine/loot/LootItemsTest.java index 314d70878..cdb592da4 100644 --- a/core/src/test/java/art/arcane/iris/engine/loot/LootItemsTest.java +++ b/core/src/test/java/art/arcane/iris/engine/loot/LootItemsTest.java @@ -1,10 +1,8 @@ package art.arcane.iris.engine.loot; -import art.arcane.iris.engine.object.entity.IrisAttributeModifier; -import art.arcane.iris.engine.object.loot.IrisEnchantment; -import art.arcane.iris.engine.object.loot.IrisLoot; -import art.arcane.iris.engine.object.loot.IrisLootTable; -import art.arcane.volmlib.util.collection.KList; +import art.arcane.iris.builtin.loot.LootEntry; +import art.arcane.iris.builtin.loot.LootTable; +import art.arcane.iris.engine.object.TestSettings; import art.arcane.volmlib.util.math.RNG; import com.volmit.item.ItemDrop; import com.volmit.item.ItemRegistry; @@ -37,10 +35,10 @@ public class LootItemsTest { @Test public void anEntryDrawsAmountEnchantmentsAttributesAndDamageFromOneStreamInThatOrder() { - IrisLoot entry = new IrisLoot().setType("diamond_sword").setMinAmount(1).setMaxAmount(3) - .setMinDurability(0.25).setMaxDurability(0.75) - .setEnchantments(new KList<>(new IrisEnchantment("sharpness", 1, 5, 1D))) - .setAttributes(new KList<>(new IrisAttributeModifier("max_health", "bonus", "ADD_NUMBER", 2, 6, 1D))); + LootEntry entry = entry(""" + {"type": "diamond_sword", "minAmount": 1, "maxAmount": 3, "minDurability": 0.25, "maxDurability": 0.75, + "enchantments": [{"enchantment": "sharpness", "minLevel": 1, "maxLevel": 5, "chance": 1}], + "attributes": [{"attribute": "max_health", "name": "bonus", "operation": "ADD_NUMBER", "minAmount": 2, "maxAmount": 6, "chance": 1}]}"""); RNG expected = new RNG(5L); int amount = (int) (1 + expected.nextLong(3)); expected.nextDouble(); @@ -59,7 +57,7 @@ public class LootItemsTest { @Test public void anItemThatCannotBeDamagedDrawsNoDamageAndKeepsTheStreamAligned() { - IrisLoot entry = new IrisLoot().setType("diamond").setMinAmount(2).setMaxAmount(2); + LootEntry entry = entry("{\"type\": \"diamond\", \"minAmount\": 2, \"maxAmount\": 2}"); RNG rng = new RNG(9L); RNG untouched = new RNG(9L); @@ -75,32 +73,37 @@ public class LootItemsTest { RNG rng = new RNG(9L); RNG untouched = new RNG(9L); - assertNull(new LootItems(registry, false).give(new IrisLoot().setType("not_an_item"), rng)); - assertNull(new LootItems(registry, false).give(new IrisLoot().setType("air"), rng)); + assertNull(new LootItems(registry, false).give(entry("{\"type\": \"not_an_item\"}"), rng)); + assertNull(new LootItems(registry, false).give(entry("{\"type\": \"air\"}"), rng)); assertEquals(untouched.nextLong(), rng.nextLong()); } @Test public void debugItemsSayWhereTheyCameFrom() { - IrisLootTable table = new IrisLootTable().setName("dungeon").setRarity(4); - table.setLoot(new KList<>(new IrisLoot().setType("diamond").setRarity(3))); - table.setMinPicked(1).setMaxPicked(1); + LootTable table = table("{\"name\": \"dungeon\", \"rarity\": 4, \"minPicked\": 1, \"maxPicked\": 1, \"loot\": [{\"type\": \"diamond\", \"rarity\": 3}]}"); - List drops = new LootItems(registry, true).draw(table, LOOT_SEED, 0, 64, 0); + List drops = new LootItems(registry, true).draw("dungeon", table, LOOT_SEED, 0, 64, 0); for (ItemDrop drop : drops) { assertEquals(new ItemDrop.Source("dungeon", 4, 3), drop.source()); } - assertTrue(new LootItems(registry, false).draw(table, LOOT_SEED, 0, 64, 0).stream().allMatch(drop -> drop.source() == null)); + assertTrue(new LootItems(registry, false).draw("dungeon", table, LOOT_SEED, 0, 64, 0).stream().allMatch(drop -> drop.source() == null)); } @Test public void aTableGivesTheSameItemsAtTheSameSpotAndSeed() { - IrisLootTable table = new IrisLootTable().setName("tools").setMinPicked(2).setMaxPicked(4); - table.setLoot(new KList<>(new IrisLoot().setType("diamond").setMaxAmount(5), new IrisLoot().setType("diamond_sword"))); + LootTable table = table("{\"name\": \"tools\", \"minPicked\": 2, \"maxPicked\": 4, \"loot\": [{\"type\": \"diamond\", \"maxAmount\": 5}, {\"type\": \"diamond_sword\"}]}"); LootItems items = new LootItems(registry, false); - assertEquals(items.draw(table, LOOT_SEED, 10, 64, -30), items.draw(table, LOOT_SEED, 10, 64, -30)); + assertEquals(items.draw("tools", table, LOOT_SEED, 10, 64, -30), items.draw("tools", table, LOOT_SEED, 10, 64, -30)); + } + + private static LootEntry entry(String json) { + return TestSettings.of(LootEntry.class, json); + } + + private static LootTable table(String json) { + return TestSettings.of(LootTable.class, json); } } diff --git a/core/src/test/java/art/arcane/iris/engine/loot/LootResolverTest.java b/core/src/test/java/art/arcane/iris/engine/loot/LootResolverTest.java index f80ba209b..b264d5312 100644 --- a/core/src/test/java/art/arcane/iris/engine/loot/LootResolverTest.java +++ b/core/src/test/java/art/arcane/iris/engine/loot/LootResolverTest.java @@ -6,13 +6,16 @@ import art.arcane.iris.engine.framework.LootResolver; import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.loot.IrisLootMode; -import art.arcane.iris.engine.object.loot.IrisLootReference; -import art.arcane.iris.engine.object.loot.IrisLootTable; +import art.arcane.iris.builtin.loot.LootSettings; +import art.arcane.iris.builtin.loot.LootTable; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.BuiltInPack; +import art.arcane.iris.core.modules.ModuleResourceFixture; +import art.arcane.iris.core.modules.ModuleSettings; +import art.arcane.iris.engine.object.TestSettings; import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.volmlib.util.collection.KList; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; import art.arcane.volmlib.util.math.RNG; import com.volmit.item.ItemRegistry; import org.junit.Test; @@ -70,20 +73,17 @@ public class LootResolverTest { @Test public void spatialSeedsIncludeWorldTableAndAbsolutePosition() { - IrisLootTable first = new IrisLootTable().setName("first"); - IrisLootTable second = new IrisLootTable().setName("second"); + long baseline = LootTables.seed(41L, "first", 0, 64, 0); - long baseline = LootTables.seed(41L, first, 0, 64, 0); - - assertEquals(baseline, LootTables.seed(41L, first, 0, 64, 0)); - assertNotEquals(baseline, LootTables.seed(42L, first, 0, 64, 0)); - assertNotEquals(baseline, LootTables.seed(41L, second, 0, 64, 0)); - assertNotEquals(baseline, LootTables.seed(41L, first, 16, 64, 0)); + assertEquals(baseline, LootTables.seed(41L, "first", 0, 64, 0)); + assertNotEquals(baseline, LootTables.seed(42L, "first", 0, 64, 0)); + assertNotEquals(baseline, LootTables.seed(41L, "second", 0, 64, 0)); + assertNotEquals(baseline, LootTables.seed(41L, "first", 16, 64, 0)); } @Test public void spatialRarityIsStableAndDistributed() { - IrisLootTable table = new IrisLootTable().setName("distribution"); + String table = "distribution"; int successes = 0; for (int x = 0; x < 65_536; x++) { @@ -103,7 +103,7 @@ public class LootResolverTest { @Test public void nativeOrObjectLootSuppressesFallbackReferences() { ResolutionFixture fixture = new ResolutionFixture(); - List sources = new ArrayList<>(); + List sources = new ArrayList<>(); LootTables.resolveEnvironmentSources( sources, @@ -113,7 +113,7 @@ public class LootResolverTest { 70, 20, true, - table -> table + key -> key ); assertTrue(sources.isEmpty()); @@ -122,7 +122,7 @@ public class LootResolverTest { @Test public void emptyPlacementUsesEachFallbackScopeOnce() { ResolutionFixture fixture = new ResolutionFixture(); - List sources = new ArrayList<>(); + List sources = new ArrayList<>(); LootTables.resolveEnvironmentSources( sources, @@ -132,10 +132,10 @@ public class LootResolverTest { 70, 20, false, - table -> table + key -> key ); - assertEquals(List.of(fixture.dimensionTable, fixture.regionTable, fixture.surfaceTable), sources); + assertEquals(List.of("dimension", "region", "surface"), sources); } @Test @@ -170,7 +170,7 @@ public class LootResolverTest { } IllegalArgumentException failure = assertThrows(IllegalArgumentException.class, - () -> LootResolver.scaleSources(sources, IrisLootReference.MAX_MULTIPLIER, new RNG(17L))); + () -> LootResolver.scaleSources(sources, LootSettings.MAX_MULTIPLIER, new RNG(17L))); assertTrue(failure.getMessage().contains("maximum of 256 sources")); assertEquals(17, sources.size()); @@ -183,7 +183,7 @@ public class LootResolverTest { sources.add("table-" + index); } - LootResolver.scaleSources(sources, IrisLootReference.MAX_MULTIPLIER, new RNG(17L)); + LootResolver.scaleSources(sources, LootSettings.MAX_MULTIPLIER, new RNG(17L)); assertEquals(256, sources.size()); } @@ -231,26 +231,26 @@ public class LootResolverTest { public void combinedMultiplierAboveReferenceCapRemainsUsableUnderResolvedSourceCap() { List sources = new ArrayList<>(List.of("table")); - LootResolver.scaleSources(sources, IrisLootReference.MAX_MULTIPLIER * 2D, new RNG(17L)); + LootResolver.scaleSources(sources, LootSettings.MAX_MULTIPLIER * 2D, new RNG(17L)); assertEquals(32, sources.size()); } @Test public void lootMultiplierCapIsPublishedInSchemaMetadata() throws Exception { - Field multiplier = IrisLootReference.class.getDeclaredField("multiplier"); + Field multiplier = LootSettings.class.getDeclaredField("multiplier"); MaxNumber maximum = multiplier.getAnnotation(MaxNumber.class); Desc description = multiplier.getAnnotation(Desc.class); - assertEquals(IrisLootReference.MAX_MULTIPLIER, maximum.value(), 0D); + assertEquals(LootSettings.MAX_MULTIPLIER, maximum.value(), 0D); assertTrue(description.value().contains("0 to 16")); } @Test public void emptyLootTableReturnsNoItems() { - IrisLootTable table = new IrisLootTable().setName("empty"); + LootTable table = TestSettings.of(LootTable.class, "{\"name\": \"empty\"}"); - assertTrue(new LootItems(mock(ItemRegistry.class), false).draw(table, 7L, 0, 64, 0).isEmpty()); + assertTrue(new LootItems(mock(ItemRegistry.class), false).draw("empty", table, 7L, 0, 64, 0).isEmpty()); } @Test @@ -264,23 +264,23 @@ public class LootResolverTest { private static final class ResolutionFixture { private final Engine engine = mock(Engine.class, RETURNS_DEEP_STUBS); - private final IrisLootTable dimensionTable = new IrisLootTable().setName("dimension"); - private final IrisLootTable regionTable = new IrisLootTable().setName("region"); - private final IrisLootTable surfaceTable = new IrisLootTable().setName("surface"); private ResolutionFixture() { IrisDimension dimension = mock(IrisDimension.class); IrisRegion region = mock(IrisRegion.class); IrisBiome surface = mock(IrisBiome.class); IrisComplex complex = engine.getComplex(); - IrisLootReference dimensionReference = reference(dimensionTable); - IrisLootReference regionReference = reference(regionTable); - IrisLootReference surfaceReference = reference(surfaceTable); + IrisData data = mock(IrisData.class); + ModuleResourceFixture tables = ModuleResourceFixture.serve(data); + for (String key : List.of("dimension", "region", "surface")) { + tables.resource(LootResources.TABLES, key, TestSettings.of(LootTable.class, "{\"name\": \"" + key + "\"}")); + } + when(engine.getData()).thenReturn(data); when(engine.getDimension()).thenReturn(dimension); - when(dimension.getLoot()).thenReturn(dimensionReference); - when(region.getLoot()).thenReturn(regionReference); - when(surface.getLoot()).thenReturn(surfaceReference); + when(dimension.getModuleSettings()).thenReturn(fallbackTo("dimension")); + when(region.getModuleSettings()).thenReturn(fallbackTo("region")); + when(surface.getModuleSettings()).thenReturn(fallbackTo("surface")); when(surface.getLoadKey()).thenReturn("surface"); when(complex.getRegionStream().get(10, 20)).thenReturn(region); when(complex.getTrueBiomeStream().get(10, 20)).thenReturn(surface); @@ -288,12 +288,8 @@ public class LootResolverTest { when(engine.getCaveBiome(10, 70, 20)).thenReturn(surface); } - private IrisLootReference reference(IrisLootTable table) { - IrisLootReference reference = mock(IrisLootReference.class); - when(reference.getMode()).thenReturn(IrisLootMode.FALLBACK); - when(reference.getMultiplier()).thenReturn(1D); - when(reference.getLootTables(any())).thenReturn(new KList<>(table)); - return reference; + private static ModuleSettings fallbackTo(String table) { + return BuiltInPack.settings(TestSettings.of(LootSettings.class, "{\"mode\": \"FALLBACK\", \"tables\": [\"" + table + "\"]}")); } } diff --git a/core/src/test/java/art/arcane/iris/engine/loot/LootResourcesTest.java b/core/src/test/java/art/arcane/iris/engine/loot/LootResourcesTest.java index a1e0d4029..af0187f87 100644 --- a/core/src/test/java/art/arcane/iris/engine/loot/LootResourcesTest.java +++ b/core/src/test/java/art/arcane/iris/engine/loot/LootResourcesTest.java @@ -21,7 +21,7 @@ package art.arcane.iris.engine.loot; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.project.ModuleResourceSchemas; import art.arcane.iris.core.project.SchemaTestPlatform; -import art.arcane.iris.engine.object.loot.IrisLootTable; +import art.arcane.iris.builtin.loot.LootTable; import art.arcane.volmlib.util.json.JSONObject; import com.volmit.host.ValidatorRegistration; import org.junit.Rule; @@ -53,7 +53,7 @@ public class LootResourcesTest { assertEquals(List.of("iris:loot/table"), catalog.resourceKinds().stream().map(registration -> registration.kind().id().toString()) .filter(id -> id.startsWith("iris:loot/")).toList()); assertTrue(catalog.validators().stream().map(ValidatorRegistration::validator).anyMatch(LootValidator.class::isInstance)); - assertFalse(data.getLoaders().containsKey(IrisLootTable.class)); + assertFalse(data.getLoaders().containsKey(LootTable.class)); } finally { data.close(); } @@ -64,19 +64,18 @@ public class LootResourcesTest { Path pack = lootPack("tables"); IrisData data = IrisData.openValidation(pack.toFile()); try { - IrisLootTable table = LootResources.table(data, "dungeon/chest"); + LootTable table = LootResources.table(data, "dungeon/chest"); - assertEquals("Chest", table.getName()); - assertEquals("dungeon/chest", table.getLoadKey()); - assertEquals(pack.resolve("loot/dungeon/chest.json").toFile(), table.getLoadFile()); + assertEquals("Chest", table.name()); + assertEquals(1, table.loot().size()); + assertEquals("stick", table.loot().getFirst().type()); assertEquals(List.of("dungeon/chest"), LootResources.tableKeys(data)); - assertEquals(List.of(table), LootResources.tables(data, List.of("dungeon/chest", "missing"))); assertNull(LootResources.table(data, "missing")); assertNull(LootResources.table(data, " ")); write(pack, "loot/dungeon/chest.json", "{\"name\":\"Renamed\"}"); data.dump(); - assertEquals("Renamed", LootResources.table(data, "dungeon/chest").getName()); + assertEquals("Renamed", LootResources.table(data, "dungeon/chest").name()); } finally { data.close(); } diff --git a/core/src/test/java/art/arcane/iris/engine/loot/LootTablesClearModeTest.java b/core/src/test/java/art/arcane/iris/engine/loot/LootTablesClearModeTest.java index 64f4a4eca..3c5f4de75 100644 --- a/core/src/test/java/art/arcane/iris/engine/loot/LootTablesClearModeTest.java +++ b/core/src/test/java/art/arcane/iris/engine/loot/LootTablesClearModeTest.java @@ -1,6 +1,6 @@ package art.arcane.iris.engine.loot; -import art.arcane.iris.engine.object.loot.IrisLootMode; +import art.arcane.iris.builtin.loot.LootMode; import org.junit.Test; import java.util.ArrayList; @@ -13,18 +13,18 @@ public class LootTablesClearModeTest { @Test public void clearSuppressesItsOwnTablesAndReplaceDoesNot() { List cleared = new ArrayList<>(List.of("placement", "dimension")); - LootTables.injectSources(cleared, List.of("biome"), IrisLootMode.CLEAR, false); + LootTables.injectSources(cleared, List.of("biome"), LootMode.CLEAR, false); assertTrue("CLEAR must clear parents and contribute nothing", cleared.isEmpty()); List replaced = new ArrayList<>(List.of("placement", "dimension")); - LootTables.injectSources(replaced, List.of("biome"), IrisLootMode.REPLACE, false); + LootTables.injectSources(replaced, List.of("biome"), LootMode.REPLACE, false); assertEquals(List.of("biome"), replaced); } @Test public void clearIgnoresTheFallbackFlag() { List sources = new ArrayList<>(List.of("placement")); - LootTables.injectSources(sources, List.of("biome"), IrisLootMode.CLEAR, true); + LootTables.injectSources(sources, List.of("biome"), LootMode.CLEAR, true); assertTrue(sources.isEmpty()); } } diff --git a/core/src/test/java/art/arcane/iris/engine/loot/LootValidatorTest.java b/core/src/test/java/art/arcane/iris/engine/loot/LootValidatorTest.java index b27b04f32..d99ee0f65 100644 --- a/core/src/test/java/art/arcane/iris/engine/loot/LootValidatorTest.java +++ b/core/src/test/java/art/arcane/iris/engine/loot/LootValidatorTest.java @@ -1,8 +1,8 @@ package art.arcane.iris.engine.loot; -import art.arcane.iris.engine.object.loot.IrisLoot; -import art.arcane.iris.engine.object.loot.IrisLootTable; -import art.arcane.iris.engine.object.annotations.MaxNumber; +import art.arcane.iris.builtin.loot.LootEntry; +import art.arcane.iris.builtin.loot.LootTable; +import com.volmit.config.MaxNumber; import com.volmit.validation.Problem; import com.volmit.validation.Severity; import org.junit.Rule; @@ -110,11 +110,11 @@ public class LootValidatorTest { @Test public void lootWorkCapsArePublishedInSchemaMetadata() throws Exception { - assertSchemaMaximum(IrisLootTable.class, "minPicked", IrisLootTable.MAX_PICKED); - assertSchemaMaximum(IrisLootTable.class, "maxPicked", IrisLootTable.MAX_PICKED); - assertSchemaMaximum(IrisLootTable.class, "maxTries", IrisLootTable.MAX_TRIES); - assertSchemaMaximum(IrisLoot.class, "minAmount", IrisLoot.MAX_AMOUNT); - assertSchemaMaximum(IrisLoot.class, "maxAmount", IrisLoot.MAX_AMOUNT); + assertSchemaMaximum(LootTable.class, "minPicked", LootTable.MAX_PICKED); + assertSchemaMaximum(LootTable.class, "maxPicked", LootTable.MAX_PICKED); + assertSchemaMaximum(LootTable.class, "maxTries", LootTable.MAX_TRIES); + assertSchemaMaximum(LootEntry.class, "minAmount", LootEntry.MAX_AMOUNT); + assertSchemaMaximum(LootEntry.class, "maxAmount", LootEntry.MAX_AMOUNT); } private void assertSchemaMaximum(Class type, String fieldName, int expected) throws Exception { diff --git a/core/src/test/java/art/arcane/iris/engine/object/loot/IrisLootKeyAccessorTest.java b/core/src/test/java/art/arcane/iris/engine/object/loot/IrisLootKeyAccessorTest.java deleted file mode 100644 index c2174da10..000000000 --- a/core/src/test/java/art/arcane/iris/engine/object/loot/IrisLootKeyAccessorTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2026 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.engine.object.loot; - -import art.arcane.iris.engine.object.loot.IrisLoot; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -/** - * The modded item translator reads loot keys through these accessors instead of reflecting on IrisLoot fields, so - * they are part of the platform-neutral contract. - */ -public class IrisLootKeyAccessorTest { - @Test - public void typeKeyReturnsAuthoredKeyVerbatim() { - IrisLoot loot = new IrisLoot(); - loot.setType("mymod:ruby_sword"); - assertEquals("mymod:ruby_sword", loot.getTypeKey()); - } - - @Test - public void typeKeyDefaultsToEmptyString() { - assertEquals("", new IrisLoot().getTypeKey()); - } - - @Test - public void dyeColorKeyReturnsAuthoredValueAndNullWhenUnset() { - IrisLoot loot = new IrisLoot(); - assertNull(loot.getDyeColorKey()); - loot.setDyeColor("LIGHT_BLUE"); - assertEquals("LIGHT_BLUE", loot.getDyeColorKey()); - } -} diff --git a/core/src/test/java/art/arcane/iris/engine/object/value/IrisDurationTest.java b/core/src/test/java/art/arcane/iris/engine/object/value/IrisDurationTest.java deleted file mode 100644 index d63da6877..000000000 --- a/core/src/test/java/art/arcane/iris/engine/object/value/IrisDurationTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package art.arcane.iris.engine.object.value; - -import art.arcane.iris.engine.object.value.IrisDuration; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class IrisDurationTest { - @Test - public void convertsRealAndMinecraftUnitsToMilliseconds() { - IrisDuration duration = new IrisDuration(); - duration.setMilliseconds(1); - duration.setMinecraftTicks(1); - duration.setSeconds(1); - duration.setMinutes(1); - duration.setMinecraftHours(1); - duration.setHours(1); - duration.setMinecraftDays(1); - duration.setMinecraftWeeks(1); - duration.setMinecraftLunarCycles(1); - duration.setDays(1); - - assertEquals(109_311_051L, duration.toMilliseconds()); - } - - @Test - public void convertsMinecraftCalendarUnitsUsingTwentyMinuteDays() { - IrisDuration day = new IrisDuration(); - IrisDuration week = new IrisDuration(); - IrisDuration lunarCycle = new IrisDuration(); - day.setMinecraftDays(1); - week.setMinecraftWeeks(1); - lunarCycle.setMinecraftLunarCycles(1); - - assertEquals(1_200_000L, day.toMilliseconds()); - assertEquals(8_400_000L, week.toMilliseconds()); - assertEquals(9_600_000L, lunarCycle.toMilliseconds()); - } -} diff --git a/core/src/test/java/art/arcane/iris/engine/spawn/EntityResolutionPinTest.java b/core/src/test/java/art/arcane/iris/engine/spawn/EntityResolutionPinTest.java index 616a1d096..390aae459 100644 --- a/core/src/test/java/art/arcane/iris/engine/spawn/EntityResolutionPinTest.java +++ b/core/src/test/java/art/arcane/iris/engine/spawn/EntityResolutionPinTest.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.spawn; import art.arcane.iris.engine.loot.LootItems; -import art.arcane.iris.engine.object.entity.IrisEntity; +import art.arcane.iris.builtin.spawn.EntityDefinition; import art.arcane.iris.spi.PlatformWorld; import art.arcane.volmlib.util.math.RNG; import com.google.gson.Gson; @@ -64,9 +64,9 @@ public class EntityResolutionPinTest { when(registry.maxDurability("iron_helmet")).thenReturn(OptionalInt.of(165)); when(registry.maxDurability("diamond_sword")).thenReturn(OptionalInt.of(1561)); PlatformWorld world = mock(PlatformWorld.class); - IrisEntity entity = new Gson().fromJson(ENTITY, IrisEntity.class); + EntityDefinition entity = new Gson().fromJson(ENTITY, EntityDefinition.class); - EntitySpec spec = new EntityResolution(new LootItems(registry, false), world).resolve(entity, new RNG(STREAM_SEED)); + EntitySpec spec = new EntityResolution(new LootItems(registry, false), world, new EffectTimers()).resolve(entity, new RNG(STREAM_SEED)); assertEquals(-819231818, spec.toString().hashCode()); } diff --git a/core/src/test/java/art/arcane/iris/engine/spawn/EntitySpawningTest.java b/core/src/test/java/art/arcane/iris/engine/spawn/EntitySpawningTest.java index b66829125..366890911 100644 --- a/core/src/test/java/art/arcane/iris/engine/spawn/EntitySpawningTest.java +++ b/core/src/test/java/art/arcane/iris/engine/spawn/EntitySpawningTest.java @@ -25,10 +25,10 @@ import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.EngineGeneration; import art.arcane.iris.engine.framework.SeedManager; import art.arcane.iris.engine.mantle.EngineMantle; -import art.arcane.iris.engine.object.entity.IrisEntity; -import art.arcane.iris.engine.object.entity.IrisEntitySpawn; -import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; -import art.arcane.iris.engine.object.marker.IrisMarker; +import art.arcane.iris.builtin.spawn.EntityDefinition; +import art.arcane.iris.builtin.spawn.SpawnMarker; +import art.arcane.iris.builtin.spawn.Spawner; +import art.arcane.iris.engine.object.TestSettings; import art.arcane.iris.engine.object.world.IrisWorld; import art.arcane.iris.spi.PlatformWorld; import art.arcane.volmlib.util.collection.KList; @@ -97,10 +97,9 @@ public class EntitySpawningTest { @Test public void aMarkerMeansItsSpawnersAndWhetherItGoesAwayWhenItsBlockChanges() { - IrisMarker marker = new IrisMarker(); - marker.setSpawners(new KList<>("zombies", "missing")).setEmptyAbove(true).setRemoveOnChange(false); + SpawnMarker marker = TestSettings.of(SpawnMarker.class, "{\"spawners\": [\"zombies\", \"missing\"], \"emptyAbove\": true, \"removeOnChange\": false}"); fixture.resource(SpawnResources.MARKERS, "camp", marker); - fixture.resource(SpawnResources.SPAWNERS, "zombies", new IrisSpawner()); + fixture.resource(SpawnResources.SPAWNERS, "zombies", new Spawner()); EntitySpawns.MarkerRule rule = new EntitySpawning().marker(world, "camp").orElseThrow(); @@ -117,16 +116,10 @@ public class EntitySpawningTest { @Test public void aMarkerSpawnPlansEntitiesOneBlockAboveTheMarkerWithoutSurfaceChecks() { - IrisSpawner spawner = new IrisSpawner(); - spawner.setLoadKey("camp/zombies"); - spawner.getSpawns().add(new IrisEntitySpawn().setEntity("zombie").setMinSpawns(2).setMaxSpawns(2)); + Spawner spawner = TestSettings.of(Spawner.class, "{\"spawns\": [{\"entity\": \"zombie\", \"minSpawns\": 2, \"maxSpawns\": 2}]}"); fixture.resource(SpawnResources.SPAWNERS, "camp/zombies", spawner); - IrisMarker marker = new IrisMarker(); - marker.setExhaustionChance(2); - fixture.resource(SpawnResources.MARKERS, "camp", marker); - IrisEntity zombie = new IrisEntity(); - zombie.setType("minecraft:zombie"); - fixture.resource(SpawnResources.ENTITIES, "zombie", zombie); + fixture.resource(SpawnResources.MARKERS, "camp", TestSettings.of(SpawnMarker.class, "{\"exhaustionChance\": 2}")); + fixture.resource(SpawnResources.ENTITIES, "zombie", TestSettings.of(EntityDefinition.class, "{\"type\": \"minecraft:zombie\"}")); when(engine.getMinHeight()).thenReturn(-64); EntitySpawns.Plan plan = new EntitySpawning() @@ -145,8 +138,7 @@ public class EntitySpawningTest { @Test public void aSpawnerThatCannotFireOrHasNoEntitiesPlansNothing() { - IrisSpawner empty = new IrisSpawner(); - fixture.resource(SpawnResources.SPAWNERS, "empty", empty); + fixture.resource(SpawnResources.SPAWNERS, "empty", new Spawner()); Optional plan = new EntitySpawning().plan(world, new EntitySpawns.Marker(MARKER_BLOCK, "camp", "empty", false)); @@ -155,9 +147,8 @@ public class EntitySpawningTest { @Test public void anEntityOfThePackResolvesToTheSpecTheHostSpawns() { - IrisEntity entity = new IrisEntity(); - entity.setType("minecraft:cow").setCustomName("&6Bessie").setBaby(true); - fixture.resource(SpawnResources.ENTITIES, "cow", entity); + fixture.resource(SpawnResources.ENTITIES, "cow", TestSettings.of(EntityDefinition.class, + "{\"type\": \"minecraft:cow\", \"customName\": \"&6Bessie\", \"baby\": true}")); EntitySpec spec = new EntitySpawning().entity(world, "cow").orElseThrow(); diff --git a/core/src/test/java/art/arcane/iris/engine/spawn/SpawnDurationTest.java b/core/src/test/java/art/arcane/iris/engine/spawn/SpawnDurationTest.java new file mode 100644 index 000000000..1ebcf39b8 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/spawn/SpawnDurationTest.java @@ -0,0 +1,38 @@ +package art.arcane.iris.engine.spawn; + +import art.arcane.iris.engine.object.TestSettings; +import art.arcane.iris.builtin.spawn.SpawnDuration; +import art.arcane.iris.builtin.spawn.SpawnRate; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class SpawnDurationTest { + @Test + public void convertsRealAndMinecraftUnitsToMilliseconds() { + SpawnDuration duration = TestSettings.of(SpawnDuration.class, """ + {"milliseconds": 1, "minecraftTicks": 1, "seconds": 1, "minutes": 1, "minecraftHours": 1, "hours": 1, + "minecraftDays": 1, "minecraftWeeks": 1, "minecraftLunarCycles": 1, "days": 1}"""); + + assertEquals(109_311_051L, duration.toMilliseconds()); + } + + @Test + public void convertsMinecraftCalendarUnitsUsingTwentyMinuteDays() { + assertEquals(1_200_000L, TestSettings.of(SpawnDuration.class, "{\"minecraftDays\": 1}").toMilliseconds()); + assertEquals(8_400_000L, TestSettings.of(SpawnDuration.class, "{\"minecraftWeeks\": 1}").toMilliseconds()); + assertEquals(9_600_000L, TestSettings.of(SpawnDuration.class, "{\"minecraftLunarCycles\": 1}").toMilliseconds()); + } + + @Test + public void aRateSpreadsItsAmountOverItsDurationAndHasNoLimitWithoutOne() { + SpawnRate rate = TestSettings.of(SpawnRate.class, "{\"amount\": 4, \"per\": {\"seconds\": 2}}"); + + assertEquals(500L, rate.interval()); + assertFalse(rate.isInfinite()); + assertTrue(TestSettings.of(SpawnRate.class, "{\"amount\": 4}").isInfinite()); + assertEquals(1L, new SpawnRate().interval()); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/spawn/SpawnResourcesTest.java b/core/src/test/java/art/arcane/iris/engine/spawn/SpawnResourcesTest.java index 13e7d542e..5b3d39ad9 100644 --- a/core/src/test/java/art/arcane/iris/engine/spawn/SpawnResourcesTest.java +++ b/core/src/test/java/art/arcane/iris/engine/spawn/SpawnResourcesTest.java @@ -19,9 +19,9 @@ package art.arcane.iris.engine.spawn; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.entity.IrisEntity; -import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; -import art.arcane.iris.engine.object.marker.IrisMarker; +import art.arcane.iris.builtin.spawn.EntityDefinition; +import art.arcane.iris.builtin.spawn.SpawnMarker; +import art.arcane.iris.builtin.spawn.Spawner; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -51,9 +51,9 @@ public class SpawnResourcesTest { .filter(kind -> kind.id().toString().startsWith("iris:spawn/")).toList(); assertEquals(List.of("iris:spawn/entity", "iris:spawn/marker", "iris:spawn/spawner"), kinds.stream().map(kind -> kind.id().toString()).toList()); assertEquals(List.of("entities", "markers", "spawners"), kinds.stream().map(kind -> kind.folder()).toList()); - assertFalse(data.getLoaders().containsKey(IrisSpawner.class)); - assertFalse(data.getLoaders().containsKey(IrisEntity.class)); - assertFalse(data.getLoaders().containsKey(IrisMarker.class)); + assertFalse(data.getLoaders().containsKey(Spawner.class)); + assertFalse(data.getLoaders().containsKey(EntityDefinition.class)); + assertFalse(data.getLoaders().containsKey(SpawnMarker.class)); } finally { data.close(); } @@ -64,13 +64,12 @@ public class SpawnResourcesTest { Path pack = spawnPack("spawns"); IrisData data = IrisData.openValidation(pack.toFile()); try { - IrisSpawner spawner = SpawnResources.spawner(data, "camp/zombies"); + Spawner spawner = SpawnResources.spawner(data, "camp/zombies"); - assertEquals("camp/zombies", spawner.getLoadKey()); - assertEquals(pack.resolve("spawners/camp/zombies.json").toFile(), spawner.getLoadFile()); - assertEquals("minecraft:zombie", SpawnResources.entity(data, "zombie").getType()); - assertEquals(List.of("camp/zombies"), SpawnResources.marker(data, "camp").getSpawners()); - assertEquals(List.of(spawner), SpawnResources.spawners(data, List.of("camp/zombies", "missing"))); + assertEquals("zombie", spawner.spawns().getFirst().entity()); + assertEquals("minecraft:zombie", SpawnResources.entity(data, "zombie").type()); + assertEquals(List.of("camp/zombies"), SpawnResources.marker(data, "camp").spawners()); + assertEquals(List.of(new SpawnResources.KeyedSpawner("camp/zombies", spawner)), SpawnResources.spawners(data, List.of("camp/zombies", "missing"))); assertEquals(List.of("zombie"), SpawnResources.entityKeys(data)); assertEquals(List.of("camp"), SpawnResources.markerKeys(data)); assertEquals(List.of("camp/zombies"), SpawnResources.spawnerKeys(data)); @@ -79,7 +78,7 @@ public class SpawnResourcesTest { write(pack, "entities/zombie.json", "{\"type\":\"minecraft:husk\"}"); data.dump(); - assertEquals("minecraft:husk", SpawnResources.entity(data, "zombie").getType()); + assertEquals("minecraft:husk", SpawnResources.entity(data, "zombie").type()); } finally { data.close(); } diff --git a/core/src/test/java/art/arcane/iris/purity/PackTypeBukkitPurityGateTest.java b/core/src/test/java/art/arcane/iris/purity/PackTypeBukkitPurityGateTest.java index fc680340a..a6f113906 100644 --- a/core/src/test/java/art/arcane/iris/purity/PackTypeBukkitPurityGateTest.java +++ b/core/src/test/java/art/arcane/iris/purity/PackTypeBukkitPurityGateTest.java @@ -1,14 +1,7 @@ package art.arcane.iris.purity; -import art.arcane.iris.engine.object.entity.IrisEffect; -import art.arcane.iris.engine.object.entity.IrisEntity; -import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; import art.arcane.iris.engine.object.image.IrisImage; import art.arcane.iris.engine.object.image.IrisImageMap; -import art.arcane.iris.engine.object.loot.IrisLoot; -import art.arcane.iris.engine.object.loot.IrisLootTable; -import art.arcane.iris.engine.object.loot.IrisVanillaLootTable; -import art.arcane.iris.engine.object.marker.IrisMarker; import art.arcane.iris.engine.object.material.IrisBlockData; import art.arcane.iris.engine.object.mod.IrisMod; import art.arcane.iris.engine.object.noise.expression.IrisExpression; @@ -128,11 +121,7 @@ public class PackTypeBukkitPurityGateTest { private static final List MODULE_RESOURCE_ROOTS = List.of( "art.arcane.iris.engine.object.structure.IrisStructure", "art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool", - "art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece", - "art.arcane.iris.engine.object.loot.IrisLootTable", - "art.arcane.iris.engine.object.entity.spawn.IrisSpawner", - "art.arcane.iris.engine.object.entity.IrisEntity", - "art.arcane.iris.engine.object.marker.IrisMarker"); + "art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece"); /** * Types reachable from a pack that are not roots and carry no {@code @Snippet}, but are @@ -140,8 +129,7 @@ public class PackTypeBukkitPurityGateTest { */ private static final List ADDITIONAL_PACK_TYPES = List.of( "art.arcane.iris.engine.object.prefab.TileData", - "art.arcane.iris.engine.object.prefab.LegacyTileData", - "art.arcane.iris.engine.object.loot.IrisVanillaLootTable"); + "art.arcane.iris.engine.object.prefab.LegacyTileData"); /** * Bukkit-registry constant holders that a core pack type may reference, so their class initializer @@ -211,7 +199,7 @@ public class PackTypeBukkitPurityGateTest { BukkitHidingClassLoader hiding = new BukkitHidingClassLoader(getClass().getClassLoader()); List gateTypes = gateTypes(); assertTrue("expected the @Snippet scan to find the pack snippet types, found only " - + gateTypes.size(), gateTypes.size() > 60); + + gateTypes.size(), gateTypes.size() > 40); List failures = new ArrayList<>(); List skipped = new ArrayList<>(); diff --git a/core/src/test/java/art/arcane/iris/util/project/matter/RegistryMatterContextTest.java b/core/src/test/java/art/arcane/iris/util/project/matter/RegistryMatterContextTest.java deleted file mode 100644 index 7e6271aba..000000000 --- a/core/src/test/java/art/arcane/iris/util/project/matter/RegistryMatterContextTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package art.arcane.iris.util.project.matter; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.modules.ModuleResourceFixture; -import art.arcane.iris.engine.spawn.SpawnResources; -import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; -import art.arcane.iris.util.project.matter.slices.SpawnerMatter; -import org.junit.Test; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -import static org.junit.Assert.assertSame; -import static org.mockito.Mockito.mock; - -public class RegistryMatterContextTest { - @Test - public void registrySliceResolvesThroughExplicitDataOnIoWorker() throws Exception { - IrisSpawner firstResolved = new IrisSpawner(); - IrisSpawner secondResolved = new IrisSpawner(); - IrisData firstData = dataReturning(firstResolved); - IrisData secondData = dataReturning(secondResolved); - ExecutorService executor = Executors.newSingleThreadExecutor(); - try { - Future firstRead = executor.submit(() -> readSpawner(firstData)); - Future secondRead = executor.submit(() -> readSpawner(secondData)); - assertSame(firstResolved, firstRead.get()); - assertSame(secondResolved, secondRead.get()); - } finally { - executor.shutdownNow(); - } - } - - private IrisSpawner readSpawner(IrisData data) throws Exception { - ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - try (DataOutputStream output = new DataOutputStream(bytes)) { - output.writeUTF("test-spawner"); - } - try (IrisMatterContext.Scope scope = IrisMatterContext.open(data); - DataInputStream input = new DataInputStream(new ByteArrayInputStream(bytes.toByteArray()))) { - return new SpawnerMatter().readNode(input); - } - } - - private IrisData dataReturning(IrisSpawner resolved) { - IrisData data = mock(IrisData.class); - ModuleResourceFixture.serve(data).resource(SpawnResources.SPAWNERS, "test-spawner", resolved); - return data; - } -} diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/biomes/tropical/volcanoes.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/biomes/tropical/volcanoes.json new file mode 100644 index 000000000..a36c777d1 --- /dev/null +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/biomes/tropical/volcanoes.json @@ -0,0 +1,72 @@ +{ + "name": "Tropical Volcanoes", + "color": "#8C1E1E", + "rarity": 1, + "derivative": "minecraft:the_void", + "vanillaDerivative": "minecraft:the_void", + "customDerivitives": [{ + "category": "jungle", + "id": "tropical_volcano", + "grassColor": "#BDBF0B", + "foliageColor": "#BDBF0B", + "fogColor": "#DD793C", + "downfallType": "none" + }], + "children": ["tropical/volcanoes-lava"], + "generators": [{ + "generator": "mountain", + "max": 180, + "min": 30 + }], + "layers": [ + { + "minHeight": 1, + "maxHeight": 1, + "palette": [{"block": "minecraft:basalt"}] + }, + { + "minHeight": 2, + "maxHeight": 2, + "palette": [ + { + "block": "minecraft:basalt", + "data": {"axis": "x"} + }, + { + "block": "minecraft:basalt", + "data": {"axis": "y"} + }, + { + "block": "minecraft:basalt", + "data": {"axis": "z"} + } + ] + }, + { + "minHeight": 3, + "maxHeight": 10, + "palette": [{"block": "minecraft:blackstone"}] + }, + { + "minHeight": 1, + "maxHeight": 2, + "palette": [{"block": "minecraft:tuff"}] + } + ], + "effects": [{ + "particleAltX": 0.001, + "particleAltY": 0.13885, + "particleAltZ": 0.001, + "chance": 1, + "particleEffect": "CAMPFIRE_SIGNAL_SMOKE", + "particleOffset": 0, + "interval": 300, + "particleCount": 0 + }], + "childStyle": { + "style": "GLOB", + "zoom": 0.2, + "exponent": 4 + }, + "childShrinkFactor": 1 +} diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/dimensions/overworld.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/dimensions/overworld.json new file mode 100644 index 000000000..645d60456 --- /dev/null +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/dimensions/overworld.json @@ -0,0 +1,946 @@ +{ + "version": 4002, + "name": "Overworld", + "importedStructures": { + "datapackOverrides": true, + "adjustments": [ + { + "match": [ + "minecraft:stronghold" + ], + "yBand": { + "min": -120, + "max": -20 + }, + "terrain": { + "mode": "ENCASE", + "horizontalPadding": 4, + "ceilingPadding": 4, + "floorPadding": 4, + "encasePalette": { + "zoom": 1, + "palette": [ + { + "block": "minecraft:stone_bricks", + "weight": 6 + }, + { + "block": "minecraft:mossy_stone_bricks", + "weight": 2 + }, + { + "block": "minecraft:cracked_stone_bricks", + "weight": 2 + }, + { + "block": "minecraft:cobblestone", + "weight": 1 + } + ] + } + } + }, + { + "match": [ + "minecraft:trial_chambers" + ], + "yShift": -64 + }, + { + "match": [ + "minecraft:mineshaft" + ], + "preserveSourceY": true + }, + { + "match": [ + "minecraft:village" + ], + "stilt": { + "maxDepth": 2, + "palette": { + "palette": [ + { + "block": "minecraft:dirt" + } + ] + } + } + } + ] + }, + "structures": [ + { + "nativeStructures": [ + { + "structure": "minecraft:ancient_city" + } + ], + "placementId": "ancient-city-native", + "nativeSuppression": "REPLACE_SOURCE", + "underground": true, + "terrain": { + "mode": "FORCE_CARVE", + "horizontalPadding": 14, + "ceilingPadding": 12, + "floorPadding": 0, + "shape": "ERODED", + "erosionStrength": 1.0, + "erosionFrequency": 0.05 + }, + "stilt": { + "maxDepth": 768, + "spacing": 1, + "palette": { + "style": { + "style": "STATIC" + }, + "palette": [ + { + "block": "minecraft:deepslate_bricks", + "weight": 6 + }, + { + "block": "minecraft:cracked_deepslate_bricks", + "weight": 1 + }, + { + "block": "minecraft:deepslate_tiles", + "weight": 2 + }, + { + "block": "minecraft:cracked_deepslate_tiles", + "weight": 1 + } + ] + } + }, + "minHeight": -220, + "maxHeight": -220, + "distribution": "RANDOM_SPREAD", + "spacing": 64, + "separation": 5, + "salt": 42069 + } + ], + "fullbright": false, + "upperDimension": "", + "upperDimensionGap": 32, + "upperDimensionCarving": false, + "upperDimensionObjects": false, + "environment": "NORMAL", + "dimensionAngleDeg": 69, + "fluidHeight": 50, + "continentZoom": 1, + "continentalStyle": { + "style": "NOWHERE_CELLULAR", + "fracture": { + "style": "FRACTAL_SMOKE", + "axialFracturing": true, + "multiplier": 1, + "fracture": { + "style": "STATIC", + "multiplier": 1, + "axialFracturing": true + } + }, + "axialFracturing": true, + "zoom": 6 + }, + "logicalHeight": 512, + "dimensionHeight": { + "max": 512, + "min": -256 + }, + "landChance": 0.69, + "regionStyle": { + "style": "CELLULAR_IRIS_DOUBLE", + "axialFracturing": true, + "fracture": { + "axialFracturing": true, + "multiplier": 9, + "style": "FRACTAL_WATER", + "zoom": 0.15, + "fracture": { + "style": "STATIC", + "multiplier": 1, + "axialFracturing": true + } + } + }, + "regionZoom": 16.15, + "regions": [ + "frozen", + "hot", + "terralost", + "mushroom", + "forests", + "tundra", + "magnetics", + "temperate", + "estranged", + "tropical", + "swamp", + "prismatics" + ], + "seaBiomeStyle": { + "style": "SIMPLEX", + "axialFracturing": true + }, + "landBiomeStyle": { + "style": "NOWHERE_CELLULAR", + "axialFracturing": true, + "fracture": { + "multiplier": 55, + "axialFracturing": true, + "style": "NOWHERE", + "zoom": 0.15, + "fracture": { + "axialFracturing": true, + "style": "STATIC", + "multiplier": 4 + } + } + }, + "ores": [ + { + "threshold": 1, + "range": { + "min": 0, + "max": 0 + }, + "palette": { + "palette": [ + { + "block": "minecraft:bedrock" + } + ] + }, + "chanceStyle": { + "style": "FLAT" + } + }, + { + "threshold": 0.625, + "range": { + "min": 1, + "max": 1 + }, + "palette": { + "palette": [ + { + "block": "minecraft:bedrock" + } + ] + }, + "chanceStyle": "snippet/style/bedrock" + }, + { + "threshold": 0.35, + "range": { + "min": 2, + "max": 4 + }, + "palette": { + "palette": [ + { + "block": "minecraft:bedrock" + } + ] + }, + "chanceStyle": "snippet/style/bedrock" + }, + { + "threshold": 1, + "range": { + "min": 1, + "max": 57 + }, + "palette": { + "palette": [ + { + "block": "minecraft:deepslate" + } + ] + }, + "chanceStyle": { + "style": "FLAT" + } + }, + { + "threshold": 0.874, + "range": { + "min": 58, + "max": 58 + }, + "palette": { + "palette": [ + { + "block": "minecraft:deepslate" + } + ] + }, + "chanceStyle": "snippet/style/deepslate" + }, + { + "threshold": 0.75, + "range": { + "min": 59, + "max": 59 + }, + "palette": { + "palette": [ + { + "block": "minecraft:deepslate" + } + ] + }, + "chanceStyle": "snippet/style/deepslate" + }, + { + "threshold": 0.625, + "range": { + "min": 60, + "max": 60 + }, + "palette": { + "palette": [ + { + "block": "minecraft:deepslate" + } + ] + }, + "chanceStyle": "snippet/style/deepslate" + }, + { + "threshold": 0.5, + "range": { + "min": 61, + "max": 61 + }, + "palette": { + "palette": [ + { + "block": "minecraft:deepslate" + } + ] + }, + "chanceStyle": "snippet/style/deepslate" + }, + { + "threshold": 0.375, + "range": { + "min": 62, + "max": 62 + }, + "palette": { + "palette": [ + { + "block": "minecraft:deepslate" + } + ] + }, + "chanceStyle": "snippet/style/deepslate" + }, + { + "threshold": 0.25, + "range": { + "min": 63, + "max": 63 + }, + "palette": { + "palette": [ + { + "block": "minecraft:deepslate" + } + ] + }, + "chanceStyle": "snippet/style/deepslate" + }, + { + "threshold": 0.125, + "range": { + "min": 64, + "max": 64 + }, + "palette": { + "palette": [ + { + "block": "minecraft:deepslate" + } + ] + }, + "chanceStyle": "snippet/style/deepslate" + } + ], + "shoreBiomeStyle": { + "style": "NOWHERE_CELLULAR" + }, + "deposits": [ + { + "minHeight": 19, + "maxPerChunk": 8, + "maxHeight": 390, + "minPerChunk": 1, + "minSize": 25, + "maxSize": 25, + "palette": [ + { + "block": "minecraft:granite" + } + ], + "varience": 2 + }, + { + "minHeight": 19, + "maxPerChunk": 8, + "maxHeight": 310, + "minPerChunk": 1, + "minSize": 25, + "maxSize": 25, + "palette": [ + { + "block": "minecraft:andesite" + } + ], + "varience": 2 + }, + { + "minHeight": 19, + "maxPerChunk": 8, + "maxHeight": 309, + "minPerChunk": 1, + "minSize": 25, + "maxSize": 25, + "palette": [ + { + "block": "minecraft:diorite" + } + ], + "varience": 2 + }, + { + "minHeight": 19, + "maxPerChunk": 8, + "maxHeight": 389, + "minPerChunk": 1, + "minSize": 25, + "maxSize": 25, + "palette": [ + { + "block": "minecraft:gravel" + } + ], + "varience": 2 + }, + { + "minHeight": 400, + "maxHeight": 767, + "heightDistribution": "UNIFORM", + "surfaceClearance": 0, + "minPerChunk": 60, + "maxPerChunk": 60, + "minSize": 17, + "maxSize": 17, + "shape": "VANILLA_ELLIPSOID", + "discardChanceOnAirExposure": 0.3, + "palette": [ + { + "block": "minecraft:coal_ore" + } + ], + "replaceableBlocks": [ + "minecraft:stone", + "minecraft:granite", + "minecraft:diorite", + "minecraft:andesite", + "minecraft:deepslate", + "minecraft:tuff" + ] + }, + { + "minHeight": 128, + "maxHeight": 512, + "heightDistribution": "TRIANGLE", + "surfaceClearance": 1, + "minPerChunk": 80, + "maxPerChunk": 80, + "minSize": 17, + "maxSize": 17, + "shape": "VANILLA_ELLIPSOID", + "discardChanceOnAirExposure": 0.65, + "palette": [ + { + "block": "minecraft:coal_ore" + } + ] + }, + { + "minHeight": 288, + "maxHeight": 896, + "heightDistribution": "TRIANGLE", + "surfaceClearance": 0, + "minPerChunk": 180, + "maxPerChunk": 180, + "minSize": 9, + "maxSize": 9, + "shape": "VANILLA_ELLIPSOID", + "palette": [ + { + "block": "minecraft:iron_ore" + } + ], + "replaceableBlocks": [ + "minecraft:stone", + "minecraft:granite", + "minecraft:diorite", + "minecraft:andesite", + "minecraft:deepslate", + "minecraft:tuff" + ] + }, + { + "minHeight": 80, + "maxHeight": 240, + "heightDistribution": "TRIANGLE", + "surfaceClearance": 0, + "minPerChunk": 40, + "maxPerChunk": 40, + "minSize": 9, + "maxSize": 9, + "shape": "VANILLA_ELLIPSOID", + "palette": [ + { + "block": "minecraft:iron_ore" + } + ] + }, + { + "minHeight": 0, + "maxHeight": 272, + "heightDistribution": "UNIFORM", + "surfaceClearance": 0, + "minPerChunk": 40, + "maxPerChunk": 40, + "minSize": 4, + "maxSize": 4, + "shape": "VANILLA_ELLIPSOID", + "palette": [ + { + "block": "minecraft:iron_ore" + } + ] + }, + { + "minHeight": 96, + "maxHeight": 352, + "heightDistribution": "TRIANGLE", + "surfaceClearance": 0, + "minPerChunk": 64, + "maxPerChunk": 64, + "minSize": 10, + "maxSize": 10, + "shape": "VANILLA_ELLIPSOID", + "biomeScope": "CAVE", + "excludedBiomes": [ + "carving/drip", + "carving/drip-child", + "carving/drip-lite", + "carving/drip-lite-child" + ], + "palette": [ + { + "block": "minecraft:copper_ore" + } + ] + }, + { + "minHeight": 96, + "maxHeight": 352, + "heightDistribution": "TRIANGLE", + "surfaceClearance": 0, + "minPerChunk": 64, + "maxPerChunk": 64, + "minSize": 20, + "maxSize": 20, + "shape": "VANILLA_ELLIPSOID", + "biomeScope": "CAVE", + "includedBiomes": [ + "carving/drip", + "carving/drip-child", + "carving/drip-lite", + "carving/drip-lite-child" + ], + "palette": [ + { + "block": "minecraft:copper_ore" + } + ] + }, + { + "minHeight": 0, + "maxHeight": 192, + "heightDistribution": "TRIANGLE", + "surfaceClearance": 0, + "minPerChunk": 16, + "maxPerChunk": 16, + "minSize": 9, + "maxSize": 9, + "shape": "VANILLA_ELLIPSOID", + "discardChanceOnAirExposure": 0.5, + "palette": [ + { + "block": "minecraft:gold_ore" + } + ] + }, + { + "minHeight": 0, + "maxHeight": 32, + "heightDistribution": "UNIFORM", + "surfaceClearance": 0, + "minPerChunk": 0, + "maxPerChunk": 2, + "minSize": 9, + "maxSize": 9, + "shape": "VANILLA_ELLIPSOID", + "discardChanceOnAirExposure": 0.5, + "palette": [ + { + "block": "minecraft:gold_ore" + } + ], + "replaceableBlocks": [ + "minecraft:stone", + "minecraft:granite", + "minecraft:diorite", + "minecraft:andesite", + "minecraft:deepslate", + "minecraft:tuff" + ] + }, + { + "minHeight": 192, + "maxHeight": 640, + "heightDistribution": "UNIFORM", + "surfaceClearance": 0, + "minPerChunk": 100, + "maxPerChunk": 100, + "minSize": 9, + "maxSize": 9, + "shape": "VANILLA_ELLIPSOID", + "biomeScope": "SURFACE", + "includedBiomes": [ + "minecraft:badlands", + "minecraft:eroded_badlands", + "minecraft:wooded_badlands" + ], + "palette": [ + { + "block": "minecraft:gold_ore" + } + ], + "replaceableBlocks": [ + "minecraft:stone", + "minecraft:granite", + "minecraft:diorite", + "minecraft:andesite", + "minecraft:deepslate", + "minecraft:tuff" + ] + }, + { + "minHeight": 0, + "maxHeight": 158, + "heightDistribution": "UNIFORM", + "surfaceClearance": 0, + "minPerChunk": 16, + "maxPerChunk": 16, + "minSize": 8, + "maxSize": 8, + "shape": "VANILLA_ELLIPSOID", + "palette": [ + { + "data": { + "lit": false + }, + "block": "minecraft:redstone_ore" + } + ] + }, + { + "minHeight": -64, + "maxHeight": 64, + "heightDistribution": "TRIANGLE", + "surfaceClearance": 0, + "minPerChunk": 16, + "maxPerChunk": 16, + "minSize": 8, + "maxSize": 8, + "shape": "VANILLA_ELLIPSOID", + "palette": [ + { + "data": { + "lit": false + }, + "block": "minecraft:redstone_ore" + } + ], + "replaceableBlocks": [ + "minecraft:stone", + "minecraft:granite", + "minecraft:diorite", + "minecraft:andesite", + "minecraft:deepslate", + "minecraft:tuff" + ] + }, + { + "minHeight": -160, + "maxHeight": 160, + "heightDistribution": "TRIANGLE", + "surfaceClearance": 0, + "minPerChunk": 28, + "maxPerChunk": 28, + "minSize": 4, + "maxSize": 4, + "shape": "VANILLA_ELLIPSOID", + "discardChanceOnAirExposure": 0.5, + "palette": [ + { + "block": "minecraft:diamond_ore" + } + ] + }, + { + "minHeight": 0, + "maxHeight": 120, + "heightDistribution": "UNIFORM", + "surfaceClearance": 0, + "minPerChunk": 8, + "maxPerChunk": 8, + "minSize": 8, + "maxSize": 8, + "shape": "VANILLA_ELLIPSOID", + "discardChanceOnAirExposure": 0.5, + "palette": [ + { + "block": "minecraft:diamond_ore" + } + ] + }, + { + "minHeight": -160, + "maxHeight": 160, + "heightDistribution": "TRIANGLE", + "surfaceClearance": 0, + "minPerChunk": 4, + "maxPerChunk": 4, + "spawnChance": 0.1111111111111111, + "minSize": 12, + "maxSize": 12, + "shape": "VANILLA_ELLIPSOID", + "discardChanceOnAirExposure": 0.7, + "palette": [ + { + "block": "minecraft:diamond_ore" + } + ] + }, + { + "minHeight": -160, + "maxHeight": 160, + "heightDistribution": "TRIANGLE", + "surfaceClearance": 0, + "minPerChunk": 16, + "maxPerChunk": 16, + "minSize": 8, + "maxSize": 8, + "shape": "VANILLA_ELLIPSOID", + "discardChanceOnAirExposure": 1.0, + "palette": [ + { + "block": "minecraft:diamond_ore" + } + ] + }, + { + "minHeight": 64, + "maxHeight": 192, + "heightDistribution": "TRIANGLE", + "surfaceClearance": 0, + "minPerChunk": 8, + "maxPerChunk": 8, + "minSize": 7, + "maxSize": 7, + "shape": "VANILLA_ELLIPSOID", + "palette": [ + { + "block": "minecraft:lapis_ore" + } + ] + }, + { + "minHeight": 0, + "maxHeight": 256, + "heightDistribution": "UNIFORM", + "surfaceClearance": 0, + "minPerChunk": 16, + "maxPerChunk": 16, + "minSize": 7, + "maxSize": 7, + "shape": "VANILLA_ELLIPSOID", + "discardChanceOnAirExposure": 1.0, + "palette": [ + { + "block": "minecraft:lapis_ore" + } + ] + }, + { + "minHeight": 96, + "maxHeight": 1088, + "heightDistribution": "TRIANGLE", + "surfaceClearance": 0, + "minPerChunk": 200, + "maxPerChunk": 200, + "minSize": 3, + "maxSize": 3, + "shape": "VANILLA_ELLIPSOID", + "biomeScope": "SURFACE", + "includedBiomes": [ + "minecraft:cherry_grove", + "minecraft:frozen_peaks", + "minecraft:grove", + "minecraft:jagged_peaks", + "minecraft:meadow", + "minecraft:snowy_slopes", + "minecraft:stony_peaks", + "minecraft:windswept_forest", + "minecraft:windswept_gravelly_hills", + "minecraft:windswept_hills" + ], + "palette": [ + { + "block": "minecraft:emerald_ore" + } + ], + "replaceableBlocks": [ + "minecraft:stone", + "minecraft:granite", + "minecraft:diorite", + "minecraft:andesite", + "minecraft:deepslate", + "minecraft:tuff" + ] + } + ], + "caveBiomeStyle": { + "style": "SIMPLEX", + "zoom": 2.6 + }, + "coordFractureZoom": 0.15, + "preventLeafDecay": true, + "useMantle": true, + "carvingEnabled": true, + "decorate": true, + "loot": { + "mode": "FALLBACK", + "tables": [ + "global-clutter" + ] + }, + "caveProfile": { + "enabled": true, + "verticalRange": { + "min": 6, + "max": 700 + }, + "baseDensityStyle": { + "style": "PERLIN_IRIS", + "zoom": 0.72 + }, + "detailDensityStyle": { + "style": "SIMPLEX", + "zoom": 0.54 + }, + "warpStyle": { + "style": "FRACTAL_WATER", + "zoom": 0.5 + }, + "baseWeight": 0.9, + "detailWeight": 0.11, + "warpStrength": 0.24, + "densityThreshold": { + "min": -0.14, + "max": -0.06, + "style": { + "style": "SIMPLEX", + "zoom": 0.74 + } + }, + "thresholdBias": 0.14, + "sampleStep": 3, + "surfaceClearance": 5, + "allowSurfaceBreak": true, + "surfaceBreakStyle": { + "style": "SIMPLEX", + "zoom": 0.88 + }, + "surfaceBreakNoiseThreshold": 0.6, + "surfaceBreakDepth": 16, + "surfaceBreakThresholdBoost": 0.1, + "objectMinDepthBelowSurface": 14, + "defaultObjectAnchor": "FLOOR", + "defaultObjectPlaceMode": "ORGANIC_STILT", + "anchorScanStep": 1, + "anchorSearchAttempts": 12, + "allowFluid": true, + "fluidMinDepthBelowSurface": 20, + "fluidRequiresFloor": true, + "allowLava": true, + "modules": [ + { + "style": { + "style": "SIMPLEX_VASCULAR", + "zoom": 1.08 + }, + "weight": 0.08, + "threshold": 0.03, + "verticalRange": { + "min": 24, + "max": 660 + }, + "invert": false + }, + { + "style": { + "style": "FRACTAL_FBM_SIMPLEX", + "zoom": 0.24 + }, + "weight": 0.04, + "threshold": 0.08, + "verticalRange": { + "min": 6, + "max": 240 + }, + "invert": true + } + ], + "verticalEdgeFade": 24, + "verticalEdgeFadeStrength": 0.18, + "minCarveCells": 24, + "recoveryThresholdBoost": 0.07 + }, + "carving": [ + { + "id": "global-deepdark-band", + "enabled": true, + "biome": "carving/standard-deepdark", + "worldYRange": { + "min": -250, + "max": -175 + } + } + ] +} diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/entities/standard/hostile/zombie.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/entities/standard/hostile/zombie.json new file mode 100644 index 000000000..3ada89f8f --- /dev/null +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/entities/standard/hostile/zombie.json @@ -0,0 +1 @@ +{"type": "ZOMBIE"} \ No newline at end of file diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/entities/standard/passive/mooshroom.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/entities/standard/passive/mooshroom.json new file mode 100644 index 000000000..f0636763e --- /dev/null +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/entities/standard/passive/mooshroom.json @@ -0,0 +1 @@ +{"type": "MOOSHROOM"} \ No newline at end of file diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/loot/global-clutter.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/loot/global-clutter.json new file mode 100644 index 000000000..e22dcdd40 --- /dev/null +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/loot/global-clutter.json @@ -0,0 +1,115 @@ +{ + "name": "Global Clutter", + "rarity": 1, + "maxPicked": 2, + "minPicked": 1, + "maxTries": 20, + "loot": [ + { + "type": "stone", + "minAmount": 1, + "maxAmount": 8, + "rarity": 1, + "slotTypes": "STORAGE" + }, + { + "type": "stick", + "minAmount": 1, + "maxAmount": 6, + "rarity": 1, + "slotTypes": "STORAGE" + }, + { + "type": "flint", + "minAmount": 1, + "maxAmount": 4, + "rarity": 2, + "slotTypes": "STORAGE" + }, + { + "type": "string", + "minAmount": 1, + "maxAmount": 4, + "rarity": 2, + "slotTypes": "STORAGE" + }, + { + "type": "leather", + "minAmount": 1, + "maxAmount": 3, + "rarity": 3, + "slotTypes": "STORAGE" + }, + { + "type": "paper", + "minAmount": 1, + "maxAmount": 5, + "rarity": 3, + "slotTypes": "STORAGE" + }, + { + "type": "torch", + "minAmount": 2, + "maxAmount": 8, + "rarity": 2, + "slotTypes": "STORAGE" + }, + { + "type": "ladder", + "minAmount": 1, + "maxAmount": 6, + "rarity": 4, + "slotTypes": "STORAGE" + }, + { + "type": "bucket", + "minAmount": 1, + "maxAmount": 1, + "rarity": 9, + "slotTypes": "STORAGE" + }, + { + "type": "arrow", + "minAmount": 2, + "maxAmount": 10, + "rarity": 4, + "slotTypes": "STORAGE" + }, + { + "type": "glass_bottle", + "minAmount": 1, + "maxAmount": 4, + "rarity": 4, + "slotTypes": "STORAGE" + }, + { + "type": "copper_ingot", + "minAmount": 1, + "maxAmount": 5, + "rarity": 6, + "slotTypes": "STORAGE" + }, + { + "type": "amethyst_shard", + "minAmount": 1, + "maxAmount": 4, + "rarity": 7, + "slotTypes": "STORAGE" + }, + { + "type": "enchanted_book", + "minAmount": 1, + "maxAmount": 1, + "rarity": 28, + "slotTypes": "STORAGE", + "enchantments": [ + { + "enchantment": "unbreaking", + "minLevel": 2, + "maxLevel": 3, + "chance": 1.0 + } + ] + } + ] +} diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/hot.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/hot.json new file mode 100644 index 000000000..09db28c64 --- /dev/null +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/hot.json @@ -0,0 +1,138 @@ +{ + "name": "Hot", + "color": "#D1CD44", + "rarity": 3, + "seaBiomeZoom": 3.5, + "landBiomes": [ + "hot/desert-dunes", + "hot/small-valley", + "hot/desert-dunes-red", + "savanna/savanna", + "mesa/dark", + "savanna/plateau", + "savanna/forest", + "savanna/acacia-denmyre", + "mesa/plateau", + "mesa/valleys", + "mesa/plateau-high", + "mesa/valleys", + "mesa/mesa", + "hot/mountain-middle", + "hot/mountain-plains", + "hot/oasis", + "vanilla/savanna_plateau", + "vanilla/windswept_savanna", + "vanilla/wooded_badlands" + ], + "caveBiomes": [ + "carving/sandstone", + "carving/sand-hollows", + "carving/red-sandstone", + "carving/mixed-sandstone", + "carving/volcanic", + "carving/ember-rifts" + ], + "shoreBiomes": [ + "hot/shore/beach", + "hot/shore/beach-grass", + "mesa/shore/beach", + "savanna/shore/beach" + ], + "seaBiomes": [ + "hot/sea/ocean", + "ocean/rich-oceans", + "hot/sea/river", + "mesa/sea/river" + ], + "landBiomeZoom": 7, + "effects": [ + { + "potionTicksMin": 87, + "potionEffect": "CONFUSION", + "chance": 1200, + "potionStrength": 0, + "potionTicksMax": 67, + "interval": 500 + }, + { + "particleAltX": 0.001, + "particleAltY": 0.00885, + "particleAltZ": 0.001, + "chance": 2, + "particleEffect": "CAMPFIRE_SIGNAL_SMOKE", + "particleOffset": 0, + "interval": 1350, + "particleCount": 0 + } + ], + "shoreHeightMin": 3.2, + "shoreHeightMax": 6.2, + "shoreHeightZoom": 1.14, + "loot": { + "mode": "FALLBACK", + "multiplier": 0.5, + "tables": [ + "hot/food", + "cactus/clutter", + "beach/clutter" + ] + }, + "caveProfile": { + "enabled": true, + "verticalRange": { + "min": 6, + "max": 90 + }, + "baseDensityStyle": { + "style": "IRIS_DOUBLE", + "zoom": 0.8 + }, + "detailDensityStyle": { + "style": "SIMPLEX", + "zoom": 0.5 + }, + "warpStyle": { + "style": "SIMPLEX", + "zoom": 0.5 + }, + "baseWeight": 1, + "detailWeight": 0, + "warpStrength": 0, + "densityThreshold": { + "min": -0.1, + "max": -0.04, + "style": { + "style": "SIMPLEX", + "zoom": 0.5 + } + }, + "thresholdBias": 0.14, + "sampleStep": 3, + "surfaceClearance": 12, + "allowSurfaceBreak": false, + "surfaceBreakStyle": { + "style": "SIMPLEX", + "zoom": 0.88 + }, + "surfaceBreakNoiseThreshold": 0.99, + "surfaceBreakDepth": 4, + "surfaceBreakThresholdBoost": 0.02, + "objectMinDepthBelowSurface": 14, + "defaultObjectAnchor": "FLOOR", + "defaultObjectPlaceMode": "ORGANIC_STILT", + "anchorScanStep": 1, + "anchorSearchAttempts": 12, + "allowFluid": true, + "fluidMinDepthBelowSurface": 20, + "fluidRequiresFloor": true, + "allowLava": true, + "modules": [] + }, + "caveBiomeZoom": 3.6, + "entitySpawners": [ + "hot/cave", + "hot/hostile", + "hot/passive", + "hot/water" + ] +} diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/mushroom.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/mushroom.json new file mode 100644 index 000000000..93e84a1da --- /dev/null +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/mushroom.json @@ -0,0 +1,266 @@ +{ + "name": "Mushroom", + "color": "#F1C3EF", + "rarity": 15, + "proceduralObjects": { + "fungi": [ + { + "name": "red-cap", + "chance": 0.05, + "density": 2, + "variants": 6, + "seed": 9301, + "stem": "minecraft:mushroom_stem", + "cap": "minecraft:red_mushroom_block", + "capShape": "DOME", + "stemHeightMin": 4, + "stemHeightMax": 9, + "stemWidth": 2, + "stemCurve": 6, + "stemWaveAmplitude": 0.4, + "stemWavePeriods": 1.5, + "capRadiusMin": 3, + "capRadiusMax": 5, + "capThickness": 2, + "capSquish": 0.7, + "capDroop": 18, + "capOverhang": 2, + "gillBlock": "minecraft:mushroom_stem", + "gillChance": 0.7, + "rotation": { + "enabled": true, + "yAxis": { + "enabled": true, + "min": 0, + "max": 360, + "interval": 90 + } + } + }, + { + "name": "brown-table", + "chance": 0.05, + "density": 2, + "variants": 6, + "seed": 9302, + "stem": "minecraft:mushroom_stem", + "cap": "minecraft:brown_mushroom_block", + "capShape": "FLAT_WIDE", + "stemHeightMin": 5, + "stemHeightMax": 11, + "stemWidth": 2, + "stemCurve": 4, + "capRadiusMin": 4, + "capRadiusMax": 7, + "capThickness": 1, + "capSquish": 0.35, + "capDroop": 8, + "capOverhang": 3, + "gillBlock": "minecraft:shroomlight", + "gillChance": 0.5, + "rotation": { + "enabled": true, + "yAxis": { + "enabled": true, + "min": 0, + "max": 360, + "interval": 90 + } + } + }, + { + "name": "spindle-toadstool", + "chance": 0.35, + "density": 3, + "variants": 6, + "seed": 9303, + "stem": "minecraft:mushroom_stem", + "stemPalette": { + "style": { + "style": "SIMPLEX", + "zoom": 0.6 + }, + "palette": [ + { + "block": "minecraft:mushroom_stem", + "weight": 5 + }, + { + "block": "minecraft:pale_oak_wood", + "weight": 1 + } + ] + }, + "cap": "minecraft:red_mushroom_block", + "capShape": "CONICAL", + "stemHeightMin": 6, + "stemHeightMax": 12, + "stemWidth": 1, + "stemCurve": 10, + "stemWaveAmplitude": 0.6, + "stemWavePeriods": 2, + "capRadiusMin": 2, + "capRadiusMax": 4, + "capThickness": 2, + "capSquish": 0.9, + "capDroop": 22, + "capOverhang": 1, + "spotBlock": "minecraft:brown_mushroom_block", + "spotChance": 0.25, + "gillBlock": "minecraft:shroomlight", + "gillChance": 0.6, + "rotation": { + "enabled": true, + "yAxis": { + "enabled": true, + "min": 0, + "max": 360, + "interval": 90 + } + } + } + ] + }, + "landBiomes": [ + "mushroom/forest", + "mushroom/crimson-forest", + "mushroom/forest-extended", + "mushroom/plains", + "mushroom/warped-forest" + ], + "caveBiomes": [ + "carving/mushroom", + "carving/rocky-cavebiome", + "carving/drip-lite", + "carving/moss-pillars", + "carving/crystalized-overgrown" + ], + "shoreBiomes": [ + "mushroom/shore/beach" + ], + "seaBiomes": [ + "mushroom/sea/ocean", + "mushroom/sea/lake" + ], + "blockDrops": [ + { + "drops": [ + { + "type": "red_mushroom", + "rarity": 8 + }, + { + "type": "brown_mushroom", + "rarity": 8 + } + ], + "blocks": [ + { + "block": "minecraft:mycelium" + }, + { + "block": "minecraft:mushroom_stem" + }, + { + "block": "minecraft:red_mushroom_block" + }, + { + "block": "minecraft:brown_mushroom_block" + } + ] + } + ], + "landBiomeZoom": 1.8, + "effects": [ + { + "particleAltX": 1e-05, + "particleAway": 1, + "particleAltY": 0.01885, + "particleAltZ": 1e-05, + "chance": 3, + "particleEffect": "CRIMSON_SPORE", + "particleDistance": 5, + "particleOffset": 2, + "interval": 50, + "particleCount": 0 + }, + { + "volume": 6.2, + "minPitch": 0.2, + "chance": 8, + "maxPitch": 0.3, + "sound": "AMBIENT.WARPED_FOREST.ADDITIONS", + "interval": 60000, + "soundDistance": 3 + } + ], + "shoreHeightMin": 3.2, + "shoreHeightMax": 6.2, + "shoreHeightZoom": 1.14, + "loot": { + "mode": "FALLBACK", + "multiplier": 0.5, + "tables": [ + "mushroom/clutter", + "mushroom/food" + ] + }, + "caveProfile": { + "enabled": true, + "verticalRange": { + "min": 6, + "max": 100 + }, + "baseDensityStyle": { + "style": "CELLULAR", + "zoom": 0.9 + }, + "detailDensityStyle": { + "style": "SIMPLEX", + "zoom": 0.5 + }, + "warpStyle": { + "style": "SIMPLEX", + "zoom": 0.5 + }, + "baseWeight": 1.0, + "detailWeight": 0.0, + "warpStrength": 0.0, + "densityThreshold": { + "min": -0.12, + "max": -0.06, + "style": { + "style": "SIMPLEX", + "zoom": 0.5 + } + }, + "thresholdBias": 0.1, + "sampleStep": 3, + "surfaceClearance": 12, + "allowSurfaceBreak": false, + "surfaceBreakStyle": { + "style": "SIMPLEX", + "zoom": 0.88 + }, + "surfaceBreakNoiseThreshold": 0.99, + "surfaceBreakDepth": 4, + "surfaceBreakThresholdBoost": 0.02, + "objectMinDepthBelowSurface": 14, + "defaultObjectAnchor": "FLOOR", + "defaultObjectPlaceMode": "ORGANIC_STILT", + "anchorScanStep": 1, + "anchorSearchAttempts": 12, + "allowFluid": true, + "fluidMinDepthBelowSurface": 20, + "fluidRequiresFloor": true, + "allowLava": true, + "modules": [] + }, + "caveBiomeZoom": 3.2, + "entitySpawners": [ + "mushroom/cave", + "mushroom/hostile", + "mushroom/passive", + "mushroom/water" + ] +} diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/swamp.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/swamp.json new file mode 100644 index 000000000..e9deba0ad --- /dev/null +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/swamp.json @@ -0,0 +1,126 @@ +{ + "name": "Swamp", + "color": "#69943C", + "rarity": 2, + "landBiomes": [ + "swamp/roofed-forest", + "swamp/sea/lake", + "swamp/roofed-wayward", + "swamp/marsh", + "swamp/handy-willow-forest", + "swamp/cambian-drift", + "swamp/swamp-forest", + "swamp/willow-forest", + "swamp/creaks", + "vanilla/mangrove_swamp" + ], + "caveBiomes": [ + "carving/swamp", + "carving/lush", + "carving/drip-lite", + "carving/drip", + "carving/moss-pillars" + ], + "shoreBiomes": [ + "swamp/shore/beach" + ], + "seaBiomes": [ + "swamp/sea/ocean", + "swamp/swamp-mangrove-lake", + "swamp/sea/ocean-tree" + ], + "landBiomeZoom": 2, + "shoreHeightMin": 1.2, + "shoreHeightMax": 3, + "shoreHeightZoom": 3.14, + "blockDrops": [ + { + "drops": [ + { + "type": "slime_ball", + "rarity": 24 + } + ], + "blocks": [ + { + "block": "minecraft:grass_block" + }, + { + "block": "minecraft:dark_oak_leaves" + }, + { + "block": "minecraft:short_grass" + }, + { + "block": "minecraft:tall_grass" + } + ] + } + ], + "loot": { + "mode": "FALLBACK", + "multiplier": 0.5, + "tables": [ + "swamp/clutter", + "swamp/food" + ] + }, + "caveProfile": { + "enabled": true, + "verticalRange": { + "min": 6, + "max": 80 + }, + "baseDensityStyle": { + "style": "FRACTAL_SMOKE", + "zoom": 0.45 + }, + "detailDensityStyle": { + "style": "SIMPLEX", + "zoom": 0.5 + }, + "warpStyle": { + "style": "SIMPLEX", + "zoom": 0.5 + }, + "baseWeight": 1, + "detailWeight": 0, + "warpStrength": 0, + "densityThreshold": { + "min": -0.14, + "max": -0.06, + "style": { + "style": "SIMPLEX", + "zoom": 0.5 + } + }, + "thresholdBias": 0.06, + "sampleStep": 3, + "surfaceClearance": 12, + "allowSurfaceBreak": false, + "surfaceBreakStyle": { + "style": "SIMPLEX", + "zoom": 0.88 + }, + "surfaceBreakNoiseThreshold": 0.99, + "surfaceBreakDepth": 4, + "surfaceBreakThresholdBoost": 0.02, + "objectMinDepthBelowSurface": 14, + "defaultObjectAnchor": "FLOOR", + "defaultObjectPlaceMode": "ORGANIC_STILT", + "anchorScanStep": 1, + "anchorSearchAttempts": 12, + "allowFluid": true, + "fluidMinDepthBelowSurface": 20, + "fluidRequiresFloor": true, + "allowLava": true, + "modules": [] + }, + "caveBiomeZoom": 3.2, + "entitySpawners": [ + "swamp/cave", + "swamp/hostile", + "swamp/passive", + "swamp/water" + ] +} diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/terralost.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/terralost.json new file mode 100644 index 000000000..0623df194 --- /dev/null +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/regions/terralost.json @@ -0,0 +1,96 @@ +{ + "name": "Terralost", + "color": "#446600", + "rarity": 5, + "landBiomes": [ + "terralost/amethyst-rainforest", + "terralost/ancient-sands", + "terralost/amethyst-canyon", + "terralost/alpine-grove", + "terralost/alpine-highlands", + "dev" + ], + "landBiomeZoom": 3, + "shoreBiomes": [ + "tundra/shore/beach" + ], + "seaBiomes": [ + "mountain/sea/river" + ], + "shoreHeightMin": 2.2, + "shoreHeightMax": 5.2, + "shoreHeightZoom": 1.14, + "loot": { + "mode": "FALLBACK", + "multiplier": 0.5, + "tables": [ + "tropical/food", + "cave/clutter" + ] + }, + "caveBiomes": [ + "carving/amethyst", + "carving/calcite", + "carving/deepslate", + "carving/deepravine", + "carving/chalk-gardens" + ], + "caveProfile": { + "enabled": true, + "verticalRange": { + "min": 6, + "max": 60 + }, + "baseDensityStyle": { + "style": "SIMPLEX", + "zoom": 0.4 + }, + "detailDensityStyle": { + "style": "SIMPLEX", + "zoom": 0.5 + }, + "warpStyle": { + "style": "SIMPLEX", + "zoom": 0.5 + }, + "baseWeight": 1.0, + "detailWeight": 0.0, + "warpStrength": 0.0, + "densityThreshold": { + "min": -0.16, + "max": -0.08, + "style": { + "style": "SIMPLEX", + "zoom": 0.5 + } + }, + "thresholdBias": 0.12, + "sampleStep": 3, + "surfaceClearance": 12, + "allowSurfaceBreak": false, + "surfaceBreakStyle": { + "style": "SIMPLEX", + "zoom": 0.88 + }, + "surfaceBreakNoiseThreshold": 0.99, + "surfaceBreakDepth": 4, + "surfaceBreakThresholdBoost": 0.02, + "objectMinDepthBelowSurface": 14, + "defaultObjectAnchor": "FLOOR", + "defaultObjectPlaceMode": "ORGANIC_STILT", + "anchorScanStep": 1, + "anchorSearchAttempts": 12, + "allowFluid": true, + "fluidMinDepthBelowSurface": 20, + "fluidRequiresFloor": true, + "allowLava": true, + "modules": [] + }, + "caveBiomeZoom": 3.1, + "entitySpawners": [ + "temperate/cave", + "temperate/hostile", + "temperate/passive", + "temperate/water" + ] +} diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/spawners/mushroom/passive.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/spawners/mushroom/passive.json new file mode 100644 index 000000000..44f7885dc --- /dev/null +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/spawners/mushroom/passive.json @@ -0,0 +1,32 @@ +{ + "group": "NORMAL", + "maximumRate": { + "amount": 15, + "per": {"seconds": 30} + }, + "timeBlock": { + "startHour": 6, + "endHour": 18 + }, + "maxEntitiesPerChunk": 2, + "weather": "NONE", + "spawns": [ + { + "entity": "standard/passive/mooshroom", + "maxSpawns": 3, + "minSpawns": 1, + "rarity": 1 + }, + { + "entity": "standard/passive/cow", + "maxSpawns": 2, + "rarity": 3 + }, + { + "entity": "standard/passive/pig", + "maxSpawns": 2, + "minSpawns": 1, + "rarity": 2 + } + ] +} diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/spawners/tropical/water.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/spawners/tropical/water.json new file mode 100644 index 000000000..1cf0b7732 --- /dev/null +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/spawners/tropical/water.json @@ -0,0 +1,33 @@ +{ + "group": "NORMAL", + "maximumRate": { + "amount": 8, + "per": { "seconds": 30 } + }, + "maxEntitiesPerChunk": 5, + "spawns": [ + { + "entity": "standard/passive/frog", + "maxSpawns": 3, + "minSpawns": 1 + }, + { + "entity": "standard/passive/tadpole", + "maxSpawns": 3, + "minSpawns": 1, + "rarity": 2 + }, + { + "entity": "standard/passive/tropicalfish", + "maxSpawns": 3, + "minSpawns": 1, + "rarity": 2 + }, + { + "entity": "standard/passive/turtle", + "maxSpawns": 3, + "minSpawns": 1, + "rarity": 2 + } + ] +} From 781ff0931d2e517a282dc4a3729da5f704086b50 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 08:51:28 +0200 Subject: [PATCH 07/10] Core stops reading the cave, floating and ore settings Engine.getCaveBiome asks the pack's CaveBiomes service (ModuleServices.overriddenCaveBiome, caveMinDepthBelowSurface) instead of the carving resolver and the biome's field; the State overload is gone and the Bukkit nms biome source stops threading one. ModuleSettings.treeBiomes/usedBiomes feed IrisRegion.getAllBiomes and IrisDimension.getReachableBiomes from LinkedBiomes settings. Tests: decoding of every moved key on the pre-port pack files (OreSettingsDecodingTest, CarveSettingsDecodingTest, FloatingSettingsDecodingTest), CarvingResolverParityTest (was IrisDimensionCarvingResolverParityTest), EngineCaveBiomeTest, CaveBiomeBandsTest, IrisRegionBiomeTreeTest, MovedModuleFieldsTest, the inferred variant keeps its module settings, and the tests that built biomes with the removed fields use module settings --- .../core/nms/v26_2_R1/CustomBiomeSource.java | 33 +- .../core/nms/v26_2_R1/IrisChunkGenerator.java | 4 +- ...IrisChunkGeneratorFailureContractTest.java | 4 +- .../iris/core/modules/ModuleServices.java | 14 + .../iris/core/modules/ModuleSettings.java | 31 + .../arcane/iris/engine/framework/Engine.java | 23 +- .../modules/CarveSettingsDecodingTest.java | 204 +++++++ .../modules/FloatingSettingsDecodingTest.java | 151 +++++ .../engine/framework/EngineCaveBiomeTest.java | 179 ++++++ ...oatingObjectPlacingBoundaryRadiusTest.java | 6 +- .../CaveApplyingBoundarySupportTest.java | 9 +- .../CaveApplyingInferenceIsolationTest.java | 3 - .../engine/modifier/CaveBiomeBandsTest.java | 98 ++++ .../engine/modifier/FloatingIslandsTest.java | 4 +- ...st.java => CarvingResolverParityTest.java} | 286 ++++----- .../FloatingChildBiomeDecodingTest.java | 11 - .../FloatingIslandBoundarySamplerTest.java | 9 +- ...vedFloatingChildCarvingResolutionTest.java | 22 +- .../object/world/MovedModuleFieldsTest.java | 53 ++ .../IrisBiomeInferenceIsolationTest.java | 21 + .../IrisDimensionReachableBiomesTest.java | 71 +-- .../world/region/IrisRegionBiomeTreeTest.java | 73 +++ .../biomes/carving/amethyst.json | 292 ++++++++++ .../biomes/magnetics/plains.json | 551 ++++++++++++++++++ .../pack-before-the-port/regions/forests.json | 107 ++++ .../snippet/cave-profile/shallow.json | 5 + 26 files changed, 1982 insertions(+), 282 deletions(-) create mode 100644 core/src/test/java/art/arcane/iris/core/modules/CarveSettingsDecodingTest.java create mode 100644 core/src/test/java/art/arcane/iris/core/modules/FloatingSettingsDecodingTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/framework/EngineCaveBiomeTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/modifier/CaveBiomeBandsTest.java rename core/src/test/java/art/arcane/iris/engine/object/terrain/carving/{IrisDimensionCarvingResolverParityTest.java => CarvingResolverParityTest.java} (59%) create mode 100644 core/src/test/java/art/arcane/iris/engine/object/world/MovedModuleFieldsTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/object/world/region/IrisRegionBiomeTreeTest.java create mode 100644 core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/biomes/carving/amethyst.json create mode 100644 core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/biomes/magnetics/plains.json create mode 100644 core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/regions/forests.json create mode 100644 core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/snippet/cave-profile/shallow.json diff --git a/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/CustomBiomeSource.java b/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/CustomBiomeSource.java index 9b2f8e6b2..7003cc9b0 100644 --- a/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/CustomBiomeSource.java +++ b/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/CustomBiomeSource.java @@ -11,7 +11,6 @@ import art.arcane.iris.engine.framework.GenerationSessionException; import art.arcane.iris.engine.framework.GenerationSessionLease; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; import art.arcane.iris.util.project.context.IrisContext; import art.arcane.volmlib.util.collection.KMap; import art.arcane.volmlib.util.math.RNG; @@ -440,16 +439,6 @@ public class CustomBiomeSource extends BiomeSource { int y, int z, Climate.Sampler sampler - ) { - return getVisibleNoiseBiomeWithActiveGenerationLease(x, y, z, sampler, null); - } - - Holder getVisibleNoiseBiomeWithActiveGenerationLease( - int x, - int y, - int z, - Climate.Sampler sampler, - IrisDimensionCarvingResolver.State resolverState ) { long cacheKey = packNoiseKey(x, y, z); Holder cachedHolder = noiseBiomeCache.get(cacheKey); @@ -457,7 +446,7 @@ public class CustomBiomeSource extends BiomeSource { return cachedHolder; } - Holder resolvedHolder = resolveVisibleBiomeHolder(x, y, z, resolverState); + Holder resolvedHolder = resolveVisibleBiomeHolder(x, y, z); Holder existingHolder = noiseBiomeCache.putIfAbsent(cacheKey, resolvedHolder); if (existingHolder != null) { return existingHolder; @@ -530,13 +519,8 @@ public class CustomBiomeSource extends BiomeSource { return holder; } - private Holder resolveVisibleBiomeHolder( - int x, - int y, - int z, - IrisDimensionCarvingResolver.State resolverState - ) { - BiomeResolution resolution = resolveBiomeResolution(x, y, z, resolverState); + private Holder resolveVisibleBiomeHolder(int x, int y, int z) { + BiomeResolution resolution = resolveBiomeResolution(x, y, z); if (resolution == null) { return getFallbackBiome(); } @@ -569,15 +553,6 @@ public class CustomBiomeSource extends BiomeSource { } private BiomeResolution resolveBiomeResolution(int x, int y, int z) { - return resolveBiomeResolution(x, y, z, null); - } - - private BiomeResolution resolveBiomeResolution( - int x, - int y, - int z, - IrisDimensionCarvingResolver.State resolverState - ) { if (engine == null || engine.isClosed()) { return null; } @@ -599,7 +574,7 @@ public class CustomBiomeSource extends BiomeSource { int surfaceInternalY = engine.getComplex().getHeightStream().get(blockX, blockZ).intValue(); underground = internalY <= surfaceInternalY - 8; irisBiome = underground - ? engine.getCaveBiome(blockX, internalY, blockZ, resolverState) + ? engine.getCaveBiome(blockX, internalY, blockZ) : engine.getComplex().getTrueBiomeStream().get(blockX, blockZ); } else { irisBiome = engine.getComplex().getTrueBiomeStream().get(blockX, blockZ); diff --git a/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/IrisChunkGenerator.java b/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/IrisChunkGenerator.java index dcb04a573..49e0ee94d 100644 --- a/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/IrisChunkGenerator.java +++ b/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/IrisChunkGenerator.java @@ -12,7 +12,6 @@ import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting; import art.arcane.iris.engine.IrisEngine; import art.arcane.iris.engine.platform.BukkitChunkGenerator; import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; import art.arcane.iris.nativegen.NativeStructureFitBridge; import art.arcane.iris.nativegen.NativeStructureGenerationException; import art.arcane.iris.nativegen.NativeStructureStartInjector; @@ -634,10 +633,9 @@ public class IrisChunkGenerator extends CustomChunkGenerator { GenerationSessionLease lease = requireGenerationLease("bukkit_nms_create_biomes"); IrisContext.Scope ignored = IrisContext.open(engine, lease.sessionId(), null)) { customBiomeSource.prepareVisibleBiomeBatch(); - IrisDimensionCarvingResolver.State resolverState = new IrisDimensionCarvingResolver.State(); ichunkaccess.fillBiomesFromNoise( (x, y, z, sampler) -> customBiomeSource.getVisibleNoiseBiomeWithActiveGenerationLease( - x, y, z, sampler, resolverState), + x, y, z, sampler), randomstate.sampler()); return CompletableFuture.completedFuture(ichunkaccess); } diff --git a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/nms/v26_2_R1/IrisChunkGeneratorFailureContractTest.java b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/nms/v26_2_R1/IrisChunkGeneratorFailureContractTest.java index 3f25b21a4..a38b3448f 100644 --- a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/nms/v26_2_R1/IrisChunkGeneratorFailureContractTest.java +++ b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/nms/v26_2_R1/IrisChunkGeneratorFailureContractTest.java @@ -1,6 +1,5 @@ package art.arcane.iris.core.nms.v26_2_R1; -import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; import org.junit.Test; import java.io.IOException; @@ -257,8 +256,7 @@ public class IrisChunkGeneratorFailureContractTest { assertTrue(createBiomes.contains("requireGenerationStage(\"bukkit_nms_create_biomes\")")); assertTrue(createBiomes.contains("customBiomeSource.prepareVisibleBiomeBatch()")); - assertTrue(createBiomes.contains("new IrisDimensionCarvingResolver.State()")); - assertTrue(createBiomes.contains("sampler, resolverState")); + assertTrue(createBiomes.contains("getVisibleNoiseBiomeWithActiveGenerationLease(")); assertTrue(buildSurface.contains("delegate.buildSurface(")); assertTrue(carvers.contains("delegate.applyCarvers(")); assertTrue(noise.contains("requireNoiseGenerationStage(")); diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleServices.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleServices.java index 0967cd1b9..d078c20a8 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleServices.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleServices.java @@ -24,6 +24,7 @@ import com.volmit.host.FeatureCatalog; import com.volmit.entity.EntitySpec; import com.volmit.item.ItemDrop; import com.volmit.service.BlockDrops; +import com.volmit.service.CaveBiomes; import com.volmit.service.EntitySpawns; import com.volmit.service.LocateResult; import com.volmit.service.Loot; @@ -47,6 +48,19 @@ public final class ModuleServices { private ModuleServices() { } + /** The pack biome key the module that decides cave biomes puts at the position, whatever the regions say; empty where it overrides nothing. {@code y} is the height above the dimension's bottom. */ + public static Optional overriddenCaveBiome(Engine engine, int x, int y, int z) { + return catalog(engine.getData()).service(CaveBiomes.class) + .flatMap(provider -> provider.overriddenBiome(engine.getGeneration().world(), x, y, z)); + } + + /** How many blocks below the surface the caves of the pack biome {@code biomeKey} begin; 0 where nothing limits them. */ + public static int caveMinDepthBelowSurface(Engine engine, String biomeKey) { + return catalog(engine.getData()).service(CaveBiomes.class) + .map(provider -> provider.minDepthBelowSurface(engine.getGeneration().world(), biomeKey)) + .orElse(0); + } + /** The objects every module would place in the chunk at {@code chunkX}, {@code chunkZ}, guessed without generating it. */ public static Set objectsAt(Engine engine, int chunkX, int chunkZ) { PackWorld world = engine.getGeneration().world(); diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleSettings.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleSettings.java index 1f99ad251..9496089f5 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleSettings.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleSettings.java @@ -19,12 +19,17 @@ package art.arcane.iris.core.modules; import com.volmit.IrisFeature; +import com.volmit.config.LinkedBiomes; import com.volmit.host.ConfiguredSettings; import com.volmit.resource.ResourceId; import java.util.Collection; +import java.util.Comparator; +import java.util.LinkedHashSet; import java.util.Map; import java.util.Optional; +import java.util.Set; +import java.util.function.Function; /** * Module settings one dimension, region, biome or object placement declares, at most one value per settings @@ -55,6 +60,32 @@ public final class ModuleSettings { return values.isEmpty(); } + /** The biomes these settings add to the biome tree of the owner's regions ({@link LinkedBiomes#treeBiomes}), in a fixed order. */ + public Set treeBiomes() { + return linkedBiomes(LinkedBiomes::treeBiomes); + } + + /** + * The biomes these settings use besides ({@link LinkedBiomes#usedBiomes}), in a fixed order. + * + * @param dimension the settings of the dimension the owner is part of + */ + public Set usedBiomes(ModuleSettings dimension) { + return linkedBiomes(linked -> linked.usedBiomes(dimension.values())); + } + + private Set linkedBiomes(Function> pick) { + if (values.isEmpty()) { + return Set.of(); + } + Set biomes = new LinkedHashSet<>(); + values.values().stream() + .filter(LinkedBiomes.class::isInstance) + .sorted(Comparator.comparing(value -> value.getClass().getName())) + .forEach(value -> biomes.addAll(pick.apply((LinkedBiomes) value))); + return biomes; + } + /** These settings as one placement's own, declared by {@code source}. */ public ConfiguredSettings placement(ResourceId source) { return isEmpty() ? ConfiguredSettings.none() : ConfiguredSettings.placement(source, values.values().toArray(IrisFeature[]::new)); diff --git a/core/src/main/java/art/arcane/iris/engine/framework/Engine.java b/core/src/main/java/art/arcane/iris/engine/framework/Engine.java index 5360568fc..21fb1668d 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/Engine.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/Engine.java @@ -28,6 +28,7 @@ import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.IrisRegistrant; import art.arcane.iris.core.nms.container.BlockPos; import art.arcane.iris.core.nms.container.Pair; +import art.arcane.iris.core.modules.ModuleServices; import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.UpperDimensionContext; import art.arcane.iris.engine.data.chunk.TerrainChunk; @@ -35,8 +36,6 @@ import art.arcane.iris.engine.mantle.EngineMantle; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.value.IrisColor; import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingEntry; -import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; import art.arcane.iris.engine.object.runtime.IrisEngineData; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.value.IrisPosition; @@ -72,6 +71,7 @@ import org.jetbrains.annotations.Nullable; import java.awt.Color; import java.util.Locale; +import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -276,20 +276,11 @@ public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer, @BlockCoordinates default IrisBiome getCaveBiome(int x, int y, int z) { - return getCaveBiome(x, y, z, null); - } - - @BlockCoordinates - default IrisBiome getCaveBiome(int x, int y, int z, IrisDimensionCarvingResolver.State state) { IrisBiome surfaceBiome = getSurfaceBiome(x, z); - int worldY = y + getWorld().minHeight(); - IrisDimensionCarvingEntry rootCarvingEntry = IrisDimensionCarvingResolver.resolveRootEntry(this, worldY, state); - if (rootCarvingEntry != null) { - IrisDimensionCarvingEntry resolvedCarvingEntry = IrisDimensionCarvingResolver.resolveFromRoot(this, rootCarvingEntry, x, z, state); - IrisBiome resolvedCarvingBiome = IrisDimensionCarvingResolver.resolveEntryBiome(this, resolvedCarvingEntry, state); - if (resolvedCarvingBiome != null) { - return resolvedCarvingBiome; - } + Optional overriddenKey = ModuleServices.overriddenCaveBiome(this, x, y, z); + IrisBiome overriddenBiome = overriddenKey.map(key -> getData().getBiomeLoader().load(key)).orElse(null); + if (overriddenBiome != null) { + return overriddenBiome; } IrisBiome caveBiome = getCaveBiome(x, z); @@ -303,7 +294,7 @@ public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer, return surfaceBiome; } - int minDepth = Math.max(0, caveBiome.getCaveMinDepthBelowSurface()); + int minDepth = Math.max(0, ModuleServices.caveMinDepthBelowSurface(this, caveBiome.getLoadKey())); if (depthBelowSurface < minDepth) { return surfaceBiome; } diff --git a/core/src/test/java/art/arcane/iris/core/modules/CarveSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/CarveSettingsDecodingTest.java new file mode 100644 index 000000000..f133ccaf2 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/modules/CarveSettingsDecodingTest.java @@ -0,0 +1,204 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.modules; + +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.carve.CarvingBiomeSettings; +import art.arcane.iris.builtin.carve.CarvingEnabledSettings; +import art.arcane.iris.builtin.carve.CarvingEntry; +import art.arcane.iris.builtin.carve.CarvingSettings; +import art.arcane.iris.builtin.carve.CaveDepthSettings; +import art.arcane.iris.builtin.carve.CaveProfile; +import art.arcane.volmlib.util.json.JSONObject; +import com.google.gson.Gson; +import com.volmit.FeatureAttachment.Target; +import com.volmit.host.LoadedPack; +import com.volmit.host.ModuleHost; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * The cave settings packs have always written, read by the carve module under their old keys: {@code caveProfile} (an object at a + * dimension, region or biome), {@code carving} and {@code carvingEnabled} (a list and a boolean at a dimension), {@code carvingBiome} and + * {@code caveMinDepthBelowSurface} (a biome key and a number at a biome). The dimension, region and biome are files of the overworld pack + * as they were before the port. + */ +public class CarveSettingsDecodingTest { + private static final String PACK = "/art/arcane/iris/core/modules/pack-before-the-port"; + + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + + private Path packFolder; + private LoadedPack pack; + private ModuleSettingsDecoder decoder; + + @Before + public void loadBuiltIns() throws IOException, URISyntaxException { + packFolder = Path.of(CarveSettingsDecodingTest.class.getResource(PACK).toURI()); + pack = LoadedPack.load(packFolder, ModuleHost.of(IrisModuleHost.builtInModules()) + .reservingFields(ModuleTargets.reservedFields()) + .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGE).copyingJarsTo(folder.newFolder("copies").toPath())); + decoder = new ModuleSettingsDecoder(pack.catalog(), packFolder, Gson::new); + } + + @After + public void closePack() { + pack.close(); + } + + @Test + public void theOverworldReadsItsCaveProfileItsCarvingBandsAndCarvingEnabled() throws IOException { + ModuleSettings settings = decoder.decode(Target.DIMENSION, file("dimensions/overworld.json"), "dimension overworld"); + + CaveProfile profile = settings.find(CaveProfile.class).orElseThrow(); + assertTrue(profile.enabled()); + assertEquals(6, profile.verticalRange().min(), 0); + assertEquals(700, profile.verticalRange().max(), 0); + assertEquals("PERLIN_IRIS", profile.baseDensityStyle().style()); + assertEquals(0.72, profile.baseDensityStyle().zoom(), 0); + assertEquals("FRACTAL_WATER", profile.warpStyle().style()); + assertEquals(-0.14, profile.densityThreshold().min(), 0); + assertEquals(3, profile.sampleStep()); + assertEquals(5, profile.surfaceClearance()); + assertEquals(14, profile.objectMinDepthBelowSurface()); + assertEquals(ObjectPlaceMode.ORGANIC_STILT, profile.defaultObjectPlaceMode().orElseThrow()); + assertEquals(2, profile.modules().size()); + assertTrue(profile.modules().get(1).invert()); + assertEquals(240, profile.modules().get(1).verticalRange().max(), 0); + + List bands = settings.find(CarvingSettings.class).orElseThrow().entries(); + assertEquals(1, bands.size()); + assertEquals("global-deepdark-band", bands.getFirst().id()); + assertTrue(bands.getFirst().enabled()); + assertEquals("carving/standard-deepdark", bands.getFirst().biome()); + assertEquals(-250, bands.getFirst().worldYRange().min(), 0); + assertEquals(-175, bands.getFirst().worldYRange().max(), 0); + assertEquals("a band that writes no children keeps Iris's defaults", 3, bands.getFirst().childRecursionDepth()); + assertEquals(1.5, bands.getFirst().childShrinkFactor(), 0); + assertEquals("CELLULAR_IRIS_DOUBLE", bands.getFirst().childStyle().style()); + + assertTrue(settings.find(CarvingEnabledSettings.class).orElseThrow().enabled()); + } + + @Test + public void aRegionReadsItsCaveProfile() throws IOException { + JSONObject region = file("regions/forests.json"); + + CaveProfile profile = decoder.decode(Target.REGION, region, "region forests").find(CaveProfile.class).orElseThrow(); + + assertTrue(profile.enabled()); + assertEquals(6, profile.verticalRange().min(), 0); + assertEquals(120, profile.verticalRange().max(), 0); + assertEquals(1, profile.baseWeight(), 0); + assertEquals(3, profile.sampleStep()); + } + + @Test + public void aBiomeReadsItsCaveProfileAndItsMinimumDepth() throws IOException { + JSONObject biome = file("biomes/carving/amethyst.json"); + + ModuleSettings settings = decoder.decode(Target.BIOME, biome, "biome carving/amethyst"); + + CaveProfile profile = settings.find(CaveProfile.class).orElseThrow(); + assertTrue(profile.enabled()); + assertEquals(620, profile.verticalRange().max(), 0); + assertEquals(0.91, profile.baseWeight(), 0); + assertEquals(2, profile.sampleStep()); + assertEquals(biome.getInt("caveMinDepthBelowSurface"), settings.find(CaveDepthSettings.class).orElseThrow().depth()); + assertEquals(10, settings.find(CaveDepthSettings.class).orElseThrow().depth()); + assertTrue("the biome writes no carvingBiome", settings.find(CarvingBiomeSettings.class).isEmpty()); + } + + @Test + public void aCaveProfileMayBeWrittenAsASnippetReference() { + ModuleSettings settings = decoder.decode(Target.BIOME, new JSONObject("{\"caveProfile\": \"snippet/cave-profile/shallow\"}"), "biome test"); + + CaveProfile profile = settings.find(CaveProfile.class).orElseThrow(); + assertTrue(profile.enabled()); + assertEquals(100, profile.verticalRange().max(), 0); + assertEquals(2, profile.sampleStep()); + } + + @Test + public void carvingBandsReadChildrenAndTheirOptions() { + JSONObject json = new JSONObject(""" + {"carving": [ + {"id": "deep", "biome": "carving/deep", "worldYRange": {"min": -64, "max": 0}, "childShrinkFactor": 2, "childRecursionDepth": 5, + "children": ["lush", " moss "], "childStyle": {"style": "SIMPLEX", "zoom": 3}}, + {"id": "off", "enabled": false, "biome": "carving/off"}, + {} + ], "carvingEnabled": false} + """); + + ModuleSettings settings = decoder.decode(Target.DIMENSION, json, "dimension test"); + + List bands = settings.find(CarvingSettings.class).orElseThrow().entries(); + assertEquals(3, bands.size()); + assertEquals(List.of("lush", " moss "), bands.getFirst().children()); + assertEquals(2, bands.getFirst().childShrinkFactor(), 0); + assertEquals(5, bands.getFirst().childRecursionDepth()); + assertEquals("SIMPLEX", bands.getFirst().childStyle().style()); + assertFalse(bands.get(1).enabled()); + assertEquals("an empty band keeps Iris's defaults", -64, bands.get(2).worldYRange().min(), 0); + assertEquals(320, bands.get(2).worldYRange().max(), 0); + assertTrue(bands.get(2).enabled()); + assertFalse(settings.find(CarvingEnabledSettings.class).orElseThrow().enabled()); + CarvingSettings carving = settings.find(CarvingSettings.class).orElseThrow(); + assertEquals("a band id stands for its biome", "carving/off", carving.biomeOf("off")); + assertEquals("anything else stands for itself", "carving/mushroom", carving.biomeOf("carving/mushroom")); + } + + @Test + public void carvingBiomeIsABiomeKeyAndRegistersItWithTheBiomeTree() { + ModuleSettings settings = decoder.decode(Target.BIOME, new JSONObject("{\"carvingBiome\": \"carving/mushroom\"}"), "biome test"); + + assertEquals("carving/mushroom", settings.find(CarvingBiomeSettings.class).orElseThrow().biome()); + assertEquals(Set.of("carving/mushroom"), settings.treeBiomes()); + assertEquals(Set.of(), settings.usedBiomes(ModuleSettings.NONE)); + } + + @Test + public void everyKeyIsOnlyReadAtTheLevelsTheOldFieldExistedAt() { + assertTrue(decoder.keys(Target.DIMENSION).containsAll(List.of("caveProfile", "carving", "carvingEnabled"))); + assertTrue(decoder.keys(Target.REGION).contains("caveProfile")); + assertTrue(decoder.keys(Target.BIOME).containsAll(List.of("caveProfile", "carvingBiome", "caveMinDepthBelowSurface"))); + assertFalse(decoder.keys(Target.REGION).contains("carving")); + assertFalse(decoder.keys(Target.DIMENSION).contains("carvingBiome")); + assertFalse(decoder.keys(Target.DIMENSION).contains("caveMinDepthBelowSurface")); + } + + private JSONObject file(String name) throws IOException { + return new JSONObject(Files.readString(packFolder.resolve(name))); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/modules/FloatingSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/FloatingSettingsDecodingTest.java new file mode 100644 index 000000000..13c5c30c7 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/modules/FloatingSettingsDecodingTest.java @@ -0,0 +1,151 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.modules; + +import art.arcane.iris.builtin.carve.CarvingEntry; +import art.arcane.iris.builtin.carve.CarvingSettings; +import art.arcane.iris.builtin.floating.FloatingBottomPaletteMode; +import art.arcane.iris.builtin.floating.FloatingChildBiome; +import art.arcane.iris.builtin.floating.FloatingChildSettings; +import art.arcane.iris.builtin.floating.MergeFloatingChildrenSettings; +import art.arcane.iris.builtin.floating.TopShapeMode; +import art.arcane.volmlib.util.json.JSONObject; +import com.google.gson.Gson; +import com.volmit.FeatureAttachment.Target; +import com.volmit.host.LoadedPack; +import com.volmit.host.ModuleHost; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * The floating island settings packs have always written, read by the floating module under their old keys: {@code floatingChildBiomes} + * (a list) and {@code mergeFloatingChildBiomes} (a boolean), both at a biome. The biome is a file of the overworld pack as it was before + * the port. + */ +public class FloatingSettingsDecodingTest { + private static final String PACK = "/art/arcane/iris/core/modules/pack-before-the-port"; + + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + + private Path packFolder; + private LoadedPack pack; + private ModuleSettingsDecoder decoder; + + @Before + public void loadBuiltIns() throws IOException, URISyntaxException { + packFolder = Path.of(FloatingSettingsDecodingTest.class.getResource(PACK).toURI()); + pack = LoadedPack.load(packFolder, ModuleHost.of(IrisModuleHost.builtInModules()) + .reservingFields(ModuleTargets.reservedFields()) + .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGE).copyingJarsTo(folder.newFolder("copies").toPath())); + decoder = new ModuleSettingsDecoder(pack.catalog(), packFolder, Gson::new); + } + + @After + public void closePack() { + pack.close(); + } + + @Test + public void aBiomeReadsItsFloatingChildrenAndTheMergeFlag() throws IOException { + JSONObject biome = file("biomes/magnetics/plains.json"); + + ModuleSettings settings = decoder.decode(Target.BIOME, biome, "biome magnetics/plains"); + + List children = settings.find(FloatingChildSettings.class).orElseThrow().children(); + assertEquals(biome.getJSONArray("floatingChildBiomes").length(), children.size()); + assertEquals(2, children.size()); + FloatingChildBiome mushroom = children.getFirst(); + assertEquals("mushroom/forest", mushroom.biome()); + assertEquals("carving/mushroom", mushroom.carving()); + assertEquals(1, mushroom.rarity()); + assertEquals(115, mushroom.minHeightAboveSurface()); + assertEquals(155, mushroom.maxHeightAboveSurface()); + assertEquals(TopShapeMode.NOISE, mushroom.topShapeMode()); + assertEquals("GLOB_IRIS_THICK", mushroom.footprintStyle().style()); + assertEquals(0.47, mushroom.footprintThreshold(), 0); + assertEquals(FloatingBottomPaletteMode.CUSTOM, mushroom.bottomPaletteMode()); + assertEquals(1, mushroom.bottomPalette().size()); + assertEquals(0.5, mushroom.objectShrinkFactor(), 0); + assertEquals("tropical/wilds", children.get(1).biome()); + assertEquals("carving/lush-child", children.get(1).carving()); + assertEquals(biome.getBoolean("mergeFloatingChildBiomes"), settings.find(MergeFloatingChildrenSettings.class).orElseThrow().merge()); + assertTrue(settings.find(MergeFloatingChildrenSettings.class).orElseThrow().merge()); + } + + @Test + public void aBiomeWithoutFloatingChildrenDeclaresNone() { + ModuleSettings settings = decoder.decode(Target.BIOME, new JSONObject("{\"mergeFloatingChildBiomes\": false, \"floatingChildBiomes\": [{}]}"), "biome test"); + + assertFalse(settings.find(MergeFloatingChildrenSettings.class).orElseThrow().merge()); + assertEquals(1, settings.find(FloatingChildSettings.class).orElseThrow().children().size()); + assertEquals("an empty child keeps Iris's defaults", 160, settings.find(FloatingChildSettings.class).orElseThrow().children().getFirst().minHeightAboveSurface()); + assertTrue(decoder.decode(Target.BIOME, new JSONObject("{}"), "biome test").isEmpty()); + } + + @Test + public void theTargetAndTheCarvingOfEveryChildAreBiomesTheDimensionUses() throws IOException { + JSONObject biome = file("biomes/magnetics/plains.json"); + ModuleSettings biomeSettings = decoder.decode(Target.BIOME, biome, "biome magnetics/plains"); + ModuleSettings dimensionSettings = decoder.decode(Target.DIMENSION, file("dimensions/overworld.json"), "dimension overworld"); + + Set used = biomeSettings.usedBiomes(dimensionSettings); + + assertEquals(new LinkedHashSet<>(List.of("mushroom/forest", "carving/mushroom", "tropical/wilds", "carving/lush-child")), used); + assertEquals(Set.of(), biomeSettings.treeBiomes()); + } + + @Test + public void aCarvingNamingABandStandsForTheBandsBiome() { + FloatingChildBiome child = new Gson().fromJson("{\"biome\": \"floating/target\", \"carving\": \"deep\"}", FloatingChildBiome.class); + CarvingEntry band = new Gson().fromJson("{\"id\": \"deep\", \"enabled\": false, \"biome\": \"carving/deep\"}", CarvingEntry.class); + ModuleSettings biomeSettings = BuiltInPack.settings(new FloatingChildSettings(List.of(child))); + ModuleSettings dimensionSettings = BuiltInPack.settings(new CarvingSettings(List.of(band))); + + assertEquals(new LinkedHashSet<>(List.of("floating/target", "carving/deep")), biomeSettings.usedBiomes(dimensionSettings)); + assertEquals("without bands the name is taken as a biome key", new LinkedHashSet<>(List.of("floating/target", "deep")), + biomeSettings.usedBiomes(ModuleSettings.NONE)); + } + + @Test + public void bothKeysAreOnlyReadAtBiomes() { + assertTrue(decoder.keys(Target.BIOME).containsAll(List.of("floatingChildBiomes", "mergeFloatingChildBiomes"))); + assertFalse(decoder.keys(Target.REGION).contains("floatingChildBiomes")); + assertFalse(decoder.keys(Target.DIMENSION).contains("mergeFloatingChildBiomes")); + } + + private JSONObject file(String name) throws IOException { + return new JSONObject(Files.readString(packFolder.resolve(name))); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/framework/EngineCaveBiomeTest.java b/core/src/test/java/art/arcane/iris/engine/framework/EngineCaveBiomeTest.java new file mode 100644 index 000000000..168935504 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/framework/EngineCaveBiomeTest.java @@ -0,0 +1,179 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.framework; + +import art.arcane.iris.builtin.carve.CaveDepthSettings; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.loader.ResourceLoader; +import art.arcane.iris.core.modules.BuiltInPack; +import art.arcane.iris.core.modules.ModuleResourceFixture; +import art.arcane.iris.engine.IrisComplex; +import art.arcane.iris.engine.decorator.DecoratorTestEngines; +import art.arcane.iris.engine.object.world.IrisWorld; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.modifier.CaveBiomeBands; +import art.arcane.iris.util.project.stream.ProceduralStream; +import com.volmit.FeatureRegistry; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.service.CaveBiomes; +import com.volmit.stage.StageGraph; +import com.volmit.world.PackWorld; +import org.junit.Before; +import org.junit.Test; + +import java.util.Optional; + +import static org.junit.Assert.assertSame; +import static org.mockito.ArgumentMatchers.anyDouble; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * The cave biome of a position: the biome a module overrides it with, else the cave biome of the column unless the surface is nearer than that + * biome's caves begin, else the surface biome. The overrides and the depths come from the pack's {@link CaveBiomes} provider. + */ +public class EngineCaveBiomeTest { + private static final int MIN_HEIGHT = -64; + private static final int SURFACE_Y = 100; + + private final IrisBiome surface = mock(IrisBiome.class); + private final IrisBiome cave = mock(IrisBiome.class); + private final IrisBiome band = mock(IrisBiome.class); + private IrisData data; + private Engine engine; + + private static final class CavesModule implements IrisModule { + private final CaveBiomes provider; + + private CavesModule(CaveBiomes provider) { + this.provider = provider; + } + + @Override + public ModuleInfo info() { + return ModuleInfo.of("test:caves", "Caves", "test"); + } + + @Override + public void register(FeatureRegistry registry) { + registry.registerService(CaveBiomes.class, provider); + } + + @Override + public void install(StageGraph graph) { + } + } + + @Before + @SuppressWarnings("unchecked") + public void mockEngine() { + data = mock(IrisData.class); + ResourceLoader biomes = mock(ResourceLoader.class); + when(data.getBiomeLoader()).thenReturn(biomes); + when(biomes.load("band/deep")).thenReturn(band); + when(biomes.load("cave/lush")).thenReturn(cave); + when(cave.getLoadKey()).thenReturn("cave/lush"); + engine = mock(Engine.class, CALLS_REAL_METHODS); + doReturn(data).when(engine).getData(); + doReturn(IrisWorld.builder().minHeight(MIN_HEIGHT).maxHeight(320).build()).when(engine).getWorld(); + doReturn(surface).when(engine).getSurfaceBiome(anyInt(), anyInt()); + doReturn(cave).when(engine).getCaveBiome(anyInt(), anyInt()); + IrisComplex complex = mock(IrisComplex.class); + @SuppressWarnings("unchecked") + ProceduralStream heights = mock(ProceduralStream.class); + when(heights.get(anyDouble(), anyDouble())).thenReturn((double) SURFACE_Y); + when(complex.getHeightStream()).thenReturn(heights); + doReturn(complex).when(engine).getComplex(); + DecoratorTestEngines.withGeneration(engine); + } + + private void serve(CaveBiomes provider) { + ModuleResourceFixture.serveModules(data, new CavesModule(provider)); + } + + private CaveBiomes caves(String overridden, int minDepth) { + return new CaveBiomes() { + @Override + public Optional overriddenBiome(PackWorld world, int x, int y, int z) { + return Optional.ofNullable(overridden); + } + + @Override + public int minDepthBelowSurface(PackWorld world, String biomeKey) { + return biomeKey.equals("cave/lush") ? minDepth : 0; + } + }; + } + + @Test + public void aBiomeTheModuleOverridesWithWinsEverywhere() { + serve(caves("band/deep", 40)); + + assertSame(band, engine.getCaveBiome(10, 0, 20)); + assertSame(band, engine.getCaveBiome(10, SURFACE_Y + 30, 20)); + } + + @Test + public void anOverrideNamingNoBiomeLeavesTheColumnsCaveBiome() { + serve(caves("band/missing", 0)); + + assertSame(cave, engine.getCaveBiome(10, 10, 20)); + } + + @Test + public void theSurfaceBiomeHoldsAtAndAboveTheSurfaceAndWithinTheCaveBiomesMinimumDepth() { + serve(caves(null, 10)); + + assertSame("above the surface", surface, engine.getCaveBiome(10, SURFACE_Y + 1, 20)); + assertSame("at the surface", surface, engine.getCaveBiome(10, SURFACE_Y, 20)); + assertSame("nearer the surface than the caves begin", surface, engine.getCaveBiome(10, SURFACE_Y - 9, 20)); + assertSame("where the caves begin", cave, engine.getCaveBiome(10, SURFACE_Y - 10, 20)); + assertSame("deeper", cave, engine.getCaveBiome(10, 3, 20)); + } + + @Test + public void aColumnWithoutACaveBiomeHasTheSurfaceBiome() { + serve(caves(null, 0)); + doReturn(null).when(engine).getCaveBiome(anyInt(), anyInt()); + + assertSame(surface, engine.getCaveBiome(10, 3, 20)); + } + + @Test + public void aPackWithoutACaveBiomeProviderOverridesNothingAndLimitsNoDepth() { + ModuleResourceFixture.serveModules(data); + + assertSame(cave, engine.getCaveBiome(10, SURFACE_Y - 1, 20)); + } + + @Test + public void theCarveModulesProviderReadsTheDepthFromTheBiomesSettings() { + IrisBiome deep = mock(IrisBiome.class); + when(deep.getModuleSettings()).thenReturn(BuiltInPack.settings(new CaveDepthSettings(25))); + IrisBiome plain = mock(IrisBiome.class); + when(plain.getModuleSettings()).thenReturn(BuiltInPack.settings()); + + org.junit.Assert.assertEquals(25, CaveBiomeBands.minDepthBelowSurface(deep)); + org.junit.Assert.assertEquals(0, CaveBiomeBands.minDepthBelowSurface(plain)); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacingBoundaryRadiusTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacingBoundaryRadiusTest.java index 8dcefee7c..b2b8acba9 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacingBoundaryRadiusTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacingBoundaryRadiusTest.java @@ -18,6 +18,8 @@ package art.arcane.iris.engine.mantle.components; +import art.arcane.iris.core.modules.BuiltInPack; +import art.arcane.iris.builtin.floating.FloatingChildSettings; import art.arcane.iris.engine.framework.EngineGeneration; import art.arcane.iris.engine.object.TestSettings; import art.arcane.iris.builtin.floating.FloatingChildBiome; @@ -44,6 +46,7 @@ import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.util.HashMap; +import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; @@ -96,7 +99,8 @@ public class FloatingObjectPlacingBoundaryRadiusTest { .setPlace(new KList<>("test/floating")) .setTranslate(new IrisObjectTranslate().setX(32)); FloatingChildBiome floatingChild = TestSettings.with(new FloatingChildBiome(), "floatingObjects", new KList<>(placement)); - IrisBiome biome = new IrisBiome().setFloatingChildBiomes(new KList<>(floatingChild)); + IrisBiome biome = new IrisBiome(); + biome.setModuleSettings(BuiltInPack.settings(new FloatingChildSettings(List.of(floatingChild)))); IrisDimension dimension = mock(IrisDimension.class); when(dimension.getReachableBiomes(org.mockito.ArgumentMatchers.any())).thenReturn(new KList<>(biome)); diff --git a/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingBoundarySupportTest.java b/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingBoundarySupportTest.java index a42912658..f76f9edad 100644 --- a/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingBoundarySupportTest.java +++ b/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingBoundarySupportTest.java @@ -7,7 +7,6 @@ import art.arcane.iris.engine.decorator.DecoratorTestEngines; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.SeedManager; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.project.hunk.Hunk; import art.arcane.volmlib.util.mantle.runtime.MantleChunk; @@ -25,7 +24,6 @@ import java.util.Map; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; @@ -54,7 +52,7 @@ public class CaveApplyingBoundarySupportTest { Engine engine = mock(Engine.class); doReturn(data).when(engine).getData(); - doReturn(resolvedCeiling).when(engine).getCaveBiome(anyInt(), eq(42), anyInt(), any(IrisDimensionCarvingResolver.State.class)); + doReturn(resolvedCeiling).when(engine).getCaveBiome(anyInt(), eq(42), anyInt()); doReturn(mock(SeedManager.class)).when(engine).getSeedManager(); DecoratorTestEngines.withGeneration(engine); @@ -78,12 +76,11 @@ public class CaveApplyingBoundarySupportTest { Long2ObjectOpenHashMap caveBiomeCache = new Long2ObjectOpenHashMap<>(); Map customBiomeCache = new HashMap<>(); - IrisDimensionCarvingResolver.State resolverState = new IrisDimensionCarvingResolver.State(); IrisBiome floor = modifier.resolveCaveBoundaryBiome( - mantleChunk, 1, 6, 2, 40, 44, resolverState, caveBiomeCache, customBiomeCache); + mantleChunk, 1, 6, 2, 40, 44, caveBiomeCache, customBiomeCache); IrisBiome ceiling = modifier.resolveCaveBoundaryBiome( - mantleChunk, 1, 42, 2, 40, 44, resolverState, caveBiomeCache, customBiomeCache); + mantleChunk, 1, 42, 2, 40, 44, caveBiomeCache, customBiomeCache); assertSame(customFloor, floor); assertSame(resolvedCeiling, ceiling); diff --git a/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingInferenceIsolationTest.java b/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingInferenceIsolationTest.java index 18a30c614..c81a2152d 100644 --- a/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingInferenceIsolationTest.java +++ b/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingInferenceIsolationTest.java @@ -8,7 +8,6 @@ import art.arcane.iris.engine.framework.SeedManager; import art.arcane.iris.engine.object.world.biome.InferredType; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.engine.object.world.IrisWorld; import art.arcane.iris.spi.IrisPlatform; @@ -83,7 +82,6 @@ public class CaveApplyingInferenceIsolationTest { int.class, int.class, int.class, - IrisDimensionCarvingResolver.State.class, Long2ObjectOpenHashMap.class, Map.class ); @@ -98,7 +96,6 @@ public class CaveApplyingInferenceIsolationTest { 0, 1, 1, - new IrisDimensionCarvingResolver.State(), new Long2ObjectOpenHashMap(), customBiomes ); diff --git a/core/src/test/java/art/arcane/iris/engine/modifier/CaveBiomeBandsTest.java b/core/src/test/java/art/arcane/iris/engine/modifier/CaveBiomeBandsTest.java new file mode 100644 index 000000000..a6075b02c --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/modifier/CaveBiomeBandsTest.java @@ -0,0 +1,98 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.modifier; + +import art.arcane.iris.builtin.carve.CarvingEntry; +import art.arcane.iris.builtin.carve.CarvingSettings; +import art.arcane.iris.builtin.carve.CaveDepthSettings; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.loader.ResourceLoader; +import art.arcane.iris.core.modules.BuiltInPack; +import art.arcane.iris.core.modules.IrisPackWorld; +import art.arcane.iris.engine.decorator.DecoratorTestEngines; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.world.IrisWorld; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import com.google.gson.Gson; +import org.junit.Before; +import org.junit.Test; + +import java.util.List; +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** What the carve module answers the host about cave biomes: the biome of the dimension's band at a height above the dimension's bottom, and the minimum depths. */ +public class CaveBiomeBandsTest { + private static final int MIN_HEIGHT = -64; + private static final String BANDS = """ + [{"id": "shallow", "biome": "band/shallow", "worldYRange": {"min": -64, "max": 0}}, + {"id": "disabled", "enabled": false, "biome": "band/disabled", "worldYRange": {"min": 100, "max": 200}}, + {"id": "unloadable", "biome": "band/missing", "worldYRange": {"min": 300, "max": 310}}, + {"id": "padded", "biome": " band/padded ", "worldYRange": {"min": 500, "max": 600}}] + """; + + private Engine engine; + private final IrisBiome shallow = mock(IrisBiome.class); + + @Before + @SuppressWarnings("unchecked") + public void mockEngine() { + IrisData data = mock(IrisData.class); + ResourceLoader biomes = mock(ResourceLoader.class); + when(data.getBiomeLoader()).thenReturn(biomes); + when(biomes.load("band/shallow")).thenReturn(shallow); + when(biomes.load("band/padded")).thenReturn(mock(IrisBiome.class)); + when(biomes.load("band/disabled")).thenReturn(mock(IrisBiome.class)); + when(shallow.getModuleSettings()).thenReturn(BuiltInPack.settings(new CaveDepthSettings(30))); + List entries = new Gson().fromJson(BANDS, new com.google.gson.reflect.TypeToken>() { }.getType()); + IrisDimension dimension = mock(IrisDimension.class); + when(dimension.getModuleSettings()).thenReturn(BuiltInPack.settings(new CarvingSettings(entries))); + engine = mock(Engine.class); + when(engine.getData()).thenReturn(data); + when(engine.getDimension()).thenReturn(dimension); + when(engine.getWorld()).thenReturn(IrisWorld.builder().minHeight(MIN_HEIGHT).maxHeight(320).build()); + DecoratorTestEngines.withGeneration(engine); + } + + @Test + public void aPositionInsideAnEnabledBandGetsTheBandsBiomeKey() { + CaveBiomeBands bands = new CaveBiomeBands(); + IrisPackWorld world = engine.getGeneration().world(); + + assertEquals("world Y -54 is in the band from -64 to 0", Optional.of("band/shallow"), bands.overriddenBiome(world, 5, 10, 5)); + assertEquals("the band's end is in it", Optional.of("band/shallow"), bands.overriddenBiome(world, 5, 64, 5)); + assertEquals("above it", Optional.empty(), bands.overriddenBiome(world, 5, 65, 5)); + assertEquals("a disabled band overrides nothing", Optional.empty(), bands.overriddenBiome(world, 5, 200 - MIN_HEIGHT - 50, 5)); + assertEquals("a band whose biome the pack lacks overrides nothing", Optional.empty(), bands.overriddenBiome(world, 5, 305 - MIN_HEIGHT, 5)); + assertEquals("the key is trimmed as the loader is asked for it", Optional.of("band/padded"), bands.overriddenBiome(world, 5, 550 - MIN_HEIGHT, 5)); + } + + @Test + public void aBiomeKeyHasTheMinimumDepthItsSettingsDeclareAndZeroWhenTheKeyIsUnknown() { + CaveBiomeBands bands = new CaveBiomeBands(); + IrisPackWorld world = engine.getGeneration().world(); + + assertEquals(30, bands.minDepthBelowSurface(world, "band/shallow")); + assertEquals(0, bands.minDepthBelowSurface(world, "band/unknown")); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/modifier/FloatingIslandsTest.java b/core/src/test/java/art/arcane/iris/engine/modifier/FloatingIslandsTest.java index b257ccb2a..2c474b4b9 100644 --- a/core/src/test/java/art/arcane/iris/engine/modifier/FloatingIslandsTest.java +++ b/core/src/test/java/art/arcane/iris/engine/modifier/FloatingIslandsTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.engine.modifier; +import art.arcane.iris.core.modules.ModuleSettings; import art.arcane.iris.engine.decorator.DecoratorTestEngines; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.EngineMetrics; @@ -9,7 +10,6 @@ import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.project.context.ChunkContext; import art.arcane.iris.util.project.hunk.Hunk; -import art.arcane.volmlib.util.collection.KList; import org.junit.Test; import static org.mockito.ArgumentMatchers.any; @@ -29,7 +29,7 @@ public class FloatingIslandsTest { public void columnsWithoutFloatingChildBiomesAreLeftAlone() { FloatingIslands islands = new FloatingIslands(engine()); IrisBiome biome = mock(IrisBiome.class); - when(biome.getFloatingChildBiomes()).thenReturn(new KList<>()); + when(biome.getModuleSettings()).thenReturn(ModuleSettings.NONE); FloatingIslandBoundarySampler sampler = mock(FloatingIslandBoundarySampler.class); when(sampler.parent(anyInt(), anyInt())).thenReturn(biome); ChunkContext context = mock(ChunkContext.class); diff --git a/core/src/test/java/art/arcane/iris/engine/object/terrain/carving/IrisDimensionCarvingResolverParityTest.java b/core/src/test/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolverParityTest.java similarity index 59% rename from core/src/test/java/art/arcane/iris/engine/object/terrain/carving/IrisDimensionCarvingResolverParityTest.java rename to core/src/test/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolverParityTest.java index 2343bfc4f..9b1dd39c7 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/terrain/carving/IrisDimensionCarvingResolverParityTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolverParityTest.java @@ -1,18 +1,21 @@ package art.arcane.iris.engine.object.terrain.carving; import art.arcane.iris.engine.object.value.IRare; -import art.arcane.iris.engine.object.value.IrisRange; +import com.volmit.config.Range; +import art.arcane.iris.builtin.carve.CarvingEntry; +import art.arcane.iris.engine.decorator.DecoratorTestEngines; import art.arcane.iris.engine.object.world.IrisWorld; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingEntry; -import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.ResourceLoader; import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineGeneration; import art.arcane.iris.engine.framework.SeedManager; import art.arcane.iris.util.project.noise.CNG; import art.arcane.volmlib.util.collection.KList; +import com.google.gson.Gson; +import com.google.gson.JsonObject; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.Server; @@ -24,7 +27,6 @@ import org.mockito.invocation.InvocationOnMock; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.lang.reflect.Proxy; -import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; @@ -48,7 +50,7 @@ import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; -public class IrisDimensionCarvingResolverParityTest { +public class CarvingResolverParityTest { private static final int MAX_CHILD_DEPTH = 32; private static final long CHILD_SEED_SALT = 0x9E3779B97F4A7C15L; @@ -81,17 +83,17 @@ public class IrisDimensionCarvingResolverParityTest { @Test public void resolverStatefulOverloadsMatchLegacyResolverAcrossSampleGrid() { Fixture fixture = createFixture(); - IrisDimensionCarvingResolver.State state = new IrisDimensionCarvingResolver.State(); + CarvingResolver.State state = new CarvingResolver.State(); for (int worldY = -64; worldY <= 320; worldY += 11) { - IrisDimensionCarvingEntry legacyRoot = legacyResolveRootEntry(fixture.engine, worldY); - IrisDimensionCarvingEntry statefulRoot = IrisDimensionCarvingResolver.resolveRootEntry(fixture.engine, worldY, state); + ResolvedCarvingEntry legacyRoot = legacyResolveRootEntry(fixture.engine, worldY); + ResolvedCarvingEntry statefulRoot = CarvingResolver.resolveRootEntry(fixture.engine, worldY, state); assertSame("root mismatch at worldY=" + worldY, legacyRoot, statefulRoot); for (int worldX = -384; worldX <= 384; worldX += 29) { for (int worldZ = -384; worldZ <= 384; worldZ += 31) { - IrisDimensionCarvingEntry legacyResolved = legacyResolveFromRoot(fixture.engine, legacyRoot, worldX, worldZ); - IrisDimensionCarvingEntry statefulResolved = IrisDimensionCarvingResolver.resolveFromRoot(fixture.engine, statefulRoot, worldX, worldZ, state); + ResolvedCarvingEntry legacyResolved = legacyResolveFromRoot(fixture.engine, legacyRoot, worldX, worldZ); + ResolvedCarvingEntry statefulResolved = CarvingResolver.resolveFromRoot(fixture.engine, statefulRoot, worldX, worldZ, state); assertSame("entry mismatch at worldY=" + worldY + " worldX=" + worldX + " worldZ=" + worldZ, legacyResolved, statefulResolved); } } @@ -101,49 +103,33 @@ public class IrisDimensionCarvingResolverParityTest { @Test public void resolverStatefulOverloadsMatchLegacyResolverAcrossMixedDepthGraph() { Fixture fixture = createMixedDepthFixture(); - IrisDimensionCarvingResolver.State state = new IrisDimensionCarvingResolver.State(); + CarvingResolver.State state = new CarvingResolver.State(); for (int worldY = -64; worldY <= 320; worldY += 17) { - IrisDimensionCarvingEntry legacyRoot = legacyResolveRootEntry(fixture.engine, worldY); - IrisDimensionCarvingEntry statefulRoot = IrisDimensionCarvingResolver.resolveRootEntry(fixture.engine, worldY, state); + ResolvedCarvingEntry legacyRoot = legacyResolveRootEntry(fixture.engine, worldY); + ResolvedCarvingEntry statefulRoot = CarvingResolver.resolveRootEntry(fixture.engine, worldY, state); assertSame("mixed root mismatch at worldY=" + worldY, legacyRoot, statefulRoot); for (int worldX = -640; worldX <= 640; worldX += 79) { for (int worldZ = -640; worldZ <= 640; worldZ += 83) { - IrisDimensionCarvingEntry legacyResolved = legacyResolveFromRoot(fixture.engine, legacyRoot, worldX, worldZ); - IrisDimensionCarvingEntry statefulResolved = IrisDimensionCarvingResolver.resolveFromRoot(fixture.engine, statefulRoot, worldX, worldZ, state); + ResolvedCarvingEntry legacyResolved = legacyResolveFromRoot(fixture.engine, legacyRoot, worldX, worldZ); + ResolvedCarvingEntry statefulResolved = CarvingResolver.resolveFromRoot(fixture.engine, statefulRoot, worldX, worldZ, state); assertSame("mixed entry mismatch at worldY=" + worldY + " worldX=" + worldX + " worldZ=" + worldZ, legacyResolved, statefulResolved); } } } } - @Test - public void caveBiomeStateOverloadMatchesDefaultOverloadAcrossSampleGrid() { - Fixture fixture = createFixture(); - IrisDimensionCarvingResolver.State state = new IrisDimensionCarvingResolver.State(); - - for (int y = 1; y <= 300; y += 17) { - for (int x = -160; x <= 160; x += 23) { - for (int z = -160; z <= 160; z += 29) { - IrisBiome defaultBiome = fixture.engine.getCaveBiome(x, y, z); - IrisBiome stateBiome = fixture.engine.getCaveBiome(x, y, z, state); - assertSame("cave biome mismatch at x=" + x + " y=" + y + " z=" + z, defaultBiome, stateBiome); - } - } - } - } - @Test public void columnAnchoredChunkPlanResolutionIsStableAcrossRepeatedBuilds() { Fixture fixture = createMixedDepthFixture(); - IrisDimensionCarvingResolver.State state = new IrisDimensionCarvingResolver.State(); - IrisDimensionCarvingEntry root = legacyResolveRootEntry(fixture.engine, 80); + CarvingResolver.State state = new CarvingResolver.State(); + ResolvedCarvingEntry root = legacyResolveRootEntry(fixture.engine, 80); for (int chunkX = -24; chunkX <= 24; chunkX += 6) { for (int chunkZ = -24; chunkZ <= 24; chunkZ += 6) { - IrisDimensionCarvingEntry[] firstPlan = buildColumnPlan(fixture.engine, root, chunkX, chunkZ, state); - IrisDimensionCarvingEntry[] secondPlan = buildColumnPlan(fixture.engine, root, chunkX, chunkZ, state); + ResolvedCarvingEntry[] firstPlan = buildColumnPlan(fixture.engine, root, chunkX, chunkZ, state); + ResolvedCarvingEntry[] secondPlan = buildColumnPlan(fixture.engine, root, chunkX, chunkZ, state); for (int columnIndex = 0; columnIndex < firstPlan.length; columnIndex++) { assertSame( "column plan mismatch at chunkX=" + chunkX + " chunkZ=" + chunkZ + " columnIndex=" + columnIndex, @@ -159,14 +145,14 @@ public class IrisDimensionCarvingResolverParityTest { public void sharedResolverStateNeverCarriesDimensionEntriesAcrossEngines() { Fixture first = createFixture(); Fixture second = createMixedDepthFixture(); - IrisDimensionCarvingResolver.State state = new IrisDimensionCarvingResolver.State(); + CarvingResolver.State state = new CarvingResolver.State(); - IrisDimensionCarvingEntry firstExpected = legacyResolveRootEntry(first.engine, 80); - IrisDimensionCarvingEntry secondExpected = legacyResolveRootEntry(second.engine, 80); + ResolvedCarvingEntry firstExpected = legacyResolveRootEntry(first.engine, 80); + ResolvedCarvingEntry secondExpected = legacyResolveRootEntry(second.engine, 80); - assertSame(firstExpected, IrisDimensionCarvingResolver.resolveRootEntry(first.engine, 80, state)); - assertSame(secondExpected, IrisDimensionCarvingResolver.resolveRootEntry(second.engine, 80, state)); - assertSame(firstExpected, IrisDimensionCarvingResolver.resolveRootEntry(first.engine, 80, state)); + assertSame(firstExpected, CarvingResolver.resolveRootEntry(first.engine, 80, state)); + assertSame(secondExpected, CarvingResolver.resolveRootEntry(second.engine, 80, state)); + assertSame(firstExpected, CarvingResolver.resolveRootEntry(first.engine, 80, state)); } @Test @@ -175,11 +161,11 @@ public class IrisDimensionCarvingResolverParityTest { Fixture second = createMixedDepthFixture(); int worldY = 83; - IrisDimensionCarvingEntry firstExpected = legacyResolveRootEntry(first.engine, worldY); - IrisDimensionCarvingEntry secondExpected = legacyResolveRootEntry(second.engine, worldY); + ResolvedCarvingEntry firstExpected = legacyResolveRootEntry(first.engine, worldY); + ResolvedCarvingEntry secondExpected = legacyResolveRootEntry(second.engine, worldY); - assertSame(firstExpected, IrisDimensionCarvingResolver.resolveRootEntry(first.engine, worldY)); - assertSame(secondExpected, IrisDimensionCarvingResolver.resolveRootEntry(second.engine, worldY)); + assertSame(firstExpected, CarvingResolver.resolveRootEntry(first.engine, worldY)); + assertSame(secondExpected, CarvingResolver.resolveRootEntry(second.engine, worldY)); } @Test @@ -188,25 +174,28 @@ public class IrisDimensionCarvingResolverParityTest { Fixture replacement = createMixedDepthFixture(); AtomicReference dimension = new AtomicReference<>(first.engine.getDimension()); AtomicReference data = new AtomicReference<>(first.engine.getData()); + AtomicReference generation = new AtomicReference<>(first.engine.getGeneration()); Engine engine = mock(Engine.class, CALLS_REAL_METHODS); doAnswer((InvocationOnMock invocation) -> dimension.get()).when(engine).getDimension(); doAnswer((InvocationOnMock invocation) -> data.get()).when(engine).getData(); + doAnswer((InvocationOnMock invocation) -> generation.get()).when(engine).getGeneration(); int worldY = 83; - IrisDimensionCarvingEntry firstExpected = legacyResolveRootEntry(first.engine, worldY); - IrisDimensionCarvingEntry replacementExpected = legacyResolveRootEntry(replacement.engine, worldY); - assertSame(firstExpected, IrisDimensionCarvingResolver.resolveRootEntry(engine, worldY)); + ResolvedCarvingEntry firstExpected = legacyResolveRootEntry(first.engine, worldY); + ResolvedCarvingEntry replacementExpected = legacyResolveRootEntry(replacement.engine, worldY); + assertSame(firstExpected, CarvingResolver.resolveRootEntry(engine, worldY)); dimension.set(replacement.engine.getDimension()); data.set(replacement.engine.getData()); - assertSame(replacementExpected, IrisDimensionCarvingResolver.resolveRootEntry(engine, worldY)); + generation.set(replacement.engine.getGeneration()); + assertSame(replacementExpected, CarvingResolver.resolveRootEntry(engine, worldY)); } @Test public void resolverStateUsesWeakRuntimeIdentityBindings() throws NoSuchFieldException { - Field engineIdentity = IrisDimensionCarvingResolver.State.class.getDeclaredField("engineIdentity"); - Field dimensionIdentity = IrisDimensionCarvingResolver.State.class.getDeclaredField("dimensionIdentity"); - Field dataIdentity = IrisDimensionCarvingResolver.State.class.getDeclaredField("dataIdentity"); + Field engineIdentity = CarvingResolver.State.class.getDeclaredField("engineIdentity"); + Field dimensionIdentity = CarvingResolver.State.class.getDeclaredField("dimensionIdentity"); + Field dataIdentity = CarvingResolver.State.class.getDeclaredField("dataIdentity"); assertSame(WeakReference.class, engineIdentity.getType()); assertSame(WeakReference.class, dimensionIdentity.getType()); @@ -240,19 +229,19 @@ public class IrisDimensionCarvingResolverParityTest { private LifetimeReferences populateThreadLocalLifetimeReferences() throws Exception { RetainedFixture fixture = createRetainedFixture(); - assertNotNull(IrisDimensionCarvingResolver.resolveRootEntry(fixture.engine(), 80)); + assertNotNull(CarvingResolver.resolveRootEntry(fixture.engine(), 80)); - Field threadStateField = IrisDimensionCarvingResolver.class.getDeclaredField("THREAD_STATE"); + Field threadStateField = CarvingResolver.class.getDeclaredField("THREAD_STATE"); threadStateField.setAccessible(true); ThreadLocal threadState = (ThreadLocal) threadStateField.get(null); Object value = threadState.get(); assertTrue(value instanceof WeakReference); @SuppressWarnings("unchecked") - WeakReference state = - (WeakReference) value; - IrisDimensionCarvingResolver.State populatedState = state.get(); + WeakReference state = + (WeakReference) value; + CarvingResolver.State populatedState = state.get(); assertNotNull(populatedState); - Field biomeCacheField = IrisDimensionCarvingResolver.State.class.getDeclaredField("biomeCache"); + Field biomeCacheField = CarvingResolver.State.class.getDeclaredField("biomeCache"); biomeCacheField.setAccessible(true); assertFalse(((Map) biomeCacheField.get(populatedState)).isEmpty()); return new LifetimeReferences( @@ -278,11 +267,11 @@ public class IrisDimensionCarvingResolverParityTest { @Test public void explicitStateRemainsStronglyCallerOwned() throws Exception { RetainedFixture fixture = createRetainedFixture(); - IrisDimensionCarvingResolver.State state = new IrisDimensionCarvingResolver.State(); - assertSame(fixture.entry(), IrisDimensionCarvingResolver.resolveRootEntry( + CarvingResolver.State state = new CarvingResolver.State(); + assertSame(fixture.entry(), CarvingResolver.resolveRootEntry( fixture.engine(), 80, state)); - Field rootEntriesField = IrisDimensionCarvingResolver.State.class + Field rootEntriesField = CarvingResolver.State.class .getDeclaredField("rootEntriesByWorldY"); rootEntriesField.setAccessible(true); System.gc(); @@ -300,26 +289,24 @@ public class IrisDimensionCarvingResolverParityTest { doReturn(biome).when(biomeLoader).load("retained"); doReturn(biomeLoader).when(data).getBiomeLoader(); - IrisDimensionCarvingEntry entry = buildEntry( - "retained", "retained", new IrisRange(-64, 320), 0, List.of()); - KList carvingEntries = new KList<>(); - carvingEntries.add(entry); - + CarvingBands bands = new CarvingBands(List.of(buildEntry("retained", "retained", Range.of(-64, 320), 0, List.of()))); IrisDimension dimension = new IrisDimension(); - dimension.setCarving(carvingEntries); - Engine engine = (Engine) Proxy.newProxyInstance( + Engine[] engine = new Engine[1]; + AtomicReference generation = new AtomicReference<>(); + engine[0] = (Engine) Proxy.newProxyInstance( Engine.class.getClassLoader(), new Class[]{Engine.class}, (proxy, method, arguments) -> switch (method.getName()) { case "getDimension" -> dimension; case "getData" -> data; + case "getGeneration" -> generation.updateAndGet(existing -> existing != null ? existing : generationWith(engine[0], bands)); case "hashCode" -> System.identityHashCode(proxy); case "equals" -> proxy == arguments[0]; case "toString" -> "carving-retention-test-engine"; default -> throw new UnsupportedOperationException(method.toString()); }); - return new RetainedFixture(engine, entry); + return new RetainedFixture(engine[0], bands.entries().getFirst()); } private Fixture createFixture() { @@ -336,7 +323,6 @@ public class IrisDimensionCarvingResolverParityTest { doReturn(2).when(childABiome).getRarity(); doReturn(5).when(childBBiome).getRarity(); doReturn(1).when(childCBiome).getRarity(); - doReturn(0).when(fallbackBiome).getCaveMinDepthBelowSurface(); @SuppressWarnings("unchecked") ResourceLoader biomeLoader = mock(ResourceLoader.class); @@ -349,29 +335,15 @@ public class IrisDimensionCarvingResolverParityTest { IrisData data = mock(IrisData.class); doReturn(biomeLoader).when(data).getBiomeLoader(); - IrisDimensionCarvingEntry rootLow = buildEntry("root-low", "root-low", new IrisRange(-64, 120), 4, List.of("child-a", "child-b")); - IrisDimensionCarvingEntry rootHigh = buildEntry("root-high", "root-high", new IrisRange(121, 320), 3, List.of("child-b", "child-c")); - IrisDimensionCarvingEntry childA = buildEntry("child-a", "child-a", new IrisRange(-2048, -1024), 3, List.of("child-b")); - IrisDimensionCarvingEntry childB = buildEntry("child-b", "child-b", new IrisRange(-2048, -1024), 2, List.of("child-c", "child-a")); - IrisDimensionCarvingEntry childC = buildEntry("child-c", "child-c", new IrisRange(-2048, -1024), 1, List.of()); + CarvingEntry rootLow = buildEntry("root-low", "root-low", Range.of(-64, 120), 4, List.of("child-a", "child-b")); + CarvingEntry rootHigh = buildEntry("root-high", "root-high", Range.of(121, 320), 3, List.of("child-b", "child-c")); + CarvingEntry childA = buildEntry("child-a", "child-a", Range.of(-2048, -1024), 3, List.of("child-b")); + CarvingEntry childB = buildEntry("child-b", "child-b", Range.of(-2048, -1024), 2, List.of("child-c", "child-a")); + CarvingEntry childC = buildEntry("child-c", "child-c", Range.of(-2048, -1024), 1, List.of()); - KList carvingEntries = new KList<>(); - carvingEntries.add(rootLow); - carvingEntries.add(rootHigh); - carvingEntries.add(childA); - carvingEntries.add(childB); - carvingEntries.add(childC); - - Map index = new HashMap<>(); - index.put(rootLow.getId(), rootLow); - index.put(rootHigh.getId(), rootHigh); - index.put(childA.getId(), childA); - index.put(childB.getId(), childB); - index.put(childC.getId(), childC); + CarvingBands bands = new CarvingBands(List.of(rootLow, rootHigh, childA, childB, childC)); IrisDimension dimension = mock(IrisDimension.class); - doReturn(carvingEntries).when(dimension).getCarving(); - doReturn(index).when(dimension).getCarvingEntryIndex(); Engine engine = mock(Engine.class, CALLS_REAL_METHODS); doReturn(dimension).when(engine).getDimension(); @@ -380,6 +352,7 @@ public class IrisDimensionCarvingResolverParityTest { doReturn(IrisWorld.builder().minHeight(-64).maxHeight(320).build()).when(engine).getWorld(); doReturn(surfaceBiome).when(engine).getSurfaceBiome(anyInt(), anyInt()); doReturn(fallbackBiome).when(engine).getCaveBiome(anyInt(), anyInt()); + DecoratorTestEngines.withGeneration(engine).state(CarvingBands.class, ignored -> bands); return new Fixture(engine); } @@ -406,7 +379,6 @@ public class IrisDimensionCarvingResolverParityTest { doReturn(4).when(childEBiome).getRarity(); doReturn(8).when(childFBiome).getRarity(); doReturn(2).when(childGBiome).getRarity(); - doReturn(0).when(fallbackBiome).getCaveMinDepthBelowSurface(); @SuppressWarnings("unchecked") ResourceLoader biomeLoader = mock(ResourceLoader.class); @@ -423,41 +395,19 @@ public class IrisDimensionCarvingResolverParityTest { IrisData data = mock(IrisData.class); doReturn(biomeLoader).when(data).getBiomeLoader(); - IrisDimensionCarvingEntry rootLow = buildEntry("root-low", "root-low", new IrisRange(-64, 120), 7, List.of("child-a", "child-d", "child-e")); - IrisDimensionCarvingEntry rootHigh = buildEntry("root-high", "root-high", new IrisRange(121, 320), 6, List.of("child-b", "child-c", "child-f")); - IrisDimensionCarvingEntry childA = buildEntry("child-a", "child-a", new IrisRange(-4096, 4096), 5, List.of("child-b", "child-g")); - IrisDimensionCarvingEntry childB = buildEntry("child-b", "child-b", new IrisRange(-4096, 4096), 1, List.of("child-c")); - IrisDimensionCarvingEntry childC = buildEntry("child-c", "child-c", new IrisRange(-4096, 4096), 0, List.of()); - IrisDimensionCarvingEntry childD = buildEntry("child-d", "child-d", new IrisRange(-4096, 4096), 6, List.of("child-e", "child-f")); - IrisDimensionCarvingEntry childE = buildEntry("child-e", "child-e", new IrisRange(-4096, 4096), 2, List.of("child-a")); - IrisDimensionCarvingEntry childF = buildEntry("child-f", "child-f", new IrisRange(-4096, 4096), 8, List.of("child-g", "child-c")); - IrisDimensionCarvingEntry childG = buildEntry("child-g", "child-g", new IrisRange(-4096, 4096), 3, List.of("child-d")); + CarvingEntry rootLow = buildEntry("root-low", "root-low", Range.of(-64, 120), 7, List.of("child-a", "child-d", "child-e")); + CarvingEntry rootHigh = buildEntry("root-high", "root-high", Range.of(121, 320), 6, List.of("child-b", "child-c", "child-f")); + CarvingEntry childA = buildEntry("child-a", "child-a", Range.of(-4096, 4096), 5, List.of("child-b", "child-g")); + CarvingEntry childB = buildEntry("child-b", "child-b", Range.of(-4096, 4096), 1, List.of("child-c")); + CarvingEntry childC = buildEntry("child-c", "child-c", Range.of(-4096, 4096), 0, List.of()); + CarvingEntry childD = buildEntry("child-d", "child-d", Range.of(-4096, 4096), 6, List.of("child-e", "child-f")); + CarvingEntry childE = buildEntry("child-e", "child-e", Range.of(-4096, 4096), 2, List.of("child-a")); + CarvingEntry childF = buildEntry("child-f", "child-f", Range.of(-4096, 4096), 8, List.of("child-g", "child-c")); + CarvingEntry childG = buildEntry("child-g", "child-g", Range.of(-4096, 4096), 3, List.of("child-d")); - KList carvingEntries = new KList<>(); - carvingEntries.add(rootLow); - carvingEntries.add(rootHigh); - carvingEntries.add(childA); - carvingEntries.add(childB); - carvingEntries.add(childC); - carvingEntries.add(childD); - carvingEntries.add(childE); - carvingEntries.add(childF); - carvingEntries.add(childG); - - Map index = new HashMap<>(); - index.put(rootLow.getId(), rootLow); - index.put(rootHigh.getId(), rootHigh); - index.put(childA.getId(), childA); - index.put(childB.getId(), childB); - index.put(childC.getId(), childC); - index.put(childD.getId(), childD); - index.put(childE.getId(), childE); - index.put(childF.getId(), childF); - index.put(childG.getId(), childG); + CarvingBands bands = new CarvingBands(List.of(rootLow, rootHigh, childA, childB, childC, childD, childE, childF, childG)); IrisDimension dimension = mock(IrisDimension.class); - doReturn(carvingEntries).when(dimension).getCarving(); - doReturn(index).when(dimension).getCarvingEntryIndex(); Engine engine = mock(Engine.class, CALLS_REAL_METHODS); doReturn(dimension).when(engine).getDimension(); @@ -466,43 +416,51 @@ public class IrisDimensionCarvingResolverParityTest { doReturn(IrisWorld.builder().minHeight(-64).maxHeight(320).build()).when(engine).getWorld(); doReturn(surfaceBiome).when(engine).getSurfaceBiome(anyInt(), anyInt()); doReturn(fallbackBiome).when(engine).getCaveBiome(anyInt(), anyInt()); + DecoratorTestEngines.withGeneration(engine).state(CarvingBands.class, ignored -> bands); return new Fixture(engine); } - private IrisDimensionCarvingEntry[] buildColumnPlan(Engine engine, IrisDimensionCarvingEntry rootEntry, int chunkX, int chunkZ, IrisDimensionCarvingResolver.State state) { - IrisDimensionCarvingEntry[] plan = new IrisDimensionCarvingEntry[256]; + private ResolvedCarvingEntry[] buildColumnPlan(Engine engine, ResolvedCarvingEntry rootEntry, int chunkX, int chunkZ, CarvingResolver.State state) { + ResolvedCarvingEntry[] plan = new ResolvedCarvingEntry[256]; for (int localX = 0; localX < 16; localX++) { int worldX = (chunkX << 4) + localX; for (int localZ = 0; localZ < 16; localZ++) { int worldZ = (chunkZ << 4) + localZ; int columnIndex = (localX << 4) | localZ; - plan[columnIndex] = IrisDimensionCarvingResolver.resolveFromRoot(engine, rootEntry, worldX, worldZ, state); + plan[columnIndex] = CarvingResolver.resolveFromRoot(engine, rootEntry, worldX, worldZ, state); } } return plan; } - private IrisDimensionCarvingEntry buildEntry(String id, String biome, IrisRange worldRange, int depth, List children) { - IrisDimensionCarvingEntry entry = new IrisDimensionCarvingEntry(); - entry.setId(id); - entry.setEnabled(true); - entry.setBiome(biome); - entry.setWorldYRange(worldRange); - entry.setChildRecursionDepth(depth); - entry.setChildren(new KList<>(children)); - return entry; + private static EngineGeneration generationWith(Engine engine, CarvingBands bands) { + EngineGeneration generation = new EngineGeneration(engine); + generation.state(CarvingBands.class, ignored -> bands); + return generation; } - private IrisDimensionCarvingEntry legacyResolveRootEntry(Engine engine, int worldY) { - IrisDimension dimension = engine.getDimension(); - List entries = dimension.getCarving(); - if (entries == null || entries.isEmpty()) { + private CarvingEntry buildEntry(String id, String biome, Range worldRange, int depth, List children) { + JsonObject json = new JsonObject(); + json.addProperty("id", id); + json.addProperty("biome", biome); + JsonObject range = new JsonObject(); + range.addProperty("min", worldRange.min()); + range.addProperty("max", worldRange.max()); + json.add("worldYRange", range); + json.addProperty("childRecursionDepth", depth); + json.add("children", new Gson().toJsonTree(children)); + return new Gson().fromJson(json, CarvingEntry.class); + } + + private ResolvedCarvingEntry legacyResolveRootEntry(Engine engine, int worldY) { + List entries = CarvingBands.of(engine).entries(); + if (entries.isEmpty()) { return null; } - IrisDimensionCarvingEntry resolved = null; - for (IrisDimensionCarvingEntry entry : entries) { + ResolvedCarvingEntry resolved = null; + for (ResolvedCarvingEntry entry : entries) { if (!legacyIsRootCandidate(engine, entry, worldY)) { continue; } @@ -513,7 +471,7 @@ public class IrisDimensionCarvingResolverParityTest { return resolved; } - private IrisDimensionCarvingEntry legacyResolveFromRoot(Engine engine, IrisDimensionCarvingEntry rootEntry, int worldX, int worldZ) { + private ResolvedCarvingEntry legacyResolveFromRoot(Engine engine, ResolvedCarvingEntry rootEntry, int worldX, int worldZ) { if (rootEntry == null) { return null; } @@ -523,22 +481,22 @@ public class IrisDimensionCarvingResolverParityTest { return null; } - int remainingDepth = clampDepth(rootEntry.getChildRecursionDepth()); + int remainingDepth = clampDepth(rootEntry.childRecursionDepth()); if (remainingDepth <= 0) { return rootEntry; } - Map entryIndex = engine.getDimension().getCarvingEntryIndex(); - IrisDimensionCarvingEntry current = rootEntry; + Map entryIndex = CarvingBands.of(engine).index(); + ResolvedCarvingEntry current = rootEntry; int depth = remainingDepth; while (depth > 0) { - IrisDimensionCarvingEntry selected = legacySelectChild(engine, current, worldX, worldZ, entryIndex); + ResolvedCarvingEntry selected = legacySelectChild(engine, current, worldX, worldZ, entryIndex); if (selected == null || selected == current) { break; } depth--; - int childDepthLimit = clampDepth(selected.getChildRecursionDepth()); + int childDepthLimit = clampDepth(selected.childRecursionDepth()); if (childDepthLimit < depth) { depth = childDepthLimit; } @@ -548,20 +506,20 @@ public class IrisDimensionCarvingResolverParityTest { return current; } - private IrisBiome legacyResolveEntryBiome(Engine engine, IrisDimensionCarvingEntry entry) { + private IrisBiome legacyResolveEntryBiome(Engine engine, ResolvedCarvingEntry entry) { if (entry == null) { return null; } - return entry.getRealBiome(engine.getData()); + return entry.realBiome(engine.getData()); } - private boolean legacyIsRootCandidate(Engine engine, IrisDimensionCarvingEntry entry, int worldY) { - if (entry == null || !entry.isEnabled()) { + private boolean legacyIsRootCandidate(Engine engine, ResolvedCarvingEntry entry, int worldY) { + if (entry == null || !entry.enabled()) { return false; } - IrisRange worldYRange = entry.getWorldYRange(); + Range worldYRange = entry.worldYRange(); if (worldYRange != null && !worldYRange.contains(worldY)) { return false; } @@ -569,15 +527,15 @@ public class IrisDimensionCarvingResolverParityTest { return legacyResolveEntryBiome(engine, entry) != null; } - private IrisDimensionCarvingEntry legacySelectChild( + private ResolvedCarvingEntry legacySelectChild( Engine engine, - IrisDimensionCarvingEntry parent, + ResolvedCarvingEntry parent, int worldX, int worldZ, - Map entryIndex + Map entryIndex ) { - KList children = parent.getChildren(); - if (children == null || children.isEmpty()) { + List children = parent.children(); + if (children.isEmpty()) { return parent; } @@ -592,8 +550,8 @@ public class IrisDimensionCarvingResolverParityTest { continue; } - IrisDimensionCarvingEntry child = entryIndex.get(childId.trim()); - if (child == null || !child.isEnabled()) { + ResolvedCarvingEntry child = entryIndex.get(childId.trim()); + if (child == null || !child.enabled()) { continue; } @@ -611,7 +569,7 @@ public class IrisDimensionCarvingResolverParityTest { } long seed = engine.getSeedManager().getCarve() ^ CHILD_SEED_SALT; - CNG childGenerator = parent.getChildrenGenerator(seed, engine.getData()); + CNG childGenerator = parent.childrenGenerator(seed, engine.getData()); LegacyCarvingChoice selected = childGenerator.fitRarity(options, worldX, worldZ); if (selected == null || selected.entry == null) { return parent; @@ -640,20 +598,20 @@ public class IrisDimensionCarvingResolverParityTest { private record Fixture(Engine engine) { } - private record RetainedFixture(Engine engine, IrisDimensionCarvingEntry entry) { + private record RetainedFixture(Engine engine, ResolvedCarvingEntry entry) { } private record LifetimeReferences( - WeakReference state, + WeakReference state, WeakReference engine ) { } private static final class LegacyCarvingChoice implements IRare { - private final IrisDimensionCarvingEntry entry; + private final ResolvedCarvingEntry entry; private final int rarity; - private LegacyCarvingChoice(IrisDimensionCarvingEntry entry, int rarity) { + private LegacyCarvingChoice(ResolvedCarvingEntry entry, int rarity) { this.entry = entry; this.rarity = rarity; } diff --git a/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/FloatingChildBiomeDecodingTest.java b/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/FloatingChildBiomeDecodingTest.java index 76ef7d2af..4c4fc4bfa 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/FloatingChildBiomeDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/FloatingChildBiomeDecodingTest.java @@ -23,7 +23,6 @@ import art.arcane.iris.builtin.floating.FloatingChildBiome; import art.arcane.iris.builtin.floating.OverrideMode; import art.arcane.iris.builtin.floating.TopShapeMode; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.world.biome.IrisBiome; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.junit.Before; @@ -33,7 +32,6 @@ import org.junit.rules.TemporaryFolder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.CALLS_REAL_METHODS; @@ -133,15 +131,6 @@ public class FloatingChildBiomeDecodingTest { assertNull(child.color().isEmpty() ? null : child.color()); } - @Test - public void aBiomeHoldsItsChildrenAsSettings() { - IrisBiome biome = gson.fromJson("{\"floatingChildBiomes\": [" + DUNES_CHILD + ", {}]}", IrisBiome.class); - - assertEquals(2, biome.getFloatingChildBiomes().size()); - assertEquals("magnetics/dunes", biome.getFloatingChildBiomes().get(0).biome()); - assertNotNull(biome.getFloatingChildBiomes().get(1)); - } - @Test public void theEdgeTaperProfileKeepsTheSettingsWidthExponentAndVariation() { FloatingChildBiome child = gson.fromJson(DUNES_CHILD, FloatingChildBiome.class); diff --git a/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySamplerTest.java b/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySamplerTest.java index 996a82d01..86b823062 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySamplerTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySamplerTest.java @@ -18,6 +18,9 @@ package art.arcane.iris.engine.object.terrain.floating; +import art.arcane.iris.core.modules.ModuleSettings; +import art.arcane.iris.core.modules.BuiltInPack; +import art.arcane.iris.builtin.floating.MergeFloatingChildrenSettings; import art.arcane.iris.builtin.floating.FloatingChildBiome; import art.arcane.iris.engine.object.TestSettings; import art.arcane.iris.builtin.floating.TopShapeMode; @@ -563,7 +566,8 @@ public class FloatingIslandBoundarySamplerTest { IrisWorld world = IrisWorld.builder().minHeight(0).maxHeight(320).build(); KList entries = new KList<>(); entries.add(entry); - when(parent.isMergeFloatingChildBiomes()).thenReturn(false); + ModuleSettings separate = BuiltInPack.settings(new MergeFloatingChildrenSettings(false)); + when(parent.getModuleSettings()).thenReturn(separate); when(entry.getFootprintCng(anyLong(), same(data))).thenReturn(footprint); when(entry.getAltitudeCng(anyLong(), same(data))).thenReturn(constant); when(entry.getRealBiome(parent, data)).thenReturn(parent); @@ -630,7 +634,8 @@ public class FloatingIslandBoundarySamplerTest { KList entries = new KList<>(); entries.add(lower); entries.add(upper); - when(parent.isMergeFloatingChildBiomes()).thenReturn(true); + ModuleSettings merged = BuiltInPack.settings(new MergeFloatingChildrenSettings(true)); + when(parent.getModuleSettings()).thenReturn(merged); for (ResolvedFloatingChild entry : entries) { when(entry.getFootprintCng(anyLong(), same(data))).thenReturn(footprint); when(entry.getAltitudeCng(anyLong(), same(data))).thenReturn(constant); diff --git a/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChildCarvingResolutionTest.java b/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChildCarvingResolutionTest.java index 72cac9e5b..836fe3879 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChildCarvingResolutionTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChildCarvingResolutionTest.java @@ -2,11 +2,15 @@ package art.arcane.iris.engine.object.terrain.floating; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingEntry; +import art.arcane.iris.builtin.carve.CarvingEntry; +import art.arcane.iris.builtin.carve.CarvingSettings; +import art.arcane.iris.core.modules.BuiltInPack; +import art.arcane.iris.core.modules.ModuleSettings; +import art.arcane.iris.engine.decorator.DecoratorTestEngines; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.ResourceLoader; import art.arcane.iris.engine.framework.Engine; -import art.arcane.volmlib.util.collection.KList; +import com.google.gson.Gson; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.Server; @@ -15,6 +19,7 @@ import org.junit.BeforeClass; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; +import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; import java.util.Map; @@ -68,11 +73,9 @@ public class ResolvedFloatingChildCarvingResolutionTest { public void resolveCarvingBiome_prefersDimensionCarvingEntryId() { IrisBiome entryBiome = mock(IrisBiome.class); IrisBiome sameKeyBiome = mock(IrisBiome.class); - IrisDimensionCarvingEntry entry = new IrisDimensionCarvingEntry(); - entry.setId("global-deepdark-band"); - entry.setBiome("carving/standard-deepdark"); + CarvingEntry entry = new Gson().fromJson("{\"id\": \"global-deepdark-band\", \"biome\": \"carving/standard-deepdark\"}", CarvingEntry.class); - Map entries = new HashMap<>(); + Map entries = new HashMap<>(); entries.put("global-deepdark-band", entry); Map biomes = new HashMap<>(); @@ -86,7 +89,7 @@ public class ResolvedFloatingChildCarvingResolutionTest { assertSame(entryBiome, resolved); } - private Fixture createFixture(Map entries, Map biomes) { + private Fixture createFixture(Map entries, Map biomes) { @SuppressWarnings("unchecked") ResourceLoader biomeLoader = mock(ResourceLoader.class); for (Map.Entry biome : biomes.entrySet()) { @@ -97,12 +100,13 @@ public class ResolvedFloatingChildCarvingResolutionTest { doReturn(biomeLoader).when(data).getBiomeLoader(); IrisDimension dimension = mock(IrisDimension.class); - doReturn(entries).when(dimension).getCarvingEntryIndex(); - doReturn(new KList<>(entries.values())).when(dimension).getCarving(); + ModuleSettings declared = BuiltInPack.settings(new CarvingSettings(new ArrayList<>(entries.values()))); + doReturn(declared).when(dimension).getModuleSettings(); Engine engine = mock(Engine.class); doReturn(data).when(engine).getData(); doReturn(dimension).when(engine).getDimension(); + DecoratorTestEngines.withGeneration(engine); return new Fixture(engine, data); } diff --git a/core/src/test/java/art/arcane/iris/engine/object/world/MovedModuleFieldsTest.java b/core/src/test/java/art/arcane/iris/engine/object/world/MovedModuleFieldsTest.java new file mode 100644 index 000000000..7845c69a3 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/object/world/MovedModuleFieldsTest.java @@ -0,0 +1,53 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.world; + +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.engine.object.world.region.IrisRegion; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertThrows; + +/** The carving, floating and ore settings are fields of modules now, not of Iris's pack classes: they stay off them. */ +public class MovedModuleFieldsTest { + @Test + public void theCaveFloatingAndOreSettingsAreNoFieldsOfTheBiome() { + for (String field : List.of("caveProfile", "carvingBiome", "caveMinDepthBelowSurface", "floatingChildBiomes", "mergeFloatingChildBiomes", + "oreDepositFrequencyMultiplier", "oreDepositSizeMultiplier", "depositVariants", "ores")) { + assertThrows(field, NoSuchFieldException.class, () -> IrisBiome.class.getDeclaredField(field)); + } + } + + @Test + public void theCaveAndOreSettingsAreNoFieldsOfTheRegion() { + for (String field : List.of("caveProfile", "depositVariants", "ores")) { + assertThrows(field, NoSuchFieldException.class, () -> IrisRegion.class.getDeclaredField(field)); + } + } + + @Test + public void theCarvingAndOreSettingsAreNoFieldsOfTheDimension() { + for (String field : List.of("caveProfile", "carving", "carvingEnabled", "depositVariants", "ores", "hideOresForHiddenOre")) { + assertThrows(field, NoSuchFieldException.class, () -> IrisDimension.class.getDeclaredField(field)); + } + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/object/world/biome/IrisBiomeInferenceIsolationTest.java b/core/src/test/java/art/arcane/iris/engine/object/world/biome/IrisBiomeInferenceIsolationTest.java index 300670488..23efc2604 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/world/biome/IrisBiomeInferenceIsolationTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/world/biome/IrisBiomeInferenceIsolationTest.java @@ -2,7 +2,10 @@ package art.arcane.iris.engine.object.world.biome; import art.arcane.iris.engine.object.world.biome.InferredType; import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.builtin.carve.CaveDepthSettings; import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.BuiltInPack; +import art.arcane.iris.core.modules.ModuleSettings; import com.google.gson.Gson; import org.junit.Test; @@ -31,4 +34,22 @@ public class IrisBiomeInferenceIsolationTest { assertEquals(InferredType.LAND, land.getInferredType()); assertEquals(InferredType.SEA, sea.getInferredType()); } + + @Test + public void aVariantKeepsTheModuleSettingsOfTheBiomeItIsCopiedFrom() { + Gson gson = new Gson(); + IrisData data = mock(IrisData.class); + when(data.getGson()).thenReturn(gson); + IrisBiome biome = gson.fromJson("{\"name\":\"Shared\"}", IrisBiome.class); + biome.setLoader(data); + biome.setLoadKey("shared"); + ModuleSettings declared = BuiltInPack.settings(new CaveDepthSettings(12)); + biome.setModuleSettings(declared); + biome.withInferredType(InferredType.LAND); + + IrisBiome sea = biome.withInferredType(InferredType.SEA); + + assertNotSame(biome, sea); + assertSame(declared, sea.getModuleSettings()); + } } diff --git a/core/src/test/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionReachableBiomesTest.java b/core/src/test/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionReachableBiomesTest.java index 20472e03c..c89f97d8b 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionReachableBiomesTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionReachableBiomesTest.java @@ -4,13 +4,20 @@ import art.arcane.iris.builtin.floating.FloatingChildBiome; import art.arcane.iris.engine.object.TestSettings; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingEntry; +import art.arcane.iris.builtin.carve.CarvingBiomeSettings; +import art.arcane.iris.builtin.carve.CarvingEntry; +import art.arcane.iris.builtin.carve.CarvingSettings; +import art.arcane.iris.builtin.floating.FloatingChildSettings; +import art.arcane.iris.core.modules.BuiltInPack; +import com.google.gson.Gson; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.ResourceLoader; import art.arcane.volmlib.util.collection.KList; +import com.volmit.IrisFeature; import org.junit.Test; +import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -24,44 +31,30 @@ public class IrisDimensionReachableBiomesTest { @Test @SuppressWarnings("unchecked") public void includesExactRecursiveGenerationClosure() { - IrisDimensionCarvingEntry deepBand = new IrisDimensionCarvingEntry() - .setId("global-deep-band") - .setBiome("deep-root"); - IrisDimensionCarvingEntry disabledBand = new IrisDimensionCarvingEntry() - .setId("disabled-band") - .setEnabled(false) - .setBiome("disabled-deep"); - IrisDimensionCarvingEntry floatingCarvingEntry = new IrisDimensionCarvingEntry() - .setId("floating-carving-entry") - .setEnabled(false) - .setBiome("entry-floating-carve"); + CarvingEntry deepBand = entry("global-deep-band", true, "deep-root"); + CarvingEntry disabledBand = entry("disabled-band", false, "disabled-deep"); + CarvingEntry floatingCarvingEntry = entry("floating-carving-entry", false, "entry-floating-carve"); IrisDimension dimension = new IrisDimension().setRegions(new KList<>("reachable", "missing")); - dimension.setCarving(new KList<>(deepBand, disabledBand, floatingCarvingEntry)); + dimension.setModuleSettings(BuiltInPack.settings(new CarvingSettings(List.of(deepBand, disabledBand, floatingCarvingEntry)))); IrisRegion reachable = new IrisRegion() .setLandBiomes(new KList<>("parent", "shared")) .setSeaBiomes(new KList<>("shared")); - IrisBiome parent = biome("parent") - .setChildren(new KList<>("child", "shared")) - .setCarvingBiome("carve") - .setFloatingChildBiomes(new KList<>(floating("floating-target", "direct-floating-carve"))); + IrisBiome parent = biome("parent", carvingBiome("carve"), floatingChildren(floating("floating-target", "direct-floating-carve"))) + .setChildren(new KList<>("child", "shared")); IrisBiome child = biome("child").setChildren(new KList<>("parent")); IrisBiome shared = biome("shared"); IrisBiome carve = biome("carve"); - IrisBiome floatingTarget = biome("floating-target") - .setChildren(new KList<>("floating-child")) - .setCarvingBiome("floating-carve"); - IrisBiome floatingChild = biome("floating-child") - .setFloatingChildBiomes(new KList<>(floating("nested-floating", "floating-carving-entry"))); + IrisBiome floatingTarget = biome("floating-target", carvingBiome("floating-carve")) + .setChildren(new KList<>("floating-child")); + IrisBiome floatingChild = biome("floating-child", floatingChildren(floating("nested-floating", "floating-carving-entry"))); IrisBiome floatingCarve = biome("floating-carve"); IrisBiome directFloatingCarve = biome("direct-floating-carve"); IrisBiome entryFloatingCarve = biome("entry-floating-carve"); IrisBiome shadowedFloatingCarve = biome("floating-carving-entry"); - IrisBiome nestedFloating = biome("nested-floating") - .setFloatingChildBiomes(new KList<>(floating("parent"))); + IrisBiome nestedFloating = biome("nested-floating", floatingChildren(floating("parent"))); IrisBiome deepRoot = biome("deep-root").setChildren(new KList<>("deep-child")); - IrisBiome deepChild = biome("deep-child").setCarvingBiome("deep-carve"); - IrisBiome deepCarve = biome("deep-carve") - .setFloatingChildBiomes(new KList<>(floating("deep-floating"))); + IrisBiome deepChild = biome("deep-child", carvingBiome("deep-carve")); + IrisBiome deepCarve = biome("deep-carve", floatingChildren(floating("deep-floating"))); IrisBiome deepFloating = biome("deep-floating").setChildren(new KList<>("deep-root")); IrisBiome disabledDeep = biome("disabled-deep"); IrisBiome unused = biome("unused"); @@ -108,11 +101,10 @@ public class IrisDimensionReachableBiomesTest { IrisDimension dimension = new IrisDimension().setRegions(new KList<>("reachable")); IrisRegion reachable = new IrisRegion().setLandBiomes(new KList<>("a")); IrisBiome a = biome("a").setChildren(new KList<>("b")); - IrisBiome b = biome("b").setCarvingBiome("c"); - IrisBiome c = biome("c").setFloatingChildBiomes(new KList<>(floating("d", "a"))); - IrisBiome d = biome("d") - .setChildren(new KList<>("a")) - .setFloatingChildBiomes(new KList<>(floating("b"))); + IrisBiome b = biome("b", carvingBiome("c")); + IrisBiome c = biome("c", floatingChildren(floating("d", "a"))); + IrisBiome d = biome("d", floatingChildren(floating("b"))) + .setChildren(new KList<>("a")); IrisData data = mock(IrisData.class); ResourceLoader regionLoader = mock(ResourceLoader.class); @@ -136,12 +128,25 @@ public class IrisDimensionReachableBiomesTest { verify(biomeLoader, times(1)).load("d"); } - private IrisBiome biome(String loadKey) { + private IrisBiome biome(String loadKey, IrisFeature... settings) { IrisBiome biome = new IrisBiome(); biome.setLoadKey(loadKey); + biome.setModuleSettings(BuiltInPack.settings(settings)); return biome; } + private CarvingBiomeSettings carvingBiome(String key) { + return new CarvingBiomeSettings(key); + } + + private FloatingChildSettings floatingChildren(FloatingChildBiome... children) { + return new FloatingChildSettings(List.of(children)); + } + + private CarvingEntry entry(String id, boolean enabled, String biome) { + return new Gson().fromJson("{\"id\": \"" + id + "\", \"enabled\": " + enabled + ", \"biome\": \"" + biome + "\"}", CarvingEntry.class); + } + private FloatingChildBiome floating(String biomeKey) { return TestSettings.with(new FloatingChildBiome(), "biome", biomeKey); } diff --git a/core/src/test/java/art/arcane/iris/engine/object/world/region/IrisRegionBiomeTreeTest.java b/core/src/test/java/art/arcane/iris/engine/object/world/region/IrisRegionBiomeTreeTest.java new file mode 100644 index 000000000..030c4e023 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/object/world/region/IrisRegionBiomeTreeTest.java @@ -0,0 +1,73 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.world.region; + +import art.arcane.iris.builtin.carve.CarvingBiomeSettings; +import art.arcane.iris.builtin.floating.FloatingChildBiome; +import art.arcane.iris.builtin.floating.FloatingChildSettings; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.loader.ResourceLoader; +import art.arcane.iris.core.modules.BuiltInPack; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.volmlib.util.collection.KList; +import com.google.gson.Gson; +import com.volmit.IrisFeature; +import org.junit.Test; + +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** The biomes of a region: the ones it lists, their children and the biomes their {@code carvingBiome} registers; not the targets of floating islands. */ +public class IrisRegionBiomeTreeTest { + @Test + @SuppressWarnings("unchecked") + public void aBiomesCarvingBiomeJoinsTheRegionAndAFloatingChildDoesNot() { + IrisRegion region = new IrisRegion().setLandBiomes(new KList<>("plains")); + FloatingChildBiome floating = new Gson().fromJson("{\"biome\": \"floating/target\", \"carving\": \"carving/pocket\"}", FloatingChildBiome.class); + IrisBiome plains = biome("plains", new CarvingBiomeSettings("carving/mushroom"), new FloatingChildSettings(List.of(floating))) + .setChildren(new KList<>("meadow")); + IrisBiome meadow = biome("meadow"); + IrisBiome mushroom = biome("carving/mushroom", new CarvingBiomeSettings("carving/nested")); + IrisBiome nested = biome("carving/nested"); + + IrisData data = mock(IrisData.class); + ResourceLoader biomes = mock(ResourceLoader.class); + when(data.getBiomeLoader()).thenReturn(biomes); + when(biomes.load("plains")).thenReturn(plains); + when(biomes.load("meadow")).thenReturn(meadow); + when(biomes.load("carving/mushroom")).thenReturn(mushroom); + when(biomes.load("carving/nested")).thenReturn(nested); + + Set keys = region.getAllBiomes(() -> data).stream().map(IrisBiome::getLoadKey).collect(Collectors.toSet()); + + assertEquals(Set.of("plains", "meadow", "carving/mushroom", "carving/nested"), keys); + } + + private static IrisBiome biome(String key, IrisFeature... settings) { + IrisBiome biome = new IrisBiome(); + biome.setLoadKey(key); + biome.setModuleSettings(BuiltInPack.settings(settings)); + return biome; + } +} diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/biomes/carving/amethyst.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/biomes/carving/amethyst.json new file mode 100644 index 000000000..9a1c2649c --- /dev/null +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/biomes/carving/amethyst.json @@ -0,0 +1,292 @@ +{ + "name": "Amethyst Cavern", + "derivative": "minecraft:dripstone_caves", + "vanillaDerivative": "minecraft:dripstone_caves", + "wall": { + "palette": [ + { + "block": "minecraft:amethyst_block", + "weight": 6 + }, + { + "block": "minecraft:budding_amethyst" + } + ] + }, + "layers": [ + { + "palette": [ + { + "block": "minecraft:amethyst_block", + "weight": 6 + }, + { + "block": "minecraft:budding_amethyst" + } + ], + "maxHeight": 2, + "minHeight": 2 + }, + { + "palette": [ + { + "block": "minecraft:deepslate" + } + ] + } + ], + "decorators": [ + { + "chance": 0.1, + "palette": [ + { + "block": "minecraft:amethyst_cluster", + "weight": 4 + }, + { + "block": "minecraft:small_amethyst_bud", + "weight": 3 + }, + { + "block": "minecraft:medium_amethyst_bud", + "weight": 2 + }, + { + "block": "minecraft:large_amethyst_bud" + } + ] + }, + { + "partOf": "CEILING", + "chance": 0.1, + "palette": [ + { + "block": "minecraft:amethyst_cluster", + "data": { + "facing": "down" + }, + "weight": 4 + }, + { + "block": "minecraft:small_amethyst_bud", + "data": { + "facing": "down" + }, + "weight": 3 + }, + { + "block": "minecraft:medium_amethyst_bud", + "data": { + "facing": "down" + }, + "weight": 2 + }, + { + "block": "minecraft:large_amethyst_bud", + "data": { + "facing": "down" + } + } + ] + } + ], + "caveCeilingLayers": [ + { + "palette": [ + { + "block": "minecraft:amethyst_block", + "weight": 6 + }, + { + "block": "minecraft:budding_amethyst" + } + ], + "maxHeight": 2, + "minHeight": 2 + }, + { + "palette": [ + { + "block": "minecraft:deepslate" + } + ] + } + ], + "objects": [ + { + "chance": 0.21, + "density": 4, + "carvingSupport": "CARVING_ONLY", + "caveAnchorMode": "PROFILE_DEFAULT", + "translate": { + "y": -1 + }, + "place": [ + "clutter/amethyst-cluster1", + "clutter/amethyst-cluster2", + "clutter/amethyst-cluster3", + "clutter/amethyst-cluster4" + ], + "bottom": true, + "force": true, + "scale": { + "size": 0.75 + } + }, + { + "chance": 0.165, + "density": 4, + "carvingSupport": "CARVING_ONLY", + "caveAnchorMode": "PROFILE_DEFAULT", + "translate": { + "y": -1 + }, + "place": [ + "clutter/amethyst-cluster1", + "clutter/amethyst-cluster2", + "clutter/amethyst-cluster3", + "clutter/amethyst-cluster4", + "clutter/amethyst-cluster5" + ], + "bottom": true, + "force": true, + "scale": { + "size": 0.75 + } + }, + { + "chance": 0.0972, + "density": 4, + "carvingSupport": "CARVING_ONLY", + "caveAnchorMode": "PROFILE_DEFAULT", + "translate": { + "y": -1 + }, + "place": [ + "clutter/amethyst-cluster1", + "clutter/amethyst-cluster2", + "clutter/amethyst-cluster3" + ], + "bottom": true, + "force": true, + "scale": { + "size": 0.75 + } + }, + { + "chance": 0.0972, + "density": 4, + "carvingSupport": "CARVING_ONLY", + "caveAnchorMode": "PROFILE_DEFAULT", + "translate": { + "y": -1 + }, + "place": [ + "clutter/rock1", + "clutter/rock2", + "clutter/rock3", + "clutter/rock4", + "clutter/boulder1", + "clutter/boulder2", + "clutter/boulder3", + "clutter/boulder4" + ], + "bottom": true, + "force": true, + "scale": { + "size": 0.75 + } + } + ], + "caveProfile": { + "enabled": true, + "verticalRange": { + "min": 6, + "max": 620 + }, + "baseDensityStyle": { + "style": "PERLIN_IRIS", + "zoom": 0.8 + }, + "detailDensityStyle": { + "style": "FRACTAL_BILLOW_SIMPLEX", + "zoom": 0.52 + }, + "warpStyle": { + "style": "SIMPLEX", + "zoom": 0.46 + }, + "baseWeight": 0.91, + "detailWeight": 0.1, + "warpStrength": 0.18, + "densityThreshold": { + "min": -0.12, + "max": -0.04, + "style": { + "style": "SIMPLEX", + "zoom": 0.7 + } + }, + "thresholdBias": 0.12, + "sampleStep": 2, + "surfaceClearance": 6, + "allowSurfaceBreak": true, + "surfaceBreakStyle": { + "style": "SIMPLEX", + "zoom": 0.9 + }, + "surfaceBreakNoiseThreshold": 0.68, + "surfaceBreakDepth": 12, + "surfaceBreakThresholdBoost": 0.1, + "objectMinDepthBelowSurface": 16, + "defaultObjectAnchor": "FLOOR", + "defaultObjectPlaceMode": "ORGANIC_STILT", + "anchorScanStep": 1, + "anchorSearchAttempts": 18, + "allowFluid": true, + "fluidMinDepthBelowSurface": 20, + "fluidRequiresFloor": true, + "allowLava": true, + "modules": [ + { + "style": { + "style": "SIMPLEX_VASCULAR", + "zoom": 0.98 + }, + "weight": 0.08, + "threshold": 0.03, + "verticalRange": { + "min": 24, + "max": 680 + }, + "invert": false + }, + { + "style": { + "style": "FRACTAL_BILLOW_SIMPLEX", + "zoom": 0.34 + }, + "weight": 0.04, + "threshold": 0.07, + "verticalRange": { + "min": 8, + "max": 260 + }, + "invert": true + } + ], + "verticalEdgeFade": 26, + "verticalEdgeFadeStrength": 0.18, + "minCarveCells": 24, + "recoveryThresholdBoost": 0.07 + }, + "caveMinDepthBelowSurface": 10, + "children": [ + "carving/amethyst-child" + ], + "childStyle": { + "style": "CELLULAR_IRIS_DOUBLE", + "zoom": 0.74 + }, + "childShrinkFactor": 1.54 +} diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/biomes/magnetics/plains.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/biomes/magnetics/plains.json new file mode 100644 index 000000000..eeb79f2a0 --- /dev/null +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/biomes/magnetics/plains.json @@ -0,0 +1,551 @@ +{ + "name": "Magnetics Plains", + "color": "#89C46A", + "rarity": 1, + "derivative": "minecraft:plains", + "vanillaDerivative": "minecraft:plains", + "generators": [ + { + "min": -3, + "max": 14, + "generator": "magnetics/plains" + } + ], + "wall": { + "palette": [ + { + "block": "minecraft:mossy_cobblestone" + }, + { + "block": "minecraft:cobblestone" + }, + { + "block": "minecraft:stone" + }, + { + "block": "minecraft:moss_block" + } + ] + }, + "layers": [ + { + "maxHeight": 1, + "palette": [ + { + "block": "minecraft:grass_block" + }, + { + "block": "minecraft:moss_block" + } + ], + "slopeCondition": { + "maximumSlope": 4 + } + }, + { + "minHeight": 1, + "maxHeight": 3, + "palette": [ + { + "block": "minecraft:dirt" + }, + { + "block": "minecraft:rooted_dirt" + }, + { + "block": "minecraft:coarse_dirt" + } + ] + }, + { + "minHeight": 3, + "maxHeight": 6, + "palette": [ + { + "block": "minecraft:mossy_cobblestone" + }, + { + "block": "minecraft:cobblestone" + }, + { + "block": "minecraft:stone" + } + ] + }, + { + "minHeight": 6, + "maxHeight": 18, + "palette": [ + { + "block": "minecraft:stone" + }, + { + "block": "minecraft:andesite" + }, + { + "block": "minecraft:deepslate" + }, + { + "block": "minecraft:cobblestone" + } + ] + } + ], + "objects": [ + { + "place": [ + "trees/oak/antioch1", + "trees/oak/antioch2", + "trees/oak/antioch4", + "trees/oak/antioch5", + "trees/oak/antioch6", + "trees/oak/antioch7", + "trees/oak/antioch8", + "trees/oak/antioch9", + "trees/oak/antioch10", + "trees/oak/antioch11", + "trees/oak/antioch12", + "trees/oak/antioch13" + ], + "carvingSupport": "SURFACE_ONLY", + "chance": 0.5, + "mode": "CENTER_STILT", + "stiltSettings": { + "yMax": 4, + "yRand": 1 + }, + "rotation": { + "yAxis": { + "min": 0, + "max": 270, + "interval": 90, + "enabled": true + }, + "enabled": true + } + } + ], + "decorators": [ + { + "chance": 0.2, + "palette": [ + { + "block": "minecraft:dandelion" + }, + { + "block": "minecraft:poppy" + }, + { + "block": "minecraft:blue_orchid" + }, + { + "block": "minecraft:allium" + }, + { + "block": "minecraft:azure_bluet" + }, + { + "block": "minecraft:cornflower" + }, + { + "block": "minecraft:lily_of_the_valley" + } + ] + }, + { + "chance": 0.75, + "palette": [ + { + "block": "minecraft:short_grass" + } + ] + } + ], + "mergeFloatingChildBiomes": true, + "floatingChildBiomes": [ + { + "biome": "mushroom/forest", + "rarity": 1, + "footprintStyle": { + "style": "GLOB_IRIS_THICK", + "zoom": 0.76, + "fracture": { + "style": "SIMPLEX", + "zoom": 0.16, + "multiplier": 5 + } + }, + "footprintThreshold": 0.47, + "pickerStyle": { + "style": "SIMPLEX", + "zoom": 4.0 + }, + "altitudeStyle": { + "style": "SIMPLEX", + "zoom": 2.7 + }, + "minHeightAboveSurface": 115, + "maxHeightAboveSurface": 155, + "topShapeMode": "NOISE", + "maxTopHeight": 17, + "topShapeStyle": { + "style": "PERLIN_IRIS_THICK", + "zoom": 0.55, + "fracture": { + "style": "SIMPLEX", + "zoom": 0.18, + "multiplier": 6 + } + }, + "topShapeAmp": 0.75, + "edgeTaperWidth": 14, + "edgeTaperExponent": 1.4, + "edgeTaperVariationStyle": { + "style": "SIMPLEX", + "zoom": 0.18 + }, + "edgeTaperVariationAmplitude": 4, + "bottomStyle": { + "style": "SIMPLEX_VASCULAR", + "zoom": 0.3, + "fracture": { + "style": "SIMPLEX", + "zoom": 0.13, + "multiplier": 5 + } + }, + "bottomDepthMin": 6, + "bottomDepthMax": 46, + "bottomExponent": 2.2, + "bottomPaletteMode": "CUSTOM", + "bottomPalette": [ + { + "minHeight": 18, + "maxHeight": 18, + "palette": [ + { + "block": "minecraft:andesite" + } + ] + } + ], + "maxThickness": 72, + "wallWarpStyle": { + "style": "SIMPLEX", + "zoom": 0.25, + "fracture": { + "style": "SIMPLEX", + "zoom": 0.12, + "multiplier": 3 + } + }, + "wallWarpAmplitude": 5, + "carving": "carving/mushroom", + "carveStyle": { + "style": "SIMPLEX", + "zoom": 0.22, + "fracture": { + "style": "SIMPLEX", + "zoom": 0.14, + "multiplier": 3 + } + }, + "carveThreshold": 0.84, + "inheritDecorators": true, + "inheritObjects": true, + "objectShrinkFactor": 0.5, + "topObjectMode": "MERGE", + "topObjectOverrides": [ + { + "place": [ + "trees/mushroom/mushclut1", + "trees/mushroom/mushclut2", + "trees/mushroom/mushclut3", + "trees/mushroom/mushclut4", + "trees/mushroom/mushclut5", + "trees/mushroom/mushclut6", + "trees/mushroom/mushclut7", + "trees/mushroom/mushclut8", + "trees/mushroom/mushclut9", + "trees/mushroom/mushclut10" + ], + "chance": 0.82, + "mode": "CENTER_HEIGHT", + "density": 7, + "scale": { + "size": 0.85 + }, + "warp": { + "style": "SIMPLEX", + "zoom": 0.28, + "multiplier": 1.1 + }, + "rotation": { + "yAxis": { + "min": 0, + "max": 270, + "interval": 90, + "enabled": true + }, + "enabled": true + } + }, + { + "place": [ + "trees/mushroom/browngeneric1", + "trees/mushroom/browngeneric2", + "trees/mushroom/redgeneric3", + "trees/mushroom/redgeneric4", + "trees/mushroom/redgeneric5", + "trees/mushroom/redgeneric6", + "trees/mushroom/redgeneric7", + "trees/mushroom/redgeneric8", + "trees/mushroom/redgeneric9", + "trees/mushroom/redgeneric10", + "trees/mushroom/redgeneric11", + "trees/mushroom/redlumotall1", + "trees/mushroom/redlumotall2", + "trees/mushroom/redlumotall3", + "trees/mushroom/redlumotall4", + "trees/mushroom/redlumotall5" + ], + "chance": 0.62, + "mode": "CENTER_STILT", + "density": 5, + "scale": { + "size": 0.8 + }, + "warp": { + "style": "SIMPLEX_VASCULAR", + "zoom": 0.32, + "multiplier": 1.0 + }, + "rotation": { + "yAxis": { + "min": 0, + "max": 270, + "interval": 90, + "enabled": true + }, + "enabled": true + } + }, + { + "place": [ + "trees/mushroom/smolshroom1", + "trees/mushroom/smolshroom2", + "trees/mushroom/smolshroom3", + "trees/mushroom/smolshroom4", + "trees/mushroom/smolshroom5" + ], + "chance": 0.85, + "mode": "CENTER_HEIGHT", + "density": 8, + "scale": { + "size": 0.9 + }, + "warp": { + "style": "SIMPLEX", + "zoom": 0.2, + "multiplier": 0.7 + }, + "rotation": { + "yAxis": { + "min": 0, + "max": 270, + "interval": 90, + "enabled": true + }, + "enabled": true + } + } + ], + "bottomObjectMode": "REPLACE", + "bottomObjectOverrides": [ + { + "place": [ + "trees/mushroom/mushclut1", + "trees/mushroom/mushclut2", + "trees/mushroom/mushclut3", + "trees/mushroom/mushclut4", + "trees/mushroom/mushclut5", + "trees/mushroom/mushclut6", + "trees/mushroom/mushclut7", + "trees/mushroom/mushclut8", + "trees/mushroom/mushclut9", + "trees/mushroom/mushclut10", + "trees/mushroom/smolshroom1", + "trees/mushroom/smolshroom2", + "trees/mushroom/smolshroom3", + "trees/mushroom/smolshroom4", + "trees/mushroom/smolshroom5" + ], + "chance": 0.5, + "mode": "FAST_MIN_HEIGHT", + "density": 5, + "scale": { + "size": 0.7 + }, + "warp": { + "style": "SIMPLEX", + "zoom": 0.25, + "multiplier": 0.8 + }, + "rotation": { + "yAxis": { + "min": 0, + "max": 270, + "interval": 90, + "enabled": true + }, + "enabled": true + } + } + ] + }, + { + "biome": "tropical/wilds", + "rarity": 1, + "footprintStyle": { + "style": "GLOB_IRIS_DOUBLE", + "zoom": 0.72, + "fracture": { + "style": "SIMPLEX", + "zoom": 0.24, + "multiplier": 4 + } + }, + "footprintThreshold": 0.5, + "pickerStyle": { + "style": "SIMPLEX", + "zoom": 4.0 + }, + "altitudeStyle": { + "style": "SIMPLEX", + "zoom": 2.3 + }, + "minHeightAboveSurface": 75, + "maxHeightAboveSurface": 115, + "topShapeMode": "NOISE", + "maxTopHeight": 18, + "topShapeStyle": { + "style": "FRACTAL_WATER", + "zoom": 0.38, + "fracture": { + "style": "SIMPLEX", + "zoom": 0.18, + "multiplier": 4 + } + }, + "topShapeAmp": 0.7, + "edgeTaperWidth": 15, + "edgeTaperExponent": 1.35, + "edgeTaperVariationStyle": { + "style": "SIMPLEX", + "zoom": 0.2 + }, + "edgeTaperVariationAmplitude": 4, + "bottomStyle": { + "style": "SIMPLEX_VASCULAR", + "zoom": 0.32, + "fracture": { + "style": "SIMPLEX", + "zoom": 0.14, + "multiplier": 5 + } + }, + "bottomDepthMin": 6, + "bottomDepthMax": 44, + "bottomExponent": 2.15, + "maxThickness": 72, + "wallWarpStyle": { + "style": "SIMPLEX", + "zoom": 0.26, + "fracture": { + "style": "SIMPLEX", + "zoom": 0.13, + "multiplier": 3 + } + }, + "wallWarpAmplitude": 5, + "carving": "carving/lush-child", + "carveStyle": { + "style": "SIMPLEX", + "zoom": 0.22, + "fracture": { + "style": "SIMPLEX", + "zoom": 0.14, + "multiplier": 3 + } + }, + "carveThreshold": 0.86, + "inheritDecorators": true, + "inheritObjects": true, + "objectShrinkFactor": 0.5, + "topObjectMode": "MERGE", + "topObjectOverrides": [ + { + "place": [ + "clutter/shrub4", + "clutter/shrub5", + "clutter/shrub6", + "clutter/oakshrub1", + "clutter/oakshrub2", + "clutter/oakshrub3" + ], + "chance": 0.75, + "mode": "CENTER_HEIGHT", + "density": 8 + }, + { + "place": [ + "trees/oak/antioch7", + "trees/oak/antioch8", + "trees/oak/antioch9", + "trees/oak/antioch10", + "trees/oak/antioch11", + "trees/oak/antioch12" + ], + "chance": 0.5, + "mode": "CENTER_STILT", + "density": 5, + "rotation": { + "yAxis": { + "min": 0, + "max": 270, + "interval": 90, + "enabled": true + }, + "enabled": true + } + } + ], + "bottomObjectMode": "INHERIT_ONLY", + "bottomObjectOverrides": [ + { + "place": [ + "trees/oak/antioch7", + "trees/oak/antioch8", + "trees/oak/antioch9", + "trees/oak/antioch10", + "clutter/boulder1", + "clutter/boulder2", + "clutter/boulder3" + ], + "chance": 0.5, + "mode": "FAST_MIN_HEIGHT", + "density": 6, + "rotation": { + "yAxis": { + "min": 0, + "max": 270, + "interval": 90, + "enabled": true + }, + "enabled": true + } + } + ] + } + ] +} diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/regions/forests.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/regions/forests.json new file mode 100644 index 000000000..eaaad5baa --- /dev/null +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/regions/forests.json @@ -0,0 +1,107 @@ +{ + "name": "Forests", + "color": "#9BEE61", + "rarity": 1, + "landBiomes": [ + "tundra/forest", + "tundra/autumn", + "mountain/plains", + "temperate/reaching-forest-violet", + "temperate/flower-forest", + "temperate/birch-tall", + "temperate/osaka-red-forest", + "mountain/mountain", + "temperate/combo-forest", + "tundra/redwood-forest", + "vanilla/old_growth_birch_forest", + "vanilla/old_growth_pine_taiga", + "vanilla/windswept_forest" + ], + "caveBiomes": [ + "carving/rocky-cavebiome", + "carving/lush", + "carving/mountain-caves", + "carving/moss-pillars" + ], + "shoreBiomes": [ + "temperate/shore/beach", + "temperate/shore/oak-beach" + ], + "seaBiomeZoom": 6, + "seaBiomes": [ + "ocean/deep", + "ocean/dark-depth-ocean", + "ocean/rich-oceans" + ], + "shoreBiomeZoom": 0.15, + "landBiomeZoom": 3.5, + "shoreHeightMin": 1, + "shoreHeightMax": 5.2, + "shoreHeightZoom": 1.14, + "loot": { + "mode": "FALLBACK", + "multiplier": 0.5, + "tables": [ + "temperate/clutter", + "temperate/food" + ] + }, + "caveProfile": { + "enabled": true, + "verticalRange": { + "min": 6, + "max": 120 + }, + "baseDensityStyle": { + "style": "PERLIN", + "zoom": 0.55 + }, + "detailDensityStyle": { + "style": "SIMPLEX", + "zoom": 0.5 + }, + "warpStyle": { + "style": "SIMPLEX", + "zoom": 0.5 + }, + "baseWeight": 1, + "detailWeight": 0, + "warpStrength": 0, + "densityThreshold": { + "min": -0.14, + "max": -0.06, + "style": { + "style": "SIMPLEX", + "zoom": 0.5 + } + }, + "thresholdBias": 0.06, + "sampleStep": 3, + "surfaceClearance": 12, + "allowSurfaceBreak": false, + "surfaceBreakStyle": { + "style": "SIMPLEX", + "zoom": 0.88 + }, + "surfaceBreakNoiseThreshold": 0.99, + "surfaceBreakDepth": 4, + "surfaceBreakThresholdBoost": 0.02, + "objectMinDepthBelowSurface": 14, + "defaultObjectAnchor": "FLOOR", + "defaultObjectPlaceMode": "ORGANIC_STILT", + "anchorScanStep": 1, + "anchorSearchAttempts": 12, + "allowFluid": true, + "fluidMinDepthBelowSurface": 20, + "fluidRequiresFloor": true, + "allowLava": true, + "modules": [] + }, + "caveBiomeZoom": 3.3, + "entitySpawners": [ + "temperate/cave", + "temperate/hostile", + "temperate/passive", + "temperate/water" + ] +} diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/snippet/cave-profile/shallow.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/snippet/cave-profile/shallow.json new file mode 100644 index 000000000..da6bec3e8 --- /dev/null +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/snippet/cave-profile/shallow.json @@ -0,0 +1,5 @@ +{ + "enabled": true, + "verticalRange": {"min": 10, "max": 100}, + "sampleStep": 2 +} From fbbc9ce4ac5c77b747c83862c4bb83e62cce8961 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 13:00:03 +0200 Subject: [PATCH 08/10] Modded loot, drops, spawns, mobs and effects ask the modules through host-typed content services --- .../iris/modded/ModdedBlockBreakHandler.java | 91 +----- .../arcane/iris/modded/ModdedDeathLoot.java | 22 +- .../iris/modded/ModdedEngineEffects.java | 157 ++++------- .../modded/ModdedEntityCommandRunner.java | 24 +- .../iris/modded/ModdedEntitySpawner.java | 171 ++++++----- .../iris/modded/ModdedItemTranslator.java | 160 ++++------- .../arcane/iris/modded/ModdedLootApplier.java | 143 ++-------- .../iris/modded/ModdedWorldManager.java | 265 +++--------------- .../modded/command/ModdedStudioCommands.java | 67 +---- .../modded/ModdedBlockBreakHandlerTest.java | 41 --- .../modded/ModdedEntitySpawnerParityTest.java | 11 - .../iris/modded/ModdedLootApplierTest.java | 12 +- .../modded/ModdedSpawnerRarityParityTest.java | 75 ----- .../iris/core/content/ContentEffect.java | 44 +++ .../iris/core/content/ContentEntity.java | 57 ++++ .../arcane/iris/core/content/ContentItem.java | 40 +++ .../arcane/iris/core/content/ContentLoot.java | 47 ++++ .../iris/core/content/ContentServices.java | 192 +++++++++++++ .../iris/core/content/ContentSpawns.java | 85 ++++++ .../core/pack/ModuleResourceClosureTest.java | 134 +++++++++ .../iris/core/pack/PackExportClosureTest.java | 6 +- .../iris/engine/loot/PlacementLootTest.java | 150 ++++++++++ .../engine/loot/ResolvedBlockDropTest.java | 72 +++++ .../object/value/IRareWeightingTest.java | 56 ++++ 24 files changed, 1178 insertions(+), 944 deletions(-) delete mode 100644 adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedBlockBreakHandlerTest.java delete mode 100644 adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedSpawnerRarityParityTest.java create mode 100644 core/src/main/java/art/arcane/iris/core/content/ContentEffect.java create mode 100644 core/src/main/java/art/arcane/iris/core/content/ContentEntity.java create mode 100644 core/src/main/java/art/arcane/iris/core/content/ContentItem.java create mode 100644 core/src/main/java/art/arcane/iris/core/content/ContentLoot.java create mode 100644 core/src/main/java/art/arcane/iris/core/content/ContentServices.java create mode 100644 core/src/main/java/art/arcane/iris/core/content/ContentSpawns.java create mode 100644 core/src/test/java/art/arcane/iris/core/pack/ModuleResourceClosureTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/loot/PlacementLootTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/loot/ResolvedBlockDropTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/object/value/IRareWeightingTest.java diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedBlockBreakHandler.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedBlockBreakHandler.java index d2382d541..3d9e88c5e 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedBlockBreakHandler.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedBlockBreakHandler.java @@ -18,21 +18,13 @@ package art.arcane.iris.modded; -import art.arcane.iris.engine.spawn.SpawnResources; -import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.content.ContentLoot; +import art.arcane.iris.core.content.ContentServices; +import art.arcane.iris.core.content.ContentSpawns; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.LootResolver; import art.arcane.iris.engine.framework.TreeBlockMaterial; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.material.IrisBlockData; -import art.arcane.iris.engine.object.loot.IrisBlockDrops; -import art.arcane.iris.engine.object.loot.IrisLoot; -import art.arcane.iris.engine.object.marker.IrisMarker; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.modded.service.ModdedTreeFellerService; import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.matter.MatterMarker; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; @@ -204,26 +196,13 @@ public final class ModdedBlockBreakHandler { BlockState brokenState, Engine engine ) { - KList providers = providers(engine, position, brokenState); - if (providers.isEmpty()) { + ContentLoot.BlockDrops dropped = ContentServices.blockDrops(engine, position.getX(), position.getY(), position.getZ(), + ModdedBlockState.serialize(brokenState)); + if (dropped.drops().isEmpty() && !dropped.replacesVanillaDrops()) { return Result.empty(); } - KList drops = new KList<>(); - boolean replaceVanillaDrops = false; - for (IrisBlockDrops provider : providers) { - replaceVanillaDrops |= provider.isReplaceVanillaDrops(); - for (IrisLoot loot : provider.getDrops()) { - if (!LootResolver.oneIn(RNG.r, loot.getRarity())) { - continue; - } - ItemStack stack = ModdedItemTranslator.stack(loot, RNG.r, level); - if (stack != null && !stack.isEmpty()) { - drops.add(stack); - } - } - } - return new Result(drops, replaceVanillaDrops, null); + return new Result(ModdedItemTranslator.stacks(dropped.drops(), level), dropped.replacesVanillaDrops(), null); } private static void removeMarker(Engine engine, BlockPos position) { @@ -236,8 +215,7 @@ public final class ModdedBlockBreakHandler { if ("cave_floor".equals(tag) || "cave_ceiling".equals(tag)) { return; } - IrisMarker configured = SpawnResources.marker(engine.getData(), tag); - if (configured == null || configured.isRemoveOnChange()) { + if (ContentServices.markerRule(engine, tag).map(ContentSpawns.MarkerRule::removeOnChange).orElse(true)) { engine.getMantle().getMantle().remove(position.getX(), mantleY, position.getZ(), MatterMarker.class); } } @@ -248,59 +226,6 @@ public final class ModdedBlockBreakHandler { engine.getMantle().getMantle().remove(position.getX(), mantleY, position.getZ(), TreeBlockMaterial.class); } - private static KList providers(Engine engine, BlockPos position, BlockState brokenState) { - KList providers = new KList<>(); - IrisData data = engine.getData(); - int relativeY = position.getY() - engine.getMinHeight(); - IrisBiome biome = engine.getBiome(position.getX(), relativeY, position.getZ()); - if (biome != null) { - addMatching(providers, biome.getBlockDrops(), brokenState, data); - } - if (skipsParents(providers)) { - return providers; - } - IrisRegion region = engine.getRegion(position.getX(), position.getZ()); - if (region != null) { - addMatching(providers, region.getBlockDrops(), brokenState, data); - } - addMatching(providers, engine.getDimension().getBlockDrops(), brokenState, data); - return providers; - } - - private static void addMatching(KList matches, KList candidates, BlockState brokenState, IrisData data) { - for (IrisBlockDrops candidate : candidates) { - if (matches(candidate, brokenState, data)) { - matches.add(candidate); - } - } - } - - private static boolean skipsParents(KList providers) { - for (IrisBlockDrops provider : providers) { - if (provider.isSkipParents()) { - return true; - } - } - return false; - } - - private static boolean matches(IrisBlockDrops provider, BlockState brokenState, IrisData data) { - for (IrisBlockData configuredBlock : provider.getBlocks()) { - PlatformBlockState resolved = configuredBlock.getBlockData(data); - if (resolved == null || !(resolved.nativeHandle() instanceof BlockState configuredState)) { - continue; - } - if (matchesState(configuredState, brokenState, provider.isExactBlocks())) { - return true; - } - } - return false; - } - - static boolean matchesState(BlockState configuredState, BlockState brokenState, boolean exact) { - return exact ? configuredState.equals(brokenState) : configuredState.getBlock() == brokenState.getBlock(); - } - public static Engine engineFor(ServerLevel level) { ChunkGenerator generator = level.getChunkSource().getGenerator(); if (!(generator instanceof IrisModdedChunkGenerator irisGenerator)) { diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedDeathLoot.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedDeathLoot.java index 51a5b493b..a41dff2b0 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedDeathLoot.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedDeathLoot.java @@ -18,10 +18,8 @@ package art.arcane.iris.modded; -import art.arcane.iris.engine.loot.LootResources; +import art.arcane.iris.core.content.ContentServices; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.loot.InventorySlotType; -import art.arcane.iris.engine.object.loot.IrisLootTable; import art.arcane.iris.spi.IrisLogging; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; @@ -34,22 +32,23 @@ import net.minecraft.world.entity.vehicle.ContainerEntity; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.chunk.ChunkGenerator; +import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; public final class ModdedDeathLoot { private static final String TAG_PREFIX = "iris_loot|"; - private static final Set WARNED_TABLES = ConcurrentHashMap.newKeySet(); private static final Set WARNED_ENTITY_TYPES = ConcurrentHashMap.newKeySet(); private ModdedDeathLoot() { } - public static void bind(Engine engine, Entity entity, KList tableKeys, int spawnX, int spawnY, int spawnZ, RNG rng) { + /** Makes the loot of the pack's tables {@code tableKeys} the loot {@code entity} drops, or holds if it is a container; {@code shuffleSeed} seeds how a container's loot is shuffled. */ + public static void bind(Engine engine, Entity entity, List tableKeys, int spawnX, int spawnY, int spawnZ, long shuffleSeed) { if (engine == null || entity == null || tableKeys == null || tableKeys.isEmpty()) { return; } - LootBinding binding = new LootBinding(rng.getSeed(), spawnX, spawnY, spawnZ, new KList<>(tableKeys)); + LootBinding binding = new LootBinding(shuffleSeed, spawnX, spawnY, spawnZ, new KList<>(tableKeys)); if (entity instanceof Mob) { entity.addTag(encode(binding)); return; @@ -105,15 +104,8 @@ public final class ModdedDeathLoot { private static KList resolve(Engine engine, ServerLevel level, LootBinding binding) { KList drops = new KList<>(); for (String key : binding.tableKeys()) { - IrisLootTable table = LootResources.table(engine.getData(), key); - if (table == null) { - if (WARNED_TABLES.add(key)) { - IrisLogging.warn("Iris death loot: unknown loot table '" + key + "'"); - } - continue; - } - drops.addAll(ModdedItemTranslator.loot(table, engine.getSeedManager().getLoot(), InventorySlotType.STORAGE, level, - binding.spawnX(), binding.spawnY(), binding.spawnZ())); + drops.addAll(ModdedItemTranslator.stacks( + ContentServices.tableItems(engine, binding.spawnX(), binding.spawnY(), binding.spawnZ(), key), level)); } return drops; } diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineEffects.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineEffects.java index e35633c29..9243d96ac 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineEffects.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineEffects.java @@ -19,14 +19,11 @@ package art.arcane.iris.modded; import art.arcane.iris.core.IrisSettings; +import art.arcane.iris.core.content.ContentEffect; +import art.arcane.iris.core.content.ContentServices; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.EngineAssignedComponent; import art.arcane.iris.engine.framework.EngineEffects; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.marker.IrisCommand; -import art.arcane.iris.engine.object.marker.IrisCommandRegistry; -import art.arcane.iris.engine.object.entity.IrisEffect; -import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.spi.IrisLogging; import art.arcane.volmlib.util.math.RNG; import net.minecraft.core.Holder; @@ -194,17 +191,16 @@ public final class ModdedEngineEffects extends EngineAssignedComponent implement } samplePlayer(state); - if (!IrisSettings.get().getWorld().isEffectSystem()) { + if (!IrisSettings.get().getWorld().isEffectSystem() || !state.sampled()) { return; } - IrisRegion region = state.region(); - if (region != null) { - applyEffects(level, player, region.getEffects()); - } - IrisBiome biome = state.biome(); - if (biome != null) { - applyEffects(level, player, biome.getEffects()); + for (ContentEffect effect : ContentServices.ambientEffects(getEngine(), state.sampledX(), state.sampledY(), state.sampledZ())) { + try { + applyEffect(level, player, effect); + } catch (Throwable error) { + IrisLogging.reportError(error); + } } } @@ -222,36 +218,24 @@ public final class ModdedEngineEffects extends EngineAssignedComponent implement state.sampled(true); state.lastPosition(player.getX(), player.getY(), player.getZ()); state.lastSample(now); - int blockX = floor(player.getX()); - int blockY = floor(player.getY()) - getEngine().getWorld().minHeight(); - int blockZ = floor(player.getZ()); - state.biome(getEngine().getBiome(blockX, blockY, blockZ)); - state.region(getEngine().getRegion(blockX, blockZ)); + state.sampledAt(floor(player.getX()), floor(player.getY()), floor(player.getZ())); } - private void applyEffects(ServerLevel level, ServerPlayer player, Iterable effects) { - for (IrisEffect effect : effects) { - try { - applyEffect(level, player, effect); - } catch (Throwable error) { - IrisLogging.reportError(error); - } + private void applyEffect(ServerLevel level, ServerPlayer player, ContentEffect effect) { + if (effect.sound() != null) { + applySound(player, effect.sound()); + } + if (effect.particles() != null) { + applyParticles(level, player, effect.particles()); + } + applyCommands(level, player, effect.commands()); + if (effect.potion() != null) { + applyPotion(player, effect.potion()); } } - private void applyEffect(ServerLevel level, ServerPlayer player, IrisEffect effect) { - if (!effect.shouldApplyNow()) { - return; - } - - applySound(player, effect); - applyParticles(level, player, effect); - applyCommands(level, player, effect.getCommandRegistry()); - applyPotion(player, effect); - } - - private void applySound(ServerPlayer player, IrisEffect effect) { - String key = normalizeRegistryKey(effect.getSoundKey()); + private void applySound(ServerPlayer player, ContentEffect.Sound effect) { + String key = normalizeRegistryKey(effect.key()); if (key == null) { return; } @@ -264,18 +248,13 @@ public final class ModdedEngineEffects extends EngineAssignedComponent implement return; } - int distance = effect.getSoundDistance(); - double x = player.getX() + RNG.r.i(-distance, distance); - double y = player.getY() + RNG.r.i(-distance, distance); - double z = player.getZ() + RNG.r.i(-distance, distance); - float volume = (float) effect.getVolume(); - float pitch = (float) RNG.r.d(effect.getMinPitch(), effect.getMaxPitch()); player.connection.send(new ClientboundSoundPacket( - sound.get(), SoundSource.MASTER, x, y, z, volume, pitch, ThreadLocalRandom.current().nextLong())); + sound.get(), SoundSource.MASTER, player.getX() + effect.offsetX(), player.getY() + effect.offsetY(), + player.getZ() + effect.offsetZ(), effect.volume(), effect.pitch(), ThreadLocalRandom.current().nextLong())); } - private void applyParticles(ServerLevel level, ServerPlayer player, IrisEffect effect) { - String key = normalizeRegistryKey(effect.getParticleEffectKey()); + private void applyParticles(ServerLevel level, ServerPlayer player, ContentEffect.Particles effect) { + String key = normalizeRegistryKey(effect.key()); if (key == null) { return; } @@ -295,59 +274,34 @@ public final class ModdedEngineEffects extends EngineAssignedComponent implement } Vec3 direction = player.getLookAngle(); - double forward = RNG.r.i(effect.getParticleDistance()) + effect.getParticleAway(); - double sideways = RNG.r.d(-effect.getParticleDistanceWidth(), effect.getParticleDistanceWidth()); - double surfaceX = player.getX() + direction.x * forward + direction.z * sideways; - double surfaceZ = player.getZ() + direction.z * forward - direction.x * sideways; + double surfaceX = player.getX() + direction.x * effect.forward() + direction.z * effect.sideways(); + double surfaceZ = player.getZ() + direction.z * effect.forward() - direction.x * effect.sideways(); int surfaceY = getEngine().getHeight(floor(surfaceX), floor(surfaceZ)); - double x = surfaceX + RNG.r.d(); - double y = surfaceY + 1.0D + level.getMinY() + RNG.r.i(effect.getParticleOffset()); - double z = surfaceZ + RNG.r.d(); - double altX = randomized(effect.getParticleAltX(), effect.isRandomAltX()); - double altY = randomized(effect.getParticleAltY(), effect.isRandomAltY()); - double altZ = randomized(effect.getParticleAltZ(), effect.isRandomAltZ()); + double x = surfaceX + effect.jitterX(); + double y = surfaceY + 1.0D + level.getMinY() + effect.lift(); + double z = surfaceZ + effect.jitterZ(); level.sendParticles(player, simpleParticle, false, false, - x, y, z, effect.getParticleCount(), altX, altY, altZ, effect.getExtra()); + x, y, z, effect.count(), effect.altX(), effect.altY(), effect.altZ(), effect.extra()); } - private void applyCommands(ServerLevel level, ServerPlayer player, IrisCommandRegistry registry) { - if (registry == null || registry.getRawCommands() == null || registry.getRawCommands().isEmpty()) { - return; - } - - ModdedPlatformWorld world = new ModdedPlatformWorld(level); - double x = commandCoordinate(player.getX(), registry.getCommandOffsetX(), registry.isCommandRandomAltX()); - double y = commandCoordinate(player.getY(), registry.getCommandOffsetY(), registry.isCommandRandomAltY()); - double z = commandCoordinate(player.getZ(), registry.getCommandOffsetZ(), registry.isCommandRandomAltZ()); - for (IrisCommand command : registry.getRawCommands()) { - command.run(world, floor(x), floor(y), floor(z)); - if (registry.isCommandAllRandomLocations()) { - x = commandCoordinate(player.getX(), registry.getCommandOffsetX(), registry.isCommandRandomAltX()); - y = commandCoordinate(player.getY(), registry.getCommandOffsetY(), registry.isCommandRandomAltY()); - z = commandCoordinate(player.getZ(), registry.getCommandOffsetZ(), registry.isCommandRandomAltZ()); - } + private void applyCommands(ServerLevel level, ServerPlayer player, List commands) { + for (ContentEffect.Command command : commands) { + ModdedEntityCommandRunner.run(List.of(command.command()), level, floor(player.getX() + command.offsetX()), + floor(player.getY() + command.offsetY()), floor(player.getZ() + command.offsetZ())); } } - private void applyPotion(ServerPlayer player, IrisEffect effect) { - int strength = effect.getPotionStrength(); - if (strength < 0) { - return; - } - - Holder type = resolvePotion(effect.getPotionEffect()); + private void applyPotion(ServerPlayer player, ContentEffect.Potion effect) { + Holder type = resolvePotion(effect.key()); MobEffectInstance current = player.getEffect(type); - if (current != null && !shouldReplacePotionEffect(current.getAmplifier(), strength)) { + if (current != null && !shouldReplacePotionEffect(current.getAmplifier(), effect.strength())) { return; } if (current != null) { player.removeEffect(type); } - int minimum = Math.min(effect.getPotionTicksMin(), effect.getPotionTicksMax()); - int maximum = Math.max(effect.getPotionTicksMin(), effect.getPotionTicksMax()); - int duration = RNG.r.i(minimum, maximum); - player.addEffect(new MobEffectInstance(type, duration, strength, true, false, false)); + player.addEffect(new MobEffectInstance(type, effect.ticks(), effect.strength(), true, false, false)); } private Holder resolvePotion(String rawKey) { @@ -405,14 +359,6 @@ public final class ModdedEngineEffects extends EngineAssignedComponent implement return (int) Math.floor(value); } - private static double randomized(double value, boolean random) { - return random ? RNG.r.d(-value, value) : value; - } - - private static double commandCoordinate(double base, double offset, boolean random) { - return base + randomized(offset, random); - } - private static void warnUnknown(Set warned, String type, String key) { if (warned.add(key)) { IrisLogging.warn("Unknown " + type + " type: \"" + key + "\"."); @@ -421,8 +367,9 @@ public final class ModdedEngineEffects extends EngineAssignedComponent implement private static final class PlayerState { private ServerPlayer player; - private IrisBiome biome; - private IrisRegion region; + private int sampledX; + private int sampledY; + private int sampledZ; private double lastX; private double lastY; private double lastZ; @@ -446,20 +393,22 @@ public final class ModdedEngineEffects extends EngineAssignedComponent implement this.player = player; } - private IrisBiome biome() { - return biome; + private int sampledX() { + return sampledX; } - private void biome(IrisBiome biome) { - this.biome = biome; + private int sampledY() { + return sampledY; } - private IrisRegion region() { - return region; + private int sampledZ() { + return sampledZ; } - private void region(IrisRegion region) { - this.region = region; + private void sampledAt(int x, int y, int z) { + sampledX = x; + sampledY = y; + sampledZ = z; } private double lastX() { diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEntityCommandRunner.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEntityCommandRunner.java index 4f1a2da40..6a8e47189 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEntityCommandRunner.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEntityCommandRunner.java @@ -1,16 +1,18 @@ package art.arcane.iris.modded; -import art.arcane.iris.engine.object.marker.IrisCommand; +import art.arcane.iris.core.content.ContentEntity; import art.arcane.iris.spi.IrisLogging; -import art.arcane.volmlib.util.collection.KList; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; +import java.util.List; + final class ModdedEntityCommandRunner { private ModdedEntityCommandRunner() { } - static void run(KList commands, ServerLevel level, int blockX, int blockY, int blockZ) { + /** Schedules the commands, which a module already checked against the time and weather, at the block. */ + static void run(List commands, ServerLevel level, int blockX, int blockY, int blockZ) { if (commands.isEmpty()) { return; } @@ -21,24 +23,20 @@ final class ModdedEntityCommandRunner { return; } - ModdedPlatformWorld world = new ModdedPlatformWorld(level); - for (IrisCommand command : commands) { - if (command == null || !command.isValid(world)) { - continue; - } + for (ContentEntity.Command command : commands) { schedule(command, server, scheduler, blockX, blockY, blockZ); } } - private static void schedule(IrisCommand command, MinecraftServer server, ModdedScheduler scheduler, int blockX, int blockY, int blockZ) { - int delay = clampDelay(command.getDelay(), 0); - int repeatDelay = clampDelay(command.getRepeatDelay(), 1); - for (String raw : command.getCommands()) { + private static void schedule(ContentEntity.Command command, MinecraftServer server, ModdedScheduler scheduler, int blockX, int blockY, int blockZ) { + int delay = clampDelay(command.delay(), 0); + int repeatDelay = clampDelay(command.repeatDelay(), 1); + for (String raw : command.commands()) { String prepared = prepareCommand(raw, blockX, blockY, blockZ); if (prepared == null) { continue; } - if (command.isRepeat()) { + if (command.repeat()) { scheduler.laterGlobal(() -> new RepeatingCommand(server, scheduler, prepared, repeatDelay).run(), delay); } else { scheduler.laterGlobal(() -> ModdedServerCommands.dispatch(server, prepared), delay); diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEntitySpawner.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEntitySpawner.java index 75acb8011..a877367c6 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEntitySpawner.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEntitySpawner.java @@ -20,14 +20,10 @@ package art.arcane.iris.modded; import art.arcane.iris.core.IrisSettings; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.LootResolver; -import art.arcane.iris.engine.object.entity.IrisAttributeModifier; -import art.arcane.iris.engine.object.entity.IrisEntity; -import art.arcane.iris.engine.object.entity.IrisEffect; -import art.arcane.iris.engine.object.loot.IrisLoot; +import art.arcane.iris.core.content.ContentEntity; +import art.arcane.iris.core.content.ContentItem; import art.arcane.iris.modded.api.ModdedCustomContentRegistry; import art.arcane.iris.spi.IrisLogging; -import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; @@ -82,8 +78,9 @@ public final class ModdedEntitySpawner { private ModdedEntitySpawner() { } - public static Entity spawn(Engine engine, IrisEntity irisEntity, ServerLevel level, int blockX, int blockY, int blockZ, RNG rng) { - if (engine == null || irisEntity == null || level == null) { + /** Spawns {@code entity}, whose every random choice a module made, at the block; null when it cannot appear. */ + public static Entity spawn(Engine engine, ContentEntity entity, ServerLevel level, int blockX, int blockY, int blockZ) { + if (engine == null || entity == null || level == null) { return null; } if (!chunksSafe(level, blockX >> 4, blockZ >> 4)) { @@ -93,73 +90,71 @@ public final class ModdedEntitySpawner { double x = blockX + 0.5; double y = blockY + 0.5; double z = blockZ + 0.5; - boolean riseEffectActive = irisEntity.isSpawnEffectRiseOutOfGround() && hasPlayersNearby(level, x, y, z); + boolean riseEffectActive = entity.riseOutOfGround() && hasPlayersNearby(level, x, y, z); int spawnBlockY = riseEffectActive ? blockY - 5 : blockY; double spawnY = spawnBlockY + 0.5; - Entity created = create(irisEntity, level, x, spawnY, z); + Entity created = create(entity, level, x, spawnY, z); if (created == null) { return null; } - if (irisEntity.isSpecialType() && !irisEntity.isApplySettingsToCustomMobAnyways()) { + if (entity.isSpecial() && !entity.applySettingsToSpecial()) { return created; } - applyConfig(engine, irisEntity, created, level, blockX, spawnBlockY, blockZ, rng, riseEffectActive); + applyConfig(engine, entity, created, level, blockX, spawnBlockY, blockZ, riseEffectActive); return created; } - private static Entity create(IrisEntity irisEntity, ServerLevel level, double x, double y, double z) { - if (irisEntity.isSpecialType()) { - return ModdedCustomContentRegistry.spawnMob(level, x, y, z, irisEntity.getSpecialType()); + private static Entity create(ContentEntity entity, ServerLevel level, double x, double y, double z) { + if (entity.isSpecial()) { + return ModdedCustomContentRegistry.spawnMob(level, x, y, z, entity.specialType()); } - EntityType type = resolveType(irisEntity.getType()); + EntityType type = resolveType(entity.type()); if (type == null) { return null; } - Entity entity = type.spawn(level, BlockPos.containing(x, y, z), reasonFor(irisEntity.getReason())); - if (entity != null) { - entity.snapTo(x, y, z, 0F, 0F); + Entity created = type.spawn(level, BlockPos.containing(x, y, z), reasonFor(entity.reason())); + if (created != null) { + created.snapTo(x, y, z, 0F, 0F); } - return entity; + return created; } - private static void applyConfig(Engine engine, IrisEntity irisEntity, Entity entity, ServerLevel level, int blockX, int blockY, int blockZ, RNG rng, boolean riseEffectActive) { - String customName = irisEntity.getCustomName(); - if (customName != null) { - entity.setCustomName(Component.literal(colorize(customName))); - } - entity.setCustomNameVisible(irisEntity.isCustomNameVisible()); - entity.setGlowingTag(irisEntity.isGlowing()); - entity.setNoGravity(!irisEntity.isGravity()); - entity.setInvulnerable(irisEntity.isInvulnerable()); - entity.setSilent(irisEntity.isSilent()); + private static void applyConfig(Engine engine, ContentEntity spec, Entity entity, ServerLevel level, int blockX, int blockY, int blockZ, boolean riseEffectActive) { + ContentEntity.Flags flags = spec.flags(); + entity.setCustomName(Component.literal(colorize(spec.customName()))); + entity.setCustomNameVisible(flags.customNameVisible()); + entity.setGlowingTag(flags.glowing()); + entity.setNoGravity(!flags.gravity()); + entity.setInvulnerable(flags.invulnerable()); + entity.setSilent(flags.silent()); - boolean persistent = irisEntity.isKeepEntity() || forcePersist(); + boolean persistent = flags.keepEntity() || forcePersist(); applyPersistence(entity, persistent); - applyPassengers(engine, irisEntity, entity, level, blockX, blockY, blockZ, rng); + applyPassengers(engine, spec, entity, level, blockX, blockY, blockZ); if (entity instanceof LivingEntity living) { - applyAttributes(irisEntity, living, level, rng); + applyAttributes(spec, living, level); } - if (!irisEntity.getLoot().getTables().isEmpty()) { - ModdedDeathLoot.bind(engine, entity, irisEntity.getLoot().getTables(), blockX, blockY, blockZ, rng); + if (!spec.lootTables().isEmpty()) { + ModdedDeathLoot.bind(engine, entity, spec.lootTables(), blockX, blockY, blockZ, spec.lootShuffleSeed()); } if (entity instanceof Mob mob) { - mob.setNoAi(shouldDisableAi(irisEntity.isAi())); - ModdedEntityAwareness.configure(mob, irisEntity.isAware()); - mob.setCanPickUpLoot(irisEntity.isPickupItems()); - if (!irisEntity.isRemovable()) { + mob.setNoAi(shouldDisableAi(flags.ai())); + ModdedEntityAwareness.configure(mob, flags.aware()); + mob.setCanPickUpLoot(flags.pickupItems()); + if (!flags.removable()) { mob.setPersistenceRequired(); } - if (irisEntity.getLeashHolder() != null) { - Entity holder = spawn(engine, irisEntity.getLeashHolder(), level, blockX, blockY, blockZ, rng.nextParallelRNG(LEASH_RNG_SEED)); + if (spec.leashHolder() != null) { + Entity holder = spawn(engine, spec.leashHolder(), level, blockX, blockY, blockZ); if (holder != null) { mob.setLeashedTo(holder, true); } @@ -167,56 +162,51 @@ public final class ModdedEntitySpawner { } if (entity instanceof LivingEntity equippable) { - applyEquipment(irisEntity, equippable, level, rng); + applyEquipment(spec, equippable, level); } - if (irisEntity.isBaby()) { + if (flags.baby()) { applyBaby(entity); } if (entity instanceof Panda panda) { - panda.setMainGene(gene(irisEntity.getPandaMainGene())); - panda.setHiddenGene(gene(irisEntity.getPandaHiddenGene())); + panda.setMainGene(gene(spec.pandaMainGene())); + panda.setHiddenGene(gene(spec.pandaHiddenGene())); } if (entity instanceof Villager villager) { ModdedEntityPersistence.configure(villager, true); } - applySpawnEffect(irisEntity.getSpawnEffect(), entity, level); - ModdedEntityCommandRunner.run(irisEntity.getRawCommands(), level, blockX, blockY, blockZ); + applySpawnEffect(spec.spawnEffect(), entity, level); + ModdedEntityCommandRunner.run(spec.commands(), level, blockX, blockY, blockZ); if (riseEffectActive && entity instanceof LivingEntity living) { startRiseEffect(engine, level, entity, living); } } - private static void applyPassengers(Engine engine, IrisEntity irisEntity, Entity entity, ServerLevel level, int blockX, int blockY, int blockZ, RNG rng) { - int index = 0; - for (IrisEntity passengerEntity : irisEntity.getPassengers()) { - Entity passenger = spawn(engine, passengerEntity, level, blockX, blockY, blockZ, rng.nextParallelRNG(PASSENGER_RNG_BASE + index++)); + private static void applyPassengers(Engine engine, ContentEntity spec, Entity entity, ServerLevel level, int blockX, int blockY, int blockZ) { + for (ContentEntity passengerSpec : spec.passengers()) { + Entity passenger = spawn(engine, passengerSpec, level, blockX, blockY, blockZ); if (passenger != null) { passenger.startRiding(entity); } } } - private static void applyAttributes(IrisEntity irisEntity, LivingEntity living, ServerLevel level, RNG rng) { - KList modifiers = irisEntity.getAttributes(); - if (modifiers.isEmpty()) { + private static void applyAttributes(ContentEntity spec, LivingEntity living, ServerLevel level) { + if (spec.attributes().isEmpty()) { return; } Registry registry = level.registryAccess().lookupOrThrow(Registries.ATTRIBUTE); int index = 0; - for (IrisAttributeModifier modifier : modifiers) { + for (ContentItem.Attribute modifier : spec.attributes()) { index++; - if (rng.nextDouble() >= modifier.getChance()) { - continue; - } - Holder holder = ModdedItemTranslator.resolveAttribute(registry, modifier.getAttribute()); + Holder holder = ModdedItemTranslator.resolveAttribute(registry, modifier.attribute()); if (holder == null) { - if (WARNED_ATTRIBUTES.add(modifier.getAttribute())) { - IrisLogging.warn("Iris entity: unknown attribute '" + modifier.getAttribute() + "'"); + if (WARNED_ATTRIBUTES.add(modifier.attribute())) { + IrisLogging.warn("Iris entity: unknown attribute '" + modifier.attribute() + "'"); } continue; } @@ -224,28 +214,29 @@ public final class ModdedEntitySpawner { if (instance == null) { continue; } - Identifier id = Identifier.tryParse("iris:" + normalizeName(modifier.getName()) + "_" + index); + Identifier id = Identifier.tryParse("iris:" + normalizeName(modifier.name()) + "_" + index); if (id == null) { continue; } - instance.addOrReplacePermanentModifier(new AttributeModifier(id, modifier.getAmount(rng), ModdedItemTranslator.operationFor(modifier.getOperation()))); + instance.addOrReplacePermanentModifier(new AttributeModifier(id, modifier.amount(), ModdedItemTranslator.operationFor(modifier.operation()))); } } - private static void applyEquipment(IrisEntity irisEntity, LivingEntity living, ServerLevel level, RNG rng) { - setSlot(living, EquipmentSlot.HEAD, irisEntity.getHelmet(), level, rng); - setSlot(living, EquipmentSlot.CHEST, irisEntity.getChestplate(), level, rng); - setSlot(living, EquipmentSlot.LEGS, irisEntity.getLeggings(), level, rng); - setSlot(living, EquipmentSlot.FEET, irisEntity.getBoots(), level, rng); - setSlot(living, EquipmentSlot.MAINHAND, irisEntity.getMainHand(), level, rng); - setSlot(living, EquipmentSlot.OFFHAND, irisEntity.getOffHand(), level, rng); + private static void applyEquipment(ContentEntity spec, LivingEntity living, ServerLevel level) { + ContentEntity.Equipment equipment = spec.equipment(); + setSlot(living, EquipmentSlot.HEAD, equipment.helmet(), level); + setSlot(living, EquipmentSlot.CHEST, equipment.chestplate(), level); + setSlot(living, EquipmentSlot.LEGS, equipment.leggings(), level); + setSlot(living, EquipmentSlot.FEET, equipment.boots(), level); + setSlot(living, EquipmentSlot.MAINHAND, equipment.mainHand(), level); + setSlot(living, EquipmentSlot.OFFHAND, equipment.offHand(), level); } - private static void setSlot(LivingEntity living, EquipmentSlot slot, IrisLoot loot, ServerLevel level, RNG rng) { - if (loot == null || !LootResolver.oneIn(rng, loot.getRarity())) { + private static void setSlot(LivingEntity living, EquipmentSlot slot, ContentItem item, ServerLevel level) { + if (item == null) { return; } - ItemStack stack = ModdedItemTranslator.stack(loot, rng, level); + ItemStack stack = ModdedItemTranslator.stack(item, level); if (stack != null && !stack.isEmpty()) { living.setItemSlot(slot, stack); } @@ -257,11 +248,11 @@ public final class ModdedEntitySpawner { } } - static boolean isAreaClearForSpawn(ServerLevel level, IrisEntity irisEntity, int blockX, int blockY, int blockZ) { - if (irisEntity.isSpecialType()) { + static boolean isAreaClearForSpawn(ServerLevel level, ContentEntity entity, int blockX, int blockY, int blockZ) { + if (entity.isSpecial()) { return true; } - EntityType type = resolveType(irisEntity.getType()); + EntityType type = resolveType(entity.type()); if (type == null) { return true; } @@ -320,21 +311,21 @@ public final class ModdedEntitySpawner { return false; } - private static void applySpawnEffect(IrisEffect effect, Entity entity, ServerLevel level) { - if (effect == null || !effect.shouldApplyNow()) { + private static void applySpawnEffect(ContentEntity.SpawnEffect effect, Entity entity, ServerLevel level) { + if (effect == null) { return; } - SoundEvent sound = resolveSound(effect.getSoundKey()); + SoundEvent sound = resolveSound(effect.sound()); if (sound != null) { - double soundX = entity.getX() + RNG.r.i(-effect.getSoundDistance(), effect.getSoundDistance()); - double soundY = entity.getY() + RNG.r.i(-effect.getSoundDistance(), effect.getSoundDistance()); - double soundZ = entity.getZ() + RNG.r.i(-effect.getSoundDistance(), effect.getSoundDistance()); + double soundX = entity.getX() + RNG.r.i(-effect.soundDistance(), effect.soundDistance()); + double soundY = entity.getY() + RNG.r.i(-effect.soundDistance(), effect.soundDistance()); + double soundZ = entity.getZ() + RNG.r.i(-effect.soundDistance(), effect.soundDistance()); level.playSound(null, soundX, soundY, soundZ, sound, SoundSource.MASTER, - (float) effect.getVolume(), (float) RNG.r.d(effect.getMinPitch(), effect.getMaxPitch())); + (float) effect.volume(), (float) RNG.r.d(effect.minPitch(), effect.maxPitch())); } - ParticleOptions particle = resolveParticle(effect.getParticleEffectKey()); + ParticleOptions particle = resolveParticle(effect.particle()); if (particle == null) { return; } @@ -342,13 +333,13 @@ public final class ModdedEntitySpawner { double addition = RNG.r.d(); double subtraction = RNG.r.d(); double particleX = entity.getX() + addition - subtraction + RNG.r.d(); - double particleY = entity.getY() + 0.25 + addition - subtraction + RNG.r.i(effect.getParticleOffset()); + double particleY = entity.getY() + 0.25 + addition - subtraction + RNG.r.i(effect.particleOffset()); double particleZ = entity.getZ() + addition - subtraction + RNG.r.d(); - double altX = effect.isRandomAltX() ? RNG.r.d(-effect.getParticleAltX(), effect.getParticleAltX()) : effect.getParticleAltX(); - double altY = effect.isRandomAltY() ? RNG.r.d(-effect.getParticleAltY(), effect.getParticleAltY()) : effect.getParticleAltY(); - double altZ = effect.isRandomAltZ() ? RNG.r.d(-effect.getParticleAltZ(), effect.getParticleAltZ()) : effect.getParticleAltZ(); - level.sendParticles(particle, particleX, particleY, particleZ, effect.getParticleCount(), - altX, altY, altZ, effect.getExtra()); + double altX = effect.randomAltX() ? RNG.r.d(-effect.altX(), effect.altX()) : effect.altX(); + double altY = effect.randomAltY() ? RNG.r.d(-effect.altY(), effect.altY()) : effect.altY(); + double altZ = effect.randomAltZ() ? RNG.r.d(-effect.altZ(), effect.altZ()) : effect.altZ(); + level.sendParticles(particle, particleX, particleY, particleZ, effect.particleCount(), + altX, altY, altZ, effect.extra()); } private static SoundEvent resolveSound(String key) { diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedItemTranslator.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedItemTranslator.java index 690e25d8d..5230f7adf 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedItemTranslator.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedItemTranslator.java @@ -18,19 +18,11 @@ package art.arcane.iris.modded; -import art.arcane.iris.engine.framework.LootResolver; -import art.arcane.iris.engine.loot.LootTables; -import art.arcane.iris.engine.object.loot.InventorySlotType; -import art.arcane.iris.engine.object.entity.IrisAttributeModifier; -import art.arcane.iris.engine.object.loot.IrisEnchantment; -import art.arcane.iris.engine.object.loot.IrisLoot; -import art.arcane.iris.engine.object.loot.IrisLootTable; +import art.arcane.iris.core.content.ContentItem; import art.arcane.iris.spi.IrisLogging; import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.collection.KMap; import art.arcane.volmlib.util.format.Form; import art.arcane.volmlib.util.json.JSONObject; -import art.arcane.volmlib.util.math.RNG; import com.mojang.brigadier.exceptions.CommandSyntaxException; import net.minecraft.core.Holder; import net.minecraft.core.Registry; @@ -63,6 +55,7 @@ import net.minecraft.world.item.enchantment.ItemEnchantments; import java.util.ArrayList; import java.util.List; import java.util.Locale; +import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @@ -74,42 +67,27 @@ public final class ModdedItemTranslator { private ModdedItemTranslator() { } - public static KList loot(IrisLootTable table, long lootSeed, InventorySlotType slot, ServerLevel level, int x, int y, int z) { - KList out = new KList<>(); - KList entries = table.getLoot(); - if (entries.isEmpty() || table.getMaxTries() <= 0) { - return out; - } - - RNG rng = LootTables.rng(lootSeed, table, x, y, z); - int m = 0; - int c = 0; - int mx = Math.max(0, LootResolver.inclusive(rng, table.getMinPicked(), table.getMaxPicked())); - - while (m < mx && c++ < table.getMaxTries()) { - int entryIndex = rng.nextInt(entries.size()); - IrisLoot entry = entries.get(entryIndex); - if (entry == null || entry.getSlotTypes() != slot) { - continue; - } - ItemStack item = item(entry, table, rng, lootSeed, entryIndex, level, x, y, z); - if (item != null && !item.isEmpty()) { - out.add(item); - m++; + /** The stacks of {@code items}, without the ones the platform cannot make. */ + public static KList stacks(List items, ServerLevel level) { + KList stacks = new KList<>(); + for (ContentItem item : items) { + ItemStack stack = stack(item, level); + if (stack != null && !stack.isEmpty()) { + stacks.add(stack); } } - - return out; + return stacks; } - public static ItemStack stack(IrisLoot loot, RNG rng, ServerLevel level) { + /** The stack of {@code item}, or null when the platform has no such item. */ + public static ItemStack stack(ContentItem item, ServerLevel level) { try { - ItemStack stack = baseStack(loot, rng); + ItemStack stack = baseStack(item); if (stack == null || stack.isEmpty()) { return null; } - applyComponents(loot, stack, rng, level); - applyCustomNbt(stack, loot.getCustomNbt()); + applyComponents(item, stack, level); + applyCustomNbt(stack, item.customNbt()); return stack; } catch (Throwable e) { IrisLogging.reportError(e); @@ -117,28 +95,8 @@ public final class ModdedItemTranslator { } } - public static ItemStack item(IrisLoot loot, IrisLootTable table, RNG rng, long lootSeed, int entryIndex, ServerLevel level, int x, int y, int z) { - long combinedRarity = LootResolver.combinedRarity(loot.getRarity(), table.getRarity()); - if (!LootTables.spatialOneIn(lootSeed, table, entryIndex, x, y, z, combinedRarity)) { - return null; - } - - try { - ItemStack stack = baseStack(loot, rng); - if (stack == null || stack.isEmpty()) { - return null; - } - applyComponents(loot, stack, rng, level); - applyCustomNbt(stack, loot.getCustomNbt()); - return stack; - } catch (Throwable e) { - IrisLogging.reportError(e); - return null; - } - } - - private static ItemStack baseStack(IrisLoot loot, RNG rng) { - String raw = loot.getTypeKey(); + private static ItemStack baseStack(ContentItem item) { + String raw = item.item(); if (raw == null || raw.isBlank()) { return null; } @@ -150,55 +108,53 @@ public final class ModdedItemTranslator { return null; } - Item item = BuiltInRegistries.ITEM.getValue(id); - return new ItemStack(item, Math.max(1, LootResolver.inclusive(rng, loot.getMinAmount(), loot.getMaxAmount()))); + return new ItemStack(BuiltInRegistries.ITEM.getValue(id), item.amount()); } - private static void applyComponents(IrisLoot loot, ItemStack stack, RNG rng, ServerLevel level) { - applyEnchantments(loot, stack, rng, level); - applyAttributes(loot, stack, rng, level); + private static void applyComponents(ContentItem item, ItemStack stack, ServerLevel level) { + applyEnchantments(item, stack, level); + applyAttributes(item, stack, level); - if (loot.isUnbreakable()) { + if (item.unbreakable()) { stack.set(DataComponents.UNBREAKABLE, Unit.INSTANCE); } - if (loot.getItemFlags().isNotEmpty()) { - applyItemFlags(loot, stack); + if (!item.flags().isEmpty()) { + applyItemFlags(item, stack); } - if (loot.getCustomModel() != null) { - stack.set(DataComponents.CUSTOM_MODEL_DATA, new CustomModelData(List.of(loot.getCustomModel().floatValue()), List.of(), List.of(), List.of())); + if (item.customModel() != null) { + stack.set(DataComponents.CUSTOM_MODEL_DATA, new CustomModelData(List.of(item.customModel().floatValue()), List.of(), List.of(), List.of())); } - if (stack.getMaxDamage() > 0) { + if (stack.getMaxDamage() > 0 && item.damage() != null) { int max = stack.getMaxDamage(); - int damage = (int) Math.round(Math.max(0, Math.min(max, (1D - rng.d(loot.getMinDurability(), loot.getMaxDurability())) * max))); + int damage = (int) Math.round(Math.max(0, Math.min(max, item.damage() * max))); stack.set(DataComponents.DAMAGE, damage); } - if (loot.getLeatherColor() != null) { + if (item.leatherColor() != null) { try { - int rgb = Integer.decode(loot.getLeatherColor()) & 0xFFFFFF; + int rgb = Integer.decode(item.leatherColor()) & 0xFFFFFF; stack.set(DataComponents.DYED_COLOR, new DyedItemColor(rgb)); } catch (NumberFormatException e) { - warnOnce("leatherColor:" + loot.getLeatherColor(), "Iris loot: invalid leatherColor '" + loot.getLeatherColor() + "'"); + warnOnce("leatherColor:" + item.leatherColor(), "Iris loot: invalid leatherColor '" + item.leatherColor() + "'"); } } - String dye = loot.getDyeColorKey(); - if (dye != null) { - applyDyeColor(stack, dye); + if (item.dyeColor() != null) { + applyDyeColor(stack, item.dyeColor()); } - if (loot.getDisplayName() != null) { - stack.set(DataComponents.CUSTOM_NAME, Component.literal(colorize(loot.getDisplayName()))); + if (item.displayName() != null) { + stack.set(DataComponents.CUSTOM_NAME, Component.literal(colorize(item.displayName()))); } - applyLore(loot, stack); + applyLore(item, stack); } - private static void applyEnchantments(IrisLoot loot, ItemStack stack, RNG rng, ServerLevel level) { - if (loot.getEnchantments().isEmpty()) { + private static void applyEnchantments(ContentItem item, ItemStack stack, ServerLevel level) { + if (item.enchantments().isEmpty()) { return; } @@ -207,8 +163,8 @@ public final class ModdedItemTranslator { ItemEnchantments.Mutable mutable = new ItemEnchantments.Mutable(stack.getOrDefault(component, ItemEnchantments.EMPTY)); boolean changed = false; - for (IrisEnchantment enchantment : loot.getEnchantments()) { - String name = enchantment.getEnchantment(); + for (ContentItem.Enchantment enchantment : item.enchantments()) { + String name = enchantment.key(); if (name == null || name.isBlank()) { continue; } @@ -221,10 +177,8 @@ public final class ModdedItemTranslator { warnOnce("enchantment:" + key, "Iris loot: unknown enchantment '" + name + "'"); continue; } - if (rng.nextDouble() < enchantment.getChance()) { - mutable.set(holder.get(), enchantment.getLevel(rng)); - changed = true; - } + mutable.set(holder.get(), enchantment.level()); + changed = true; } if (changed) { @@ -232,8 +186,8 @@ public final class ModdedItemTranslator { } } - private static void applyAttributes(IrisLoot loot, ItemStack stack, RNG rng, ServerLevel level) { - if (loot.getAttributes().isEmpty()) { + private static void applyAttributes(ContentItem item, ItemStack stack, ServerLevel level) { + if (item.attributes().isEmpty()) { return; } @@ -241,21 +195,17 @@ public final class ModdedItemTranslator { ItemAttributeModifiers.Builder builder = ItemAttributeModifiers.builder(); boolean changed = false; - for (IrisAttributeModifier attribute : loot.getAttributes()) { - if (rng.nextDouble() >= attribute.getChance()) { - continue; - } - double amount = attribute.getAmount(rng); - Holder holder = resolveAttribute(registry, attribute.getAttribute()); + for (ContentItem.Attribute attribute : item.attributes()) { + Holder holder = resolveAttribute(registry, attribute.attribute()); if (holder == null) { - warnOnce("attribute:" + attribute.getAttribute(), "Iris loot: unknown attribute '" + attribute.getAttribute() + "'"); + warnOnce("attribute:" + attribute.attribute(), "Iris loot: unknown attribute '" + attribute.attribute() + "'"); continue; } - Identifier modifierId = attributeModifierId(attribute.getName()); + Identifier modifierId = attributeModifierId(attribute.name()); if (modifierId == null) { continue; } - AttributeModifier modifier = new AttributeModifier(modifierId, amount, operationFor(attribute.getOperation())); + AttributeModifier modifier = new AttributeModifier(modifierId, attribute.amount(), operationFor(attribute.operation())); builder.add(holder, modifier, EquipmentSlotGroup.ANY); changed = true; } @@ -311,11 +261,11 @@ public final class ModdedItemTranslator { return Identifier.tryParse("iris:" + normalized); } - private static void applyItemFlags(IrisLoot loot, ItemStack stack) { + private static void applyItemFlags(ContentItem item, ItemStack stack) { TooltipDisplay display = stack.getOrDefault(DataComponents.TOOLTIP_DISPLAY, TooltipDisplay.DEFAULT); boolean changed = false; - for (String flag : loot.getItemFlags()) { + for (String flag : item.flags()) { if (flag == null || flag.isBlank()) { continue; } @@ -356,13 +306,13 @@ public final class ModdedItemTranslator { stack.set(DataComponents.BASE_COLOR, color); } - private static void applyLore(IrisLoot loot, ItemStack stack) { - if (loot.getLore().isEmpty()) { + private static void applyLore(ContentItem item, ItemStack stack) { + if (item.lore().isEmpty()) { return; } List lines = new ArrayList<>(); - for (String line : loot.getLore()) { + for (String line : item.lore()) { String colored = colorize(line); if (colored.length() > 24) { for (String wrapped : Form.wrapWords(colored, 24).split("\\Q\n\\E")) { @@ -375,7 +325,7 @@ public final class ModdedItemTranslator { stack.set(DataComponents.LORE, new ItemLore(lines)); } - private static void applyCustomNbt(ItemStack stack, KMap customNbt) { + private static void applyCustomNbt(ItemStack stack, Map customNbt) { if (customNbt == null || customNbt.isEmpty()) { return; } diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedLootApplier.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedLootApplier.java index 5ea3ab45c..f81f51935 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedLootApplier.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedLootApplier.java @@ -18,19 +18,11 @@ package art.arcane.iris.modded; -import art.arcane.iris.engine.loot.LootResources; -import art.arcane.iris.engine.object.loot.IrisObjectLoot; -import art.arcane.iris.engine.object.loot.IrisObjectVanillaLoot; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.core.content.ContentLoot; +import art.arcane.iris.core.content.ContentServices; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.LootResolver; -import art.arcane.iris.engine.loot.LootTables; -import art.arcane.iris.engine.framework.PlacedObject; -import art.arcane.iris.engine.object.loot.IObjectLoot; -import art.arcane.iris.engine.object.loot.InventorySlotType; -import art.arcane.iris.engine.object.loot.IrisLootTable; import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.spi.PlatformBlockState; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.mantle.runtime.MantleChunk; import art.arcane.volmlib.util.math.RNG; @@ -53,7 +45,6 @@ import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets; import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.phys.Vec3; -import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; @@ -65,10 +56,10 @@ public final class ModdedLootApplier { if (!isCanonicalContainer(pos, state)) { return; } - RNG rng = LootResolver.containerRng(engine.getSeedManager().getLoot(), pos.getX(), pos.getY(), pos.getZ()); boolean nativeLootDefined = hasNativeLootTable(level, pos, state); - List sources = resolveSources(engine, level, rng, pos, state, mc, nativeLootDefined); - if (sources.isEmpty()) { + String containerKey = ModdedBlockResolution.isStorageChest(state) ? ModdedBlockState.serialize(state) : null; + List parts = ContentServices.containerLoot(engine, pos.getX(), pos.getY(), pos.getZ(), containerKey, nativeLootDefined); + if (parts.isEmpty()) { return; } @@ -80,97 +71,38 @@ public final class ModdedLootApplier { KList items = new KList<>(); LootParams nativeParams = null; - for (LootSource source : sources) { - if (source instanceof IrisLootSource irisSource) { - IrisLootTable table = irisSource.table(); - if (table == null) { - continue; - } - items.addAll(ModdedItemTranslator.loot(table, engine.getSeedManager().getLoot(), InventorySlotType.STORAGE, level, pos.getX(), pos.getY(), pos.getZ())); + for (ContentLoot.Part part : parts) { + if (part instanceof ContentLoot.Items drawn) { + items.addAll(ModdedItemTranslator.stacks(drawn.items(), level)); continue; } - if (source instanceof NativeLootSource nativeSource) { + if (part instanceof ContentLoot.PlatformTable platform) { + LootTable table = nativeTable(level, platform.key()); + if (table == null) { + IrisLogging.warn("Unknown vanilla loot table " + platform.key()); + continue; + } if (nativeParams == null) { nativeParams = new LootParams.Builder(level) .withParameter(LootContextParams.ORIGIN, Vec3.atCenterOf(pos)) .create(LootContextParamSets.CHEST); } - items.addAll(nativeSource.table().getRandomItems(nativeParams, rng.nextLong())); + items.addAll(table.getRandomItems(nativeParams, platform.seed())); } } - fillContainer(container, items, rng); + fillContainer(container, items, LootResolver.containerRng(engine.getSeedManager().getLoot(), pos.getX(), pos.getY(), pos.getZ())); } - private static List resolveSources(Engine engine, ServerLevel level, RNG rng, BlockPos pos, BlockState state, MantleChunk mc, boolean nativeLootDefined) { - int rx = pos.getX(); - int rz = pos.getZ(); - int ry = pos.getY() - engine.getWorld().minHeight(); - List sources = new ArrayList<>(); - boolean objectLootDefined = nativeLootDefined; - - PlacedObject po = engine.getObjectPlacement(rx, ry, rz, mc); - if (po != null && po.getPlacement() != null && ModdedBlockResolution.isStorageChest(state)) { - objectLootDefined = objectLootDefined - || po.getPlacement().getLoot().isNotEmpty() - || po.getPlacement().getVanillaLoot().isNotEmpty(); - Candidate picked = pickPlacementTable(engine, level, po.getPlacement(), state, rng); - if (picked != null) { - sources.add(picked.source()); - if (po.getPlacement().isOverrideGlobalLoot()) { - return sources; - } - } + private static LootTable nativeTable(ServerLevel level, String name) { + ResourceKey key = resolveNativeKey(name, candidate -> hasNativeTable(level, candidate)); + if (key == null) { + return null; } - - LootTables.resolveEnvironmentSources( - sources, - engine, - rng, - rx, - ry, - rz, - objectLootDefined, - IrisLootSource::new - ); - return sources; - } - - private static Candidate pickPlacementTable(Engine engine, ServerLevel level, IrisObjectPlacement placement, BlockState state, RNG rng) { - List exact = new ArrayList<>(); - List basic = new ArrayList<>(); - List global = new ArrayList<>(); - - for (IrisObjectLoot loot : placement.getLoot()) { - if (loot == null || loot.getWeight() <= 0) { - continue; - } - IrisLootTable table = LootResources.table(engine.getData(), loot.getName()); - if (table == null) { - IrisLogging.warn("Couldn't find loot table " + loot.getName()); - continue; - } - bucket(engine, loot, new Candidate(new IrisLootSource(table), loot.getWeight()), state, exact, basic, global); - } - - for (IrisObjectVanillaLoot loot : placement.getVanillaLoot()) { - if (loot == null || loot.getWeight() <= 0) { - continue; - } - ResourceKey key = resolveNativeKey(loot.getName(), candidate -> hasNativeTable(level, candidate)); - if (key == null) { - IrisLogging.warn("Couldn't find vanilla loot table " + loot.getName()); - continue; - } - LootTable table = level.getServer().reloadableRegistries().lookup() - .lookupOrThrow(Registries.LOOT_TABLE) - .getOrThrow(key) - .value(); - bucket(engine, loot, new Candidate(new NativeLootSource(table), loot.getWeight()), state, exact, basic, global); - } - - List pool = !exact.isEmpty() ? exact : !basic.isEmpty() ? basic : global; - return LootResolver.pickWeighted(pool, Candidate::weight, rng); + return level.getServer().reloadableRegistries().lookup() + .lookupOrThrow(Registries.LOOT_TABLE) + .getOrThrow(key) + .value(); } static ResourceKey resolveNativeKey(String name, Predicate> registryContains) { @@ -197,21 +129,6 @@ public final class ModdedLootApplier { .isPresent(); } - private static void bucket(Engine engine, IObjectLoot loot, Candidate candidate, BlockState state, List exact, List basic, List global) { - if (loot.getFilter().isEmpty()) { - global.add(candidate); - return; - } - - for (PlatformBlockState filterState : loot.getFilter(engine.getData())) { - BlockState filter = (BlockState) filterState.nativeHandle(); - if (loot.isExact() ? filter == state : filter.getBlock() == state.getBlock()) { - (loot.isExact() ? exact : basic).add(candidate); - return; - } - } - } - static boolean isCanonicalContainer(BlockPos pos, BlockState state) { if (!(state.getBlock() instanceof ChestBlock) || state.getValue(ChestBlock.TYPE) == ChestType.SINGLE) { return true; @@ -324,16 +241,4 @@ public final class ModdedLootApplier { container.setItem(i, items[i]); } } - - private interface LootSource { - } - - private record IrisLootSource(IrisLootTable table) implements LootSource { - } - - private record NativeLootSource(LootTable table) implements LootSource { - } - - private record Candidate(LootSource source, int weight) { - } } diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedWorldManager.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedWorldManager.java index 9688ed336..5ccb51b3d 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedWorldManager.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedWorldManager.java @@ -18,25 +18,15 @@ package art.arcane.iris.modded; -import art.arcane.iris.engine.spawn.SpawnResources; import art.arcane.iris.core.IrisSettings; +import art.arcane.iris.core.content.ContentServices; +import art.arcane.iris.core.content.ContentSpawns; import art.arcane.iris.core.gui.PregeneratorJob; import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.EngineLifecycleTasks; import art.arcane.iris.engine.framework.EngineWorldManager; -import art.arcane.iris.engine.framework.LootResolver; -import art.arcane.iris.engine.object.value.IRare; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.entity.IrisEntity; -import art.arcane.iris.engine.object.entity.IrisEntitySpawn; -import art.arcane.iris.engine.object.marker.IrisMarker; import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.engine.object.value.IrisRange; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.engine.object.entity.spawn.IrisSpawnGroup; -import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; -import art.arcane.iris.engine.object.entity.spawn.IrisSurface; import art.arcane.iris.spi.IrisLogging; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.mantle.flag.MantleFlag; @@ -45,7 +35,6 @@ import art.arcane.volmlib.util.mantle.runtime.MantleChunk; import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.matter.Matter; import art.arcane.volmlib.util.matter.MatterMarker; -import art.arcane.volmlib.util.matter.slices.MarkerMatter; import it.unimi.dsi.fastutil.objects.Object2IntMap; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; @@ -60,6 +49,8 @@ import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.phys.AABB; import java.util.HashSet; +import java.util.List; +import java.util.Optional; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; @@ -397,8 +388,8 @@ public final class ModdedWorldManager implements EngineWorldManager { if (tag.equals("cave_floor") || tag.equals("cave_ceiling")) { return; } - IrisMarker resolved = SpawnResources.marker(engine.getData(), tag); - if (resolved == null) { + Optional rule = ContentServices.markerRule(engine, tag); + if (rule.isEmpty()) { return; } @@ -406,20 +397,17 @@ public final class ModdedWorldManager implements EngineWorldManager { int worldZ = (chunkZ << 4) + (z & 15); int worldY = yf + minHeight; - if (resolved.isEmptyAbove() && aboveObstructed(level, worldX, worldY, worldZ)) { + if (rule.get().emptyAbove() && aboveObstructed(level, worldX, worldY, worldZ)) { obstructed.add(new IrisPosition(worldX, yf, worldZ)); return; } - KList spawners = resolveMarkerSpawners(resolved); + List spawners = rule.get().spawners(); if (spawners.isEmpty()) { return; } - IrisSpawner chosen = spawners.getRandom(); - if (chosen == null) { - return; - } - spawnFromSpawner(level, new IrisPosition(worldX, worldY, worldZ), chosen, initial); + String chosen = spawners.get(RNG.r.nextInt(spawners.size())); + spawnAtMarker(level, new IrisPosition(worldX, worldY, worldZ), tag, chosen, initial); }); Mantle mantle = engine.getMantle().getMantle(); for (IrisPosition position : obstructed) { @@ -427,43 +415,14 @@ public final class ModdedWorldManager implements EngineWorldManager { } } - private KList resolveMarkerSpawners(IrisMarker marker) { - KList spawners = new KList<>(); - for (String key : marker.getSpawners()) { - IrisSpawner spawner = SpawnResources.spawner(engine.getData(), key); - if (spawner == null) { - IrisLogging.error("Cannot load spawner: " + key + " for marker on " + engine.getName()); - continue; - } - spawner.setReferenceMarker(marker); - spawners.add(spawner); - } - return spawners; - } - - private void spawnFromSpawner(ServerLevel level, IrisPosition position, IrisSpawner spawner, boolean initial) { - KList spawns = initial ? spawner.getInitialSpawns() : spawner.getSpawns(); - if (spawns.isEmpty()) { - return; - } - for (IrisEntitySpawn entry : spawns) { - entry.setReferenceSpawner(spawner); - entry.setReferenceMarker(spawner.getReferenceMarker()); - } - IrisEntitySpawn chosen = rarityPick(spawns); - if (chosen == null) { - return; - } - - int chunkX = position.getX() >> 4; - int chunkZ = position.getZ() >> 4; - if (!canSpawn(spawner, chunkX, chunkZ)) { - return; - } - int spawned = spawnEntryAt(level, chosen, spawner, position); - if (spawned > 0) { - spawner.spawn(engine, chunkX, chunkZ); - } + private void spawnAtMarker(ServerLevel level, IrisPosition position, String marker, String spawner, boolean initial) { + ContentServices.planMarkerSpawn(engine, position.getX(), position.getY(), position.getZ(), marker, spawner, initial) + .ifPresent(plan -> { + if (plan.exhaustsMarker()) { + engine.getMantle().getMantle().remove(position.getX(), position.getY() - engine.getWorld().minHeight(), position.getZ(), MatterMarker.class); + } + spawn(level, plan); + }); } private void spawnAmbient(ServerLevel level, int chunkX, int chunkZ, boolean initial) { @@ -472,184 +431,55 @@ public final class ModdedWorldManager implements EngineWorldManager { return; } - int blockX = chunkX << 4; - int blockZ = chunkZ << 4; - IrisBiome biome = engine.getSurfaceBiome(blockX, blockZ); - IrisRegion region = engine.getRegion(blockX, blockZ); - int chunkMobs = countChunkLivingEntities(level, chunkX, chunkZ); - - KList pool = new KList<>(); - collectSpawns(pool, SpawnResources.spawners(engine.getData(), engine.getDimension().getEntitySpawners()), biome, chunkX, chunkZ, chunkMobs, initial); - collectSpawns(pool, SpawnResources.spawners(engine.getData(), region.getEntitySpawners()), null, chunkX, chunkZ, chunkMobs, initial); - collectSpawns(pool, SpawnResources.spawners(engine.getData(), biome.getEntitySpawners()), null, chunkX, chunkZ, chunkMobs, initial); - if (pool.isEmpty()) { - return; - } - - IrisEntitySpawn chosen = rarityPick(pool); - if (chosen == null || chosen.getReferenceSpawner() == null) { - return; - } - IrisSpawner spawner = chosen.getReferenceSpawner(); - if (!canSpawn(spawner, chunkX, chunkZ)) { - return; - } - int spawned = spawnEntry(level, chosen, spawner, chunkX, chunkZ); - if (spawned > 0) { - spawner.spawn(engine, chunkX, chunkZ); - } + ContentServices.planChunkSpawn(engine, chunkX, chunkZ, countChunkLivingEntities(level, chunkX, chunkZ), initial) + .ifPresent(plan -> spawn(level, plan)); } - private void collectSpawns(KList pool, KList spawners, IrisBiome biomeFilter, int chunkX, int chunkZ, int chunkMobs, boolean initial) { - for (IrisSpawner spawner : spawners) { - if (spawner == null) { - continue; - } - if (spawner.getMaxEntitiesPerChunk() <= chunkMobs) { - continue; - } - if (biomeFilter != null && !spawner.isValid(biomeFilter)) { - continue; - } - if (!canSpawn(spawner, chunkX, chunkZ)) { - continue; - } - KList spawns = initial ? spawner.getInitialSpawns() : spawner.getSpawns(); - for (IrisEntitySpawn entry : spawns) { - entry.setReferenceSpawner(spawner); - entry.setReferenceMarker(spawner.getReferenceMarker()); - pool.add(entry); - } - } - } - - private int spawnEntry(ServerLevel level, IrisEntitySpawn entry, IrisSpawner spawner, int chunkX, int chunkZ) { - IrisEntity irisEntity = entry.getRealEntity(engine); - if (irisEntity == null) { - return 0; - } - - int min = entry.getMinSpawns(); - int max = entry.getMaxSpawns(); - int count = LootResolver.inclusive(RNG.r, min, max); - if (count <= 0) { - return 0; - } - - RNG entityRng = entry.getRng().aquire(() -> new RNG(engine.getSeedManager().getEntity())); - IrisSpawnGroup group = spawner.getGroup(); - KList caveFloors = group == IrisSpawnGroup.CAVE - ? engine.getMantle().findMarkers(chunkX, chunkZ, MarkerMatter.CAVE_FLOOR) - : new KList<>(); + /** Spawns the entities of the plan that the light, the surface below and the space around them allow, and tells the plan how many appeared. */ + private void spawn(ServerLevel level, ContentSpawns.Plan plan) { int spawned = 0; - for (int i = 0; i < count; i++) { - int worldX; - int worldY; - int worldZ; - if (group == IrisSpawnGroup.CAVE) { - if (caveFloors.isEmpty()) { - continue; - } - IrisPosition caveFloor = caveFloors.getRandom(RNG.r); - worldX = caveFloor.getX(); - worldY = caveFloor.getY() + 1; - worldZ = caveFloor.getZ(); - } else { - worldX = (chunkX << 4) + RNG.r.i(16); - worldZ = (chunkZ << 4) + RNG.r.i(16); - int surfaceY = level.getMinY() + engine.getHeight(worldX, worldZ, false); - int solidY = level.getMinY() + engine.getHeight(worldX, worldZ, true); - worldY = group == IrisSpawnGroup.NORMAL - ? surfaceY + 1 - : RNG.r.i(solidY + 1, surfaceY); - } - if (worldY <= level.getMinY() || worldY >= level.getMaxY()) { - continue; - } - // Rarity is applied exactly once, as pool weighting in rarityPick - never re-rolled per position (Bukkit parity). - if (!lightAllowed(spawner, level, worldX, worldY, worldZ)) { - continue; - } - if (!surfaceMatches(irisEntity.getSurface(), level, worldX, worldY, worldZ)) { - continue; - } - if (!ModdedEntitySpawner.isAreaClearForSpawn(level, irisEntity, worldX, worldY, worldZ)) { - continue; - } - if (ModdedEntitySpawner.spawn(engine, irisEntity, level, worldX, worldY, worldZ, entityRng) != null) { + for (ContentSpawns.Attempt attempt : plan.attempts()) { + if (spawnIfAllowed(level, attempt)) { spawned++; } } - return spawned; + plan.spawned(spawned); } - private int spawnEntryAt(ServerLevel level, IrisEntitySpawn entry, IrisSpawner spawner, IrisPosition position) { - IrisEntity irisEntity = entry.getRealEntity(engine); - if (irisEntity == null) { - return 0; + private boolean spawnIfAllowed(ServerLevel level, ContentSpawns.Attempt attempt) { + if (attempt.worldY() <= level.getMinY() || attempt.worldY() >= level.getMaxY()) { + return false; } - - int min = entry.getMinSpawns(); - int max = entry.getMaxSpawns(); - int count = LootResolver.inclusive(RNG.r, min, max); - if (count <= 0) { - return 0; + if (attempt.restrictsLight() && !lightAllowed(attempt, level)) { + return false; } - - exhaustMarker(spawner, position); - - RNG entityRng = entry.getRng().aquire(() -> new RNG(engine.getSeedManager().getEntity())); - int worldX = position.getX(); - int worldY = position.getY() + 1; - int worldZ = position.getZ(); - int spawned = 0; - for (int i = 0; i < count; i++) { - // Rarity is applied exactly once, as pool weighting in rarityPick - never re-rolled per position (Bukkit parity). - if (!lightAllowed(spawner, level, worldX, worldY, worldZ)) { - continue; - } - if (ModdedEntitySpawner.spawn(engine, irisEntity, level, worldX, worldY, worldZ, entityRng) != null) { - spawned++; - } + if (attempt.checkSurface() && !surfaceAllows(attempt, level)) { + return false; } - return spawned; + return ModdedEntitySpawner.spawn(engine, attempt.entity(), level, attempt.x(), attempt.worldY(), attempt.z()) != null; } - private void exhaustMarker(IrisSpawner spawner, IrisPosition position) { - IrisMarker marker = spawner.getReferenceMarker(); - if (marker == null || !marker.shouldExhaust()) { - return; - } - engine.getMantle().getMantle().remove(position.getX(), position.getY() - engine.getWorld().minHeight(), position.getZ(), MatterMarker.class); + private static boolean lightAllowed(ContentSpawns.Attempt attempt, ServerLevel level) { + int light = level.getMaxLocalRawBrightness(new BlockPos(attempt.x(), attempt.worldY(), attempt.z())); + return light >= attempt.minLight() && light <= attempt.maxLight(); } - private boolean canSpawn(IrisSpawner spawner, int chunkX, int chunkZ) { - return spawner.canSpawn(engine, chunkX, chunkZ); + private static boolean surfaceAllows(ContentSpawns.Attempt attempt, ServerLevel level) { + BlockState below = level.getBlockState(new BlockPos(attempt.x(), attempt.worldY() - 1, attempt.z())); + return matchesSurface(attempt.surface(), below) + && ModdedEntitySpawner.isAreaClearForSpawn(level, attempt.entity(), attempt.x(), attempt.worldY(), attempt.z()); } - private boolean lightAllowed(IrisSpawner spawner, ServerLevel level, int worldX, int worldY, int worldZ) { - IrisRange range = spawner.getAllowedLightLevels(); - if (range.getMin() > 0 || range.getMax() < 15) { - return range.contains(level.getMaxLocalRawBrightness(new BlockPos(worldX, worldY, worldZ))); - } - return true; - } - - private boolean surfaceMatches(IrisSurface surface, ServerLevel level, int worldX, int worldY, int worldZ) { - BlockState below = level.getBlockState(new BlockPos(worldX, worldY - 1, worldZ)); - return matchesSurface(surface, below); - } - - private static boolean matchesSurface(IrisSurface surface, BlockState below) { + private static boolean matchesSurface(ContentSpawns.Surface surface, BlockState below) { if (ModdedBlockResolution.isSolid(below)) { - return surface == IrisSurface.LAND || surface == IrisSurface.OVERWORLD - || (surface == IrisSurface.ANIMAL && isAnimalGround(below)); + return surface == ContentSpawns.Surface.LAND || surface == ContentSpawns.Surface.OVERWORLD + || (surface == ContentSpawns.Surface.ANIMAL && isAnimalGround(below)); } if (below.is(Blocks.LAVA)) { - return surface == IrisSurface.LAVA; + return surface == ContentSpawns.Surface.LAVA; } if (ModdedBlockResolution.isWater(below) || ModdedBlockResolution.isWaterLogged(below) || isAquaticFoliage(below)) { - return surface == IrisSurface.WATER || surface == IrisSurface.OVERWORLD; + return surface == ContentSpawns.Surface.WATER || surface == ContentSpawns.Surface.OVERWORLD; } return false; } @@ -770,11 +600,6 @@ public final class ModdedWorldManager implements EngineWorldManager { return !studio || studioSetting; } - private IrisEntitySpawn rarityPick(KList entries) { - KList weighted = IRare.expandWeighted(entries); - return weighted.isEmpty() ? entries.getRandom() : weighted.getRandom(); - } - private static long pack(int x, int z) { return (((long) x) & 0xFFFFFFFFL) | ((((long) z) & 0xFFFFFFFFL) << 32); } diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java index a7de7a58f..b2179a80f 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java @@ -18,9 +18,6 @@ package art.arcane.iris.modded.command; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.engine.spawn.SpawnResources; -import art.arcane.iris.engine.loot.LootResources; import art.arcane.iris.modded.ModdedIrisLog; import art.arcane.iris.core.IrisSettings; import art.arcane.iris.core.gui.GuiHost; @@ -37,13 +34,10 @@ import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.biome.IrisBiomeGeneratorLink; import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.entity.IrisEntitySpawn; import art.arcane.iris.engine.object.terrain.IrisGenerator; +import art.arcane.iris.core.pack.ModuleResourceClosure; import art.arcane.iris.core.pack.PackExportClosure; -import art.arcane.iris.engine.object.entity.IrisEntity; -import art.arcane.iris.engine.object.marker.IrisMarker; import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.modded.ModdedDimensionManager; import art.arcane.iris.modded.ModdedEngineBootstrap; @@ -56,7 +50,6 @@ import art.arcane.volmlib.util.format.Form; import art.arcane.volmlib.util.io.IO; import art.arcane.volmlib.util.json.JSONObject; import art.arcane.volmlib.util.math.M; -import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.Spiraler; import com.mojang.brigadier.arguments.IntegerArgumentType; import com.mojang.brigadier.arguments.LongArgumentType; @@ -887,12 +880,9 @@ public final class ModdedStudioCommands { LinkedHashSet regionKeys = new LinkedHashSet<>(); LinkedHashSet biomeKeys = new LinkedHashSet<>(); - LinkedHashSet entityKeys = new LinkedHashSet<>(); - LinkedHashSet spawnerKeys = new LinkedHashSet<>(); LinkedHashSet generatorKeys = new LinkedHashSet<>(); - LinkedHashSet lootKeys = new LinkedHashSet<>(); + ModuleResourceClosure moduleResources = new ModuleResourceClosure(dm); LinkedHashSet objectKeys = new LinkedHashSet<>(); - LinkedHashSet markerKeys = new LinkedHashSet<>(); LinkedHashSet structureKeys = new LinkedHashSet<>(); dimension.getAllRegions(() -> dm).forEach((IrisRegion region) -> { @@ -905,8 +895,7 @@ public final class ModdedStudioCommands { biomeKeys.add(biome.getLoadKey()); } }); - lootKeys.addAll(dimension.getLoot().getTables()); - spawnerKeys.addAll(dimension.getEntitySpawners()); + moduleResources.followSettingsOf(dimension); collectStructureKeys(structureKeys, dimension.getStructures()); for (String regionKey : regionKeys) { @@ -919,11 +908,10 @@ public final class ModdedStudioCommands { biomeKeys.add(biome.getLoadKey()); } }); - lootKeys.addAll(region.getLoot().getTables()); - spawnerKeys.addAll(region.getEntitySpawners()); + moduleResources.followSettingsOf(region); + moduleResources.follow(region.getObjects()); collectStructureKeys(structureKeys, region.getStructures()); objectKeys.addAll(PackExportClosure.collectObjectKeys(region.getObjects())); - markerKeys.addAll(PackExportClosure.collectMarkerKeys(region.getObjects())); } for (String biomeKey : biomeKeys) { IrisBiome biome = dm.getBiomeLoader().load(biomeKey); @@ -931,33 +919,10 @@ public final class ModdedStudioCommands { continue; } biome.getGenerators().forEach((IrisBiomeGeneratorLink link) -> generatorKeys.add(link.getGenerator())); - lootKeys.addAll(biome.getLoot().getTables()); - spawnerKeys.addAll(biome.getEntitySpawners()); + moduleResources.followSettingsOf(biome); + moduleResources.follow(biome.getObjects()); collectStructureKeys(structureKeys, biome.getStructures()); objectKeys.addAll(PackExportClosure.collectObjectKeys(biome.getObjects())); - markerKeys.addAll(PackExportClosure.collectMarkerKeys(biome.getObjects())); - } - for (String markerKey : markerKeys) { - IrisMarker marker = SpawnResources.marker(dm, markerKey); - if (marker == null) { - continue; - } - spawnerKeys.addAll(marker.getSpawners()); - } - for (String spawnerKey : spawnerKeys) { - IrisSpawner spawner = SpawnResources.spawner(dm, spawnerKey); - if (spawner == null) { - continue; - } - spawner.getSpawns().forEach((IrisEntitySpawn spawn) -> entityKeys.add(spawn.getEntity())); - spawner.getInitialSpawns().forEach((IrisEntitySpawn spawn) -> entityKeys.add(spawn.getEntity())); - } - for (String entityKey : entityKeys) { - IrisEntity entity = SpawnResources.entity(dm, entityKey); - if (entity == null) { - continue; - } - lootKeys.addAll(entity.getLoot().getTables()); } StringBuilder hashes = new StringBuilder(); @@ -990,18 +955,7 @@ public final class ModdedStudioCommands { for (String key : biomeKeys) { hashes.append(copyJson(folder, "biomes", key, dm.getBiomeLoader().findFile(key))); } - for (String key : entityKeys) { - hashes.append(copyJson(folder, "entities", key, loadFile(SpawnResources.entity(dm, key)))); - } - for (String key : lootKeys) { - hashes.append(copyJson(folder, "loot", key, loadFile(LootResources.table(dm, key)))); - } - for (String key : spawnerKeys) { - hashes.append(copyJson(folder, "spawners", key, loadFile(SpawnResources.spawner(dm, key)))); - } - for (String key : markerKeys) { - hashes.append(copyJson(folder, "markers", key, loadFile(SpawnResources.marker(dm, key)))); - } + hashes.append(moduleResources.writeTo(folder, true)); JSONObject meta = new JSONObject(); meta.put("hash", IO.hash(hashes.toString())); @@ -1091,9 +1045,4 @@ public final class ModdedStudioCommands { thread.start(); return 1; } - - /** The file a resource was read from, or null when the pack has no such resource. */ - private static File loadFile(IrisRegistrant resource) { - return resource == null ? null : resource.getLoadFile(); - } } diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedBlockBreakHandlerTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedBlockBreakHandlerTest.java deleted file mode 100644 index 36569bced..000000000 --- a/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedBlockBreakHandlerTest.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Servers - * Copyright (c) 2026 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.modded; - -import net.minecraft.core.Direction; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.StairBlock; -import net.minecraft.world.level.block.state.BlockState; -import org.junit.Test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class ModdedBlockBreakHandlerTest { - @Test - public void exactMatchingIncludesPropertiesWhileTypeMatchingDoesNot() { - BlockState north = Blocks.OAK_STAIRS.defaultBlockState().setValue(StairBlock.FACING, Direction.NORTH); - BlockState east = Blocks.OAK_STAIRS.defaultBlockState().setValue(StairBlock.FACING, Direction.EAST); - - assertTrue(ModdedBlockBreakHandler.matchesState(north, north, true)); - assertFalse(ModdedBlockBreakHandler.matchesState(north, east, true)); - assertTrue(ModdedBlockBreakHandler.matchesState(north, east, false)); - assertFalse(ModdedBlockBreakHandler.matchesState(north, Blocks.COBBLESTONE.defaultBlockState(), false)); - } -} diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedEntitySpawnerParityTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedEntitySpawnerParityTest.java index 2087b728b..396d541dc 100644 --- a/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedEntitySpawnerParityTest.java +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedEntitySpawnerParityTest.java @@ -1,6 +1,5 @@ package art.arcane.iris.modded; -import art.arcane.iris.engine.object.entity.IrisEffect; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.EntitySpawnReason; @@ -149,16 +148,6 @@ public class ModdedEntitySpawnerParityTest { assertEquals(EntitySpawnReason.NATURAL, ModdedEntitySpawner.reasonFor("not_a_spawn_reason")); } - @Test - public void entityEffectExposesNeutralRegistryKeys() { - IrisEffect effect = new IrisEffect() - .setSound("minecraft:block.amethyst_block.chime") - .setParticleEffect("minecraft:flame"); - - assertEquals("minecraft:block.amethyst_block.chime", effect.getSoundKey()); - assertEquals("minecraft:flame", effect.getParticleEffectKey()); - } - private static long pack(int x, int z) { return (((long) x) & 0xFFFFFFFFL) | ((((long) z) & 0xFFFFFFFFL) << 32); } diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedLootApplierTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedLootApplierTest.java index 75fec1946..001e84ec7 100644 --- a/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedLootApplierTest.java +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedLootApplierTest.java @@ -2,7 +2,7 @@ package art.arcane.iris.modded; import art.arcane.iris.engine.framework.LootResolver; import art.arcane.iris.engine.loot.LootTables; -import art.arcane.iris.engine.object.loot.IrisLootMode; +import art.arcane.iris.builtin.loot.LootMode; import art.arcane.volmlib.util.math.RNG; import net.minecraft.resources.Identifier; import net.minecraft.resources.ResourceKey; @@ -31,7 +31,7 @@ public class ModdedLootApplierTest { public void addAppendsSourcesInOrder() { List sources = new ArrayList<>(List.of("placement-native")); - LootTables.injectSources(sources, List.of("dimension-iris", "region-iris"), IrisLootMode.ADD, false); + LootTables.injectSources(sources, List.of("dimension-iris", "region-iris"), LootMode.ADD, false); assertEquals(List.of("placement-native", "dimension-iris", "region-iris"), sources); } @@ -40,7 +40,7 @@ public class ModdedLootApplierTest { public void clearRemovesEverythingAndContributesNothing() { List sources = new ArrayList<>(List.of("placement-native", "dimension-iris")); - LootTables.injectSources(sources, List.of("biome-iris"), IrisLootMode.CLEAR, false); + LootTables.injectSources(sources, List.of("biome-iris"), LootMode.CLEAR, false); assertEquals(List.of(), sources); } @@ -49,7 +49,7 @@ public class ModdedLootApplierTest { public void replaceRemovesNativeAndIrisSourcesBeforeAdding() { List sources = new ArrayList<>(List.of("placement-native", "dimension-iris")); - LootTables.injectSources(sources, List.of("biome-iris"), IrisLootMode.REPLACE, false); + LootTables.injectSources(sources, List.of("biome-iris"), LootMode.REPLACE, false); assertEquals(List.of("biome-iris"), sources); } @@ -64,7 +64,7 @@ public class ModdedLootApplierTest { public void fallbackDoesNotOverrideExistingNativeOrIrisSources() { List sources = new ArrayList<>(List.of("placement-native", "dimension-iris")); - LootTables.injectSources(sources, List.of("fallback-iris"), IrisLootMode.FALLBACK, false); + LootTables.injectSources(sources, List.of("fallback-iris"), LootMode.FALLBACK, false); assertEquals(List.of("placement-native", "dimension-iris"), sources); } @@ -73,7 +73,7 @@ public class ModdedLootApplierTest { public void fallbackAddsSourcesWhenPlacementIsEmpty() { List sources = new ArrayList<>(); - LootTables.injectSources(sources, List.of("fallback-iris"), IrisLootMode.FALLBACK, true); + LootTables.injectSources(sources, List.of("fallback-iris"), LootMode.FALLBACK, true); assertEquals(List.of("fallback-iris"), sources); } diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedSpawnerRarityParityTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedSpawnerRarityParityTest.java deleted file mode 100644 index 6cd6650a2..000000000 --- a/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedSpawnerRarityParityTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package art.arcane.iris.modded; - -import art.arcane.iris.engine.object.value.IRare; -import art.arcane.iris.engine.object.entity.IrisEntitySpawn; -import art.arcane.volmlib.util.collection.KList; -import org.junit.Test; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class ModdedSpawnerRarityParityTest { - private static IrisEntitySpawn spawn(int rarity) { - IrisEntitySpawn spawn = new IrisEntitySpawn(); - spawn.setRarity(rarity); - return spawn; - } - - @Test - public void rarityIsAppliedOnceAsPoolWeightOnly() { - IrisEntitySpawn common = spawn(1); - IrisEntitySpawn rare = spawn(4); - - KList expanded = IRare.expandWeighted(List.of(common, rare)); - - // totalRarity 5 -> common appears 5/1 = 5 times, rare 5/4 = 1 time. - assertEquals(6, expanded.size()); - assertEquals(5, expanded.stream().filter(entry -> entry == common).count()); - assertEquals(1, expanded.stream().filter(entry -> entry == rare).count()); - } - - @Test - public void rarityZeroAndNegativeAreClampedToOne() { - assertEquals(1, IRare.get(spawn(0))); - assertEquals(1, IRare.get(spawn(-5))); - assertEquals(3, IRare.get(spawn(3))); - } - - @Test - public void perPositionSpawnLoopsDoNotRerollEntryRarity() throws Exception { - String source = Files.readString(Path.of(System.getProperty("iris.moddedCommonSources"), - "art/arcane/iris/modded/ModdedWorldManager.java")); - - for (String method : List.of("private int spawnEntry(", "private int spawnEntryAt(")) { - String body = methodBody(source, method); - assertFalse(method + " must not re-roll rarity per position; rarityPick already weighted the pool", - body.contains("getRarity()")); - assertTrue(method + " must keep the min/max spawn-count roll", - body.contains("LootResolver.inclusive(")); - } - } - - private static String methodBody(String source, String declaration) { - int start = source.indexOf(declaration); - assertTrue("ModdedWorldManager must declare " + declaration, start >= 0); - int open = source.indexOf('{', start); - int depth = 0; - for (int index = open; index < source.length(); index++) { - char character = source.charAt(index); - if (character == '{') { - depth++; - } else if (character == '}') { - depth--; - if (depth == 0) { - return source.substring(open + 1, index); - } - } - } - throw new AssertionError(declaration + " is not brace balanced"); - } -} diff --git a/core/src/main/java/art/arcane/iris/core/content/ContentEffect.java b/core/src/main/java/art/arcane/iris/core/content/ContentEffect.java new file mode 100644 index 000000000..47c5c0cd7 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/content/ContentEffect.java @@ -0,0 +1,44 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.content; + +import java.util.List; + +/** + * An ambient effect that plays now, in host terms: what {@code com.volmit.service.AmbientEffects.Effect} says. The + * adapter carries out the parts it has, in the order sound, particles, commands, potion. + */ +public record ContentEffect(Sound sound, Particles particles, List commands, Potion potion) { + /** A sound, with blocks offset from the player and the volume and pitch decided. */ + public record Sound(String key, int offsetX, int offsetY, int offsetZ, float volume, float pitch) { + } + + /** Particles {@code forward} blocks ahead of the player and {@code sideways} to the right, on the surface there. */ + public record Particles(String key, double forward, double sideways, double jitterX, double jitterZ, int lift, int count, + double altX, double altY, double altZ, double extra) { + } + + /** Commands run offset from the player. */ + public record Command(ContentEntity.Command command, double offsetX, double offsetY, double offsetZ) { + } + + /** A potion effect for the player; one with a stronger amplifier already on the player stays. */ + public record Potion(String key, int strength, int ticks) { + } +} diff --git a/core/src/main/java/art/arcane/iris/core/content/ContentEntity.java b/core/src/main/java/art/arcane/iris/core/content/ContentEntity.java new file mode 100644 index 000000000..a447c6c75 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/content/ContentEntity.java @@ -0,0 +1,57 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.content; + +import java.util.List; + +/** + * An entity a module decided on, in host terms: what {@code com.volmit.entity.EntitySpec} says, for adapters that cannot + * name IrisApi types. Everything random was decided by the module; the adapter creates and configures the entity. + */ +public record ContentEntity(String type, String specialType, String reason, String customName, Flags flags, Equipment equipment, + List passengers, List attributes, List lootTables, + long lootShuffleSeed, ContentEntity leashHolder, SpawnEffect spawnEffect, boolean riseOutOfGround, + String pandaMainGene, String pandaHiddenGene, boolean applySettingsToSpecial, + List commands) { + /** Whether the entity is a mob of another plugin. */ + public boolean isSpecial() { + return !specialType.isEmpty(); + } + + /** What an entity can be set to be, whatever its kind. */ + public record Flags(boolean customNameVisible, boolean aware, boolean ai, boolean glowing, boolean gravity, + boolean invulnerable, boolean silent, boolean pickupItems, boolean removable, + boolean keepEntity, boolean baby) { + } + + /** The items an entity wears and holds; null for an empty slot. */ + public record Equipment(ContentItem helmet, ContentItem chestplate, ContentItem leggings, ContentItem boots, + ContentItem mainHand, ContentItem offHand) { + } + + /** Sound and particles shown around an entity that appears; the adapter makes the random choices of the particle motion. */ + public record SpawnEffect(String sound, int soundDistance, double minPitch, double maxPitch, double volume, + String particle, int particleOffset, int particleCount, double altX, double altY, + double altZ, boolean randomAltX, boolean randomAltY, boolean randomAltZ, double extra) { + } + + /** Console commands run when an entity appears; {@code {x}}, {@code {y}} and {@code {z}} stand for its block position. */ + public record Command(List commands, long delay, boolean repeat, long repeatDelay) { + } +} diff --git a/core/src/main/java/art/arcane/iris/core/content/ContentItem.java b/core/src/main/java/art/arcane/iris/core/content/ContentItem.java new file mode 100644 index 000000000..14d620ae7 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/content/ContentItem.java @@ -0,0 +1,40 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.content; + +import java.util.List; +import java.util.Map; + +/** + * An item a module decided on, in host terms: what {@code com.volmit.item.ItemDrop} says, for adapters that cannot name + * IrisApi types. The module made every random choice; the adapter only creates the item on its platform. + * + * @param damage the fraction of the item's durability already used, or null to leave it undamaged + */ +public record ContentItem(String item, int amount, String displayName, List lore, List enchantments, + List attributes, boolean unbreakable, List flags, Integer customModel, + Double damage, String leatherColor, String dyeColor, Map customNbt) { + /** An enchantment at the level the module decided. */ + public record Enchantment(String key, int level) { + } + + /** An attribute modifier with the amount the module decided. */ + public record Attribute(String attribute, String name, String operation, double amount) { + } +} diff --git a/core/src/main/java/art/arcane/iris/core/content/ContentLoot.java b/core/src/main/java/art/arcane/iris/core/content/ContentLoot.java new file mode 100644 index 000000000..018aec7f8 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/content/ContentLoot.java @@ -0,0 +1,47 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.content; + +import java.util.List; + +/** Where a container's items come from and what a broken block drops, in host terms. */ +public final class ContentLoot { + private ContentLoot() { + } + + /** One source of a container's items, in the order their items are added. */ + public sealed interface Part permits Items, PlatformTable { + } + + /** Items a module drew from one of the pack's loot tables. */ + public record Items(List items) implements Part { + } + + /** A loot table of the platform, which the adapter draws with {@code seed} so the same container always gets the same items. */ + public record PlatformTable(String key, long seed) implements Part { + } + + /** + * What the modules drop for a broken block. + * + * @param replacesVanillaDrops whether the platform's own drops of the block are not dropped + */ + public record BlockDrops(List drops, boolean replacesVanillaDrops) { + } +} diff --git a/core/src/main/java/art/arcane/iris/core/content/ContentServices.java b/core/src/main/java/art/arcane/iris/core/content/ContentServices.java new file mode 100644 index 000000000..3741733c6 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/content/ContentServices.java @@ -0,0 +1,192 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.content; + +import art.arcane.iris.core.modules.ModuleServices; +import art.arcane.iris.core.modules.PlatformBlockStates; +import art.arcane.iris.engine.framework.Engine; +import com.volmit.block.BlockState; +import com.volmit.entity.EntitySpec; +import com.volmit.item.ItemAttribute; +import com.volmit.item.ItemDrop; +import com.volmit.item.ItemEnchantment; +import com.volmit.service.AmbientEffects; +import com.volmit.service.BlockDrops; +import com.volmit.service.EntitySpawns; +import com.volmit.service.Loot; +import com.volmit.world.BlockPosition; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * What the pack's modules say about loot, block drops, spawns and ambient effects, for adapters that cannot name IrisApi + * types: the questions take plain values and the answers are the host types of this package. The modded adapters, which + * fill containers, drop blocks, spawn mobs and play effects themselves, ask here instead of reading the pack's classes. + */ +public final class ContentServices { + private ContentServices() { + } + + /** + * The sources of the loot of the container at {@code x}, {@code worldY}, {@code z}, in the order their items are added. + * + * @param containerKey the platform's key for the block when it is a storage chest an object may have given loot, else null + */ + public static List containerLoot(Engine engine, int x, int worldY, int z, String containerKey, boolean nativeLootDefined) { + BlockState container = containerKey == null ? null : BlockState.parse(PlatformBlockStates.namespaced(containerKey)); + Loot.Site site = new Loot.Site(position(engine, x, worldY, z), container, nativeLootDefined, false); + List parts = new ArrayList<>(); + for (Loot.Source source : ModuleServices.lootTables(engine, site)) { + switch (source) { + case Loot.Table table -> parts.add(new ContentLoot.Items(tableItems(engine, x, worldY, z, table.key()))); + case Loot.PlatformTable table -> parts.add(new ContentLoot.PlatformTable(table.key(), table.seed())); + } + } + return parts; + } + + /** The items the pack's loot table {@code tableKey} gives at the spot. */ + public static List tableItems(Engine engine, int x, int worldY, int z, String tableKey) { + Loot.Site site = new Loot.Site(position(engine, x, worldY, z), null, false, false); + return ModuleServices.lootItems(engine, site, tableKey).stream().map(ContentServices::itemOf).toList(); + } + + /** What the modules drop for the block with the platform's key {@code blockKey} broken at the spot. */ + public static ContentLoot.BlockDrops blockDrops(Engine engine, int x, int worldY, int z, String blockKey) { + BlockDrops.Result result = ModuleServices.blockDrops(engine, new BlockDrops.Broken(position(engine, x, worldY, z), + BlockState.parse(PlatformBlockStates.namespaced(blockKey)))); + return new ContentLoot.BlockDrops(result.drops().stream().map(ContentServices::itemOf).toList(), result.replacesVanillaDrops()); + } + + /** What the first module with something to spawn in the chunk plans. */ + public static Optional planChunkSpawn(Engine engine, int chunkX, int chunkZ, int livingEntities, boolean initial) { + return planned(engine, new EntitySpawns.Chunk(chunkX, chunkZ, livingEntities, initial)); + } + + /** What the first module that knows the spawner plans at the marker block. */ + public static Optional planMarkerSpawn(Engine engine, int x, int worldY, int z, String marker, String spawner, boolean initial) { + return planned(engine, new EntitySpawns.Marker(position(engine, x, worldY, z), marker, spawner, initial)); + } + + /** What the marker with the tag {@code tag} does; empty for a tag no module knows. */ + public static Optional markerRule(Engine engine, String tag) { + return ModuleServices.markerRule(engine, tag) + .map(rule -> new ContentSpawns.MarkerRule(rule.spawners(), rule.emptyAbove(), rule.removeOnChange())); + } + + /** The entity of the pack named {@code key} as a module would spawn it; empty for an unknown key. */ + public static Optional entity(Engine engine, String key) { + return ModuleServices.entity(engine, key).map(ContentServices::entityOf); + } + + /** The ambient effects due for a player standing at the spot. */ + public static List ambientEffects(Engine engine, int x, int worldY, int z) { + return ModuleServices.ambientEffects(engine, position(engine, x, worldY, z)).stream().map(ContentServices::effectOf).toList(); + } + + private static Optional planned(Engine engine, EntitySpawns.Site site) { + return ModuleServices.planSpawn(engine, site).map(planned -> new ContentSpawns.Plan(planned, attemptsOf(engine, planned.plan()))); + } + + private static List attemptsOf(Engine engine, EntitySpawns.Plan plan) { + List attempts = new ArrayList<>(); + for (EntitySpawns.Attempt attempt : plan.attempts()) { + attempts.add(new ContentSpawns.Attempt(attempt.at().x(), attempt.at().y() + engine.getMinHeight(), attempt.at().z(), + entityOf(attempt.entity()), ContentSpawns.surfaceOf(attempt.surface()), attempt.minLight(), attempt.maxLight(), + attempt.checkSurface())); + } + return attempts; + } + + private static BlockPosition position(Engine engine, int x, int worldY, int z) { + return new BlockPosition(x, worldY - engine.getMinHeight(), z); + } + + private static ContentItem itemOf(ItemDrop drop) { + return new ContentItem(drop.item(), drop.amount(), drop.displayName(), drop.lore(), + drop.enchantments().stream().map(ContentServices::enchantmentOf).toList(), + drop.attributes().stream().map(ContentServices::attributeOf).toList(), drop.unbreakable(), drop.flags(), + drop.customModel(), drop.damage(), drop.leatherColor(), drop.dyeColor(), drop.customNbt()); + } + + private static ContentItem.Enchantment enchantmentOf(ItemEnchantment enchantment) { + return new ContentItem.Enchantment(enchantment.key(), enchantment.level()); + } + + private static ContentItem.Attribute attributeOf(ItemAttribute attribute) { + return new ContentItem.Attribute(attribute.attribute(), attribute.name(), attribute.operation(), attribute.amount()); + } + + private static ContentEntity entityOf(EntitySpec spec) { + return new ContentEntity(spec.type(), spec.specialType(), spec.reason(), spec.customName(), flagsOf(spec.flags()), + equipmentOf(spec.equipment()), spec.passengers().stream().map(ContentServices::entityOf).toList(), + spec.attributes().stream().map(ContentServices::attributeOf).toList(), spec.lootTables(), spec.lootShuffleSeed(), + spec.leashHolder() == null ? null : entityOf(spec.leashHolder()), spawnEffectOf(spec.spawnEffect()), + spec.riseOutOfGround(), spec.pandaMainGene(), spec.pandaHiddenGene(), spec.applySettingsToSpecial(), + spec.commands().stream().map(ContentServices::commandOf).toList()); + } + + private static ContentEntity.Flags flagsOf(EntitySpec.Flags flags) { + return new ContentEntity.Flags(flags.customNameVisible(), flags.aware(), flags.ai(), flags.glowing(), flags.gravity(), + flags.invulnerable(), flags.silent(), flags.pickupItems(), flags.removable(), flags.keepEntity(), flags.baby()); + } + + private static ContentEntity.Equipment equipmentOf(EntitySpec.Equipment equipment) { + return new ContentEntity.Equipment(optionalItem(equipment.helmet()), optionalItem(equipment.chestplate()), + optionalItem(equipment.leggings()), optionalItem(equipment.boots()), optionalItem(equipment.mainHand()), + optionalItem(equipment.offHand())); + } + + private static ContentItem optionalItem(ItemDrop drop) { + return drop == null ? null : itemOf(drop); + } + + private static ContentEntity.SpawnEffect spawnEffectOf(EntitySpec.SpawnEffect effect) { + if (effect == null) { + return null; + } + return new ContentEntity.SpawnEffect(effect.sound(), effect.soundDistance(), effect.minPitch(), effect.maxPitch(), + effect.volume(), effect.particle(), effect.particleOffset(), effect.particleCount(), effect.altX(), effect.altY(), + effect.altZ(), effect.randomAltX(), effect.randomAltY(), effect.randomAltZ(), effect.extra()); + } + + private static ContentEntity.Command commandOf(EntitySpec.Command command) { + return new ContentEntity.Command(command.commands(), command.delay(), command.repeat(), command.repeatDelay()); + } + + private static ContentEffect effectOf(AmbientEffects.Effect effect) { + return new ContentEffect(soundOf(effect.sound()), particlesOf(effect.particles()), + effect.commands().stream().map(command -> new ContentEffect.Command(commandOf(command.command()), + command.offsetX(), command.offsetY(), command.offsetZ())).toList(), + effect.potion() == null ? null : new ContentEffect.Potion(effect.potion().key(), effect.potion().strength(), effect.potion().ticks())); + } + + private static ContentEffect.Sound soundOf(AmbientEffects.Sound sound) { + return sound == null ? null : new ContentEffect.Sound(sound.key(), sound.offsetX(), sound.offsetY(), sound.offsetZ(), + sound.volume(), sound.pitch()); + } + + private static ContentEffect.Particles particlesOf(AmbientEffects.Particles particles) { + return particles == null ? null : new ContentEffect.Particles(particles.key(), particles.forward(), particles.sideways(), + particles.jitterX(), particles.jitterZ(), particles.lift(), particles.count(), particles.altX(), particles.altY(), + particles.altZ(), particles.extra()); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/content/ContentSpawns.java b/core/src/main/java/art/arcane/iris/core/content/ContentSpawns.java new file mode 100644 index 000000000..66e422749 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/content/ContentSpawns.java @@ -0,0 +1,85 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.content; + +import art.arcane.iris.core.modules.ModuleServices; +import com.volmit.service.EntitySpawns; + +import java.util.List; + +/** What the modules plan to spawn, in host terms. */ +public final class ContentSpawns { + private ContentSpawns() { + } + + /** The ground or fluid an entity spawns on. */ + public enum Surface { + LAND, ANIMAL, WATER, OVERWORLD, LAVA + } + + /** + * One entity to spawn at a block, if the light there lies in the range (when {@link #restrictsLight()}) and, when + * {@code checkSurface}, the block below suits the entity's surface and the space it needs is free. + * + * @param x world X + * @param worldY world Y + * @param z world Z + * @param checkSurface whether to check the surface and the free space + */ + public record Attempt(int x, int worldY, int z, ContentEntity entity, Surface surface, int minLight, int maxLight, + boolean checkSurface) { + /** Whether the light level matters. */ + public boolean restrictsLight() { + return minLight > 0 || maxLight < 15; + } + } + + /** What a marker does: the keys of its spawners, whether it needs free space above it and whether it goes away when its block changes. */ + public record MarkerRule(List spawners, boolean emptyAbove, boolean removeOnChange) { + } + + /** Entities to spawn, tried one after the other; tell the plan how many appeared, so the spawner's rate limits count them. */ + public static final class Plan { + private final ModuleServices.PlannedSpawn planned; + private final List attempts; + + Plan(ModuleServices.PlannedSpawn planned, List attempts) { + this.planned = planned; + this.attempts = List.copyOf(attempts); + } + + public List attempts() { + return attempts; + } + + /** Whether the marker that led here is used up and should be removed. */ + public boolean exhaustsMarker() { + return planned.plan().exhaustsMarker(); + } + + /** Reports how many of the planned entities appeared. */ + public void spawned(int count) { + planned.spawned(count); + } + } + + static Surface surfaceOf(EntitySpawns.Surface surface) { + return Surface.valueOf(surface.name()); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/pack/ModuleResourceClosureTest.java b/core/src/test/java/art/arcane/iris/core/pack/ModuleResourceClosureTest.java new file mode 100644 index 000000000..a7bbfdb9b --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/pack/ModuleResourceClosureTest.java @@ -0,0 +1,134 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.pack; + +import art.arcane.iris.builtin.loot.LootTable; +import art.arcane.iris.builtin.spawn.EntityDefinition; +import art.arcane.iris.builtin.spawn.SpawnMarker; +import art.arcane.iris.builtin.spawn.Spawner; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.volmlib.util.json.JSONObject; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** An export carries the loot tables, spawners, entities and markers that the pack's settings and placements reference, and what those reference. */ +public class ModuleResourceClosureTest { + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Test + public void followsEveryLevelsSettingsAndThePlacementsThroughSpawnersEntitiesAndMarkers() throws Exception { + IrisData data = IrisData.openValidation(pack().toFile()); + try { + ModuleResourceClosure closure = new ModuleResourceClosure(data); + IrisDimension dimension = data.getDimensionLoader().load("main"); + IrisRegion region = data.getRegionLoader().load("region"); + IrisBiome biome = data.getBiomeLoader().load("biome"); + + closure.followSettingsOf(dimension); + closure.followSettingsOf(region); + closure.followSettingsOf(biome); + closure.follow(biome.getObjects()); + + assertEquals(List.of("drops", "global", "regional"), closure.keysOf(LootTable.class)); + assertEquals(List.of("camp/zombies", "cave", "marker/spawner"), closure.keysOf(Spawner.class)); + assertEquals(List.of("beta/sentinel", "cow", "zombie"), closure.keysOf(EntityDefinition.class)); + assertEquals(List.of("camp"), closure.keysOf(SpawnMarker.class)); + } finally { + data.close(); + } + } + + @Test + public void whatIsNotReferencedIsNotExportedAndMissingKeysAreSkipped() throws Exception { + IrisData data = IrisData.openValidation(pack().toFile()); + try { + ModuleResourceClosure closure = new ModuleResourceClosure(data); + + closure.followSettingsOf(data.getRegionLoader().load("region")); + + assertEquals(List.of("regional"), closure.keysOf(LootTable.class)); + assertEquals(List.of(), closure.keysOf(Spawner.class)); + assertFalse(closure.keysOf(LootTable.class).contains("unused")); + assertTrue(new ModuleResourceClosure(data).isEmpty()); + } finally { + data.close(); + } + } + + @Test + public void writesEachResourceUnderTheFolderOfItsKind() throws Exception { + IrisData data = IrisData.openValidation(pack().toFile()); + try { + ModuleResourceClosure closure = new ModuleResourceClosure(data); + closure.followSettingsOf(data.getDimensionLoader().load("main")); + File target = temporaryFolder.newFolder("export"); + + String hashes = closure.writeTo(target, true); + + assertFalse(hashes.isEmpty()); + assertEquals("Global", new JSONObject(Files.readString(target.toPath().resolve("loot/global.json"))).getString("name")); + assertTrue(Files.isRegularFile(target.toPath().resolve("spawners/camp/zombies.json"))); + assertTrue(Files.isRegularFile(target.toPath().resolve("entities/zombie.json"))); + assertFalse(Files.exists(target.toPath().resolve("loot/unused.json"))); + } finally { + data.close(); + } + } + + private Path pack() throws Exception { + File pack = temporaryFolder.newFolder("pack"); + write(pack, "dimensions/main.json", "{\"regions\":[\"region\"],\"loot\":{\"tables\":[\"global\"]},\"entitySpawners\":[\"camp/zombies\"]}"); + write(pack, "regions/region.json", "{\"landBiomes\":[\"biome\"],\"loot\":{\"tables\":[\"regional\"]}}"); + write(pack, "biomes/biome.json", "{\"name\":\"Biome\",\"entitySpawners\":[\"cave\"],\"blockDrops\":[{\"blocks\":[{\"block\":\"stone\"}],\"drops\":[{\"type\":\"gravel\"}]}]," + + "\"objects\":[{\"place\":[\"hut\"],\"loot\":[{\"name\":\"drops\"}],\"markers\":[{\"marker\":\"camp\",\"mark\":[{\"block\":\"stone\"}]}]}]}"); + write(pack, "loot/global.json", "{\"name\":\"Global\",\"loot\":[{\"type\":\"stick\"}]}"); + write(pack, "loot/regional.json", "{\"name\":\"Regional\",\"loot\":[{\"type\":\"stick\"}]}"); + write(pack, "loot/drops.json", "{\"name\":\"Drops\",\"loot\":[{\"type\":\"stick\"}]}"); + write(pack, "loot/unused.json", "{\"name\":\"Unused\",\"loot\":[{\"type\":\"stick\"}]}"); + write(pack, "spawners/camp/zombies.json", "{\"spawns\":[{\"entity\":\"zombie\"}],\"initialSpawns\":[{\"entity\":\"beta/sentinel\"}]}"); + write(pack, "spawners/cave.json", "{\"spawns\":[{\"entity\":\"cow\"}]}"); + write(pack, "spawners/marker/spawner.json", "{\"spawns\":[{\"entity\":\"cow\"}]}"); + write(pack, "entities/zombie.json", "{\"type\":\"minecraft:zombie\",\"loot\":{\"tables\":[\"drops\"]}}"); + write(pack, "entities/beta/sentinel.json", "{\"type\":\"minecraft:skeleton\"}"); + write(pack, "entities/cow.json", "{\"type\":\"minecraft:cow\"}"); + write(pack, "markers/camp.json", "{\"spawners\":[\"marker/spawner\"]}"); + return pack.toPath(); + } + + private static void write(File root, String relative, String content) throws Exception { + Path path = root.toPath().resolve(relative); + Files.createDirectories(path.getParent()); + Files.writeString(path, content, StandardCharsets.UTF_8); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/pack/PackExportClosureTest.java b/core/src/test/java/art/arcane/iris/core/pack/PackExportClosureTest.java index b5b58bc89..11c720d60 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/PackExportClosureTest.java +++ b/core/src/test/java/art/arcane/iris/core/pack/PackExportClosureTest.java @@ -59,9 +59,9 @@ public class PackExportClosureTest { String modded = Files.readString(Path.of( "../adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java")).replace("\r\n", "\n"); - assertTrue("modded packager must write spawners/", modded.contains("\"spawners\"")); - assertTrue("modded packager must write markers/", modded.contains("\"markers\"")); - assertTrue("modded packager must include initial spawns", modded.contains("getInitialSpawns")); + assertTrue("modded packager must write the spawn and loot resources the settings reference", + modded.contains("moduleResources.writeTo(folder, true)")); + assertTrue("modded packager must export the placements' references", modded.contains("moduleResources.follow(region.getObjects())")); assertTrue("modded packager must export region objects", modded.contains("region.getObjects()")); int moddedValidation = modded.indexOf("PackValidator.validateForPackaging(packFolder)"); assertTrue("modded packager must validate before mutating package state", diff --git a/core/src/test/java/art/arcane/iris/engine/loot/PlacementLootTest.java b/core/src/test/java/art/arcane/iris/engine/loot/PlacementLootTest.java new file mode 100644 index 000000000..40a3214aa --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/loot/PlacementLootTest.java @@ -0,0 +1,150 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import art.arcane.iris.builtin.loot.LootTable; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.ModuleResourceFixture; +import art.arcane.iris.engine.UsableBlockPlatform; +import art.arcane.iris.engine.object.TestSettings; +import art.arcane.iris.engine.object.loot.IObjectLoot; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.service.Loot; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * The loot table an object placement gives a chest: a table naming the chest's exact state beats one naming its kind of + * block, which beats one naming no block; the weights pick among equals; platform tables count when the platform has them. + */ +public class PlacementLootTest { + private static final String CHEST = "minecraft:chest[facing=north]"; + private static final String EAST_CHEST = "minecraft:chest[facing=east]"; + private static final long LOOT_SEED = 99L; + + private PlacementLoot placement; + + @BeforeClass + public static void bindPlatform() { + UsableBlockPlatform.bind(); + } + + @AfterClass + public static void unbindPlatform() { + UsableBlockPlatform.unbind(); + } + + @Before + public void servePackTables() { + IrisData data = mock(IrisData.class); + ModuleResourceFixture fixture = ModuleResourceFixture.serve(data); + for (String key : List.of("everywhere", "chests", "this-chest", "other")) { + fixture.resource(LootResources.TABLES, key, TestSettings.of(LootTable.class, "{\"name\": \"" + key + "\"}")); + } + placement = new PlacementLoot(data, () -> Set.of("minecraft:chests/simple_dungeon"), LOOT_SEED); + } + + @Test + public void aTableThatNamesTheExactStateBeatsOneThatNamesTheKindOfBlock() { + List pack = List.of(entry("everywhere", 1, false), entry("chests", 1, false, CHEST), entry("this-chest", 1, true, CHEST)); + + assertEquals(new Loot.Table("this-chest"), pick(List.of(), pack, CHEST)); + assertEquals(new Loot.Table("chests"), pick(List.of(), pack, EAST_CHEST)); + } + + @Test + public void aTableThatNamesNoBlockServesChestsNothingElseNames() { + List pack = List.of(entry("everywhere", 1, false), entry("other", 1, false, "minecraft:barrel")); + + assertEquals(new Loot.Table("everywhere"), pick(List.of(), pack, CHEST)); + } + + @Test + public void exactEntriesDoNotApplyToOtherStatesAndNothingMatchingGivesNothing() { + List pack = List.of(entry("this-chest", 1, true, CHEST), entry("other", 1, false, "minecraft:barrel")); + + assertNull(pick(List.of(), pack, EAST_CHEST)); + } + + @Test + public void weightsPickAmongEqualsAndZeroWeightsAreIgnored() { + List pack = List.of(entry("everywhere", 3, false), entry("chests", 1, false), entry("other", 0, false)); + int everywhere = 0; + RNG rng = new RNG(5L); + + for (int i = 0; i < 4000; i++) { + Loot.Source picked = placement.pick(List.of(), pack, block(CHEST), rng, 0, 64, 0); + if (picked.equals(new Loot.Table("everywhere"))) { + everywhere++; + } else { + assertEquals(new Loot.Table("chests"), picked); + } + } + + assertEquals(3000, everywhere, 150); + } + + @Test + public void aPlatformTableWithAnythingThePlatformHasIsASourceWithTheSeedOfItsIdentity() { + List platform = List.of(entry("chests/simple_dungeon", 1, false), entry("chests/missing", 1, false)); + + Loot.Source picked = pick(platform, List.of(), CHEST); + + assertEquals(new Loot.PlatformTable("minecraft:chests/simple_dungeon", + LootTables.seed(LOOT_SEED, "Vanilla minecraft:chests/simple_dungeon", 0, 64, 0)), picked); + } + + @Test + public void tablesTheWorldLacksAreSkipped() { + assertNull(pick(List.of(entry("chests/missing", 1, false)), List.of(entry("not-a-table", 1, false)), CHEST)); + } + + private Loot.Source pick(List platform, List pack, String container) { + return placement.pick(platform, pack, block(container), new RNG(1L), 0, 64, 0); + } + + private static PlatformBlockState block(String key) { + return UsableBlockPlatform.block(key); + } + + private static IObjectLoot entry(String name, int weight, boolean exact, String... filter) { + IObjectLoot loot = mock(IObjectLoot.class); + when(loot.getName()).thenReturn(name); + when(loot.getWeight()).thenReturn(weight); + when(loot.isExact()).thenReturn(exact); + KList filterStates = new KList<>(); + for (String key : filter) { + filterStates.add(block(key)); + } + when(loot.getFilter(org.mockito.ArgumentMatchers.any())).thenReturn(filterStates); + return loot; + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/loot/ResolvedBlockDropTest.java b/core/src/test/java/art/arcane/iris/engine/loot/ResolvedBlockDropTest.java new file mode 100644 index 000000000..2faf1f9e3 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/loot/ResolvedBlockDropTest.java @@ -0,0 +1,72 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import art.arcane.iris.builtin.loot.BlockDrop; +import art.arcane.iris.engine.UsableBlockPlatform; +import art.arcane.iris.engine.object.TestSettings; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockSpec; +import com.volmit.block.BlockState; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +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; + +/** Which broken blocks a block drop applies to: the exact state it names, or any state of that block. */ +public class ResolvedBlockDropTest { + private static final String NORTH_STAIRS = "minecraft:oak_stairs[facing=north]"; + private static final String EAST_STAIRS = "minecraft:oak_stairs[facing=east]"; + private static final String COBBLESTONE = "minecraft:cobblestone"; + + @BeforeClass + public static void bindPlatform() { + UsableBlockPlatform.bind(); + } + + @AfterClass + public static void unbindPlatform() { + UsableBlockPlatform.unbind(); + } + + @Test + public void exactMatchingIncludesPropertiesWhileTypeMatchingDoesNot() { + ResolvedBlockDrop exact = resolved(true); + ResolvedBlockDrop byType = resolved(false); + + assertTrue(exact.dropsFor(NORTH_STAIRS)); + assertFalse(exact.dropsFor(EAST_STAIRS)); + assertTrue(byType.dropsFor(NORTH_STAIRS)); + assertTrue(byType.dropsFor(EAST_STAIRS)); + assertFalse(byType.dropsFor(COBBLESTONE)); + assertFalse(exact.dropsFor(COBBLESTONE)); + } + + private static ResolvedBlockDrop resolved(boolean exactBlocks) { + BlockDrop drop = TestSettings.of(BlockDrop.class, "{\"exactBlocks\": " + exactBlocks + ", \"blocks\": [{\"block\": \"oak_stairs\"}]}"); + BlockRegistry blocks = mock(BlockRegistry.class); + when(blocks.resolve(any(BlockSpec.class))).thenReturn(BlockState.parse(NORTH_STAIRS)); + return ResolvedBlockDrop.of(drop, blocks); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/object/value/IRareWeightingTest.java b/core/src/test/java/art/arcane/iris/engine/object/value/IRareWeightingTest.java new file mode 100644 index 000000000..c434ced95 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/object/value/IRareWeightingTest.java @@ -0,0 +1,56 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.object.value; + +import art.arcane.volmlib.util.collection.KList; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; + +/** Rarity weights a pool exactly once: the entity spawners of both platforms pick a spawn from the expanded pool. */ +public class IRareWeightingTest { + private record Spawn(int rarity) implements IRare { + @Override + public int getRarity() { + return rarity; + } + } + + @Test + public void rarityIsAppliedOnceAsPoolWeightOnly() { + Spawn common = new Spawn(1); + Spawn rare = new Spawn(4); + + KList expanded = IRare.expandWeighted(List.of(common, rare)); + + // totalRarity 5 -> common appears 5/1 = 5 times, rare 5/4 = 1 time. + assertEquals(6, expanded.size()); + assertEquals(5, expanded.stream().filter(entry -> entry == common).count()); + assertEquals(1, expanded.stream().filter(entry -> entry == rare).count()); + } + + @Test + public void rarityZeroAndNegativeAreClampedToOne() { + assertEquals(1, IRare.get(new Spawn(0))); + assertEquals(1, IRare.get(new Spawn(-5))); + assertEquals(3, IRare.get(new Spawn(3))); + } +} From dce02229f1eb1f72330b729abbe4c71d3af0c1a3 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 13:04:02 +0200 Subject: [PATCH 09/10] Tests for ambient effects, the spawner gate, content services, placement loot and the studio schemas of the spawn kinds --- .../core/content/ContentServicesTest.java | 133 +++++++++++++++++ .../engine/spawn/AmbientEffectingTest.java | 141 ++++++++++++++++++ .../iris/engine/spawn/SpawnResourcesTest.java | 23 +++ .../iris/engine/spawn/SpawnerGateTest.java | 113 ++++++++++++++ 4 files changed, 410 insertions(+) create mode 100644 core/src/test/java/art/arcane/iris/core/content/ContentServicesTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/spawn/AmbientEffectingTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/spawn/SpawnerGateTest.java diff --git a/core/src/test/java/art/arcane/iris/core/content/ContentServicesTest.java b/core/src/test/java/art/arcane/iris/core/content/ContentServicesTest.java new file mode 100644 index 000000000..2251510cd --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/content/ContentServicesTest.java @@ -0,0 +1,133 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.content; + +import art.arcane.iris.builtin.loot.LootTable; +import art.arcane.iris.builtin.spawn.EntityDefinition; +import art.arcane.iris.builtin.spawn.SpawnMarker; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.ModuleResourceFixture; +import art.arcane.iris.engine.UsableBlockPlatform; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineGeneration; +import art.arcane.iris.engine.framework.SeedManager; +import art.arcane.iris.engine.loot.LootModule; +import art.arcane.iris.engine.loot.LootResources; +import art.arcane.iris.engine.object.TestSettings; +import art.arcane.iris.engine.object.world.IrisWorld; +import art.arcane.iris.engine.spawn.SpawnModule; +import art.arcane.iris.engine.spawn.SpawnResources; +import art.arcane.iris.spi.PlatformWorld; +import com.volmit.item.ItemRegistry; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; +import java.util.OptionalInt; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** The answers of the loot and spawn modules reach adapters that cannot name IrisApi as host-typed values. */ +public class ContentServicesTest { + private Engine engine; + + @BeforeClass + public static void bindPlatform() { + UsableBlockPlatform.bind(); + } + + @AfterClass + public static void unbindPlatform() { + UsableBlockPlatform.unbind(); + } + + @Before + public void buildEngine() { + engine = mock(Engine.class); + IrisData data = mock(IrisData.class); + ModuleResourceFixture fixture = ModuleResourceFixture.serve(data); + ModuleResourceFixture.serveModules(data, new SpawnModule(), new LootModule()); + ItemRegistry items = mock(ItemRegistry.class); + when(items.maxDurability(anyString())).thenReturn(OptionalInt.of(0)); + when(data.getPackResources().items()).thenReturn(items); + when(engine.getData()).thenReturn(data); + IrisWorld engineWorld = mock(IrisWorld.class); + when(engineWorld.platformWorld()).thenReturn(mock(PlatformWorld.class)); + when(engine.getWorld()).thenReturn(engineWorld); + SeedManager seeds = mock(SeedManager.class); + when(seeds.getEntity()).thenReturn(11L); + when(seeds.getLoot()).thenReturn(5L); + when(engine.getSeedManager()).thenReturn(seeds); + when(engine.getMinHeight()).thenReturn(-64); + when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); + fixture.resource(SpawnResources.ENTITIES, "guard", TestSettings.of(EntityDefinition.class, """ + {"type": "minecraft:zombie", "customName": "Guard", "baby": true, "glowing": true, + "helmet": {"type": "iron_helmet", "enchantments": [{"enchantment": "protection", "minLevel": 3, "maxLevel": 3}]}, + "loot": {"tables": ["guard/drops"]}, + "rawCommands": [{"commands": ["say hi {x}"], "delay": 4, "repeat": true, "repeatDelay": 20}]}""")); + fixture.resource(SpawnResources.MARKERS, "camp", TestSettings.of(SpawnMarker.class, + "{\"spawners\": [], \"emptyAbove\": false, \"removeOnChange\": false}")); + fixture.resource(LootResources.TABLES, "guard/drops", TestSettings.of(LootTable.class, + "{\"name\": \"Drops\", \"minPicked\": 1, \"maxPicked\": 1, \"loot\": [{\"type\": \"bread\", \"minAmount\": 3, \"maxAmount\": 3}]}")); + } + + @Test + public void anEntityKeepsEveryDecisionTheModuleMade() { + ContentEntity guard = ContentServices.entity(engine, "guard").orElseThrow(); + + assertEquals("minecraft:zombie", guard.type()); + assertEquals("Guard", guard.customName()); + assertTrue(guard.flags().baby()); + assertTrue(guard.flags().glowing()); + assertFalse(guard.isSpecial()); + assertEquals("iron_helmet", guard.equipment().helmet().item()); + assertEquals(List.of(new ContentItem.Enchantment("protection", 3)), guard.equipment().helmet().enchantments()); + assertEquals(List.of("guard/drops"), guard.lootTables()); + assertEquals(List.of(new ContentEntity.Command(List.of("say hi {x}"), 4, true, 20)), guard.commands()); + assertTrue(ContentServices.entity(engine, "nobody").isEmpty()); + } + + @Test + public void aMarkerRuleIsTheModulesAnswer() { + ContentSpawns.MarkerRule rule = ContentServices.markerRule(engine, "camp").orElseThrow(); + + assertEquals(List.of(), rule.spawners()); + assertFalse(rule.emptyAbove()); + assertFalse(rule.removeOnChange()); + assertTrue(ContentServices.markerRule(engine, "unknown").isEmpty()); + } + + @Test + public void aTablesItemsAreDrawnByTheModuleAtTheSpot() { + List items = ContentServices.tableItems(engine, 10, 64, -3, "guard/drops"); + + assertEquals(1, items.size()); + assertEquals("bread", items.getFirst().item()); + assertEquals(3, items.getFirst().amount()); + assertEquals(items, ContentServices.tableItems(engine, 10, 64, -3, "guard/drops")); + assertTrue(ContentServices.tableItems(engine, 10, 64, -3, "missing").isEmpty()); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/spawn/AmbientEffectingTest.java b/core/src/test/java/art/arcane/iris/engine/spawn/AmbientEffectingTest.java new file mode 100644 index 000000000..c3c681d4e --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/spawn/AmbientEffectingTest.java @@ -0,0 +1,141 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.spawn; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.BuiltInPack; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineGeneration; +import art.arcane.iris.engine.object.TestSettings; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.engine.object.world.IrisWorld; +import art.arcane.iris.builtin.spawn.EffectSettings; +import art.arcane.iris.spi.PlatformWorld; +import com.volmit.service.AmbientEffects; +import com.volmit.world.BlockPosition; +import com.volmit.world.PackWorld; +import org.junit.Before; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** The ambient effects due around a player: the region's, then the biome's, each when its interval and chance allow, fully decided. */ +public class AmbientEffectingTest { + private static final BlockPosition AT = new BlockPosition(10, 70, -20); + private static final String SOUND_AND_POTION = """ + {"effects": [{"sound": "ambient.cave", "soundDistance": 4, "minPitch": 0.5, "maxPitch": 0.5, "volume": 2, + "potionEffect": "luck", "potionStrength": 1, "potionTicksMin": 100, "potionTicksMax": 100, + "interval": 1, "chance": 1}]}"""; + private static final String PARTICLES_AND_COMMANDS = """ + {"effects": [{"particleEffect": "flame", "particleDistance": 1, "particleAway": 5, "particleDistanceWidth": 0, + "particleCount": 2, "particleAltX": 0.5, "randomAltX": false, "randomAltZ": false, "extra": 0.25, + "commandRegistry": {"rawCommands": [{"commands": ["say hi {x}"], "delay": 3}, + {"commands": ["say never"], "weather": "DOWNFALL"}], + "commandOffsetX": 2, "commandRandomAltX": false, "commandAllRandomLocations": false}, + "interval": 1, "chance": 1}]}"""; + + private Engine engine; + private IrisRegion region; + private IrisBiome biome; + private PackWorld world; + + @Before + public void buildWorld() { + engine = mock(Engine.class); + when(engine.getData()).thenReturn(mock(IrisData.class)); + IrisWorld engineWorld = mock(IrisWorld.class); + PlatformWorld platformWorld = mock(PlatformWorld.class); + when(engineWorld.platformWorld()).thenReturn(platformWorld); + when(engine.getWorld()).thenReturn(engineWorld); + region = mock(IrisRegion.class); + biome = mock(IrisBiome.class); + when(region.getModuleSettings()).thenReturn(ModuleSettingsOf.none()); + when(biome.getModuleSettings()).thenReturn(ModuleSettingsOf.none()); + when(engine.getRegion(10, -20)).thenReturn(region); + when(engine.getBiome(10, 70, -20)).thenReturn(biome); + world = new EngineGeneration(engine).world(); + } + + @Test + public void anAreaWithoutEffectsHasNothingDue() { + assertEquals(List.of(), new AmbientEffecting().due(world, AT)); + } + + @Test + public void aSoundAndAPotionComeWithTheirDecidedValues() throws Exception { + when(biome.getModuleSettings()).thenReturn(BuiltInPack.settings(TestSettings.of(EffectSettings.class, SOUND_AND_POTION))); + Thread.sleep(5); + + List due = new AmbientEffecting().due(world, AT); + + assertEquals(1, due.size()); + AmbientEffects.Sound sound = due.getFirst().sound(); + assertEquals("ambient.cave", sound.key()); + assertTrue(Math.abs(sound.offsetX()) <= 4 && Math.abs(sound.offsetY()) <= 4 && Math.abs(sound.offsetZ()) <= 4); + assertEquals(2F, sound.volume(), 0); + assertEquals(0.5F, sound.pitch(), 0); + assertEquals(new AmbientEffects.Potion("luck", 1, 100), due.getFirst().potion()); + assertNull(due.getFirst().particles()); + assertTrue(due.getFirst().commands().isEmpty()); + } + + @Test + public void particlesAndOnlyTheCommandsThatMayRunNowComeWithTheirOffsets() throws Exception { + when(region.getModuleSettings()).thenReturn(BuiltInPack.settings(TestSettings.of(EffectSettings.class, PARTICLES_AND_COMMANDS))); + Thread.sleep(5); + + AmbientEffects.Effect effect = new AmbientEffecting().due(world, AT).getFirst(); + + assertEquals("flame", effect.particles().key()); + assertEquals(5, effect.particles().forward(), 0); + assertEquals(0, effect.particles().sideways(), 0); + assertEquals(0.5, effect.particles().altX(), 0); + assertEquals(0.25, effect.particles().extra(), 0); + assertEquals(2, effect.particles().count()); + assertEquals(1, effect.commands().size()); + assertEquals(List.of("say hi {x}"), effect.commands().getFirst().command().commands()); + assertEquals(3, effect.commands().getFirst().command().delay()); + assertEquals(2, effect.commands().getFirst().offsetX(), 0); + assertNull(effect.sound()); + assertNull(effect.potion()); + } + + @Test + public void anEffectPlaysOnlyOncePerInterval() { + when(biome.getModuleSettings()).thenReturn(BuiltInPack.settings(TestSettings.of(EffectSettings.class, + SOUND_AND_POTION.replace("\"interval\": 1", "\"interval\": 600000")))); + AmbientEffecting effecting = new AmbientEffecting(); + + assertEquals(1, effecting.due(world, AT).size()); + assertEquals(0, effecting.due(world, AT).size()); + } + + private static final class ModuleSettingsOf { + private static art.arcane.iris.core.modules.ModuleSettings none() { + return art.arcane.iris.core.modules.ModuleSettings.NONE; + } + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/spawn/SpawnResourcesTest.java b/core/src/test/java/art/arcane/iris/engine/spawn/SpawnResourcesTest.java index 5b3d39ad9..b97b5f2a2 100644 --- a/core/src/test/java/art/arcane/iris/engine/spawn/SpawnResourcesTest.java +++ b/core/src/test/java/art/arcane/iris/engine/spawn/SpawnResourcesTest.java @@ -19,6 +19,9 @@ package art.arcane.iris.engine.spawn; import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.project.ModuleResourceSchemas; +import art.arcane.iris.core.project.SchemaTestPlatform; +import art.arcane.volmlib.util.json.JSONObject; import art.arcane.iris.builtin.spawn.EntityDefinition; import art.arcane.iris.builtin.spawn.SpawnMarker; import art.arcane.iris.builtin.spawn.Spawner; @@ -35,6 +38,7 @@ import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; /** Spawners, entities and markers are resource kinds of module {@code iris:spawn}, read from the folders packs have always had. */ public class SpawnResourcesTest { @@ -84,6 +88,25 @@ public class SpawnResourcesTest { } } + @Test + public void studioDescribesSpawnersEntitiesAndMarkers() throws Exception { + Path pack = spawnPack("studio"); + IrisData data = IrisData.openValidation(pack.toFile()); + try (SchemaTestPlatform ignored = SchemaTestPlatform.bind(temporaryFolder.getRoot())) { + List entries = ModuleResourceSchemas.entries(data, true); + + for (String schema : List.of("spawners", "entities", "markers")) { + assertTrue(schema, entries.stream().anyMatch(entry -> entry.getString("url").equals("./.iris/schema/" + schema + "-schema.json"))); + assertTrue(schema, Files.exists(pack.resolve(".iris/schema/" + schema + "-schema.json"))); + } + JSONObject entity = new JSONObject(Files.readString(pack.resolve(".iris/schema/entities-schema.json"))); + assertTrue(entity.toString().contains("passengers")); + assertTrue(entity.toString().contains("tables")); + } finally { + data.close(); + } + } + private Path spawnPack(String name) throws Exception { File pack = temporaryFolder.newFolder(name); write(pack.toPath(), "dimensions/main.json", "{\"regions\":[\"region\"]}"); diff --git a/core/src/test/java/art/arcane/iris/engine/spawn/SpawnerGateTest.java b/core/src/test/java/art/arcane/iris/engine/spawn/SpawnerGateTest.java new file mode 100644 index 000000000..4184581c5 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/spawn/SpawnerGateTest.java @@ -0,0 +1,113 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.spawn; + +import art.arcane.iris.builtin.spawn.Spawner; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.TestSettings; +import art.arcane.iris.engine.object.runtime.IrisEngineData; +import art.arcane.iris.engine.object.world.IrisWorld; +import art.arcane.iris.engine.object.world.biome.InferredType; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.spi.PlatformWorld; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** Whether a spawner may fire: the biome kind its group wants, the world's time and weather, and its rates in the engine's data. */ +public class SpawnerGateTest { + private Engine engine; + private PlatformWorld world; + + @Before + public void buildEngine() { + engine = mock(Engine.class); + IrisWorld engineWorld = mock(IrisWorld.class); + world = mock(PlatformWorld.class); + when(engineWorld.platformWorld()).thenReturn(world); + when(engine.getWorld()).thenReturn(engineWorld); + when(engine.getEngineData()).thenReturn(new IrisEngineData()); + } + + @Test + public void theGroupDecidesWhichBiomesSuit() { + Spawner normal = spawner("{\"group\": \"NORMAL\"}"); + Spawner underwater = spawner("{\"group\": \"UNDERWATER\"}"); + Spawner beach = spawner("{\"group\": \"BEACH\"}"); + Spawner cave = spawner("{\"group\": \"CAVE\"}"); + + assertTrue(SpawnerGate.suits(normal, biome(InferredType.LAND))); + assertFalse(SpawnerGate.suits(normal, biome(InferredType.SEA))); + assertTrue(SpawnerGate.suits(underwater, biome(InferredType.SEA))); + assertFalse(SpawnerGate.suits(underwater, biome(InferredType.LAND))); + assertTrue(SpawnerGate.suits(beach, biome(InferredType.SHORE))); + assertFalse(SpawnerGate.suits(beach, biome(InferredType.CAVE))); + assertTrue(SpawnerGate.suits(cave, biome(InferredType.SEA))); + } + + @Test + public void timeAndWeatherMustMatch() { + Spawner daytimeRain = spawner("{\"timeBlock\": {\"startHour\": 8, \"endHour\": 18}, \"weather\": \"DOWNFALL\"}"); + when(world.getTime()).thenReturn(6000L); + when(world.isStorming()).thenReturn(true); + assertTrue(SpawnerGate.suits(daytimeRain, world)); + + when(world.isStorming()).thenReturn(false); + assertFalse(SpawnerGate.suits(daytimeRain, world)); + + when(world.isStorming()).thenReturn(true); + when(world.getTime()).thenReturn(20000L); + assertFalse(SpawnerGate.suits(daytimeRain, world)); + } + + @Test + public void aSpawnerWithoutRatesAlwaysMayFire() { + Spawner free = spawner("{}"); + + SpawnerGate.spawned("free", free, engine, 3, 4); + + assertTrue(SpawnerGate.canSpawn("free", free, engine, 3, 4)); + } + + @Test + public void aRateHoldsTheSpawnerBackForItsIntervalPerWorldAndPerChunk() { + Spawner limited = spawner("{\"maximumRate\": {\"amount\": 1, \"per\": {\"minutes\": 10}}, \"maximumRatePerChunk\": {\"amount\": 1, \"per\": {\"minutes\": 10}}}"); + + assertTrue(SpawnerGate.canSpawn("limited", limited, engine, 3, 4)); + SpawnerGate.spawned("limited", limited, engine, 3, 4); + + assertFalse(SpawnerGate.canSpawn("limited", limited, engine, 3, 4)); + assertFalse(SpawnerGate.canSpawn("limited", limited, engine, 9, 9)); + assertTrue(SpawnerGate.canSpawn("other", limited, engine, 9, 9)); + } + + private static Spawner spawner(String json) { + return TestSettings.of(Spawner.class, json); + } + + private static IrisBiome biome(InferredType type) { + IrisBiome biome = mock(IrisBiome.class); + when(biome.getInferredType()).thenReturn(type); + return biome; + } +} From 00f220264adcc3fa9f9cd4e32c5183561a92b6df Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 13:08:32 +0200 Subject: [PATCH 10/10] Loot and spawn decoding fixture carries the style snippets the dimension's ores now read --- .../pack-before-loot-and-spawn/snippet/style/bedrock.json | 3 +++ .../pack-before-loot-and-spawn/snippet/style/deepslate.json | 3 +++ 2 files changed, 6 insertions(+) create mode 100644 core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/snippet/style/bedrock.json create mode 100644 core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/snippet/style/deepslate.json diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/snippet/style/bedrock.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/snippet/style/bedrock.json new file mode 100644 index 000000000..b883eb62d --- /dev/null +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/snippet/style/bedrock.json @@ -0,0 +1,3 @@ +{ + "style": "STATIC" +} \ No newline at end of file diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/snippet/style/deepslate.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/snippet/style/deepslate.json new file mode 100644 index 000000000..b883eb62d --- /dev/null +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-loot-and-spawn/snippet/style/deepslate.json @@ -0,0 +1,3 @@ +{ + "style": "STATIC" +} \ No newline at end of file