From d705dee379cb76ffa2c232f26e6245156a6ddbb4 Mon Sep 17 00:00:00 2001 From: piexel Date: Tue, 10 Nov 2026 11:46:07 +0100 Subject: [PATCH 1/4] Add a weighted list pick to the API Biome, region and child lists are about to count entries by weight. The pick walks such a list with a noise from 0 to 1 and takes an edge rule, so a module that picks from a pack's lists lands on the entry the host does. v3: 96beb86e0 --- .../main/java/com/volmit/world/Weighted.java | 59 +++++++++++++++++++ .../test/java/com/volmit/WeightedTest.java | 45 ++++++++++++++ 2 files changed, 104 insertions(+) create mode 100644 api/api/src/main/java/com/volmit/world/Weighted.java create mode 100644 api/host/src/test/java/com/volmit/WeightedTest.java diff --git a/api/api/src/main/java/com/volmit/world/Weighted.java b/api/api/src/main/java/com/volmit/world/Weighted.java new file mode 100644 index 000000000..ce0d70234 --- /dev/null +++ b/api/api/src/main/java/com/volmit/world/Weighted.java @@ -0,0 +1,59 @@ +package com.volmit.world; + +import java.util.List; +import java.util.Objects; + +/** A list entry that counts as {@code weight} copies of itself in a row, as biome, region and child lists write it. + * {@link #pick} walks such a list with a noise from 0 to 1, so a module that picks among a pack's weighted lists + * (a region's biomes, a biome's children) lands on the same entry the host does. + */ +public record Weighted(T value, int weight) { + public static final int MIN_WEIGHT = 1; + public static final int MAX_WEIGHT = 1000; + + /** Which entry gets noise lying exactly on the edge between two. Cellular noise sits on such edges over whole cells, + * so this decides real patches of terrain. A region's biome list gives edges to the earlier entry and children to the + * later one. + */ + public enum Edge { + EARLIER, + LATER + } + + public Weighted { + Objects.requireNonNull(value, "value"); + if (weight < MIN_WEIGHT || weight > MAX_WEIGHT) { + throw new IllegalArgumentException("Weight must be from " + MIN_WEIGHT + " to " + MAX_WEIGHT + ": " + weight); + } + } + + /** Picks along the list as if every entry were written out {@code weight} times: the noise from 0 to 1 is split into + * equal slots, one per copy, in list order. Noise below 0 picks the first entry, noise above 1 the last; an empty list + * picks nothing. + */ + public static T pick(List> entries, double noise, Edge edge) { + if (entries.isEmpty()) { + return null; + } + + double slotPosition = noise * totalWeight(entries); + int slotsUpToHere = 0; + for (Weighted entry : entries) { + slotsUpToHere += entry.weight(); + boolean inThisEntry = edge == Edge.EARLIER ? slotPosition <= slotsUpToHere : slotPosition < slotsUpToHere; + if (inThisEntry) { + return entry.value(); + } + } + + return entries.getLast().value(); + } + + public static int totalWeight(List> entries) { + int total = 0; + for (Weighted entry : entries) { + total += entry.weight(); + } + return total; + } +} diff --git a/api/host/src/test/java/com/volmit/WeightedTest.java b/api/host/src/test/java/com/volmit/WeightedTest.java new file mode 100644 index 000000000..a6f26b172 --- /dev/null +++ b/api/host/src/test/java/com/volmit/WeightedTest.java @@ -0,0 +1,45 @@ +package com.volmit; + +import com.volmit.world.Weighted; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class WeightedTest { + @Test + void weightedEntriesCountAsCopiesOfThemselvesInARow() { + assertThrows(IllegalArgumentException.class, () -> new Weighted<>("plains", 0)); + assertThrows(IllegalArgumentException.class, () -> new Weighted<>("plains", Weighted.MAX_WEIGHT + 1)); + assertThrows(NullPointerException.class, () -> new Weighted(null, 1)); + + var entries = List.of(new Weighted<>("barren", 3), new Weighted<>("forest", 1)); + assertEquals("barren", Weighted.pick(entries, 0.74, Weighted.Edge.EARLIER)); + assertEquals("forest", Weighted.pick(entries, 0.76, Weighted.Edge.EARLIER)); + assertEquals("barren", Weighted.pick(entries, -0.5, Weighted.Edge.EARLIER)); + assertEquals("forest", Weighted.pick(entries, 1.5, Weighted.Edge.LATER)); + assertNull(Weighted.pick(List.>of(), 0.5, Weighted.Edge.EARLIER)); + } + + @Test + void anEdgeGoesWhereTheRuleSays() { + var entries = List.of(new Weighted<>("first", 1), new Weighted<>("second", 1)); + assertEquals("first", Weighted.pick(entries, 0.5, Weighted.Edge.EARLIER)); + assertEquals("second", Weighted.pick(entries, 0.5, Weighted.Edge.LATER)); + assertEquals("second", Weighted.pick(entries, Math.nextUp(0.5), Weighted.Edge.EARLIER)); + } + + @Test + void halfSlotWeightsMatchTheOldRoundedChildPick() { + var oldSlots = List.of("barren", "barren", "barren", "forest", "barren", "barren"); + var converted = List.of(new Weighted<>("barren", 5), new Weighted<>("forest", 2), new Weighted<>("barren", 3)); + for (int step = 0; step <= 1000; step++) { + double noise = step / 1000D; + String oldPick = oldSlots.get((int) Math.round(noise * (oldSlots.size() - 1))); + assertEquals(oldPick, Weighted.pick(converted, noise, Weighted.Edge.LATER), "noise " + noise); + } + } +} From 3d55236f97d1fb256e908b38a0070402b5846c13 Mon Sep 17 00:00:00 2001 From: piexel Date: Tue, 10 Nov 2026 11:46:19 +0100 Subject: [PATCH 2/4] Pick regions, biomes and children by weight Rarity gave every list entry a share of 1 / rarity and children rounded slots; a weight on the list entry says what a pack author means. Dimension regions, region biome lists, biome children and carving children are now entries with a weight (1 to 1000), picked along the list in the order written, region and biome lists giving the edge to the earlier entry and children to the later. A biome keeps itself among its children only where it lists itself. PackBiome and PackRegion carry the weighted lists, and the carving module picks with the API's Weighted.pick. Rarity is gone from biomes and regions, and the three fixture packs are rewritten to the entry format. No pin or golden moved: the changed generator seed only touches biomes of rarity other than 1, and no pinned world reads one. The fixture packs now have weights where their regions had rarities: pack-before-the-port forests 15, magnetics 1; pack-before-loot-and-spawn hot 10, terralost 6, mushroom 2, swamp 15, the rest 1. v3: 0fbce6ba2 a598b4323 96beb86e0 --- .../iris/core/commands/CommandStudio.java | 5 +- .../core/IrisWorldGeneratorResolverTest.java | 4 +- .../command/ModdedCommandSuggestions.java | 2 +- .../modded/command/ModdedStudioCommands.java | 6 +- api/CONTRACTS.md | 2 +- .../main/java/com/volmit/world/PackBiome.java | 12 +- .../java/com/volmit/world/PackRegion.java | 10 +- .../test/java/com/volmit/ApiValuesTest.java | 18 +- .../iris/core/modules/IrisPackResources.java | 12 +- .../core/pack/PackDimensionValidator.java | 27 ++- .../iris/core/pack/PackImageMapValidator.java | 4 +- .../iris/core/pack/PackValidationIo.java | 6 + .../arcane/iris/core/service/StudioSVC.java | 8 +- .../iris/core/studio/map/ChildPicks.java | 22 +- .../core/studio/map/MapPickInspection.java | 18 +- .../iris/core/studio/map/MapPickPath.java | 54 ++--- .../art/arcane/iris/engine/IrisComplex.java | 166 +++------------ .../iris/engine/UpperDimensionContext.java | 52 ++--- .../arcane/iris/engine/framework/Engine.java | 2 +- .../iris/engine/framework/HintedLocator.java | 23 +- .../engine/image/IrisImageMapRuntime.java | 7 +- .../iris/engine/object/value/IRare.java | 97 --------- .../engine/object/world/biome/IrisBiome.java | 50 +++-- .../object/world/biome/IrisBiomeEntry.java | 70 ++++++ .../object/world/dimension/IrisDimension.java | 30 ++- .../object/world/region/IrisRegion.java | 66 +++--- .../object/world/region/IrisRegionEntry.java | 70 ++++++ .../arcane/iris/util/project/noise/CNG.java | 74 ------- .../util/project/stream/ProceduralStream.java | 46 +--- core/src/main/resources/messages/en_US.json | 2 +- .../modules/CarveSettingsDecodingTest.java | 7 +- .../iris/core/modules/CarveTestWorld.java | 4 +- .../core/modules/IrisPackResourcesTest.java | 24 ++- .../modules/PackModuleResourceKindTest.java | 4 +- .../DefaultPackBootstrapProvisionerTest.java | 8 +- .../pack/ExportClosureComparisonTest.java | 4 +- .../core/pack/ModulePackValidationTest.java | 4 +- .../core/pack/ModuleResourceClosureTest.java | 4 +- .../pack/PackBiomeLayerValidatorTest.java | 4 +- .../iris/core/pack/PackDownloaderTest.java | 16 +- .../PackGeneratorDuplicateValidatorTest.java | 4 +- .../core/pack/PackImageMapValidatorTest.java | 36 ++-- .../PackStyledRangeDefaultValidatorTest.java | 4 +- .../PackValidatorDimensionHeightTest.java | 20 +- .../pack/PackValidatorHostFilesParseTest.java | 2 +- ...kValidatorImportedStructurePolicyTest.java | 4 +- .../core/pack/PackValidatorReadOnlyTest.java | 4 +- .../pack/PackValidatorStructureGraphTest.java | 16 +- ...kValidatorStructureTerrainBackendTest.java | 8 +- .../pack/PackValidatorSurfaceSupportTest.java | 4 +- .../project/ImageMapStudioExporterTest.java | 4 +- .../StudioSVCWorldPackPublishTest.java | 4 +- .../studio/map/MapPickInspectionTest.java | 2 +- .../iris/core/studio/map/MapPickPathTest.java | 17 +- .../iris/core/studio/map/PickedWorld.java | 44 ++-- .../engine/IrisComplexImplodeParityTest.java | 92 -------- .../engine/framework/HintedLocatorTest.java | 9 +- .../structure/StructureResourcesTest.java | 4 +- .../iris/engine/loot/LootResourcesTest.java | 4 +- .../mantle/components/CaveCarvingTest.java | 2 +- .../modifier/CarvePipelineHarnessTest.java | 2 +- .../CaveApplyingBoundarySupportTest.java | 2 +- .../engine/modifier/CaveApplyingTest.java | 2 +- .../engine/modifier/CaveBiomeBandsTest.java | 2 +- .../carving/CarvingResolverParityTest.java | 200 ++++++++++-------- ...vedFloatingChildCarvingResolutionTest.java | 2 +- .../object/world/RemovedDeadFieldsTest.java | 3 + .../biome/IrisBiomeWeightedChildrenTest.java | 106 ++++++++++ .../IrisDimensionReachableBiomesTest.java | 42 ++-- .../world/region/IrisRegionBiomeTreeTest.java | 5 +- .../iris/engine/spawn/SpawnResourcesTest.java | 4 +- .../biomes/tropical/volcanoes.json | 5 +- .../dimensions/overworld.json | 24 +-- .../regions/hot.json | 67 +++--- .../regions/mushroom.json | 27 ++- .../regions/swamp.json | 39 ++-- .../regions/terralost.json | 27 ++- .../biomes/carving/amethyst.json | 2 +- .../biomes/estranged/bloomspire-orchard.json | 1 - .../biomes/magnetics/plains.json | 1 - .../pack-before-the-port/biomes/mesa/red.json | 1 - .../dimensions/overworld.json | 24 +-- .../pack-before-the-port/regions/forests.json | 45 ++-- .../regions/magnetics.json | 31 ++- .../pack-terrain/biomes/mesa/yellow.json | 5 +- .../biomes/mountain/shore/beach.json | 1 - .../terrain/carving/CarvingResolver.java | 144 ++----------- .../terrain/carving/ResolvedCarvingEntry.java | 3 +- .../iris/modules/carve/CarvingChild.java | 54 +++++ .../iris/modules/carve/CarvingEntry.java | 6 +- 90 files changed, 1022 insertions(+), 1183 deletions(-) delete mode 100644 core/src/main/java/art/arcane/iris/engine/object/value/IRare.java create mode 100644 core/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeEntry.java create mode 100644 core/src/main/java/art/arcane/iris/engine/object/world/region/IrisRegionEntry.java delete mode 100644 core/src/test/java/art/arcane/iris/engine/IrisComplexImplodeParityTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/object/world/biome/IrisBiomeWeightedChildrenTest.java create mode 100644 module/src/main/java/art/arcane/iris/modules/carve/CarvingChild.java 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 9bd8244d2..b0b27d1d5 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 @@ -334,7 +334,7 @@ public class CommandStudio implements DirectorExecutor { boolean progressShown = false; int c = -1; try { - engine.getDimension().getRegions().forEach(key -> data.put(key, new AtomicInteger(0))); + engine.getDimension().getRegionKeys().forEach(key -> data.put(key, new AtomicInteger(0))); multiBurst = new MultiBurst("Region Sampler"); var executor = multiBurst.burst(Math.min(radius * radius, 1 << 20)); sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_GENERATING_DATA)); @@ -356,8 +356,7 @@ public class CommandStudio implements DirectorExecutor { executor.complete(); sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_DONE)); - var loader = engine.getData().getRegionLoader(); - data.forEach((k, v) -> sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_MESSAGE, MessageArgument.untrusted("k", k), MessageArgument.untrusted("value", loader.load(k).getRarity()), MessageArgument.untrusted("value2", Form.f((double) v.get() / totalTasks * 100, 2))))); + data.forEach((k, v) -> sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_MESSAGE, MessageArgument.untrusted("k", k), MessageArgument.untrusted("value", engine.getDimension().getRegionWeight(k)),MessageArgument.untrusted("value2", Form.f((double) v.get() / totalTasks * 100, 2))))); } catch (Throwable e) { Iris.reportError(e); sender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_REGIONS_SCAN_FAILED, diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/IrisWorldGeneratorResolverTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/IrisWorldGeneratorResolverTest.java index 88467a5a8..6691b7cf4 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/IrisWorldGeneratorResolverTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/IrisWorldGeneratorResolverTest.java @@ -526,11 +526,11 @@ public class IrisWorldGeneratorResolverTest { Files.createDirectories(packRoot.resolve("biomes")); Files.writeString( packRoot.resolve("dimensions/main.json"), - "{\"regions\":[\"region\"]}", + "{\"regions\":[{\"region\":\"region\"}]}", StandardCharsets.UTF_8); Files.writeString( packRoot.resolve("regions/region.json"), - "{\"landBiomes\":[\"biome\"]}", + "{\"landBiomes\":[{\"biome\":\"biome\"}]}", StandardCharsets.UTF_8); Files.writeString( packRoot.resolve("biomes/biome.json"), diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandSuggestions.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandSuggestions.java index e1bc143cb..f637b9a78 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandSuggestions.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandSuggestions.java @@ -91,7 +91,7 @@ final class ModdedCommandSuggestions { try { Engine engine = IrisModdedCommands.engineFor(context.getSource().getLevel()); if (engine != null) { - return SharedSuggestionProvider.suggest(engine.getDimension().getRegions(), builder); + return SharedSuggestionProvider.suggest(engine.getDimension().getRegionKeys(), builder); } } catch (Throwable e) { warnTabFailure("region keys", context.getSource(), e); 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 6c88ec510..e2731467d 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 @@ -788,7 +788,7 @@ public final class ModdedStudioCommands { int diameter = radius * 2; int totalTasks = diameter * diameter; KMap counts = new KMap<>(); - engine.getDimension().getRegions().forEach((String key) -> counts.put(key, new AtomicInteger(0))); + engine.getDimension().getRegionKeys().forEach((String key) -> counts.put(key, new AtomicInteger(0))); // finally-scoped: a throw mid-scan previously leaked the sampler's whole // ForkJoinPool (close() is the only thing that shuts it down). MultiBurst burst = new MultiBurst("Region Sampler"); @@ -803,9 +803,7 @@ public final class ModdedStudioCommands { burst.close(); } server.execute(() -> counts.forEach((String key, AtomicInteger count) -> { - IrisRegion region = engine.getData().getRegionLoader().load(key); - String rarity = region == null ? "?" : String.valueOf(region.getRarity()); - IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_RARITY, MessageArgument.untrusted("key", key), MessageArgument.untrusted("rarity", rarity), MessageArgument.untrusted("value", Form.f((double) count.get() / totalTasks * 100, 2)))); + IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_RARITY, MessageArgument.untrusted("key", key), MessageArgument.untrusted("rarity", engine.getDimension().getRegionWeight(key)),MessageArgument.untrusted("value", Form.f((double) count.get() / totalTasks * 100, 2)))); })); } catch (Throwable e) { ModdedIrisLog.error("Iris region sampling failed", e); diff --git a/api/CONTRACTS.md b/api/CONTRACTS.md index 9b36ee862..fb549c6d9 100644 --- a/api/CONTRACTS.md +++ b/api/CONTRACTS.md @@ -36,7 +36,7 @@ types that carry them and lists what the Iris adapter still owes. | Noise from pack-described styles | `NoiseStyle`, `StyledRange`, `PackResources.noise()`, `NoiseFactory`, `NoiseSampler` | | Values in settings | `BlockSpec`, `PaletteSpec`, `NoiseStyle`, `StyledRange`, `Range`, `BlockPosition`, `JigsawOverrides`, `Object` as `ValueKind.AnyKind` | | Decisions over and fit of the platform's own structures | service `VanillaStructures` (`rule`, `starts`, `shift`, `reach`, `beforePieces`, `afterPieces`, `setup`), `VanillaStructureRule`, `VanillaStructureContext`, `VanillaStructureStart`, `VanillaStructureStartContext`, `VanillaStructureSetup`, `PlatformStart`, `StartMemo`, `StartReach`, `StructureFit` (`Start`, `Piece`, `ColumnVisitor`), `DecorationStep`, `TerrainAdaptation`, `PieceKind`, `TemplateCells`, `world.BlockAccess`, host `FeatureCatalog.registrations(service)` | -| Pack-scoped resolution | `ResourceId` (`ofPackKey`, `ofPlatformKey`), `ContentKey`, `PackResources` (`find(kind, id)`, `require`, `ids(kind)`, `idOf`; kinds `BIOMES`, `REGIONS`, `OBJECTS`, `EXPRESSIONS`, `IMAGE_MAPS`), `PackBiome`, `PackRegion`, `PackExpression`, `PackImageMap` | +| Pack-scoped resolution | `ResourceId` (`ofPackKey`, `ofPlatformKey`), `ContentKey`, `PackResources` (`find(kind, id)`, `require`, `ids(kind)`, `idOf`; kinds `BIOMES`, `REGIONS`, `OBJECTS`, `EXPRESSIONS`, `IMAGE_MAPS`), `PackBiome`, `PackRegion` (their children and biome lists are `Weighted` entries; `Weighted.pick` walks them the way the host does), `PackExpression`, `PackImageMap` | | Module-owned pack resources | `ResourceKind`, `FeatureRegistry.registerResourceKind`, `@ResourceRef`, host `ModuleHost.reservingFolders`, `FeatureCatalog.resourceKinds()`, `ResourceKindSchema`, `ValueKind.ResourceReferenceKind` | | Module-owned pack checks | `Validator`, `ValidationContext`, `Problem`, `Severity`, `Subject`, `FeatureRegistry.registerValidator`, host `FeatureCatalog.validators()` | | Per-world module state | `PackWorld` (`state`), `InvocationContext.world()`, host `WorldStates` | diff --git a/api/api/src/main/java/com/volmit/world/PackBiome.java b/api/api/src/main/java/com/volmit/world/PackBiome.java index 4299cf8dd..51603bfd2 100644 --- a/api/api/src/main/java/com/volmit/world/PackBiome.java +++ b/api/api/src/main/java/com/volmit/world/PackBiome.java @@ -7,21 +7,21 @@ import java.util.Objects; /** A biome of the loaded pack, found through {@code PackResources} by the ids a {@link BiomeSample} gives. * platformBiome is the platform biome the host writes for it. vanillaBiome is the biome vanilla's own rules see it as, * such as which structures may start in it: the platform biome unless the pack says otherwise. children are the pack - * biomes that can generate inside it. Rarity is relative to the biome's siblings: higher is rarer. + * biomes that can generate inside it, in the order the child noise walks them; the biome itself is listed among them + * where it stays itself. */ -public record PackBiome(ResourceId id, String name, ResourceId platformBiome, ResourceId vanillaBiome, int rarity, - List children) { +public record PackBiome(ResourceId id, String name, ResourceId platformBiome, ResourceId vanillaBiome, + List> children) { public PackBiome { Objects.requireNonNull(id, "id"); Objects.requireNonNull(name, "name"); Objects.requireNonNull(platformBiome, "platformBiome"); Objects.requireNonNull(vanillaBiome, "vanillaBiome"); - if (rarity < 1) throw new IllegalArgumentException("Biome rarity must be at least 1: " + rarity); children = List.copyOf(children); } /** A biome that vanilla's rules see as its platform biome. */ - public PackBiome(ResourceId id, String name, ResourceId platformBiome, int rarity, List children) { - this(id, name, platformBiome, platformBiome, rarity, children); + public PackBiome(ResourceId id, String name, ResourceId platformBiome, List> children) { + this(id, name, platformBiome, platformBiome, children); } } diff --git a/api/api/src/main/java/com/volmit/world/PackRegion.java b/api/api/src/main/java/com/volmit/world/PackRegion.java index 2473e20a2..3677439be 100644 --- a/api/api/src/main/java/com/volmit/world/PackRegion.java +++ b/api/api/src/main/java/com/volmit/world/PackRegion.java @@ -5,15 +5,15 @@ import java.util.List; import java.util.Objects; /** A region of the loaded pack, found through {@code PackResources} by the id a {@link BiomeSample} gives. - * The biome lists name the pack biomes the region generates on land, at sea, on shores and in caves. - * Rarity is relative to the other regions: higher is rarer. + * The biome lists name the pack biomes the region generates on land, at sea, on shores and in caves, in the order + * the biome noise walks them. */ -public record PackRegion(ResourceId id, String name, int rarity, List landBiomes, - List seaBiomes, List shoreBiomes, List caveBiomes) { +public record PackRegion(ResourceId id, String name, List> landBiomes, + List> seaBiomes, List> shoreBiomes, + List> caveBiomes) { public PackRegion { Objects.requireNonNull(id, "id"); Objects.requireNonNull(name, "name"); - if (rarity < 1) throw new IllegalArgumentException("Region rarity must be at least 1: " + rarity); landBiomes = List.copyOf(landBiomes); seaBiomes = List.copyOf(seaBiomes); shoreBiomes = List.copyOf(shoreBiomes); diff --git a/api/host/src/test/java/com/volmit/ApiValuesTest.java b/api/host/src/test/java/com/volmit/ApiValuesTest.java index dd56100b0..e9c471676 100644 --- a/api/host/src/test/java/com/volmit/ApiValuesTest.java +++ b/api/host/src/test/java/com/volmit/ApiValuesTest.java @@ -160,24 +160,20 @@ class ApiValuesTest { @Test void packBiomesAndRegionsAreImmutableValues() { - var children = new ArrayList<>(List.of(ResourceId.parse("pack:dunes"))); - var desert = new PackBiome(ResourceId.parse("pack:desert"), "Desert", ResourceId.parse("minecraft:desert"), 2, children); + var children = new ArrayList<>(List.of(new Weighted<>(ResourceId.parse("pack:dunes"), 2))); + var desert = new PackBiome(ResourceId.parse("pack:desert"), "Desert", ResourceId.parse("minecraft:desert"), children); children.clear(); - assertEquals(List.of(ResourceId.parse("pack:dunes")), desert.children()); + assertEquals(List.of(new Weighted<>(ResourceId.parse("pack:dunes"), 2)), desert.children()); assertThrows(UnsupportedOperationException.class, () -> desert.children().clear()); - assertThrows(IllegalArgumentException.class, - () -> new PackBiome(desert.id(), "Desert", desert.platformBiome(), 0, List.of())); assertEquals(desert.platformBiome(), desert.vanillaBiome(), "vanilla sees the platform biome unless a pack says otherwise"); var mesa = new PackBiome(ResourceId.parse("pack:mesa"), "Mesa", ResourceId.parse("minecraft:desert"), - ResourceId.parse("minecraft:badlands"), 1, List.of()); + ResourceId.parse("minecraft:badlands"), List.of()); assertEquals(ResourceId.parse("minecraft:badlands"), mesa.vanillaBiome()); - var land = List.of(desert.id()); - var arid = new PackRegion(ResourceId.parse("pack:arid"), "Arid", 1, land, List.of(), List.of(), List.of()); + var land = List.of(new Weighted<>(desert.id(), 1)); + var arid = new PackRegion(ResourceId.parse("pack:arid"), "Arid", land, List.of(), List.of(), List.of()); assertEquals(land, arid.landBiomes()); - assertThrows(UnsupportedOperationException.class, () -> arid.caveBiomes().add(desert.id())); - assertThrows(IllegalArgumentException.class, - () -> new PackRegion(arid.id(), "Arid", 0, land, List.of(), List.of(), List.of())); + assertThrows(UnsupportedOperationException.class, () -> arid.caveBiomes().add(new Weighted<>(desert.id(), 1))); } static final class Keep {} diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java b/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java index 74d40820f..e58251356 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java @@ -26,6 +26,7 @@ import art.arcane.iris.engine.object.image.IrisImageMap; import art.arcane.iris.engine.object.noise.expression.IrisExpression; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.biome.IrisBiomeEntry; import art.arcane.iris.engine.object.world.region.IrisRegion; import com.volmit.block.BlockRegistry; import com.volmit.host.ResourceKindRegistration; @@ -39,6 +40,7 @@ import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceKind; import com.volmit.world.PackBiome; import com.volmit.world.PackRegion; +import com.volmit.world.Weighted; import java.util.Arrays; import java.util.Collection; @@ -247,16 +249,16 @@ public final class IrisPackResources implements PackResources { private PackBiome biomeOf(ResourceId id, IrisBiome biome) { return new PackBiome(id, biome.getName(), ResourceId.parse(biome.getDerivativeKey()), ResourceId.parse(biome.getVanillaDerivativeKey()), - biome.getRarity(), idsOf(biome.getChildren())); + weightedIdsOf(biome.getChildren())); } private PackRegion regionOf(ResourceId id, IrisRegion region) { - return new PackRegion(id, region.getName(), region.getRarity(), idsOf(region.getLandBiomes()), idsOf(region.getSeaBiomes()), - idsOf(region.getShoreBiomes()), idsOf(region.getCaveBiomes())); + return new PackRegion(id, region.getName(), weightedIdsOf(region.getLandBiomes()), weightedIdsOf(region.getSeaBiomes()), + weightedIdsOf(region.getShoreBiomes()), weightedIdsOf(region.getCaveBiomes())); } - private List idsOf(Collection keys) { - return keys.stream().map(ids::of).toList(); + private List> weightedIdsOf(Collection entries) { + return entries.stream().map(entry -> new Weighted<>(ids.of(entry.getBiome()), entry.getWeight())).toList(); } /** One kind of pack resource: the keys the pack has, how a key's resource is read, an index from ids to keys and what was read so far. */ diff --git a/core/src/main/java/art/arcane/iris/core/pack/PackDimensionValidator.java b/core/src/main/java/art/arcane/iris/core/pack/PackDimensionValidator.java index 58d98e712..27cad20b3 100644 --- a/core/src/main/java/art/arcane/iris/core/pack/PackDimensionValidator.java +++ b/core/src/main/java/art/arcane/iris/core/pack/PackDimensionValidator.java @@ -24,6 +24,7 @@ import art.arcane.iris.engine.object.world.dimension.IrisDimensionType; import art.arcane.iris.engine.object.world.IrisWorldBoundary; import art.arcane.volmlib.util.json.JSONArray; import art.arcane.volmlib.util.json.JSONObject; +import com.volmit.world.Weighted; import java.io.File; import java.nio.charset.StandardCharsets; @@ -59,7 +60,8 @@ final class PackDimensionValidator { int resolvedRegions = 0; for (int i = 0; i < regionsArray.length(); i++) { - String regionKey = regionsArray.optString(i, null); + String regionKey = PackValidationIo.entryKey(regionsArray, i, "region"); + validateWeight(regionsArray.optJSONObject(i), "Dimension '" + dimensionKey + "' regions[" + i + "]", blockingErrors); if (regionKey == null || regionKey.isBlank()) { warnings.add("Dimension '" + dimensionKey + "' has a blank region entry at index " + i + "."); continue; @@ -78,10 +80,10 @@ final class PackDimensionValidator { continue; } - int anyBiome = countBiomeRefs(regionJson, "landBiomes", biomesFolder, regionKey, warnings) - + countBiomeRefs(regionJson, "seaBiomes", biomesFolder, regionKey, warnings) - + countBiomeRefs(regionJson, "shoreBiomes", biomesFolder, regionKey, warnings) - + countBiomeRefs(regionJson, "caveBiomes", biomesFolder, regionKey, warnings); + int anyBiome = countBiomeRefs(regionJson, "landBiomes", biomesFolder, regionKey, blockingErrors, warnings) + + countBiomeRefs(regionJson, "seaBiomes", biomesFolder, regionKey, blockingErrors, warnings) + + countBiomeRefs(regionJson, "shoreBiomes", biomesFolder, regionKey, blockingErrors, warnings) + + countBiomeRefs(regionJson, "caveBiomes", biomesFolder, regionKey, blockingErrors, warnings); if (anyBiome == 0) { blockingErrors.add("Region '" + regionKey + "' has no resolvable biomes."); } @@ -94,14 +96,25 @@ final class PackDimensionValidator { } } - private static int countBiomeRefs(JSONObject regionJson, String field, File biomesFolder, String regionKey, List warnings) { + private static void validateWeight(JSONObject entry, String path, List blockingErrors) { + if (entry == null) { + return; + } + Integer weight = PackIntegerChecks.integerField(entry, "weight", Weighted.MIN_WEIGHT, path, blockingErrors); + PackIntegerChecks.requireMinimum(path + ".weight", weight, Weighted.MIN_WEIGHT, blockingErrors); + PackIntegerChecks.requireMaximum(path + ".weight", weight, Weighted.MAX_WEIGHT, blockingErrors); + } + + private static int countBiomeRefs(JSONObject regionJson, String field, File biomesFolder, String regionKey, + List blockingErrors, List warnings) { JSONArray arr = regionJson.optJSONArray(field); if (arr == null) { return 0; } int resolved = 0; for (int i = 0; i < arr.length(); i++) { - String biomeKey = arr.optString(i, null); + String biomeKey = PackValidationIo.entryKey(arr, i, "biome"); + validateWeight(arr.optJSONObject(i), "Region '" + regionKey + "' " + field + "[" + i + "]", blockingErrors); if (biomeKey == null || biomeKey.isBlank()) { continue; } diff --git a/core/src/main/java/art/arcane/iris/core/pack/PackImageMapValidator.java b/core/src/main/java/art/arcane/iris/core/pack/PackImageMapValidator.java index 4332a1c8d..f133e2e8c 100644 --- a/core/src/main/java/art/arcane/iris/core/pack/PackImageMapValidator.java +++ b/core/src/main/java/art/arcane/iris/core/pack/PackImageMapValidator.java @@ -519,7 +519,7 @@ final class PackImageMapValidator { return; } for (int index = 0; index < values.length(); index++) { - if (biomeKey.equals(values.optString(index, null))) { + if (biomeKey.equals(PackValidationIo.entryKey(values, index, "biome"))) { roles.add(role); return; } @@ -532,7 +532,7 @@ final class PackImageMapValidator { ) { Set regionKeys = new TreeSet<>(); if (dimension.getRegions() != null) { - for (String regionKey : dimension.getRegions()) { + for (String regionKey : dimension.getRegionKeys()) { String normalized = normalized(regionKey); if (normalized != null) { regionKeys.add(normalized); diff --git a/core/src/main/java/art/arcane/iris/core/pack/PackValidationIo.java b/core/src/main/java/art/arcane/iris/core/pack/PackValidationIo.java index 215b878fe..3008da4a0 100644 --- a/core/src/main/java/art/arcane/iris/core/pack/PackValidationIo.java +++ b/core/src/main/java/art/arcane/iris/core/pack/PackValidationIo.java @@ -57,6 +57,12 @@ public final class PackValidationIo { } } + /** The key the entry at {@code index} of a weighted list names in {@code field}; null when the entry is not an object with one. */ + static String entryKey(JSONArray entries, int index, String field) { + JSONObject entry = entries.optJSONObject(index); + return entry == null ? null : entry.optString(field, null); + } + static boolean isScannableJsonPath(Path path) { String name = path.getFileName().toString(); if (!name.endsWith(".json")) { diff --git a/core/src/main/java/art/arcane/iris/core/service/StudioSVC.java b/core/src/main/java/art/arcane/iris/core/service/StudioSVC.java index 85e00578f..a34d916e6 100644 --- a/core/src/main/java/art/arcane/iris/core/service/StudioSVC.java +++ b/core/src/main/java/art/arcane/iris/core/service/StudioSVC.java @@ -1230,7 +1230,7 @@ public class StudioSVC implements IrisService { { "name": "%s", "version": 1, - "regions": ["starter"], + "regions": [{"region": "starter", "weight": 1}], "logicalHeight": 384, "dimensionHeight": {"min": -64, "max": 320} } @@ -1238,9 +1238,9 @@ public class StudioSVC implements IrisService { Files.writeString(stage.resolve("regions/starter.json"), """ { "name": "Starter", - "landBiomes": ["starter"], - "seaBiomes": ["starter"], - "shoreBiomes": ["starter"] + "landBiomes": [{"biome": "starter", "weight": 1}], + "seaBiomes": [{"biome": "starter", "weight": 1}], + "shoreBiomes": [{"biome": "starter", "weight": 1}] } """, StandardCharsets.UTF_8); Files.writeString(stage.resolve("biomes/starter.json"), """ diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/ChildPicks.java b/core/src/main/java/art/arcane/iris/core/studio/map/ChildPicks.java index ee02bf4ec..d0296c973 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/ChildPicks.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/ChildPicks.java @@ -20,6 +20,7 @@ package art.arcane.iris.core.studio.map; import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.object.world.biome.IrisBiome; +import com.volmit.world.Weighted; import java.util.ArrayList; import java.util.List; @@ -35,13 +36,13 @@ final class ChildPicks { List picks = new ArrayList<>(); IrisBiome parent = biome; for (int level = 0; level < IrisComplex.CHILD_PICK_LEVELS && !parent.getChildren().isEmpty(); level++) { - List slots = complex.childSlots(parent); - if (slots.isEmpty()) { + List> options = complex.childOptions(parent); + if (options.isEmpty()) { break; } double noise = complex.childNoise(parent).noiseFast2D(x, z); - IrisBiome picked = slots.get(slotIndex(noise, slots.size())).withInferredType(parent.getInferredType()); - ChildPick pick = new ChildPick(parent, slots, noise, picked); + IrisBiome picked = Weighted.pick(options, noise, IrisComplex.CHILD_EDGE).withInferredType(parent.getInferredType()); + ChildPick pick = new ChildPick(parent, options, noise, picked); picks.add(pick); if (pick.kept()) { break; @@ -57,17 +58,8 @@ final class ChildPicks { return picks.isEmpty() ? listNoise : picks.getLast().noise(); } - /** The slot the child noise picks, rounded the way {@code CNG.fit2D} rounds. */ - static int slotIndex(double noise, int slotCount) { - if (slotCount == 1) { - return 0; - } - long rounded = Math.round(noise * (slotCount - 1)); - return (int) Math.clamp(rounded, 0, slotCount - 1); - } - - /** One level of children: the parent's slots, the noise that read them, and the biome it picked. */ - record ChildPick(IrisBiome parent, List slots, double noise, IrisBiome picked) { + /** One level of children: the parent's weighted list, the noise that read it, and the biome it picked. */ + record ChildPick(IrisBiome parent, List> options, double noise, IrisBiome picked) { boolean kept() { return Objects.equals(picked.getLoadKey(), parent.getLoadKey()); } diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/MapPickInspection.java b/core/src/main/java/art/arcane/iris/core/studio/map/MapPickInspection.java index 0cb9c592a..5938bbcee 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/MapPickInspection.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/MapPickInspection.java @@ -23,6 +23,7 @@ import art.arcane.iris.engine.framework.Engine; 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.region.IrisRegion; +import com.volmit.world.Weighted; import java.util.ArrayList; import java.util.Comparator; @@ -62,7 +63,7 @@ public final class MapPickInspection { if (complex.getFocusRegion() != null) { return new Inspection("One region is focused", List.of()); } - SpreadCounter regions = new SpreadCounter("Region noise", MapPickPath.regionBands(engine)); + SpreadCounter regions = new SpreadCounter("Region noise", MapPickPath.regionBands(engine), Weighted.Edge.EARLIER); area.forEachSpot((x, z) -> { if (complex.getImageMapRuntime().sampleRegion(x, z) == null) { regions.add(complex.getRegionStyleStream().get(x, z)); @@ -172,7 +173,7 @@ public final class MapPickInspection { private SpreadCounter listCounter(InferredType list) { String name = MapPickPath.listName(list); String title = Character.toUpperCase(name.charAt(0)) + name.substring(1) + " biome noise"; - return new SpreadCounter(title, MapPickPath.biomeBands(engine, view, region, list)); + return new SpreadCounter(title, MapPickPath.biomeBands(engine, view, region, list), Weighted.Edge.EARLIER); } } @@ -202,7 +203,8 @@ public final class MapPickInspection { private SpreadCounter counterOf(ChildPicks.ChildPick pick) { return new SpreadCounter(pick.parent().getName() + " child noise", - MapPickPath.slotBands(pick.slots(), slot -> MapPickPath.biomeLabel(engine, view, slot))); + MapPickPath.weightBands(pick.options(), option -> MapPickPath.biomeLabel(engine, view, option)), + IrisComplex.CHILD_EDGE); } } @@ -210,13 +212,15 @@ public final class MapPickInspection { private static final class SpreadCounter { private final String title; private final List bands; + private final Weighted.Edge edge; private final long[] histogram = new long[HISTOGRAM_BINS]; private final long[] samplesByBand; private long samples; - private SpreadCounter(String title, List bands) { + private SpreadCounter(String title, List bands, Weighted.Edge edge) { this.title = title; this.bands = bands; + this.edge = edge; this.samplesByBand = new long[bands.size()]; } @@ -248,10 +252,12 @@ public final class MapPickInspection { return samples == 0 ? 0D : count / (double) samples; } - // The generator gives values below 0 the first option and values above 1 the last, as these bands do. + // The generator gives values below 0 the first option and values above 1 the last, as these bands do; a value + // on the edge between two bands goes where the list's edge rule sends it. private int bandIndexOf(double noise) { for (int index = 0; index < bands.size(); index++) { - if (noise <= bands.get(index).to()) { + double to = bands.get(index).to(); + if (edge == Weighted.Edge.EARLIER ? noise <= to : noise < to) { return index; } } diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/MapPickPath.java b/core/src/main/java/art/arcane/iris/core/studio/map/MapPickPath.java index bb21b6cfa..729136c1e 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/MapPickPath.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/MapPickPath.java @@ -21,10 +21,11 @@ package art.arcane.iris.core.studio.map; import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.render.RenderType; -import art.arcane.iris.engine.object.value.IRare; 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.region.IrisRegion; +import art.arcane.iris.engine.object.world.region.IrisRegionEntry; +import com.volmit.world.Weighted; import java.util.ArrayList; import java.util.List; @@ -93,13 +94,13 @@ public final class MapPickPath { /** Each of the dimension's regions' share of the region noise. */ static List regionBands(Engine engine) { - List regions = engine.getData().getRegionLoader().loadAll(engine.getDimension().getRegions()); - return rarityBands(regions, region -> MapLabel.of(engine, region)); + List> regions = IrisRegionEntry.load(engine.getDimension().getRegions(), engine.getData().getRegionLoader()); + return weightBands(regions, region -> MapLabel.of(engine, region)); } /** Each biome of the region's list of this type's share of the list's noise; empty when the list is. */ static List biomeBands(Engine engine, MapView view, IrisRegion region, InferredType type) { - return rarityBands(engine.getComplex().pickableBiomes(region, type), biome -> biomeLabel(engine, view, biome)); + return weightBands(engine.getComplex().pickableBiomes(region, type), biome -> biomeLabel(engine, view, biome)); } // The base biome: the noise picks from the land or sea list the continent noise chose, then children replace it. @@ -126,14 +127,14 @@ public final class MapPickPath { private static IrisBiome addListStep(List path, Engine engine, MapView view, IrisRegion region, InferredType type, double x, double z) { IrisComplex complex = engine.getComplex(); - List options = complex.pickableBiomes(region, type); + List> options = complex.pickableBiomes(region, type); if (options.isEmpty()) { return null; } double noise = complex.biomePickNoise(region, type).get(x, z); - IrisBiome picked = IRare.pick(options, noise); + IrisBiome picked = Weighted.pick(options, noise, Weighted.Edge.EARLIER); path.add(new PickStep(Kind.BIOME, biomeLabel(engine, view, picked), listName(type), null, - noise, rarityBands(options, option -> biomeLabel(engine, view, option)))); + noise, weightBands(options, option -> biomeLabel(engine, view, option)))); return picked; } @@ -141,38 +142,21 @@ public final class MapPickPath { for (ChildPicks.ChildPick pick : ChildPicks.from(engine.getComplex(), biome, x, z)) { path.add(new PickStep(Kind.CHILD, biomeLabel(engine, view, pick.picked()), null, pick.kept() ? null : pick.parent().getName(), pick.noise(), - slotBands(pick.slots(), option -> biomeLabel(engine, view, option)))); + weightBands(pick.options(), option -> biomeLabel(engine, view, option)))); } } - /** Each option's share of the noise, 1 / rarity wide, in the order {@link IRare#pick} walks them. */ - static List rarityBands(List options, Function label) { - double total = options.stream().mapToDouble(option -> 1D / IRare.get(option)).sum(); + /** Each entry's share of the noise, as wide as its weight, in the order {@link Weighted#pick} walks them. */ + static List weightBands(List> entries, Function label) { + int totalWeight = Weighted.totalWeight(entries); List bands = new ArrayList<>(); - double from = 0D; - for (int index = 0; index < options.size(); index++) { - T option = options.get(index); - double to = index == options.size() - 1 ? 1D : from + 1D / IRare.get(option) / total; - bands.add(new PickBand(label.apply(option), from, to)); - from = to; - } - return bands; - } - - /** Each slot's share of the child noise, neighbouring slots of one biome joined into one band. */ - static List slotBands(List slots, Function label) { - List bands = new ArrayList<>(); - int last = slots.size() - 1; - for (int index = 0; index <= last; index++) { - double from = index == 0 ? 0D : (index - 0.5D) / last; - double to = index == last ? 1D : (index + 0.5D) / last; - MapLabel option = label.apply(slots.get(index)); - PickBand previous = bands.isEmpty() ? null : bands.getLast(); - if (previous != null && previous.option().key().equals(option.key())) { - bands.set(bands.size() - 1, new PickBand(option, previous.from(), to)); - } else { - bands.add(new PickBand(option, from, to)); - } + int weightBefore = 0; + for (int index = 0; index < entries.size(); index++) { + Weighted entry = entries.get(index); + int weightUpToHere = weightBefore + entry.weight(); + double to = index == entries.size() - 1 ? 1D : (double) weightUpToHere / totalWeight; + bands.add(new PickBand(label.apply(entry.value()), (double) weightBefore / totalWeight, to)); + weightBefore = weightUpToHere; } return bands; } 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 6962355af..698d617b3 100644 --- a/core/src/main/java/art/arcane/iris/engine/IrisComplex.java +++ b/core/src/main/java/art/arcane/iris/engine/IrisComplex.java @@ -25,11 +25,13 @@ import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.image.IrisImageMapRuntime; 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.biome.IrisBiomeEntry; import art.arcane.iris.engine.object.world.biome.IrisBiomeGeneratorLink; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.terrain.IrisGenerator; import art.arcane.iris.engine.object.noise.IrisInterpolator; import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.engine.object.world.region.IrisRegionEntry; import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.PlatformBiome; @@ -42,6 +44,7 @@ import art.arcane.iris.util.project.interpolation.NoiseBoundsProvider; import art.arcane.iris.util.project.noise.CNG; import art.arcane.iris.util.project.stream.ProceduralStream; import art.arcane.iris.util.project.stream.interpolation.Interpolated; +import com.volmit.world.Weighted; import lombok.AccessLevel; import lombok.Data; import lombok.EqualsAndHashCode; @@ -84,6 +87,8 @@ public class IrisComplex implements DataProvider { /** How many levels of children a biome can be replaced through, parent first. */ public static final int CHILD_PICK_LEVELS = DEEPEST_CHILD_LEVEL + 1; private static final int CHILD_NOISE_SIGNATURE = 123; + /** Noise lying exactly between two children goes to the later one; region and biome lists give it to the earlier. */ + public static final Weighted.Edge CHILD_EDGE = Weighted.Edge.LATER; private static final InferredType[] INFERRED_BIOME_PREPARATION_ORDER = { InferredType.LAND, InferredType.CAVE, @@ -134,8 +139,6 @@ public class IrisComplex implements DataProvider { // Copy-on-write: reads happen per column on every burst thread; the synchronizedMap // monitor was taken on every HIT. Writes are once per biome and bounded, so a fresh map // per insert is cheap. Identity keying is load-bearing (IrisBiome is mutable/value-hashed). - private volatile IdentityHashMap childSelectionPlans = new IdentityHashMap<>(); - private final Object childSelectionPlanLock = new Object(); public IrisComplex(Engine engine) { this(engine, false); @@ -167,7 +170,7 @@ public class IrisComplex implements DataProvider { prepareInferredBiomes(focusRegion, regionsToPrepare); focusRegion.getAllBiomes(this).forEach(this::registerGenerators); } else { - engine.getDimension().getRegions().forEach(regionKey -> { + engine.getDimension().getRegionKeys().forEach(regionKey -> { IrisRegion region = data.getRegionLoader().load(regionKey); if (region == null) { return; @@ -220,7 +223,7 @@ public class IrisComplex implements DataProvider { ProceduralStream.of((x, z) -> focusRegion, Interpolated.of(a -> 0D, a -> focusRegion)) : regionStyleStream - .selectRarity(data.getRegionLoader().loadAll(engine.getDimension().getRegions())) + .selectWeighted(IrisRegionEntry.load(engine.getDimension().getRegions(), data.getRegionLoader())) .cache2D("regionStream", engine, cacheSize); regionStream = focusRegion != null ? proceduralRegionStream : proceduralRegionStream .convertAware2D((region, x, z) -> { @@ -375,9 +378,9 @@ public class IrisComplex implements DataProvider { String key = UUID.randomUUID().toString(); IrisRegion region = new IrisRegion(); - region.getLandBiomes().add(focus.getLoadKey()); - region.getSeaBiomes().add(focus.getLoadKey()); - region.getShoreBiomes().add(focus.getLoadKey()); + region.getLandBiomes().add(new IrisBiomeEntry(focus.getLoadKey(), 1)); + region.getSeaBiomes().add(new IrisBiomeEntry(focus.getLoadKey(), 1)); + region.getShoreBiomes().add(new IrisBiomeEntry(focus.getLoadKey(), 1)); region.setLoadKey(key); region.setLoader(data); region.setLoadFile(new File(data.getDataFolder(), data.getRegionLoader().getFolderName() + "/" + key + ".json")); @@ -547,10 +550,10 @@ public class IrisComplex implements DataProvider { } private void prepareInferredBiomes(IrisRegion region, KList preparedRegions) { - loadInferredBiomes(region.getLandBiomes(), InferredType.LAND); - loadInferredBiomes(region.getCaveBiomes(), InferredType.CAVE); - loadInferredBiomes(region.getSeaBiomes(), InferredType.SEA); - loadInferredBiomes(region.getShoreBiomes(), InferredType.SHORE); + pickableBiomes(region, InferredType.LAND); + pickableBiomes(region, InferredType.CAVE); + pickableBiomes(region, InferredType.SEA); + pickableBiomes(region, InferredType.SHORE); preparedRegions.add(region); } @@ -589,7 +592,7 @@ public class IrisComplex implements DataProvider { InferredType inferredType, IrisBiome emptyBiome ) { - ProceduralStream picked = pickNoise.selectRarity(pickableBiomes(region, inferredType)); + ProceduralStream picked = pickNoise.selectWeighted(pickableBiomes(region, inferredType)); return inferredType == InferredType.CAVE ? picked.onNull(emptyBiome) : picked; } @@ -633,44 +636,40 @@ public class IrisComplex implements DataProvider { /** * The noise that picks one of the region's biomes of this type, from 0 to 1; {@link #pickableBiomes} split it by - * rarity. The biome streams pick from this very stream. + * weight. The biome streams pick from this very stream. */ public ProceduralStream biomePickNoise(IrisRegion region, InferredType inferredType) { return preparedInferredBiomeStream(inferredPickNoiseStreams, region, inferredType); } - /** The region's biomes of this type, in the order their rarities split {@link #biomePickNoise}. */ - public KList pickableBiomes(IrisRegion region, InferredType inferredType) { - KList keys = switch (inferredType) { + /** The region's biomes of this type with their weights, in the order they split {@link #biomePickNoise}. */ + public KList> pickableBiomes(IrisRegion region, InferredType inferredType) { + List entries = switch (inferredType) { case CAVE -> region.getCaveBiomes(); case LAND -> region.getLandBiomes(); case SEA -> region.getSeaBiomes(); case SHORE -> region.getShoreBiomes(); }; - return loadInferredBiomes(keys, inferredType); + KList> inferred = new KList<>(); + for (Weighted entry : IrisBiomeEntry.load(entries, data.getBiomeLoader())) { + inferred.add(new Weighted<>(entry.value().withInferredType(inferredType), entry.weight())); + } + return inferred; } /** - * The slots a biome's child noise picks from, in noise order: its children and itself, each as often as its rarity - * allows. Slot {@code i} of {@code n} is picked where {@link #childNoise} rounds to {@code i / (n - 1)}. + * What a biome's child noise picks from, with weights, in noise order: its children, and itself where it is listed + * among them. */ - public List childSlots(IrisBiome parent) { - return List.of(resolveChildSelectionPlan(parent).mappedBiomes); + public KList> childOptions(IrisBiome parent) { + return parent.getChildOptions(this); } - /** The noise that picks among {@link #childSlots}, read with {@link CNG#noiseFast2D}. */ + /** The noise that picks among {@link #childOptions}, read with {@link CNG#noiseFast2D}. */ public CNG childNoise(IrisBiome parent) { return parent.getChildrenGenerator(rng, CHILD_NOISE_SIGNATURE, parent.getChildShrinkFactor()); } - private KList loadInferredBiomes(KList keys, InferredType type) { - KList inferred = new KList<>(); - for (IrisBiome biome : data.getBiomeLoader().loadAll(keys)) { - inferred.add(biome.withInferredType(type)); - } - return inferred; - } - private void registerGenerators(IrisBiome biome) { generatorBiomes.add(biome); biome.getGenerators().forEach(c -> registerGenerator(c.getCachedGenerator(this))); @@ -796,39 +795,12 @@ public class IrisComplex implements DataProvider { return b; } - CNG childCell = childNoise(b); - ChildSelectionPlan childSelectionPlan = resolveChildSelectionPlan(b); - IrisBiome biome = childSelectionPlan.select(childCell, x, z).withInferredType(b.getInferredType()); - return implode(biome, x, z, max - 1); - } - - private ChildSelectionPlan resolveChildSelectionPlan(IrisBiome biome) { - ChildSelectionPlan cachedPlan = childSelectionPlans.get(biome); - if (cachedPlan != null) { - return cachedPlan; + IrisBiome picked = Weighted.pick(childOptions(b), childNoise(b).noiseFast2D(x, z), CHILD_EDGE); + if (picked == null) { + return b; } - synchronized (childSelectionPlanLock) { - ChildSelectionPlan synchronizedPlan = childSelectionPlans.get(biome); - if (synchronizedPlan != null) { - return synchronizedPlan; - } - - KList children = biome.getRealChildren(this); - KList options = new KList<>(); - for (IrisBiome child : children) { - if (child != null) { - options.add(child); - } - } - options.add(biome); - - ChildSelectionPlan createdPlan = ChildSelectionPlan.create(options); - IdentityHashMap next = new IdentityHashMap<>(childSelectionPlans); - next.put(biome, createdPlan); - childSelectionPlans = next; - return createdPlan; - } + return implode(picked.withInferredType(b.getInferredType()), x, z, max - 1); } private static class GeneratorBounds { @@ -1051,78 +1023,6 @@ public class IrisComplex implements DataProvider { } } - static final class ChildSelectionPlan { - private final IrisBiome[] mappedBiomes; - private final int maxIndex; - - private ChildSelectionPlan(IrisBiome[] mappedBiomes) { - this.mappedBiomes = mappedBiomes; - this.maxIndex = mappedBiomes.length - 1; - } - - static ChildSelectionPlan create(KList options) { - if (options.isEmpty()) { - return new ChildSelectionPlan(new IrisBiome[0]); - } - - int maxRarity = 1; - for (IrisBiome biome : options) { - if (biome != null && biome.getRarity() > maxRarity) { - maxRarity = biome.getRarity(); - } - } - - int rarityMax = maxRarity + 1; - boolean flip = false; - KList mapped = new KList<>(); - for (IrisBiome biome : options) { - if (biome == null) { - continue; - } - - int rarity = Math.max(1, biome.getRarity()); - int count = rarityMax - rarity; - for (int index = 0; index < count; index++) { - flip = !flip; - if (flip) { - mapped.add(biome); - } else { - mapped.add(0, biome); - } - } - } - - if (mapped.isEmpty()) { - IrisBiome[] fallback = new IrisBiome[]{options.get(0)}; - return new ChildSelectionPlan(fallback); - } - - IrisBiome[] mappedBiomes = mapped.toArray(new IrisBiome[0]); - return new ChildSelectionPlan(mappedBiomes); - } - - IrisBiome select(CNG childCell, double x, double z) { - if (mappedBiomes.length == 0) { - return null; - } - - if (mappedBiomes.length == 1) { - return mappedBiomes[0]; - } - - int selectedIndex = childCell.fit2D(0, maxIndex, x, z); - if (selectedIndex < 0) { - return mappedBiomes[0]; - } - - if (selectedIndex > maxIndex) { - return mappedBiomes[maxIndex]; - } - - return mappedBiomes[selectedIndex]; - } - } - record GeneratorGroup(IrisInterpolator interpolator, IrisGenerator[] generators) { } 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 5b8970c42..a337a9e6b 100644 --- a/core/src/main/java/art/arcane/iris/engine/UpperDimensionContext.java +++ b/core/src/main/java/art/arcane/iris/engine/UpperDimensionContext.java @@ -6,10 +6,12 @@ import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.image.IrisImageMapRuntime; 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.biome.IrisBiomeEntry; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.terrain.IrisGenerator; import art.arcane.iris.engine.object.noise.IrisInterpolator; import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.engine.object.world.region.IrisRegionEntry; import art.arcane.iris.engine.object.world.biome.IrisBiomeGeneratorLink; import art.arcane.iris.spi.IrisLogging; import art.arcane.volmlib.util.collection.KList; @@ -19,6 +21,7 @@ import art.arcane.iris.util.project.interpolation.NoiseBounds; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.project.stream.ProceduralStream; import art.arcane.iris.util.project.stream.interpolation.Interpolated; +import com.volmit.world.Weighted; import java.util.Collections; import java.util.HashMap; @@ -91,9 +94,7 @@ public class UpperDimensionContext implements DataProvider { Map> generators = new HashMap<>(); Set allBiomes = Collections.newSetFromMap(new IdentityHashMap<>()); - Map childSelectionPlans = - Collections.synchronizedMap(new IdentityHashMap<>()); - upperDim.getRegions().forEach(regionKey -> { + upperDim.getRegionKeys().forEach(regionKey -> { IrisRegion region = upperData.getRegionLoader().load(regionKey); if (region != null) { region.getAllBiomes(dataProvider).forEach(biome -> registerBiomeGenerators( @@ -132,7 +133,7 @@ public class UpperDimensionContext implements DataProvider { .create(rng.nextParallelRNG(883), upperData).stream() .zoom(upperDim.getRegionZoom()); ProceduralStream proceduralRegionStream = regionStyleStream - .selectRarity(upperData.getRegionLoader().loadAll(upperDim.getRegions())); + .selectWeighted(IrisRegionEntry.load(upperDim.getRegions(), upperData.getRegionLoader())); ProceduralStream regionStream = proceduralRegionStream .convertAware2D((region, x, z) -> mappedRegion(imageMapRuntime, region, x, z)) .cache2D("upperImageMappedRegionStream", engine, cacheSize); @@ -143,7 +144,7 @@ public class UpperDimensionContext implements DataProvider { .zoom(upperDim.getBiomeZoom()) .zoom(upperDim.getLandZoom()) .zoom(r.getLandBiomeZoom()) - .selectRarity(loadInferredBiomes(upperData, r.getLandBiomes(), InferredType.LAND))) + .selectWeighted(loadInferredBiomes(upperData, r.getLandBiomes(), InferredType.LAND))) .convertAware2D(ProceduralStream::get); ProceduralStream seaBiomeStream = regionStream .convert(r -> upperDim.getSeaBiomeStyle() @@ -151,14 +152,14 @@ public class UpperDimensionContext implements DataProvider { .zoom(upperDim.getBiomeZoom()) .zoom(upperDim.getSeaZoom()) .zoom(r.getSeaBiomeZoom()) - .selectRarity(loadInferredBiomes(upperData, r.getSeaBiomes(), InferredType.SEA))) + .selectWeighted(loadInferredBiomes(upperData, r.getSeaBiomes(), InferredType.SEA))) .convertAware2D(ProceduralStream::get); ProceduralStream shoreBiomeStream = regionStream .convert(r -> upperDim.getShoreBiomeStyle() .create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), upperData).stream() .zoom(upperDim.getBiomeZoom()) .zoom(r.getShoreBiomeZoom()) - .selectRarity(loadInferredBiomes(upperData, r.getShoreBiomes(), InferredType.SHORE))) + .selectWeighted(loadInferredBiomes(upperData, r.getShoreBiomes(), InferredType.SHORE))) .convertAware2D(ProceduralStream::get); Map> inferredStreams = new HashMap<>(); @@ -175,7 +176,7 @@ public class UpperDimensionContext implements DataProvider { return stream != null ? stream.get(x, z) : inferredStreams.get(InferredType.LAND).get(x, z); }) .convertAware2D((biome, x, z) -> implode( - biome, x, z, rng, dataProvider, childSelectionPlans, 3)); + biome, x, z, rng, dataProvider, 3)); ProceduralStream baseBiomeStream = proceduralBaseBiomeStream .convertAware2D((biome, x, z) -> mappedBiome(imageMapRuntime, biome, x, z)) .cache2D("upperImageMappedBaseBiomeStream", engine, cacheSize); @@ -268,7 +269,7 @@ public class UpperDimensionContext implements DataProvider { shoreBiomeStream); return resolved == baseBiome ? baseBiome - : implode(resolved, x, z, rng, dataProvider, childSelectionPlans, 3); + : implode(resolved, x, z, rng, dataProvider, 3); }).cache2D("upperImageMappedFinalBiomeStream", engine, cacheSize); return new UpperDimensionContext(new ContextState( @@ -337,10 +338,10 @@ public class UpperDimensionContext implements DataProvider { return mappedBlock == null ? proceduralBlock : mappedBlock; } - private static KList loadInferredBiomes(IrisData data, KList keys, InferredType type) { - KList inferred = new KList<>(); - for (IrisBiome biome : data.getBiomeLoader().loadAll(keys)) { - inferred.add(biome.withInferredType(type)); + private static KList> loadInferredBiomes(IrisData data, KList entries, InferredType type) { + KList> inferred = new KList<>(); + for (Weighted entry : IrisBiomeEntry.load(entries, data.getBiomeLoader())) { + inferred.add(new Weighted<>(entry.value().withInferredType(type), entry.weight())); } return inferred; } @@ -351,33 +352,15 @@ public class UpperDimensionContext implements DataProvider { double z, RNG rng, DataProvider dataProvider, - Map childSelectionPlans, int remainingDepth ) { if (biome == null || remainingDepth < 0 || biome.getChildren().isEmpty()) { return biome; } - IrisComplex.ChildSelectionPlan selectionPlan = childSelectionPlans.get(biome); - if (selectionPlan == null) { - synchronized (childSelectionPlans) { - selectionPlan = childSelectionPlans.get(biome); - if (selectionPlan == null) { - KList options = new KList<>(); - for (IrisBiome child : biome.getRealChildren(dataProvider)) { - if (child != null) { - options.add(child); - } - } - options.add(biome); - selectionPlan = IrisComplex.ChildSelectionPlan.create(options); - childSelectionPlans.put(biome, selectionPlan); - } - } - } - - IrisBiome selected = selectionPlan.select( - biome.getChildrenGenerator(rng, 123, biome.getChildShrinkFactor()), x, z); + IrisBiome selected = Weighted.pick(biome.getChildOptions(dataProvider), + biome.getChildrenGenerator(rng, 123, biome.getChildShrinkFactor()).noiseFast2D(x, z), + IrisComplex.CHILD_EDGE); if (selected == null) { return biome; } @@ -387,7 +370,6 @@ public class UpperDimensionContext implements DataProvider { z, rng, dataProvider, - childSelectionPlans, remainingDepth - 1); } 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 03fa989e0..1bcbe53be 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 @@ -345,7 +345,7 @@ public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer, if (focusRegion != null) { return focusRegion.getLoadKey().equals(region.getLoadKey()); } - return getDimension().getRegions().contains(region.getLoadKey()); + return getDimension().getRegionKeys().contains(region.getLoadKey()); } diff --git a/core/src/main/java/art/arcane/iris/engine/framework/HintedLocator.java b/core/src/main/java/art/arcane/iris/engine/framework/HintedLocator.java index 931760502..cdcee160b 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/HintedLocator.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/HintedLocator.java @@ -22,6 +22,7 @@ import art.arcane.iris.core.IrisSettings; import art.arcane.iris.core.modules.ModuleServices; import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.biome.IrisBiomeEntry; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.util.common.parallel.BurstExecutor; import art.arcane.iris.util.common.parallel.MultiBurst; @@ -299,21 +300,21 @@ public final class HintedLocator implements Locator { boolean hosted = false; - for (String root : region.getLandBiomes()) { + for (String root : IrisBiomeEntry.keys(region.getLandBiomes())) { if (source.closureContains(root, biomeKey)) { landHosts.add(root); hosted = true; } } - for (String root : region.getSeaBiomes()) { + for (String root : IrisBiomeEntry.keys(region.getSeaBiomes())) { if (source.closureContains(root, biomeKey)) { seaHosts.add(root); hosted = true; } } - for (String root : region.getShoreBiomes()) { + for (String root : IrisBiomeEntry.keys(region.getShoreBiomes())) { if (source.closureContains(root, biomeKey)) { shoreHosts.add(root); hosted = true; @@ -324,7 +325,7 @@ public final class HintedLocator implements Locator { surfaceRegions.add(region.getLoadKey()); } - if (region.getCaveBiomes().contains(biomeKey)) { + if (IrisBiomeEntry.keys(region.getCaveBiomes()).contains(biomeKey)) { caveRegions.add(region.getLoadKey()); } } @@ -355,7 +356,7 @@ public final class HintedLocator implements Locator { KSet caveRegions = new KSet<>(); for (IrisRegion region : engine.getDimension().getAllRegions(engine)) { - if (region != null && region.getCaveBiomes().contains(biomeKey)) { + if (region != null && IrisBiomeEntry.keys(region.getCaveBiomes()).contains(biomeKey)) { caveRegions.add(region.getLoadKey()); } } @@ -372,7 +373,7 @@ public final class HintedLocator implements Locator { return SearchPlan.unpruned(); } - if (!engine.getDimension().getRegions().contains(regionKey)) { + if (!engine.getDimension().getRegionKeys().contains(regionKey)) { return SearchPlan.impossible(); } @@ -410,21 +411,21 @@ public final class HintedLocator implements Locator { boolean hosted = false; - for (String root : region.getLandBiomes()) { + for (String root : IrisBiomeEntry.keys(region.getLandBiomes())) { if (source.closureContainsAny(root, placers.biomes())) { landHosts.add(root); hosted = true; } } - for (String root : region.getSeaBiomes()) { + for (String root : IrisBiomeEntry.keys(region.getSeaBiomes())) { if (source.closureContainsAny(root, placers.biomes())) { seaHosts.add(root); hosted = true; } } - for (String root : region.getShoreBiomes()) { + for (String root : IrisBiomeEntry.keys(region.getShoreBiomes())) { if (source.closureContainsAny(root, placers.biomes())) { shoreHosts.add(root); hosted = true; @@ -559,7 +560,7 @@ public final class HintedLocator implements Locator { continue; } - for (String child : biome.getChildren()) { + for (String child : biome.getChildKeys()) { if (child != null && !visited.contains(child)) { queue.add(child); } @@ -595,7 +596,7 @@ public final class HintedLocator implements Locator { return true; } - for (String child : biome.getChildren()) { + for (String child : biome.getChildKeys()) { if (child != null && !visited.contains(child)) { queue.add(child); } diff --git a/core/src/main/java/art/arcane/iris/engine/image/IrisImageMapRuntime.java b/core/src/main/java/art/arcane/iris/engine/image/IrisImageMapRuntime.java index 8cf796869..0ecc2ea6e 100644 --- a/core/src/main/java/art/arcane/iris/engine/image/IrisImageMapRuntime.java +++ b/core/src/main/java/art/arcane/iris/engine/image/IrisImageMapRuntime.java @@ -3,6 +3,7 @@ package art.arcane.iris.engine.image; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.biome.IrisBiomeEntry; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.image.IrisImage; import art.arcane.iris.engine.object.image.IrisImageMap; @@ -299,13 +300,13 @@ public final class IrisImageMapRuntime { if (region == null) { continue; } - if (region.getLandBiomes().contains(biomeKey)) { + if (IrisBiomeEntry.keys(region.getLandBiomes()).contains(biomeKey)) { types.add(InferredType.LAND); } - if (region.getSeaBiomes().contains(biomeKey)) { + if (IrisBiomeEntry.keys(region.getSeaBiomes()).contains(biomeKey)) { types.add(InferredType.SEA); } - if (region.getShoreBiomes().contains(biomeKey)) { + if (IrisBiomeEntry.keys(region.getShoreBiomes()).contains(biomeKey)) { types.add(InferredType.SHORE); } } diff --git a/core/src/main/java/art/arcane/iris/engine/object/value/IRare.java b/core/src/main/java/art/arcane/iris/engine/object/value/IRare.java deleted file mode 100644 index 09cfcb19d..000000000 --- a/core/src/main/java/art/arcane/iris/engine/object/value/IRare.java +++ /dev/null @@ -1,97 +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.engine.object.value; - -import art.arcane.volmlib.util.collection.KList; -import art.arcane.iris.util.project.stream.ProceduralStream; -import art.arcane.iris.util.project.stream.interpolation.Interpolated; -import java.util.List; - -public interface IRare { - static ProceduralStream stream(ProceduralStream noise, List possibilities) { - return ProceduralStream.of((x, z) -> pick(possibilities, noise.get(x, z)), - (x, y, z) -> pick(possibilities, noise.get(x, y, z)), - new Interpolated() { - @Override - public double toDouble(T t) { - return 0; - } - - @Override - public T fromDouble(double d) { - return null; - } - }); - } - - - static T pickSlowly(List possibilities, double noiseValue) { - if (possibilities.isEmpty()) { - return null; - } - - if (possibilities.size() == 1) { - return possibilities.get(0); - } - - KList rarityTypes = new KList<>(); - int totalRarity = 0; - for (T i : possibilities) { - totalRarity += IRare.get(i); - } - - for (T i : possibilities) { - rarityTypes.addMultiple(i, totalRarity / IRare.get(i)); - } - - return rarityTypes.get((int) (noiseValue * rarityTypes.last())); - } - - static T pick(List possibilities, double noiseValue) { - if (possibilities.isEmpty()) { - return null; - } - - if (possibilities.size() == 1) { - return possibilities.getFirst(); - } - - double total = 0; - for (T i : possibilities) { - total += 1d / IRare.get(i); - } - - double threshold = total * noiseValue; - double buffer = 0; - for (T i : possibilities) { - buffer += 1d / IRare.get(i); - if (buffer >= threshold) { - return i; - } - } - - return possibilities.getLast(); - } - - static int get(Object v) { - return v instanceof IRare ? Math.max(1, ((IRare) v).getRarity()) : 1; - } - - int getRarity(); -} diff --git a/core/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiome.java b/core/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiome.java index e04d4fb4f..407f03f2e 100644 --- a/core/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiome.java +++ b/core/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiome.java @@ -20,7 +20,6 @@ package art.arcane.iris.engine.object.world.biome; import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; import art.arcane.iris.engine.object.noise.NoiseStyle; -import art.arcane.iris.engine.object.value.IRare; import art.arcane.iris.engine.object.world.biome.custom.IrisBiomeCustom; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.framework.render.RenderType; @@ -33,10 +32,8 @@ import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.annotations.ArrayType; import art.arcane.iris.engine.object.annotations.DependsOn; import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; import art.arcane.iris.engine.object.annotations.MinNumber; import art.arcane.iris.engine.object.annotations.RegistryListBiome; -import art.arcane.iris.engine.object.annotations.RegistryListResource; import art.arcane.iris.engine.object.annotations.Required; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KMap; @@ -45,6 +42,7 @@ import art.arcane.iris.util.common.data.DataProvider; import art.arcane.volmlib.util.math.RNG; import art.arcane.iris.util.project.noise.CNG; import art.arcane.iris.util.project.context.IrisContext; +import com.volmit.world.Weighted; import lombok.AccessLevel; import lombok.Data; import lombok.EqualsAndHashCode; @@ -71,8 +69,10 @@ import java.util.Objects; @Desc("Represents a biome in iris. Biomes are placed inside of regions and hold objects.\nA biome consists of layers (block palletes), decorations, objects & generators.") @Data @EqualsAndHashCode(callSuper = false) -public class IrisBiome extends IrisRegistrant implements IRare { +public class IrisBiome extends IrisRegistrant { private static final int BIOME_GENERATOR_CACHE_SIZE = 8; + // The seed once added the biome's rarity; the 1 keeps biomes that had the default rarity on their old scatter. + private static final int BIOME_GENERATOR_SEED = 213949 + 228888 + 1; private static final int CHILDREN_SEED_SALT = 2137; private final transient AtomicCache> genCache = new AtomicCache<>(); @@ -87,7 +87,7 @@ public class IrisBiome extends IrisRegistrant implements IRare { @Getter(AccessLevel.NONE) @Setter(AccessLevel.NONE) private transient volatile SeededBiomeGenerator recentBiomeGenerator; - private final transient AtomicCache> realChildren = new AtomicCache<>(); + private final transient AtomicCache>> childOptions = new AtomicCache<>(); private final transient AtomicCache derivativeResolved = new AtomicCache<>(); private final transient AtomicCache vanillaDerivativeResolved = new AtomicCache<>(); private final transient AtomicCache> biomeScatterResolved = new AtomicCache<>(); @@ -102,10 +102,6 @@ public class IrisBiome extends IrisRegistrant implements IRare { @DependsOn({"biomeStyle", "biomeZoom", "biomeScatter"}) @Desc("This changes the dispersion of the biome colors if multiple derivatives are chosen.") private IrisGeneratorStyle biomeStyle = NoiseStyle.SIMPLEX.style(); - @MinNumber(1) - @MaxNumber(512) - @Desc("The rarity of this biome (integer)") - private int rarity = 1; @Desc("A color for visualizing this biome with a color. I.e. #F13AF5. This will show up on the map.") private String color = null; @Required @@ -130,10 +126,9 @@ public class IrisBiome extends IrisRegistrant implements IRare { @DependsOn({"children"}) @Desc("If this biome has children biomes, and the gen layer chooses one of this biomes children, How will it be shaped?") private IrisGeneratorStyle childStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - @RegistryListResource(IrisBiome.class) - @ArrayType(min = 1, type = String.class) - @Desc("List any biome names (file names without.json) here as children. Portions of this biome can sometimes morph into their children. Iris supports cyclic relationships such as A > B > A > B. Iris will stop checking 4 biomes down the tree.") - private KList children = new KList<>(); + @ArrayType(min = 1, type = IrisBiomeEntry.class) + @Desc("What portions of this biome turn into: the child noise picks along this list in the order it is written. List this biome itself where it should stay itself; a biome that isn't listed doesn't stay anywhere. Iris supports cyclic relationships such as A > B > A > B, and stops 4 levels down.") + private KList children = new KList<>(); @ArrayType(min = 1, type = IrisBiomeGeneratorLink.class) @Desc("Generators for this biome. Multiple generators with different interpolation sizes will mix with other biomes how you would expect. This defines your biome height relative to the fluid height. Use negative for oceans.") private KList generators = new KList().qadd(new IrisBiomeGeneratorLink()); @@ -291,7 +286,7 @@ public class IrisBiome extends IrisRegistrant implements IRare { } private CNG createBiomeGenerator(long seed, IrisData loader) { - int signature = 213949 + 228888 + getRarity() + getName().length(); + int signature = BIOME_GENERATOR_SEED + getName().length(); return biomeStyle.createNoCache(new RNG(seed).nextParallelRNG(signature), loader); } @@ -343,26 +338,29 @@ public class IrisBiome extends IrisRegistrant implements IRare { return IrisBiomeDerivatives.getCustomBiome(this, rng, engine, x, y, z); } - public KList getRealChildren(DataProvider g) { - return realChildren.aquire(() -> - { - KList realChildren = new KList<>(); + /** + * The biomes this one turns into, leaving out the entries where it stays itself. + */ + public KList getChildKeys() { + KList keys = IrisBiomeEntry.keys(getChildren()); + keys.removeIf(key -> key.equals(getLoadKey())); + return keys; + } - for (String i : getChildren()) { - realChildren.add(g.getData().getBiomeLoader().load(i)); - } - - return realChildren; - }); + /** + * What the child noise picks from, with weights, in noise order. + */ + public KList> getChildOptions(DataProvider g) { + return childOptions.aquire(() -> IrisBiomeEntry.load(getChildren(), g.getData().getBiomeLoader())); } public KList getAllChildren(DataProvider g, int limit) { KSet m = new KSet<>(); - m.addAll(getChildren()); + m.addAll(getChildKeys()); limit--; if (limit > 0) { - for (String i : getChildren()) { + for (String i : getChildKeys()) { IrisBiome b = g.getData().getBiomeLoader().load(i); m.addAll(b.getAllChildren(g, limit)); } diff --git a/core/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeEntry.java b/core/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeEntry.java new file mode 100644 index 000000000..7af35935b --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeEntry.java @@ -0,0 +1,70 @@ +/* + * 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.biome; + +import art.arcane.iris.core.loader.ResourceLoader; +import art.arcane.iris.engine.object.annotations.Desc; +import art.arcane.iris.engine.object.annotations.MaxNumber; +import art.arcane.iris.engine.object.annotations.MinNumber; +import art.arcane.iris.engine.object.annotations.RegistryListResource; +import art.arcane.iris.engine.object.annotations.Required; +import art.arcane.volmlib.util.collection.KList; +import com.volmit.world.Weighted; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.util.List; + +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("A biome in a list a noise picks from") +@Data +public class IrisBiomeEntry { + @Required + @RegistryListResource(IrisBiome.class) + @Desc("The biome (file name without .json)") + private String biome; + @MinNumber(Weighted.MIN_WEIGHT) + @MaxNumber(Weighted.MAX_WEIGHT) + @Desc("A weight of two is just as if this entry were listed twice in a row, making the biome more common. The noise picks along the list in the order it is written.") + private int weight = 1; + + public static KList keys(List entries) { + KList keys = new KList<>(); + entries.forEach(entry -> keys.add(entry.getBiome())); + return keys; + } + + /** + * The entries' biomes with their weights, in list order, leaving out biomes that don't load. + */ + public static KList> load(List entries, ResourceLoader loader) { + KList> loaded = new KList<>(); + for (IrisBiomeEntry entry : entries) { + IrisBiome biome = loader.load(entry.getBiome()); + if (biome != null) { + loaded.add(new Weighted<>(biome, entry.getWeight())); + } + } + return loaded; + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimension.java b/core/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimension.java index 849370022..cf662a7ee 100644 --- a/core/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimension.java +++ b/core/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimension.java @@ -32,6 +32,7 @@ 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.biome.custom.IrisBiomeCustom; import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.engine.object.world.region.IrisRegionEntry; import art.arcane.iris.core.IrisDatapackCompiler.DimensionHeight; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.spi.IrisLogging; @@ -135,11 +136,10 @@ public class IrisDimension extends IrisRegistrant { private IrisGeneratorStyle caveBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); @Desc("The world environment") private IrisEnvironment environment = IrisEnvironment.NORMAL; - @RegistryListResource(IrisRegion.class) @Required - @ArrayType(min = 1, type = String.class) - @Desc("Define all of the regions to include in this dimension. Dimensions -> Regions -> Biomes -> Objects etc") - private KList regions = new KList<>(); + @ArrayType(min = 1, type = IrisRegionEntry.class) + @Desc("The regions of this dimension, picked along the list by the region noise. Dimensions -> Regions -> Biomes -> Objects etc") + private KList regions = new KList<>(); @Required @MinNumber(0) @MaxNumber(1024) @@ -164,7 +164,7 @@ public class IrisDimension extends IrisRegistrant { @Desc("Minimum air gap in blocks between the lower terrain surface and the upper terrain surface.") private int upperDimensionGap = 32; @RegistryListResource(IrisBiome.class) - @Desc("Keep this either undefined or empty. Setting any biome name into this will force iris to only generate the specified biome. Great for testing.") + @Desc("Keep this either undefined or empty. Setting any biome name into this will force iris to only generate the specified biome and its children. Great for testing.") private String focus = ""; @RegistryListResource(IrisRegion.class) @Desc("Keep this either undefined or empty. Setting any region name into this will force iris to only generate the specified region. Great for testing.") @@ -268,7 +268,7 @@ public class IrisDimension extends IrisRegistrant { return regions.v(); } - for (String key : getRegions()) { + for (String key : getRegionKeys()) { IrisRegion region = data.getRegionLoader().load(key); if (region != null) { regions.put(key, region); @@ -293,10 +293,24 @@ public class IrisDimension extends IrisRegistrant { return regions.v(); } + public KList getRegionKeys() { + return IrisRegionEntry.keys(getRegions()); + } + + /** The weight the region has in the region noise's pick; 0 for a region the dimension does not list. */ + public int getRegionWeight(String regionKey) { + for (IrisRegionEntry entry : regions) { + if (entry.getRegion().equals(regionKey)) { + return entry.getWeight(); + } + } + return 0; + } + public KList getAllAnyRegions() { KList r = new KList<>(); - for (String i : getRegions()) { + for (String i : getRegionKeys()) { r.add(IrisData.loadAnyRegion(i, getLoader())); } @@ -366,7 +380,7 @@ public class IrisDimension extends IrisRegistrant { visited.add(loadKey); biomes.put(loadKey, biome); - addReachableBiomeKeys(pending, biome.getChildren()); + addReachableBiomeKeys(pending, biome.getChildKeys()); addReachableBiomeKeys(pending, biome.getModuleSettings().treeBiomes(data.getPackResources())); addReachableBiomeKeys(pending, biome.getModuleSettings().usedBiomes(data.getPackResources(), getModuleSettings(), getLoadKey())); } diff --git a/core/src/main/java/art/arcane/iris/engine/object/world/region/IrisRegion.java b/core/src/main/java/art/arcane/iris/engine/object/world/region/IrisRegion.java index 584ace764..835eb6d80 100644 --- a/core/src/main/java/art/arcane/iris/engine/object/world/region/IrisRegion.java +++ b/core/src/main/java/art/arcane/iris/engine/object/world/region/IrisRegion.java @@ -18,9 +18,9 @@ package art.arcane.iris.engine.object.world.region; -import art.arcane.iris.engine.object.value.IRare; 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.biome.IrisBiomeEntry; import art.arcane.iris.engine.framework.render.RenderType; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.spi.IrisLogging; @@ -28,9 +28,7 @@ import art.arcane.iris.core.loader.IrisRegistrant; import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.iris.engine.object.annotations.ArrayType; import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.RegistryListResource; import art.arcane.iris.engine.object.annotations.Required; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KMap; @@ -54,7 +52,7 @@ import java.util.Random; @Desc("Represents an iris region") @Data @EqualsAndHashCode(callSuper = false) -public class IrisRegion extends IrisRegistrant implements IRare { +public class IrisRegion extends IrisRegistrant { private final transient AtomicCache> cacheRidge = new AtomicCache<>(); private final transient AtomicCache> cacheSpot = new AtomicCache<>(); private final transient AtomicCache shoreHeightGenerator = new AtomicCache<>(); @@ -67,10 +65,6 @@ public class IrisRegion extends IrisRegistrant implements IRare { @Required @Desc("The name of the region") private String name = "A Region"; - @MinNumber(1) - @MaxNumber(128) - @Desc("The rarity of the region") - private int rarity = 1; @MinNumber(0) @Desc("The min shore height") private double shoreHeightMin = 1.2; @@ -92,23 +86,19 @@ public class IrisRegion extends IrisRegistrant implements IRare { @MinNumber(0.0001) @Desc("How large cave biomes are in this region") private double caveBiomeZoom = 1; - @RegistryListResource(IrisBiome.class) @Required - @ArrayType(min = 1, type = String.class) - @Desc("A list of root-level biomes in this region. Don't specify child biomes of other biomes here. Just the root parents.") - private KList landBiomes = new KList<>(); - @RegistryListResource(IrisBiome.class) - @ArrayType(type = String.class) - @Desc("A list of root-level sea biomes in this region. Optional: leave empty for land-only dimensions (flat, island, or fully-land worlds where no ocean is generated). Don't specify child biomes of other biomes here. Just the root parents.") - private KList seaBiomes = new KList<>(); - @RegistryListResource(IrisBiome.class) - @ArrayType(type = String.class) - @Desc("A list of root-level shore biomes in this region. Optional: leave empty for land-only dimensions (flat, island, or fully-land worlds where no shoreline is generated). Don't specify child biomes of other biomes here. Just the root parents.") - private KList shoreBiomes = new KList<>(); - @RegistryListResource(IrisBiome.class) - @ArrayType(min = 1, type = String.class) - @Desc("A list of root-level cave biomes in this region, used for carved cave interiors. Don't specify child biomes of other biomes here. Just the root parents.") - private KList caveBiomes = new KList<>(); + @ArrayType(min = 1, type = IrisBiomeEntry.class) + @Desc("The root-level land biomes of this region, picked along the list by the biome noise. Don't list child biomes of other biomes here, just the root parents.") + private KList landBiomes = new KList<>(); + @ArrayType(type = IrisBiomeEntry.class) + @Desc("The root-level sea biomes of this region, picked along the list by the biome noise. Optional: leave empty for land-only dimensions (flat, island, or fully-land worlds where no ocean is generated). Don't list child biomes of other biomes here, just the root parents.") + private KList seaBiomes = new KList<>(); + @ArrayType(type = IrisBiomeEntry.class) + @Desc("The root-level shore biomes of this region, picked along the list by the biome noise. Optional: leave empty for land-only dimensions (flat, island, or fully-land worlds where no shoreline is generated). Don't list child biomes of other biomes here, just the root parents.") + private KList shoreBiomes = new KList<>(); + @ArrayType(min = 1, type = IrisBiomeEntry.class) + @Desc("The root-level cave biomes of this region, picked along the list by the cave biome noise and used for carved cave interiors. Don't list child biomes of other biomes here, just the root parents.") + private KList caveBiomes = new KList<>(); @Desc("A color for visualizing this region with a color. I.e. #F13AF5. This will show up on the map.") private String color = null; @@ -127,10 +117,10 @@ public class IrisRegion extends IrisRegistrant implements IRare { public KSet getAllBiomeIds() { KSet names = new KSet<>(); - names.addAll(landBiomes); - names.addAll(caveBiomes); - names.addAll(seaBiomes); - names.addAll(shoreBiomes); + names.addAll(IrisBiomeEntry.keys(landBiomes)); + names.addAll(IrisBiomeEntry.keys(caveBiomes)); + names.addAll(IrisBiomeEntry.keys(seaBiomes)); + names.addAll(IrisBiomeEntry.keys(shoreBiomes)); return names; } @@ -155,7 +145,7 @@ public class IrisRegion extends IrisRegistrant implements IRare { names.addAll(biome.getModuleSettings().treeBiomes(g.getData().getPackResources())); b.put(biome.getLoadKey(), biome); - names.addAll(biome.getChildren()); + names.addAll(biome.getChildKeys()); } } @@ -181,7 +171,7 @@ public class IrisRegion extends IrisRegistrant implements IRare { { KList realCaveBiomes = new KList<>(); - for (String i : getCaveBiomes()) { + for (String i : IrisBiomeEntry.keys(getCaveBiomes())) { realCaveBiomes.add(g.getData().getBiomeLoader().load(i)); } @@ -194,7 +184,7 @@ public class IrisRegion extends IrisRegistrant implements IRare { { KList realShoreBiomes = new KList<>(); - for (String i : getShoreBiomes()) { + for (String i : IrisBiomeEntry.keys(getShoreBiomes())) { realShoreBiomes.add(g.getData().getBiomeLoader().load(i)); } @@ -207,7 +197,7 @@ public class IrisRegion extends IrisRegistrant implements IRare { { KList realSeaBiomes = new KList<>(); - for (String i : getSeaBiomes()) { + for (String i : IrisBiomeEntry.keys(getSeaBiomes())) { realSeaBiomes.add(g.getData().getBiomeLoader().load(i)); } @@ -220,7 +210,7 @@ public class IrisRegion extends IrisRegistrant implements IRare { { KList realLandBiomes = new KList<>(); - for (String i : getLandBiomes()) { + for (String i : IrisBiomeEntry.keys(getLandBiomes())) { realLandBiomes.add(g.getData().getBiomeLoader().load(i)); } @@ -231,10 +221,10 @@ public class IrisRegion extends IrisRegistrant implements IRare { public KList getAllAnyBiomes() { KMap b = new KMap<>(); KSet names = new KSet<>(); - names.addAll(landBiomes); - names.addAll(caveBiomes); - names.addAll(seaBiomes); - names.addAll(shoreBiomes); + names.addAll(IrisBiomeEntry.keys(landBiomes)); + names.addAll(IrisBiomeEntry.keys(caveBiomes)); + names.addAll(IrisBiomeEntry.keys(seaBiomes)); + names.addAll(IrisBiomeEntry.keys(shoreBiomes)); while (!names.isEmpty()) { for (String i : new KList<>(names)) { @@ -252,7 +242,7 @@ public class IrisRegion extends IrisRegistrant implements IRare { names.addAll(biome.getModuleSettings().treeBiomes(biome.getLoader().getPackResources())); b.put(biome.getLoadKey(), biome); - names.addAll(biome.getChildren()); + names.addAll(biome.getChildKeys()); } } diff --git a/core/src/main/java/art/arcane/iris/engine/object/world/region/IrisRegionEntry.java b/core/src/main/java/art/arcane/iris/engine/object/world/region/IrisRegionEntry.java new file mode 100644 index 000000000..96e12fabc --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/object/world/region/IrisRegionEntry.java @@ -0,0 +1,70 @@ +/* + * 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.core.loader.ResourceLoader; +import art.arcane.iris.engine.object.annotations.Desc; +import art.arcane.iris.engine.object.annotations.MaxNumber; +import art.arcane.iris.engine.object.annotations.MinNumber; +import art.arcane.iris.engine.object.annotations.RegistryListResource; +import art.arcane.iris.engine.object.annotations.Required; +import art.arcane.volmlib.util.collection.KList; +import com.volmit.world.Weighted; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.util.List; + +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("A region in the dimension's region list") +@Data +public class IrisRegionEntry { + @Required + @RegistryListResource(IrisRegion.class) + @Desc("The region (file name without .json)") + private String region; + @MinNumber(Weighted.MIN_WEIGHT) + @MaxNumber(Weighted.MAX_WEIGHT) + @Desc("A weight of two is just as if this entry were listed twice in a row, making the region more common. The noise picks along the list in the order it is written.") + private int weight = 1; + + public static KList keys(List entries) { + KList keys = new KList<>(); + entries.forEach(entry -> keys.add(entry.getRegion())); + return keys; + } + + /** + * The entries' regions with their weights, in list order, leaving out regions that don't load. + */ + public static KList> load(List entries, ResourceLoader loader) { + KList> loaded = new KList<>(); + for (IrisRegionEntry entry : entries) { + IrisRegion region = loader.load(entry.getRegion()); + if (region != null) { + loaded.add(new Weighted<>(region, entry.getWeight())); + } + } + return loaded; + } +} diff --git a/core/src/main/java/art/arcane/iris/util/project/noise/CNG.java b/core/src/main/java/art/arcane/iris/util/project/noise/CNG.java index 7f70bca25..b768c9c89 100644 --- a/core/src/main/java/art/arcane/iris/util/project/noise/CNG.java +++ b/core/src/main/java/art/arcane/iris/util/project/noise/CNG.java @@ -18,7 +18,6 @@ package art.arcane.iris.util.project.noise; -import art.arcane.iris.engine.object.value.IRare; import art.arcane.iris.engine.object.noise.NoiseStyle; import art.arcane.iris.spi.IrisLogging; import art.arcane.volmlib.util.cache.FloatCache; @@ -429,79 +428,6 @@ public class CNG { return InjectorMode.CUSTOM; } - public T fitRarity(KList b, double... dim) { - if (dim.length == 2) { - return fitRarity2D(b, dim[0], dim[1]); - } - - if (b.size() == 0) { - return null; - } - - if (b.size() == 1) { - return b.get(0); - } - - KList rarityMapped = buildRarityMapped(b); - - if (rarityMapped.size() == 1) { - return rarityMapped.get(0); - } - - if (rarityMapped.isEmpty()) { - throw new RuntimeException("BAD RARITY MAP! RELATED TO: " + b.toString(", or possibly ")); - } - - return fit(rarityMapped, dim); - } - - public T fitRarity2D(KList b, double x, double z) { - if (b.size() == 0) { - return null; - } - - if (b.size() == 1) { - return b.get(0); - } - - KList rarityMapped = buildRarityMapped(b); - if (rarityMapped.size() == 1) { - return rarityMapped.get(0); - } - - if (rarityMapped.isEmpty()) { - throw new RuntimeException("BAD RARITY MAP! RELATED TO: " + b.toString(", or possibly ")); - } - - return fit2D(rarityMapped, x, z); - } - - private KList buildRarityMapped(KList values) { - KList rarityMapped = new KList<>(); - boolean flip = false; - int max = 1; - for (T value : values) { - if (value.getRarity() > max) { - max = value.getRarity(); - } - } - - max++; - for (T value : values) { - int count = max - value.getRarity(); - for (int j = 0; j < count; j++) { - flip = !flip; - if (flip) { - rarityMapped.add(value); - } else { - rarityMapped.add(0, value); - } - } - } - - return rarityMapped; - } - public T fit2D(T[] values, double x, double z) { if (values.length == 0) { return null; diff --git a/core/src/main/java/art/arcane/iris/util/project/stream/ProceduralStream.java b/core/src/main/java/art/arcane/iris/util/project/stream/ProceduralStream.java index b7d4048f2..bdff463cf 100644 --- a/core/src/main/java/art/arcane/iris/util/project/stream/ProceduralStream.java +++ b/core/src/main/java/art/arcane/iris/util/project/stream/ProceduralStream.java @@ -21,7 +21,7 @@ package art.arcane.iris.util.project.stream; import art.arcane.iris.core.loader.IrisData; import art.arcane.volmlib.util.cache.CacheKey; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.value.IRare; +import com.volmit.world.Weighted; import art.arcane.iris.engine.object.noise.IrisStyledRange; import art.arcane.iris.spi.IrisLogging; import art.arcane.volmlib.util.collection.KList; @@ -356,45 +356,11 @@ public interface ProceduralStream extends ProceduralLayer, Interpolated { return new SelectionStream(this, types); } - @SuppressWarnings("unchecked") - default ProceduralStream selectRarity(V... types) { - KList rarityTypes = new KList<>(); - int totalRarity = 0; - for (V i : types) { - totalRarity += IRare.get(i); - } - - for (V i : types) { - rarityTypes.addMultiple(i, totalRarity / IRare.get(i)); - } - - return new SelectionStream(this, rarityTypes); - } - - default ProceduralStream selectRarity(List types) { - return IRare.stream(this.forceDouble(), types); - } - - default ProceduralStream selectRarity(List types, Function loader) { - List r = new ArrayList<>(); - for (V f : types) { - r.add(loader.apply(f)); - } - return selectRarity(r); - } - - default int countPossibilities(List types, Function loader) { - KList rarityTypes = new KList<>(); - int totalRarity = 0; - for (V i : types) { - totalRarity += IRare.get(loader.apply(i)); - } - - for (V i : types) { - rarityTypes.addMultiple(i, totalRarity / IRare.get(loader.apply(i))); - } - - return rarityTypes.size(); + default ProceduralStream selectWeighted(List> entries) { + ProceduralStream noise = this.forceDouble(); + return ProceduralStream.of((x, z) -> Weighted.pick(entries, noise.get(x, z), Weighted.Edge.EARLIER), + (x, y, z) -> Weighted.pick(entries, noise.get(x, y, z), Weighted.Edge.EARLIER), + Interpolated.of(entry -> 0D, value -> null)); } default ProceduralStream clamp(double min, double max) { diff --git a/core/src/main/resources/messages/en_US.json b/core/src/main/resources/messages/en_US.json index ee94e4f9d..14d7adc38 100644 --- a/core/src/main/resources/messages/en_US.json +++ b/core/src/main/resources/messages/en_US.json @@ -518,7 +518,7 @@ "iris.modded.moddedstudiocommands.this_command_can_only_be_used_by_players_sampling_is": "This command can only be used by players (sampling is centered on your position).", "iris.modded.moddedstudiocommands.this_dimension_is_not_generated_by_iris": "This dimension is not generated by Iris.", "iris.modded.moddedstudiocommands.sampling_region_distribution_x_chunks_around_you": "Sampling region distribution in {value}x{value2} chunks around you...", - "iris.modded.moddedstudiocommands.rarity": "{key}: rarity={rarity} / {value}%", + "iris.modded.moddedstudiocommands.rarity": "{key}: weight={rarity} / {value}%", "iris.modded.moddedstudiocommands.region_sampling_failed": "Region sampling failed: {value}", "iris.modded.moddedworldcommands.required_pack_is_not_installed_install_then_restart": "Required pack '{pack}' is not installed. Install it with /iris download, then restart.", "iris.modded.moddedworldcommands.failed_inject_iris_world": "Failed to inject Iris world '{dimensionId}': {value}{errorMessage}", 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 index 19003ab05..4fbb686d5 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/CarveSettingsDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/CarveSettingsDecodingTest.java @@ -21,6 +21,7 @@ package art.arcane.iris.core.modules; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.modules.carve.CarvingBiomeSettings; import art.arcane.iris.modules.carve.CarvingEnabledSettings; +import art.arcane.iris.modules.carve.CarvingChild; import art.arcane.iris.modules.carve.CarvingEntry; import art.arcane.iris.modules.carve.CarvingSettings; import art.arcane.iris.modules.carve.CaveDepthSettings; @@ -157,7 +158,7 @@ public class CarveSettingsDecodingTest { 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}}, + "children": [{"id": "lush", "weight": 3}, {"id": " moss "}, {"id": "deep", "weight": 2}], "childStyle": {"style": "SIMPLEX", "zoom": 3}}, {"id": "off", "enabled": false, "biome": "carving/off"}, {} ], "carvingEnabled": false} @@ -167,7 +168,9 @@ public class CarveSettingsDecodingTest { List bands = settings.find(CarvingSettings.class).orElseThrow().entries(); assertEquals(3, bands.size()); - assertEquals(List.of("lush", " moss "), bands.getFirst().children()); + assertEquals(List.of("lush", " moss ", "deep"), bands.getFirst().children().stream().map(CarvingChild::id).toList()); + assertEquals("a child that writes no weight counts once", List.of(3, 1, 2), + bands.getFirst().children().stream().map(CarvingChild::weight).toList()); assertEquals(2, bands.getFirst().childShrinkFactor(), 0); assertEquals(5, bands.getFirst().childRecursionDepth()); assertEquals("SIMPLEX", bands.getFirst().childStyle().style()); diff --git a/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java b/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java index 1c2f8c2e9..87420678d 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java +++ b/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java @@ -92,9 +92,9 @@ public final class CarveTestWorld implements PackWorld { return declare(Level.DIMENSION, "overworld", value); } - public CarveTestWorld biome(String key, int rarity) { + public CarveTestWorld biome(String key) { ResourceId id = new ResourceId(NAMESPACE, key); - biomes.put(id, new PackBiome(id, key, ResourceId.parse("minecraft:plains"), rarity, List.of())); + biomes.put(id, new PackBiome(id, key, ResourceId.parse("minecraft:plains"), List.of())); return this; } diff --git a/core/src/test/java/art/arcane/iris/core/modules/IrisPackResourcesTest.java b/core/src/test/java/art/arcane/iris/core/modules/IrisPackResourcesTest.java index 2219ea145..622d93e74 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/IrisPackResourcesTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/IrisPackResourcesTest.java @@ -4,6 +4,7 @@ import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.ResourceLoader; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.biome.IrisBiomeEntry; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.volmlib.util.collection.KList; import com.volmit.block.BlockState; @@ -16,6 +17,7 @@ import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceKind; import com.volmit.world.PackBiome; import com.volmit.world.PackRegion; +import com.volmit.world.Weighted; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -70,9 +72,8 @@ public class IrisPackResourcesTest { IrisBiome dunes = new IrisBiome(); dunes.setName("Dunes"); - dunes.setRarity(3); dunes.setDerivative("minecraft:desert"); - dunes.setChildren(new KList<>(List.of("desert/oasis"))); + dunes.setChildren(new KList<>(List.of(new IrisBiomeEntry("desert/oasis", 4), new IrisBiomeEntry("desert/dunes", 2)))); when(biomeLoader.getPossibleKeys()).thenReturn(new String[]{"desert/dunes", "desert"}); when(biomeLoader.load("desert/dunes")).thenReturn(dunes); IrisBiome sharedKeyBiome = new IrisBiome(); @@ -82,11 +83,10 @@ public class IrisPackResourcesTest { IrisRegion desert = new IrisRegion(); desert.setName("The Desert"); - desert.setRarity(2); - desert.setLandBiomes(new KList<>(List.of("desert/dunes"))); - desert.setSeaBiomes(new KList<>(List.of("ocean"))); - desert.setShoreBiomes(new KList<>(List.of("beach"))); - desert.setCaveBiomes(new KList<>(List.of("caves/dry"))); + desert.setLandBiomes(new KList<>(List.of(new IrisBiomeEntry("desert/dunes", 3)))); + desert.setSeaBiomes(new KList<>(List.of(new IrisBiomeEntry("ocean", 1)))); + desert.setShoreBiomes(new KList<>(List.of(new IrisBiomeEntry("beach", 1)))); + desert.setCaveBiomes(new KList<>(List.of(new IrisBiomeEntry("caves/dry", 5), new IrisBiomeEntry("caves/lush", 2)))); when(regionLoader.getPossibleKeys()).thenReturn(new String[]{"desert"}); when(regionLoader.load("desert")).thenReturn(desert); @@ -119,15 +119,17 @@ public class IrisPackResourcesTest { public void aPackBiomeIsBuiltFromTheBiomeFile() { PackBiome biome = resources.require(PackResources.BIOMES, id("desert/dunes")); - assertEquals(new PackBiome(id("desert/dunes"), "Dunes", ResourceId.parse("minecraft:desert"), 3, List.of(id("desert/oasis"))), biome); + assertEquals(new PackBiome(id("desert/dunes"), "Dunes", ResourceId.parse("minecraft:desert"), + List.of(new Weighted<>(id("desert/oasis"), 4), new Weighted<>(id("desert/dunes"), 2))), biome); } @Test - public void aPackRegionIsBuiltFromTheRegionFileWithItsFourBiomeListsAsPackIds() { + public void aPackRegionIsBuiltFromTheRegionFileWithItsFourBiomeListsAsWeightedPackIds() { PackRegion region = resources.require(PackResources.REGIONS, id("desert")); - assertEquals(new PackRegion(id("desert"), "The Desert", 2, List.of(id("desert/dunes")), List.of(id("ocean")), - List.of(id("beach")), List.of(id("caves/dry"))), region); + assertEquals(new PackRegion(id("desert"), "The Desert", List.of(new Weighted<>(id("desert/dunes"), 3)), + List.of(new Weighted<>(id("ocean"), 1)), List.of(new Weighted<>(id("beach"), 1)), + List.of(new Weighted<>(id("caves/dry"), 5), new Weighted<>(id("caves/lush"), 2))), region); } @Test diff --git a/core/src/test/java/art/arcane/iris/core/modules/PackModuleResourceKindTest.java b/core/src/test/java/art/arcane/iris/core/modules/PackModuleResourceKindTest.java index 597aeddb5..958e99f83 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/PackModuleResourceKindTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/PackModuleResourceKindTest.java @@ -203,8 +203,8 @@ public class PackModuleResourceKindTest { private Path castlePack(String name) throws Exception { File pack = temporaryFolder.newFolder(name); - write(pack.toPath(), "dimensions/main.json", "{\"regions\":[\"region\"]}"); - write(pack.toPath(), "regions/region.json", "{\"landBiomes\":[\"biome\"]}"); + write(pack.toPath(), "dimensions/main.json", "{\"regions\":[{\"region\":\"region\"}]}"); + write(pack.toPath(), "regions/region.json", "{\"landBiomes\":[{\"biome\":\"biome\"}]}"); write(pack.toPath(), "biomes/biome.json", "{\"name\":\"Biome\"}"); PackModuleJar.write(pack.toPath(), "castle.jar", "pack.castle.CastleModule", Map.of("pack.castle.CastleModule", MODULE, "pack.castle.Keep", KEEP, "pack.castle.KeepValidator", VALIDATOR)); diff --git a/core/src/test/java/art/arcane/iris/core/pack/DefaultPackBootstrapProvisionerTest.java b/core/src/test/java/art/arcane/iris/core/pack/DefaultPackBootstrapProvisionerTest.java index 481038234..73abb8e36 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/DefaultPackBootstrapProvisionerTest.java +++ b/core/src/test/java/art/arcane/iris/core/pack/DefaultPackBootstrapProvisionerTest.java @@ -726,7 +726,7 @@ public class DefaultPackBootstrapProvisionerTest { private static byte[] packArchive(String dimensionKey, String biomeId) throws IOException { LinkedHashMap files = new LinkedHashMap<>(); files.put("dimensions/" + dimensionKey + ".json", dimensionJson(dimensionKey)); - files.put("regions/local.json", "{\"name\":\"Local\",\"landBiomes\":[\"local\"]}"); + files.put("regions/local.json", "{\"name\":\"Local\",\"landBiomes\":[{\"biome\":\"local\"}]}"); files.put("biomes/local.json", biomeJson(biomeId)); return zip(files); } @@ -735,7 +735,7 @@ public class DefaultPackBootstrapProvisionerTest { LinkedHashMap files = new LinkedHashMap<>(); files.put("dimensions/underworld.json", dimensionJson("underworld")); files.put("dimensions/underworld_roof.json", dimensionJson("underworld_roof")); - files.put("regions/local.json", "{\"name\":\"Local\",\"landBiomes\":[\"local\"]}"); + files.put("regions/local.json", "{\"name\":\"Local\",\"landBiomes\":[{\"biome\":\"local\"}]}"); files.put("biomes/local.json", biomeJson(biomeId)); return zip(files); } @@ -763,12 +763,12 @@ public class DefaultPackBootstrapProvisionerTest { Files.createDirectories(root.resolve("regions")); Files.createDirectories(root.resolve("biomes")); Files.writeString(root.resolve("dimensions/" + dimensionKey + ".json"), dimensionJson(dimensionKey), StandardCharsets.UTF_8); - Files.writeString(root.resolve("regions/local.json"), "{\"name\":\"Local\",\"landBiomes\":[\"local\"]}", StandardCharsets.UTF_8); + Files.writeString(root.resolve("regions/local.json"), "{\"name\":\"Local\",\"landBiomes\":[{\"biome\":\"local\"}]}", StandardCharsets.UTF_8); Files.writeString(root.resolve("biomes/local.json"), biomeJson(biomeId), StandardCharsets.UTF_8); } private static String dimensionJson(String name) { - return "{\"name\":\"" + name + "\",\"regions\":[\"local\"],\"logicalHeight\":256,\"dimensionHeight\":{\"min\":-64,\"max\":320}}"; + return "{\"name\":\"" + name + "\",\"regions\":[{\"region\":\"local\"}],\"logicalHeight\":256,\"dimensionHeight\":{\"min\":-64,\"max\":320}}"; } private static String biomeJson(String biomeId) { diff --git a/core/src/test/java/art/arcane/iris/core/pack/ExportClosureComparisonTest.java b/core/src/test/java/art/arcane/iris/core/pack/ExportClosureComparisonTest.java index 9ee892e3c..7244a7aa2 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/ExportClosureComparisonTest.java +++ b/core/src/test/java/art/arcane/iris/core/pack/ExportClosureComparisonTest.java @@ -200,8 +200,8 @@ public class ExportClosureComparisonTest { private Path fixturePack() throws Exception { File pack = temporaryFolder.newFolder("pack"); - write(pack, "dimensions/main.json", "{\"regions\":[\"region\"],\"structures\":[{\"structures\":[\"castle\"]}]}"); - write(pack, "regions/region.json", "{\"landBiomes\":[\"biome\"]}"); + write(pack, "dimensions/main.json", "{\"regions\":[{\"region\":\"region\"}],\"structures\":[{\"structures\":[\"castle\"]}]}"); + write(pack, "regions/region.json", "{\"landBiomes\":[{\"biome\":\"biome\"}]}"); write(pack, "biomes/biome.json", "{\"name\":\"Biome\",\"objects\":[{\"place\":[\"tree\"]}]}"); write(pack, "structures/castle.json", "{\"startPool\":\"castle/start\",\"loot\":[\"castle/chest\"]}"); write(pack, "structures/unused.json", "{\"startPool\":\"castle/start\"}"); diff --git a/core/src/test/java/art/arcane/iris/core/pack/ModulePackValidationTest.java b/core/src/test/java/art/arcane/iris/core/pack/ModulePackValidationTest.java index 67a1e1171..3d8e78c88 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/ModulePackValidationTest.java +++ b/core/src/test/java/art/arcane/iris/core/pack/ModulePackValidationTest.java @@ -104,8 +104,8 @@ public class ModulePackValidationTest { private File minimalPack(String name) throws Exception { File pack = temporaryFolder.newFolder(name); - write(pack, "dimensions/main.json", "{\"regions\":[\"region\"]}"); - write(pack, "regions/region.json", "{\"landBiomes\":[\"biome\"]}"); + write(pack, "dimensions/main.json", "{\"regions\":[{\"region\":\"region\"}]}"); + write(pack, "regions/region.json", "{\"landBiomes\":[{\"biome\":\"biome\"}]}"); write(pack, "biomes/biome.json", "{\"name\":\"Biome\"}"); return pack; } 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 index 08b3f68d1..7469ecee2 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/ModuleResourceClosureTest.java +++ b/core/src/test/java/art/arcane/iris/core/pack/ModuleResourceClosureTest.java @@ -110,8 +110,8 @@ public class ModuleResourceClosureTest { 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, "dimensions/main.json", "{\"regions\":[{\"region\":\"region\"}],\"loot\":{\"tables\":[\"global\"]},\"entitySpawners\":[\"camp/zombies\"]}"); + write(pack, "regions/region.json", "{\"landBiomes\":[{\"biome\":\"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\"}]}"); diff --git a/core/src/test/java/art/arcane/iris/core/pack/PackBiomeLayerValidatorTest.java b/core/src/test/java/art/arcane/iris/core/pack/PackBiomeLayerValidatorTest.java index 5bf9e13c2..553f7f6d3 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/PackBiomeLayerValidatorTest.java +++ b/core/src/test/java/art/arcane/iris/core/pack/PackBiomeLayerValidatorTest.java @@ -57,8 +57,8 @@ public class PackBiomeLayerValidatorTest { @Test public void independentCeilingLayersPassFullPackValidation() throws Exception { File pack = temporaryFolder.newFolder("pack"); - write(pack, "dimensions/main.json", "{\"regions\":[\"region\"]}"); - write(pack, "regions/region.json", "{\"landBiomes\":[\"biome\"]}"); + write(pack, "dimensions/main.json", "{\"regions\":[{\"region\":\"region\"}]}"); + write(pack, "regions/region.json", "{\"landBiomes\":[{\"biome\":\"biome\"}]}"); write(pack, "biomes/biome.json", "{\"name\":\"Biome\",\"layers\":[{}],\"caveCeilingLayers\":[{},{}]}"); PackValidationResult result = PackValidator.validate(pack); diff --git a/core/src/test/java/art/arcane/iris/core/pack/PackDownloaderTest.java b/core/src/test/java/art/arcane/iris/core/pack/PackDownloaderTest.java index e8bbaf5ef..a774ff3a8 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/PackDownloaderTest.java +++ b/core/src/test/java/art/arcane/iris/core/pack/PackDownloaderTest.java @@ -201,12 +201,12 @@ public class PackDownloaderTest { Path archive = temp.newFile("direct-pack.zip").toPath(); Map entries = new LinkedHashMap<>(); entries.put("README.md", "Direct pack"); - entries.put("wrapped/dimensions/direct_pack.json", "{\"name\":\"Direct\",\"regions\":[\"local\"]," + entries.put("wrapped/dimensions/direct_pack.json", "{\"name\":\"Direct\",\"regions\":[{\"region\":\"local\"}]," + "\"structures\":[{\"nativeStructures\":[{\"structure\":\"test:future_structure\"}]}]," + "\"logicalHeight\":256,\"dimensionHeight\":{\"min\":-64,\"max\":320}}"); - entries.put("wrapped/dimensions/direct_pack_supporting.json", "{\"name\":\"Supporting\",\"regions\":[\"local\"]," + entries.put("wrapped/dimensions/direct_pack_supporting.json", "{\"name\":\"Supporting\",\"regions\":[{\"region\":\"local\"}]," + "\"logicalHeight\":256,\"dimensionHeight\":{\"min\":-64,\"max\":320}}"); - entries.put("wrapped/regions/local.json", "{\"name\":\"Local\",\"landBiomes\":[\"local\"]}"); + entries.put("wrapped/regions/local.json", "{\"name\":\"Local\",\"landBiomes\":[{\"biome\":\"local\"}]}"); entries.put("wrapped/biomes/local.json", "{\"name\":\"Local\",\"derivative\":\"minecraft:plains\"}"); writeArchive(archive, entries); byte[] response = Files.readAllBytes(archive); @@ -917,7 +917,7 @@ public class PackDownloaderTest { writeDimension(root, key); Files.writeString( root.resolve("regions/local.json"), - "{\"name\":\"Local\",\"landBiomes\":[\"local\"]}", + "{\"name\":\"Local\",\"landBiomes\":[{\"biome\":\"local\"}]}", StandardCharsets.UTF_8 ); Files.writeString( @@ -939,7 +939,7 @@ public class PackDownloaderTest { Files.writeString( root.resolve("dimensions/" + key + ".json"), "{\"name\":\"" + key + "\",\"environment\":\"" + environment.name() - + "\",\"regions\":[\"local\"],\"logicalHeight\":256," + + "\",\"regions\":[{\"region\":\"local\"}],\"logicalHeight\":256," + "\"dimensionHeight\":{\"min\":-64,\"max\":320}}", StandardCharsets.UTF_8 ); @@ -951,10 +951,10 @@ public class PackDownloaderTest { LinkedHashMap entries = new LinkedHashMap<>(); entries.put( "wrapped/dimensions/" + key + ".json", - "{\"name\":\"" + key + "\",\"regions\":[\"local\"],\"logicalHeight\":256," + "{\"name\":\"" + key + "\",\"regions\":[{\"region\":\"local\"}],\"logicalHeight\":256," + "\"dimensionHeight\":{\"min\":-64,\"max\":320}}" ); - entries.put("wrapped/regions/local.json", "{\"name\":\"Local\",\"landBiomes\":[\"local\"]}"); + entries.put("wrapped/regions/local.json", "{\"name\":\"Local\",\"landBiomes\":[{\"biome\":\"local\"}]}"); entries.put("wrapped/biomes/local.json", "{\"name\":\"Local\",\"derivative\":\"minecraft:plains\"}"); writeArchive(archive, entries); return Files.readAllBytes(archive); @@ -998,7 +998,7 @@ public class PackDownloaderTest { private static void writeDimension(Path root, String key) throws IOException { Files.writeString( root.resolve("dimensions/" + key + ".json"), - "{\"name\":\"" + key + "\",\"regions\":[\"local\"],\"logicalHeight\":256," + "{\"name\":\"" + key + "\",\"regions\":[{\"region\":\"local\"}],\"logicalHeight\":256," + "\"dimensionHeight\":{\"min\":-64,\"max\":320}}", StandardCharsets.UTF_8 ); diff --git a/core/src/test/java/art/arcane/iris/core/pack/PackGeneratorDuplicateValidatorTest.java b/core/src/test/java/art/arcane/iris/core/pack/PackGeneratorDuplicateValidatorTest.java index 0e24d9e8f..a2ef63262 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/PackGeneratorDuplicateValidatorTest.java +++ b/core/src/test/java/art/arcane/iris/core/pack/PackGeneratorDuplicateValidatorTest.java @@ -90,8 +90,8 @@ public class PackGeneratorDuplicateValidatorTest { @Test public void duplicatesSurfaceAsPackWarningsNotErrors() throws Exception { File pack = temporaryFolder.newFolder("pack"); - write(pack, "dimensions/main.json", "{\"regions\":[\"region\"]}"); - write(pack, "regions/region.json", "{\"landBiomes\":[\"biome\"]}"); + write(pack, "dimensions/main.json", "{\"regions\":[{\"region\":\"region\"}]}"); + write(pack, "regions/region.json", "{\"landBiomes\":[{\"biome\":\"biome\"}]}"); write(pack, "biomes/biome.json", "{\"name\":\"Biome\",\"generators\":[{\"generator\":\"a\"},{\"generator\":\"b\"}]}"); write(pack, "generators/a.json", "{\"seed\":1}"); write(pack, "generators/b.json", "{\"seed\":1}"); diff --git a/core/src/test/java/art/arcane/iris/core/pack/PackImageMapValidatorTest.java b/core/src/test/java/art/arcane/iris/core/pack/PackImageMapValidatorTest.java index 8c0a871b9..5fb096ea0 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/PackImageMapValidatorTest.java +++ b/core/src/test/java/art/arcane/iris/core/pack/PackImageMapValidatorTest.java @@ -48,7 +48,7 @@ public class PackImageMapValidatorTest { public void acceptsCompiledTypedBindingsThroughPackValidator() throws Exception { File pack = createPack("valid", """ { - "regions": ["region"], + "regions": [{"region": "region"}], "worldBoundary": {"center": {"x": 0, "z": 0}, "size": 16}, "imageMaps": [ { @@ -121,7 +121,7 @@ public class PackImageMapValidatorTest { public void reportsBindingReferenceAndApplicationFailuresDeterministically() throws Exception { File pack = createPack("bindings", """ { - "regions": ["region"], + "regions": [{"region": "region"}], "imageMaps": [ { "key": "duplicate", @@ -174,7 +174,7 @@ public class PackImageMapValidatorTest { @Test public void validatesEveryFirstClassResourceBeforeItIsBound() throws Exception { - File pack = createPack("resources", "{\"regions\":[\"region\"]}"); + File pack = createPack("resources", "{\"regions\":[{\"region\":\"region\"}]}"); writeGray(pack, "grayscale", 2, 2); writeRgb(pack, "not-png", 1, 1, "jpeg"); Path corrupt = pack.toPath().resolve("images/corrupt.png"); @@ -209,7 +209,7 @@ public class PackImageMapValidatorTest { public void validatesLegendFilesMappedRegionRolesAndLiveSurfaceBlocks() throws Exception { File pack = createPack("legends", """ { - "regions": ["region"], + "regions": [{"region": "region"}], "imageMaps": [ {"key": "biome", "map": "biome-map", "application": "BIOME"}, {"key": "region", "map": "region-map", "application": "REGION"}, @@ -221,7 +221,7 @@ public class PackImageMapValidatorTest { writeRgb(pack, "region-map", 1, 1, "png"); writeRgb(pack, "surface", 1, 1, "png"); write(pack, "biomes/mapped-biome.json", "{\"name\":\"Mapped\"}"); - write(pack, "regions/mapped-region.json", "{\"landBiomes\":[\"mapped-biome\"]}"); + write(pack, "regions/mapped-region.json", "{\"landBiomes\":[{\"biome\":\"mapped-biome\"}]}"); write(pack, "image-maps/biome-map.json", colorMap("biome", "mapped-biome")); write(pack, "image-maps/region-map.json", colorMap("region-map", "mapped-region")); write(pack, "image-maps/surface-map.json", colorMap("surface", "minecraft:not_real")); @@ -243,7 +243,7 @@ public class PackImageMapValidatorTest { @Test public void validatesReachableGeneratorStyleMapReferences() throws Exception { - File missingPack = createPack("generator-style-missing", "{\"regions\":[\"region\"]}"); + File missingPack = createPack("generator-style-missing", "{\"regions\":[{\"region\":\"region\"}]}"); write(missingPack, "biomes/biome.json", """ {"name":"Biome","generators":[{"generator":"mapped","min":0,"max":1}]} """); @@ -257,7 +257,7 @@ public class PackImageMapValidatorTest { "generator style references missing image-map resource 'absent'")); File colorPack = createPack("generator-style-color", """ - {"regions":["region"],"regionStyle":{"imageMap":"colors"}} + {"regions":[{"region":"region"}],"regionStyle":{"imageMap":"colors"}} """); writeRgb(colorPack, "colors", 1, 1, "png"); write(colorPack, "image-maps/colors.json", colorMap("colors", "biome")); @@ -268,7 +268,7 @@ public class PackImageMapValidatorTest { "must use a scalar map type, not COLOR_MAP")); File errorPack = createPack("generator-style-error", """ - {"regions":["region"],"regionStyle":{"imageMap":"height"}} + {"regions":[{"region":"region"}],"regionStyle":{"imageMap":"height"}} """); writeGray(errorPack, "height", 4, 4); write(errorPack, "image-maps/height.json", """ @@ -285,14 +285,14 @@ public class PackImageMapValidatorTest { public void validatesUpperDimensionCoverageAgainstParentBoundary() throws Exception { File pack = createPack("upper-parent-boundary", """ { - "regions": ["region"], + "regions": [{"region": "region"}], "worldBoundary": {"center": {"x": 0, "z": 0}, "size": 16}, "upperDimension": "upper" } """); write(pack, "dimensions/upper.json", """ { - "regions": ["region"], + "regions": [{"region": "region"}], "worldBoundary": {"center": {"x": 0, "z": 0}, "size": 2}, "imageMaps": [ {"key": "terrain", "map": "upper-terrain", "application": "TERRAIN_HEIGHT"} @@ -321,14 +321,14 @@ public class PackImageMapValidatorTest { public void acceptsUpperDimensionWithoutStandaloneBoundaryWhenParentIsCovered() throws Exception { File pack = createPack("upper-parent-only-boundary", """ { - "regions": ["region"], + "regions": [{"region": "region"}], "worldBoundary": {"center": {"x": 0, "z": 0}, "size": 4}, "upperDimension": "upper" } """); write(pack, "dimensions/upper.json", """ { - "regions": ["region"], + "regions": [{"region": "region"}], "imageMaps": [ {"key": "terrain", "map": "upper-terrain", "application": "TERRAIN_HEIGHT"} ] @@ -356,14 +356,14 @@ public class PackImageMapValidatorTest { public void validatesDeclaredUpperBoundaryAlongsideParentBoundary() throws Exception { File pack = createPack("upper-own-and-parent-boundary", """ { - "regions": ["region"], + "regions": [{"region": "region"}], "worldBoundary": {"center": {"x": 0, "z": 0}, "size": 4}, "upperDimension": "upper" } """); write(pack, "dimensions/upper.json", """ { - "regions": ["region"], + "regions": [{"region": "region"}], "worldBoundary": {"center": {"x": 0, "z": 0}, "size": 16}, "imageMaps": [ {"key": "terrain", "map": "upper-terrain", "application": "TERRAIN_HEIGHT"} @@ -392,7 +392,7 @@ public class PackImageMapValidatorTest { public void enforcesTerrainHeightRangeAfterOffsetAndClamp() throws Exception { File unclamped = createPack("height-unclamped", """ { - "regions": ["region"], + "regions": [{"region": "region"}], "dimensionHeight": {"min": 0, "max": 64}, "imageMaps": [ {"key": "terrain", "map": "terrain", "application": "TERRAIN_HEIGHT"} @@ -419,7 +419,7 @@ public class PackImageMapValidatorTest { File clamped = createPack("height-clamped", """ { - "regions": ["region"], + "regions": [{"region": "region"}], "dimensionHeight": {"min": 0, "max": 64}, "imageMaps": [ {"key": "terrain", "map": "terrain", "application": "TERRAIN_HEIGHT"} @@ -455,7 +455,7 @@ public class PackImageMapValidatorTest { private File createPack(String name, String dimension) throws Exception { File pack = temporaryFolder.newFolder(name); write(pack, "dimensions/main.json", dimension); - write(pack, "regions/region.json", "{\"landBiomes\":[\"biome\"]}"); + write(pack, "regions/region.json", "{\"landBiomes\":[{\"biome\":\"biome\"}]}"); write(pack, "biomes/biome.json", "{\"name\":\"Biome\"}"); return pack; } @@ -464,7 +464,7 @@ public class PackImageMapValidatorTest { String boundary = boundarySize == null ? "" : ",\"worldBoundary\":{\"center\":{\"x\":0,\"z\":0},\"size\":" + boundarySize + "}"; - return "{\"regions\":[\"region\"]" + boundary + return "{\"regions\":[{\"region\":\"region\"}]" + boundary + ",\"imageMaps\":[{\"key\":\"terrain\",\"map\":\"terrain\"," + "\"application\":\"TERRAIN_HEIGHT\"}]}"; } diff --git a/core/src/test/java/art/arcane/iris/core/pack/PackStyledRangeDefaultValidatorTest.java b/core/src/test/java/art/arcane/iris/core/pack/PackStyledRangeDefaultValidatorTest.java index da8643075..9b8a57257 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/PackStyledRangeDefaultValidatorTest.java +++ b/core/src/test/java/art/arcane/iris/core/pack/PackStyledRangeDefaultValidatorTest.java @@ -82,8 +82,8 @@ public class PackStyledRangeDefaultValidatorTest { @Test public void emptyDensityStyleBlocksFullPackValidation() throws Exception { File pack = temporaryFolder.newFolder("pack"); - write(pack, "dimensions/main.json", "{\"regions\":[\"region\"]}"); - write(pack, "regions/region.json", "{\"landBiomes\":[\"biome\"]}"); + write(pack, "dimensions/main.json", "{\"regions\":[{\"region\":\"region\"}]}"); + write(pack, "regions/region.json", "{\"landBiomes\":[{\"biome\":\"biome\"}]}"); write(pack, "biomes/biome.json", "{\"name\":\"Biome\",\"objects\":[{\"place\":[\"o\"],\"densityStyle\":{}}]}"); PackValidationResult result = PackValidator.validate(pack); diff --git a/core/src/test/java/art/arcane/iris/core/pack/PackValidatorDimensionHeightTest.java b/core/src/test/java/art/arcane/iris/core/pack/PackValidatorDimensionHeightTest.java index ddda819da..78b8a142b 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/PackValidatorDimensionHeightTest.java +++ b/core/src/test/java/art/arcane/iris/core/pack/PackValidatorDimensionHeightTest.java @@ -24,7 +24,7 @@ public class PackValidatorDimensionHeightTest { @Test public void rejectsNonMultipleOfSixteenSpan() throws Exception { - PackValidationResult result = validate("{\"regions\":[\"region\"],\"dimensionHeight\":{\"min\":-64,\"max\":300}}"); + PackValidationResult result = validate("{\"regions\":[{\"region\":\"region\"}],\"dimensionHeight\":{\"min\":-64,\"max\":300}}"); assertFalse(result.isLoadable()); assertTrue(result.getBlockingErrors().contains( @@ -33,7 +33,7 @@ public class PackValidatorDimensionHeightTest { @Test public void rejectsMinYNotMultipleOfSixteen() throws Exception { - PackValidationResult result = validate("{\"regions\":[\"region\"],\"dimensionHeight\":{\"min\":-60,\"max\":324}}"); + PackValidationResult result = validate("{\"regions\":[{\"region\":\"region\"}],\"dimensionHeight\":{\"min\":-60,\"max\":324}}"); assertFalse(result.isLoadable()); assertTrue(result.getBlockingErrors().contains( @@ -42,17 +42,17 @@ public class PackValidatorDimensionHeightTest { @Test public void rejectsSpanOutsideBounds() throws Exception { - assertTrue(validate("{\"regions\":[\"region\"],\"dimensionHeight\":{\"min\":0,\"max\":0}}") + assertTrue(validate("{\"regions\":[{\"region\":\"region\"}],\"dimensionHeight\":{\"min\":0,\"max\":0}}") .getBlockingErrors().contains( "Dimension 'main' dimensionHeight span (max - min) is 0; it must be between 16 and 4064.")); - assertTrue(validate("{\"regions\":[\"region\"],\"dimensionHeight\":{\"min\":-2032,\"max\":2048}}") + assertTrue(validate("{\"regions\":[{\"region\":\"region\"}],\"dimensionHeight\":{\"min\":-2032,\"max\":2048}}") .getBlockingErrors().contains( "Dimension 'main' dimensionHeight span (max - min) is 4080; it must be between 16 and 4064.")); } @Test public void rejectsMinYOutsideBounds() throws Exception { - assertTrue(validate("{\"regions\":[\"region\"],\"dimensionHeight\":{\"min\":-2048,\"max\":-1664}}") + assertTrue(validate("{\"regions\":[{\"region\":\"region\"}],\"dimensionHeight\":{\"min\":-2048,\"max\":-1664}}") .getBlockingErrors().contains( "Dimension 'main' dimensionHeight.min is -2048; it must be between -2032 and 2031.")); } @@ -60,7 +60,7 @@ public class PackValidatorDimensionHeightTest { @Test public void rejectsLogicalHeightAboveTotalHeight() throws Exception { PackValidationResult result = validate( - "{\"regions\":[\"region\"],\"logicalHeight\":512,\"dimensionHeight\":{\"min\":-64,\"max\":320}}"); + "{\"regions\":[{\"region\":\"region\"}],\"logicalHeight\":512,\"dimensionHeight\":{\"min\":-64,\"max\":320}}"); assertFalse(result.isLoadable()); assertTrue(result.getBlockingErrors().contains( @@ -70,21 +70,21 @@ public class PackValidatorDimensionHeightTest { @Test public void acceptsShippingOverworldShape() throws Exception { PackValidationResult result = validate( - "{\"regions\":[\"region\"],\"logicalHeight\":512,\"dimensionHeight\":{\"min\":-256,\"max\":512}}"); + "{\"regions\":[{\"region\":\"region\"}],\"logicalHeight\":512,\"dimensionHeight\":{\"min\":-256,\"max\":512}}"); assertTrue(result.getBlockingErrors().toString(), result.isLoadable()); } @Test public void acceptsDimensionWithoutExplicitHeight() throws Exception { - PackValidationResult result = validate("{\"regions\":[\"region\"]}"); + PackValidationResult result = validate("{\"regions\":[{\"region\":\"region\"}]}"); assertTrue(result.getBlockingErrors().toString(), result.isLoadable()); } @Test public void resolvesDimensionHeightSnippet() throws Exception { - File pack = pack("{\"regions\":[\"region\"],\"dimensionHeight\":\"snippet/range/tall\"}"); + File pack = pack("{\"regions\":[{\"region\":\"region\"}],\"dimensionHeight\":\"snippet/range/tall\"}"); write(pack, "snippet/range/tall.json", "{\"min\":-60,\"max\":324}"); PackValidationResult result = PackValidator.validate(pack); @@ -135,7 +135,7 @@ public class PackValidatorDimensionHeightTest { private File pack(String dimensionJson) throws Exception { File pack = temporaryFolder.newFolder("pack-" + System.nanoTime()); write(pack, "dimensions/main.json", dimensionJson); - write(pack, "regions/region.json", "{\"landBiomes\":[\"biome\"]}"); + write(pack, "regions/region.json", "{\"landBiomes\":[{\"biome\":\"biome\"}]}"); write(pack, "biomes/biome.json", "{\"name\":\"Biome\"}"); return pack; } diff --git a/core/src/test/java/art/arcane/iris/core/pack/PackValidatorHostFilesParseTest.java b/core/src/test/java/art/arcane/iris/core/pack/PackValidatorHostFilesParseTest.java index 4232b40a3..6d0aeec67 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/PackValidatorHostFilesParseTest.java +++ b/core/src/test/java/art/arcane/iris/core/pack/PackValidatorHostFilesParseTest.java @@ -21,7 +21,7 @@ public class PackValidatorHostFilesParseTest { public void reportsEachDimensionRegionAndBiomeFileThatIsNotJson() throws Exception { File pack = temporaryFolder.newFolder("pack"); write(pack, "dimensions/main.json", "{"); - write(pack, "regions/nested/region.json", "{\"landBiomes\":[\"biome\"]}"); + write(pack, "regions/nested/region.json", "{\"landBiomes\":[{\"biome\":\"biome\"}]}"); write(pack, "biomes/nested/biome.json", "not json"); List errors = PackObjectSurfaceValidator.validateHostFilesParse(pack); diff --git a/core/src/test/java/art/arcane/iris/core/pack/PackValidatorImportedStructurePolicyTest.java b/core/src/test/java/art/arcane/iris/core/pack/PackValidatorImportedStructurePolicyTest.java index 1976c851e..0a3fa53df 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/PackValidatorImportedStructurePolicyTest.java +++ b/core/src/test/java/art/arcane/iris/core/pack/PackValidatorImportedStructurePolicyTest.java @@ -77,8 +77,8 @@ public class PackValidatorImportedStructurePolicyTest { /** The blocking errors of a pack whose one dimension declares {@code policy} as its {@code importedStructures}. */ private List validate(String policy) throws Exception { File pack = temporaryFolder.newFolder("pack"); - write(pack, "dimensions/main.json", "{\"regions\": [\"region\"], \"importedStructures\": " + policy + "}"); - write(pack, "regions/region.json", "{\"landBiomes\": [\"biome\"]}"); + write(pack, "dimensions/main.json", "{\"regions\": [{\"region\": \"region\"}], \"importedStructures\": " + policy + "}"); + write(pack, "regions/region.json", "{\"landBiomes\": [{\"biome\": \"biome\"}]}"); write(pack, "biomes/biome.json", "{\"name\": \"Biome\"}"); return PackValidator.validate(pack).getBlockingErrors(); } diff --git a/core/src/test/java/art/arcane/iris/core/pack/PackValidatorReadOnlyTest.java b/core/src/test/java/art/arcane/iris/core/pack/PackValidatorReadOnlyTest.java index bf0965f72..271aae508 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/PackValidatorReadOnlyTest.java +++ b/core/src/test/java/art/arcane/iris/core/pack/PackValidatorReadOnlyTest.java @@ -24,8 +24,8 @@ public class PackValidatorReadOnlyTest { @Test public void validationDoesNotMoveOrRewritePackFiles() throws Exception { File pack = temporaryFolder.newFolder("pack"); - write(pack, "dimensions/main.json", "{\"regions\":[\"region\"]}"); - write(pack, "regions/region.json", "{\"landBiomes\":[\"biome\"]}"); + write(pack, "dimensions/main.json", "{\"regions\":[{\"region\":\"region\"}]}"); + write(pack, "regions/region.json", "{\"landBiomes\":[{\"biome\":\"biome\"}]}"); write(pack, "biomes/biome.json", "{\"name\":\"Biome\"}"); write(pack, "generators/unused.json", "{\"name\":\"Unused\"}"); Map before = snapshot(pack.toPath()); diff --git a/core/src/test/java/art/arcane/iris/core/pack/PackValidatorStructureGraphTest.java b/core/src/test/java/art/arcane/iris/core/pack/PackValidatorStructureGraphTest.java index e6a527048..a80ef362b 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/PackValidatorStructureGraphTest.java +++ b/core/src/test/java/art/arcane/iris/core/pack/PackValidatorStructureGraphTest.java @@ -209,7 +209,7 @@ public class PackValidatorStructureGraphTest { public void rejectsDuplicatePlacementIdsAcrossResources() throws Exception { File pack = pack("\"structures\":[{\"placementId\":\"shared\"," + "\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"}]}]"); - write(pack, "regions/region.json", "{\"landBiomes\":[\"biome\"],\"structures\":[{\"placementId\":\"shared\"," + write(pack, "regions/region.json", "{\"landBiomes\":[{\"biome\":\"biome\"}],\"structures\":[{\"placementId\":\"shared\"," + "\"nativeStructures\":[{\"structure\":\"minecraft:village_plains\"}]}]}"); List errors = blockingErrors(pack); @@ -220,7 +220,7 @@ public class PackValidatorStructureGraphTest { @Test public void rejectsCanonicalAnonymousGridDuplicatesAcrossResources() throws Exception { File pack = pack("\"structures\":[{\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"}]}]"); - write(pack, "regions/region.json", "{\"landBiomes\":[\"biome\"],\"structures\":[{" + write(pack, "regions/region.json", "{\"landBiomes\":[{\"biome\":\"biome\"}],\"structures\":[{" + "\"spacing\":32,\"separation\":8,\"density\":0.02," + "\"nativeStructures\":[{\"weight\":1,\"structure\":\"minecraft:ancient_city\"}]}]}"); @@ -424,10 +424,10 @@ public class PackValidatorStructureGraphTest { public void fullPackValidationRejectsReplacementOutsideDimensionEnvelope() throws Exception { File pack = replacementPack("full-pack-below", "STRUCTURE_PIECE", true, -80, -80); write(pack, "dimensions/main.json", "{\"dimensionHeight\":{\"min\":-64,\"max\":320}," - + "\"regions\":[\"region\"],\"structures\":[{\"structures\":[\"city\"]," + + "\"regions\":[{\"region\":\"region\"}],\"structures\":[{\"structures\":[\"city\"]," + "\"nativeSuppression\":\"REPLACE_SOURCE\",\"underground\":true," + "\"minHeight\":-80,\"maxHeight\":-80}]}"); - write(pack, "regions/region.json", "{\"landBiomes\":[\"biome\"]}"); + write(pack, "regions/region.json", "{\"landBiomes\":[{\"biome\":\"biome\"}]}"); write(pack, "biomes/biome.json", "{\"name\":\"Biome\"}"); write(pack, "structures/city.json", "{\"startPool\":\"city/start\"," + "\"vanillaSource\":\"minecraft:ancient_city\",\"placeMode\":\"STRUCTURE_PIECE\"}"); @@ -447,8 +447,8 @@ public class PackValidatorStructureGraphTest { public void fullPackValidationPreservesMalformedActiveObjectPathAndReason() throws Exception { File pack = temporaryFolder.newFolder("malformed-active-object"); write(pack, "dimensions/main.json", "{\"dimensionHeight\":{\"min\":-64,\"max\":320}," - + "\"regions\":[\"region\"],\"structures\":[{\"structures\":[\"castle\"]}]}"); - write(pack, "regions/region.json", "{\"landBiomes\":[\"biome\"]}"); + + "\"regions\":[{\"region\":\"region\"}],\"structures\":[{\"structures\":[\"castle\"]}]}"); + write(pack, "regions/region.json", "{\"landBiomes\":[{\"biome\":\"biome\"}]}"); write(pack, "biomes/biome.json", "{\"name\":\"Biome\"}"); write(pack, "structures/castle.json", "{\"startPool\":\"castle/start\"}"); write(pack, "jigsaw-pools/castle/start.json", @@ -478,8 +478,8 @@ public class PackValidatorStructureGraphTest { private File pack(String dimensionMembers) throws Exception { File pack = temporaryFolder.newFolder("pack"); String members = dimensionMembers.isEmpty() ? "" : ", " + dimensionMembers; - write(pack, "dimensions/main.json", "{\"regions\": [\"region\"]" + members + "}"); - write(pack, "regions/region.json", "{\"landBiomes\": [\"biome\"]}"); + write(pack, "dimensions/main.json", "{\"regions\": [{\"region\": \"region\"}]" + members + "}"); + write(pack, "regions/region.json", "{\"landBiomes\": [{\"biome\": \"biome\"}]}"); write(pack, "biomes/biome.json", "{\"name\": \"Biome\"}"); return pack; } diff --git a/core/src/test/java/art/arcane/iris/core/pack/PackValidatorStructureTerrainBackendTest.java b/core/src/test/java/art/arcane/iris/core/pack/PackValidatorStructureTerrainBackendTest.java index a2b1b5525..26b0c8226 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/PackValidatorStructureTerrainBackendTest.java +++ b/core/src/test/java/art/arcane/iris/core/pack/PackValidatorStructureTerrainBackendTest.java @@ -25,8 +25,8 @@ public class PackValidatorStructureTerrainBackendTest { for (String mode : List.of("VACUUM", "ENCASE")) { String packName = "editable-" + mode.toLowerCase(Locale.ROOT); File pack = temporaryFolder.newFolder(packName); - write(pack, "dimensions/main.json", "{\"regions\":[\"forest\"]," + placement("dimension", "city", false, mode) + "}"); - write(pack, "regions/forest.json", "{\"landBiomes\":[\"plains\"]," + placement("region", "tower", false, mode) + "}"); + write(pack, "dimensions/main.json", "{\"regions\":[{\"region\":\"forest\"}]," + placement("dimension", "city", false, mode) + "}"); + write(pack, "regions/forest.json", "{\"landBiomes\":[{\"biome\":\"plains\"}]," +placement("region", "tower", false, mode) + "}"); write(pack, "biomes/plains.json", "{\"name\":\"Plains\"," + placement("biome", "farm", false, mode) + "}"); for (String structure : List.of("city", "tower", "farm")) { write(pack, "structures/" + structure + ".json", "{\"startPool\":\"start\"}"); @@ -67,8 +67,8 @@ public class PackValidatorStructureTerrainBackendTest { private File singleDimensionPack(String packName, String dimensionMembers) throws Exception { File pack = temporaryFolder.newFolder(packName); - write(pack, "dimensions/main.json", "{\"regions\":[\"region\"]," + dimensionMembers + "}"); - write(pack, "regions/region.json", "{\"landBiomes\":[\"biome\"]}"); + write(pack, "dimensions/main.json", "{\"regions\":[{\"region\":\"region\"}]," + dimensionMembers + "}"); + write(pack, "regions/region.json", "{\"landBiomes\":[{\"biome\":\"biome\"}]}"); write(pack, "biomes/biome.json", "{\"name\":\"Biome\"}"); return pack; } diff --git a/core/src/test/java/art/arcane/iris/core/pack/PackValidatorSurfaceSupportTest.java b/core/src/test/java/art/arcane/iris/core/pack/PackValidatorSurfaceSupportTest.java index d5b25cfc1..934124be2 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/PackValidatorSurfaceSupportTest.java +++ b/core/src/test/java/art/arcane/iris/core/pack/PackValidatorSurfaceSupportTest.java @@ -51,8 +51,8 @@ public class PackValidatorSurfaceSupportTest { public void surfaceSupportErrorsBlockFullPackValidation() throws Exception { File pack = temporaryFolder.newFolder("pack"); write(pack, "dimensions/main.json", - "{\"regions\":[\"region\"],\"objectSurfaceSupportBuffer\":99}"); - write(pack, "regions/region.json", "{\"landBiomes\":[\"biome\"]}"); + "{\"regions\":[{\"region\":\"region\"}],\"objectSurfaceSupportBuffer\":99}"); + write(pack, "regions/region.json", "{\"landBiomes\":[{\"biome\":\"biome\"}]}"); write(pack, "biomes/biome.json", "{\"name\":\"Biome\"}"); PackValidationResult result = PackValidator.validate(pack); diff --git a/core/src/test/java/art/arcane/iris/core/project/ImageMapStudioExporterTest.java b/core/src/test/java/art/arcane/iris/core/project/ImageMapStudioExporterTest.java index 4b0b6a858..14abd2327 100644 --- a/core/src/test/java/art/arcane/iris/core/project/ImageMapStudioExporterTest.java +++ b/core/src/test/java/art/arcane/iris/core/project/ImageMapStudioExporterTest.java @@ -217,8 +217,8 @@ public class ImageMapStudioExporterTest { private File minimalPack(String name) throws Exception { File pack = temporaryFolder.newFolder(name); - write(pack, "dimensions/main.json", "{\"regions\":[\"region\"]}"); - write(pack, "regions/region.json", "{\"landBiomes\":[\"biome\"]}"); + write(pack, "dimensions/main.json", "{\"regions\":[{\"region\":\"region\"}]}"); + write(pack, "regions/region.json", "{\"landBiomes\":[{\"biome\":\"biome\"}]}"); write(pack, "biomes/biome.json", "{\"name\":\"Biome\"}"); return pack; } diff --git a/core/src/test/java/art/arcane/iris/core/service/StudioSVCWorldPackPublishTest.java b/core/src/test/java/art/arcane/iris/core/service/StudioSVCWorldPackPublishTest.java index bb6ee861d..437dcbaa6 100644 --- a/core/src/test/java/art/arcane/iris/core/service/StudioSVCWorldPackPublishTest.java +++ b/core/src/test/java/art/arcane/iris/core/service/StudioSVCWorldPackPublishTest.java @@ -449,8 +449,8 @@ public class StudioSVCWorldPackPublishTest { Files.createDirectories(packRoot.resolve("dimensions")); Files.createDirectories(packRoot.resolve("regions")); Files.createDirectories(packRoot.resolve("biomes")); - Files.writeString(packRoot.resolve("dimensions/main.json"), "{\"regions\":[\"region\"]}"); - Files.writeString(packRoot.resolve("regions/region.json"), "{\"landBiomes\":[\"biome\"]}"); + Files.writeString(packRoot.resolve("dimensions/main.json"), "{\"regions\":[{\"region\":\"region\"}]}"); + Files.writeString(packRoot.resolve("regions/region.json"), "{\"landBiomes\":[{\"biome\":\"biome\"}]}"); Files.writeString(packRoot.resolve("biomes/biome.json"), "{\"name\":\"Biome\"}"); } } diff --git a/core/src/test/java/art/arcane/iris/core/studio/map/MapPickInspectionTest.java b/core/src/test/java/art/arcane/iris/core/studio/map/MapPickInspectionTest.java index 3b0b39359..f10ee8034 100644 --- a/core/src/test/java/art/arcane/iris/core/studio/map/MapPickInspectionTest.java +++ b/core/src/test/java/art/arcane/iris/core/studio/map/MapPickInspectionTest.java @@ -45,7 +45,7 @@ public class MapPickInspectionTest { dry.spreads().stream().map(MapPickInspection.Spread::title).toList()); assertRow(dry.spreads().get(0).rows().get(0), "plains", 0.5D, 1D); MapPickInspection.Spread plainsChildren = dry.spreads().get(1); - assertEquals("meadow's slot and plains' two slots are two bands", 2, plainsChildren.rows().size()); + assertEquals("meadow and plains are two bands", 2, plainsChildren.rows().size()); assertRow(plainsChildren.rows().get(0), "meadow", 0.25D, 1D); } diff --git a/core/src/test/java/art/arcane/iris/core/studio/map/MapPickPathTest.java b/core/src/test/java/art/arcane/iris/core/studio/map/MapPickPathTest.java index 3148986dc..67d1016fb 100644 --- a/core/src/test/java/art/arcane/iris/core/studio/map/MapPickPathTest.java +++ b/core/src/test/java/art/arcane/iris/core/studio/map/MapPickPathTest.java @@ -2,6 +2,7 @@ package art.arcane.iris.core.studio.map; import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.object.world.biome.InferredType; +import com.volmit.world.Weighted; import org.junit.Test; import java.util.List; @@ -36,7 +37,7 @@ public class MapPickPathTest { } @Test - public void aChildStepJoinsNeighbouringSlotsOfOneBiome() { + public void aChildStepHasABandForEveryEntryAsWideAsItsWeight() { List bands = explain(MapLayer.of(MapView.BIOMES)).get(2).bands(); assertEquals(2, bands.size()); @@ -73,11 +74,15 @@ public class MapPickPathTest { } @Test - public void slotsRoundTheWayTheChildNoiseDoes() { - assertEquals(0, ChildPicks.slotIndex(0.24D, 3)); - assertEquals(1, ChildPicks.slotIndex(0.26D, 3)); - assertEquals(2, ChildPicks.slotIndex(1.4D, 3)); - assertEquals(0, ChildPicks.slotIndex(0.9D, 1)); + public void aBiomeListedTwiceGetsABandForEachOfItsEntries() { + List bands = MapPickPath.weightBands( + List.of(new Weighted<>("barren", 5), new Weighted<>("forest", 2), new Weighted<>("barren", 3)), + key -> new MapLabel(MapLabel.Kind.BIOME, key, key, 0)); + + assertEquals(3, bands.size()); + assertBand(bands.get(0), "barren", 0D, 0.5D); + assertBand(bands.get(1), "forest", 0.5D, 0.7D); + assertBand(bands.get(2), "barren", 0.7D, 1D); } private List explain(MapLayer layer) { diff --git a/core/src/test/java/art/arcane/iris/core/studio/map/PickedWorld.java b/core/src/test/java/art/arcane/iris/core/studio/map/PickedWorld.java index 0d9e7d075..8770e0546 100644 --- a/core/src/test/java/art/arcane/iris/core/studio/map/PickedWorld.java +++ b/core/src/test/java/art/arcane/iris/core/studio/map/PickedWorld.java @@ -8,11 +8,14 @@ import art.arcane.iris.engine.framework.render.RenderType; import art.arcane.iris.engine.image.IrisImageMapRuntime; 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.biome.IrisBiomeEntry; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.engine.object.world.region.IrisRegionEntry; import art.arcane.iris.util.project.noise.CNG; import art.arcane.iris.util.project.stream.ProceduralStream; import art.arcane.volmlib.util.collection.KList; +import com.volmit.world.Weighted; import java.awt.Color; import java.util.List; @@ -24,30 +27,31 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** - * A world that picks the same way at every spot: a dry region (rarity 3, so the last quarter of the region noise) - * picked at 0.9; its land list picks plains at 0.2; plains' child noise at 0.1 rounds to its first slot, meadow; - * meadow's at 0.8 rounds to its last slot, itself. + * A world that picks the same way at every spot: a dry region (weight 1 against 3, so the last quarter of the region + * noise) picked at 0.9; its land list picks plains at 0.2; plains' child noise at 0.1 lands in its first quarter, + * meadow; meadow's at 0.8 lands in its last half, itself. */ final class PickedWorld { final Engine engine = mock(Engine.class); final IrisComplex complex = mock(IrisComplex.class); - final IrisBiome plains = biome("plains", "Plains", 1); - final IrisBiome forest = biome("forest", "Forest", 1); - final IrisBiome meadow = biome("meadow", "Meadow", 1); - final IrisBiome glade = biome("glade", "Glade", 1); - final IrisRegion warm = region("warm", "Warm", 1); - final IrisRegion dry = region("dry", "Dry", 3); + final IrisBiome plains = biome("plains", "Plains"); + final IrisBiome forest = biome("forest", "Forest"); + final IrisBiome meadow = biome("meadow", "Meadow"); + final IrisBiome glade = biome("glade", "Glade"); + final IrisRegion warm = region("warm", "Warm"); + final IrisRegion dry = region("dry", "Dry"); final IrisImageMapRuntime imageMap = mock(IrisImageMapRuntime.class); PickedWorld() { when(engine.getComplex()).thenReturn(complex); IrisDimension dimension = mock(IrisDimension.class); - when(dimension.getRegions()).thenReturn(new KList<>(List.of("warm", "dry"))); + when(dimension.getRegions()).thenReturn(new KList<>(List.of(new IrisRegionEntry("warm", 3), new IrisRegionEntry("dry", 1)))); when(engine.getDimension()).thenReturn(dimension); IrisData data = mock(IrisData.class); @SuppressWarnings("unchecked") ResourceLoader regionLoader = mock(ResourceLoader.class); - when(regionLoader.loadAll(any(KList.class))).thenReturn(new KList<>(List.of(warm, dry))); + when(regionLoader.load("warm")).thenReturn(warm); + when(regionLoader.load("dry")).thenReturn(dry); when(data.getRegionLoader()).thenReturn(regionLoader); when(engine.getData()).thenReturn(data); when(complex.getImageMapRuntime()).thenReturn(imageMap); @@ -60,26 +64,25 @@ final class PickedWorld { when(complex.getRegionStream()).thenReturn(regions); when(complex.getRegionStyleStream()).thenReturn(regionNoise); when(complex.getBridgeStream()).thenReturn(continents); - when(complex.pickableBiomes(dry, InferredType.LAND)).thenReturn(new KList<>(List.of(plains, forest))); + when(complex.pickableBiomes(dry, InferredType.LAND)).thenReturn(new KList<>(List.of(new Weighted<>(plains, 1), new Weighted<>(forest, 1)))); when(complex.biomePickNoise(dry, InferredType.LAND)).thenReturn(landNoise); when(complex.biomePicks(dry, InferredType.LAND)).thenReturn(landPicks); - children(plains, List.of(meadow, plains, plains), 0.1D); - children(meadow, List.of(glade, meadow), 0.8D); + children(plains, List.of(new Weighted<>(meadow, 1), new Weighted<>(plains, 3)), 0.1D); + children(meadow, List.of(new Weighted<>(glade, 1), new Weighted<>(meadow, 1)), 0.8D); } - private void children(IrisBiome parent, List slots, double noise) { - when(parent.getChildren()).thenReturn(new KList<>(List.of("child"))); - when(complex.childSlots(parent)).thenReturn(slots); + private void children(IrisBiome parent, List> options, double noise) { + when(parent.getChildren()).thenReturn(new KList<>(List.of(new IrisBiomeEntry("child", 1)))); + when(complex.childOptions(parent)).thenReturn(new KList<>(options)); CNG childNoise = mock(CNG.class); when(childNoise.noiseFast2D(anyDouble(), anyDouble())).thenReturn(noise); when(complex.childNoise(parent)).thenReturn(childNoise); } - private IrisBiome biome(String key, String name, int rarity) { + private IrisBiome biome(String key, String name) { IrisBiome biome = mock(IrisBiome.class); when(biome.getLoadKey()).thenReturn(key); when(biome.getName()).thenReturn(name); - when(biome.getRarity()).thenReturn(rarity); when(biome.getChildren()).thenReturn(new KList<>()); when(biome.getInferredType()).thenReturn(InferredType.LAND); when(biome.withInferredType(any(InferredType.class))).thenReturn(biome); @@ -87,11 +90,10 @@ final class PickedWorld { return biome; } - private IrisRegion region(String key, String name, int rarity) { + private IrisRegion region(String key, String name) { IrisRegion region = mock(IrisRegion.class); when(region.getLoadKey()).thenReturn(key); when(region.getName()).thenReturn(name); - when(region.getRarity()).thenReturn(rarity); when(region.getColor(complex, RenderType.REGION)).thenReturn(Color.ORANGE); return region; } diff --git a/core/src/test/java/art/arcane/iris/engine/IrisComplexImplodeParityTest.java b/core/src/test/java/art/arcane/iris/engine/IrisComplexImplodeParityTest.java deleted file mode 100644 index f1239316b..000000000 --- a/core/src/test/java/art/arcane/iris/engine/IrisComplexImplodeParityTest.java +++ /dev/null @@ -1,92 +0,0 @@ -package art.arcane.iris.engine; - -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - -public class IrisComplexImplodeParityTest { - private static Method childSelectionCreateMethod; - private static Method childSelectionSelectMethod; - - @BeforeClass - public static void setup() throws Exception { - Class childSelectionClass = Class.forName("art.arcane.iris.engine.IrisComplex$ChildSelectionPlan"); - childSelectionCreateMethod = childSelectionClass.getDeclaredMethod("create", KList.class); - childSelectionCreateMethod.setAccessible(true); - childSelectionSelectMethod = childSelectionClass.getDeclaredMethod("select", CNG.class, double.class, double.class); - childSelectionSelectMethod.setAccessible(true); - } - - @Test - public void selectionPlanMatchesLegacyFitRarityAcrossSeedAndCoordinateGrid() throws Exception { - List> scenarios = buildScenarios(); - for (int scenarioIndex = 0; scenarioIndex < scenarios.size(); scenarioIndex++) { - KList options = scenarios.get(scenarioIndex); - Object selectionPlan = childSelectionCreateMethod.invoke(null, options); - for (long seed = 1L; seed <= 7L; seed++) { - CNG generator = new CNG(new RNG(seed), 4); - for (int x = -512; x <= 512; x += 37) { - for (int z = -512; z <= 512; z += 41) { - IrisBiome expected = generator.fitRarity(options, x, z); - IrisBiome actual = (IrisBiome) childSelectionSelectMethod.invoke(selectionPlan, generator, (double) x, (double) z); - assertSame("scenario=" + scenarioIndex + " seed=" + seed + " x=" + x + " z=" + z, expected, actual); - } - } - } - } - } - - @Test - public void emptySelectionPlanMatchesLegacyEmptyBehavior() throws Exception { - KList options = new KList<>(); - CNG generator = new CNG(new RNG(9L), 2); - Object selectionPlan = childSelectionCreateMethod.invoke(null, options); - IrisBiome expected = generator.fitRarity(options, 12D, -32D); - IrisBiome actual = (IrisBiome) childSelectionSelectMethod.invoke(selectionPlan, generator, 12D, -32D); - assertNull(expected); - assertNull(actual); - } - - private List> buildScenarios() { - List> scenarios = new ArrayList<>(); - - KList scenarioA = new KList<>(); - scenarioA.add(createBiome(1)); - scenarioA.add(createBiome(3)); - scenarioA.add(createBiome(5)); - scenarioA.add(createBiome(2)); - scenarios.add(scenarioA); - - KList scenarioB = new KList<>(); - scenarioB.add(createBiome(7)); - scenarioB.add(createBiome(2)); - scenarioB.add(createBiome(2)); - scenarioB.add(createBiome(6)); - scenarioB.add(createBiome(1)); - scenarios.add(scenarioB); - - KList scenarioC = new KList<>(); - scenarioC.add(createBiome(4)); - scenarios.add(scenarioC); - - return scenarios; - } - - private IrisBiome createBiome(int rarity) { - IrisBiome biome = mock(IrisBiome.class); - doReturn(rarity).when(biome).getRarity(); - return biome; - } -} diff --git a/core/src/test/java/art/arcane/iris/engine/framework/HintedLocatorTest.java b/core/src/test/java/art/arcane/iris/engine/framework/HintedLocatorTest.java index 4e6c4cadf..7e887b970 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/HintedLocatorTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/HintedLocatorTest.java @@ -10,6 +10,7 @@ import art.arcane.iris.core.modules.ModuleSettings; import art.arcane.iris.engine.mantle.components.ObjectModule; import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.biome.IrisBiomeEntry; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.spi.IrisPlatform; @@ -121,10 +122,10 @@ public class HintedLocatorTest { return ObjectPlacement.builder().place(List.of(objectKey)).build(); } - private static KList keys(String... values) { - KList list = new KList<>(); + private static KList keys(String... values) { + KList list = new KList<>(); for (String value : values) { - list.add(value); + list.add(new IrisBiomeEntry(value, 1)); } return list; } @@ -145,7 +146,7 @@ public class HintedLocatorTest { regionKeys.add(region.getLoadKey()); } when(dimension.getAllRegions(engine)).thenReturn(list); - when(dimension.getRegions()).thenReturn(regionKeys); + when(dimension.getRegionKeys()).thenReturn(regionKeys); } private void stubBiome(IrisBiome biome) { diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureResourcesTest.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureResourcesTest.java index 3b4820195..ee5abbe4e 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureResourcesTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureResourcesTest.java @@ -169,8 +169,8 @@ public class StructureResourcesTest { private Path castlePack(String name) throws Exception { File pack = temporaryFolder.newFolder(name); - write(pack.toPath(), "dimensions/main.json", "{\"regions\":[\"region\"]}"); - write(pack.toPath(), "regions/region.json", "{\"landBiomes\":[\"biome\"]}"); + write(pack.toPath(), "dimensions/main.json", "{\"regions\":[{\"region\":\"region\"}]}"); + write(pack.toPath(), "regions/region.json", "{\"landBiomes\":[{\"biome\":\"biome\"}]}"); write(pack.toPath(), "biomes/biome.json", "{\"name\":\"Biome\"}"); write(pack.toPath(), "structures/castle.json", "{\"startPool\":\"castle/start\",\"maxDepth\":5}"); write(pack.toPath(), "jigsaw-pools/castle/start.json", "{\"pieces\":[{\"piece\":\"castle/start\"}]}"); 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 886b2e9a5..0599352b8 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 @@ -98,8 +98,8 @@ public class LootResourcesTest { private Path lootPack(String name) throws Exception { File pack = temporaryFolder.newFolder(name); - write(pack.toPath(), "dimensions/main.json", "{\"regions\":[\"region\"]}"); - write(pack.toPath(), "regions/region.json", "{\"landBiomes\":[\"biome\"]}"); + write(pack.toPath(), "dimensions/main.json", "{\"regions\":[{\"region\":\"region\"}]}"); + write(pack.toPath(), "regions/region.json", "{\"landBiomes\":[{\"biome\":\"biome\"}]}"); write(pack.toPath(), "biomes/biome.json", "{\"name\":\"Biome\"}"); write(pack.toPath(), "loot/dungeon/chest.json", "{\"name\":\"Chest\",\"loot\":[{\"type\":\"stick\"}]}"); BuiltInModulesJar.writeInto(pack.toPath()); diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/CaveCarvingTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/CaveCarvingTest.java index b976bedd6..2b248d7d9 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/CaveCarvingTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/CaveCarvingTest.java @@ -54,7 +54,7 @@ public class CaveCarvingTest { } private static CarveTestWorld newWorld() { - return new CarveTestWorld().biome("cave/lush", 1).biome("plains", 1); + return new CarveTestWorld().biome("cave/lush").biome("plains"); } @Test diff --git a/core/src/test/java/art/arcane/iris/engine/modifier/CarvePipelineHarnessTest.java b/core/src/test/java/art/arcane/iris/engine/modifier/CarvePipelineHarnessTest.java index 007986bd7..f83e0955b 100644 --- a/core/src/test/java/art/arcane/iris/engine/modifier/CarvePipelineHarnessTest.java +++ b/core/src/test/java/art/arcane/iris/engine/modifier/CarvePipelineHarnessTest.java @@ -99,7 +99,7 @@ public class CarvePipelineHarnessTest { } private Result run() { - CarveTestWorld world = new CarveTestWorld().biome("cave/lush", 1).biome("plains", 1).carveSeed(SEED).dimension(profile()); + CarveTestWorld world = new CarveTestWorld().biome("cave/lush").biome("plains").carveSeed(SEED).dimension(profile()); CarveWorld carveWorld = new CarveWorld(world.resources().noise(), SEED, HEIGHT, FLUID_HEIGHT, LAVA_HEIGHT, CarveTestWorld.MIN_HEIGHT); RecordingCaveDressing dressing = new RecordingCaveDressing(); dressing.fluid = WATER; 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 0dedd19ae..57ebf0eb4 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 @@ -33,7 +33,7 @@ public class CaveApplyingBoundarySupportTest { private static final BlockState STONE = new BlockState("minecraft:stone"); private static final BlockState SAND = new BlockState("minecraft:sand"); - private final CarveTestWorld world = new CarveTestWorld().biome("custom/floor", 1); + private final CarveTestWorld world = new CarveTestWorld().biome("custom/floor"); private final CaveBlockClasses classes = new CaveBlockClasses(new CarveTestWorld.Blocks()); @Test diff --git a/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingTest.java b/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingTest.java index 65dc733b1..f243ab974 100644 --- a/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingTest.java +++ b/core/src/test/java/art/arcane/iris/engine/modifier/CaveApplyingTest.java @@ -67,7 +67,7 @@ public class CaveApplyingTest { @Before public void setUp() { - world = new CarveTestWorld().biome("cave/lush", 1); + world = new CarveTestWorld().biome("cave/lush"); dressing.walls.put(LUSH, WALL); dressing.floors.put(LUSH, List.of(FLOOR)); dressing.ceilings.put(LUSH, List.of(CEILING)); 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 index 24d8dff44..1974e67e2 100644 --- a/core/src/test/java/art/arcane/iris/engine/modifier/CaveBiomeBandsTest.java +++ b/core/src/test/java/art/arcane/iris/engine/modifier/CaveBiomeBandsTest.java @@ -48,7 +48,7 @@ public class CaveBiomeBandsTest { public void declareBands() { List entries = new Gson().fromJson(BANDS, new com.google.gson.reflect.TypeToken>() { }.getType()); world = new CarveTestWorld() - .biome("band/shallow", 1).biome("band/padded", 1).biome("band/disabled", 1) + .biome("band/shallow").biome("band/padded").biome("band/disabled") .dimension(new CarvingSettings(entries)) .declare(Level.BIOME, "band/shallow", new CaveDepthSettings(30)); } diff --git a/core/src/test/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolverParityTest.java b/core/src/test/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolverParityTest.java index 8bc3e1ade..f4d03dddd 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolverParityTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolverParityTest.java @@ -6,26 +6,29 @@ import art.arcane.iris.modules.carve.CarvingSettings; import art.arcane.iris.core.modules.CarveTestWorld; import art.arcane.iris.core.modules.IrisPackResources; import art.arcane.iris.core.modules.IrisValues; -import art.arcane.iris.engine.object.value.IRare; import art.arcane.iris.util.project.noise.CNG; -import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; import com.google.gson.Gson; +import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.volmit.config.Range; import org.junit.Test; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertTrue; /** * The module's pick of a cave biome band is the pick the band code made with Iris's own generators: the root by world Y, then the - * child a rarity-weighted draw of the generator's noise selects. The reference below is that code, written out again. + * child a weighted walk along the entry's children list selects from the generator's noise. The reference below is that walk, + * written out again. */ public class CarvingResolverParityTest { private static final int MAX_CHILD_DEPTH = 32; @@ -35,47 +38,81 @@ public class CarvingResolverParityTest { private static final double MIN_CHILD_SCALE = 0.0001D; @Test - public void resolverMatchesLegacyResolverAcrossSampleGrid() { + public void resolverMatchesReferenceResolverAcrossSampleGrid() { Fixture fixture = createFixture(); for (int worldY = -64; worldY <= 320; worldY += 11) { - ResolvedCarvingEntry legacyRoot = fixture.legacyRootEntry(worldY); + ResolvedCarvingEntry referenceRoot = fixture.referenceRootEntry(worldY); ResolvedCarvingEntry root = fixture.resolver.rootEntryAtWorldY(worldY); - assertSame("root mismatch at worldY=" + worldY, legacyRoot, root); + assertSame("root mismatch at worldY=" + worldY, referenceRoot, root); for (int worldX = -384; worldX <= 384; worldX += 29) { for (int worldZ = -384; worldZ <= 384; worldZ += 31) { - ResolvedCarvingEntry legacyResolved = fixture.legacyResolveFromRoot(legacyRoot, worldX, worldZ); + ResolvedCarvingEntry referenceResolved = fixture.referenceResolveFromRoot(referenceRoot, worldX, worldZ); ResolvedCarvingEntry resolved = fixture.resolver.resolveFromRoot(root, worldX, worldZ); - assertSame("entry mismatch at worldY=" + worldY + " worldX=" + worldX + " worldZ=" + worldZ, legacyResolved, resolved); + assertSame("entry mismatch at worldY=" + worldY + " worldX=" + worldX + " worldZ=" + worldZ, referenceResolved, resolved); } } } } @Test - public void resolverMatchesLegacyResolverAcrossMixedDepthGraph() { + public void resolverMatchesReferenceResolverAcrossMixedDepthGraph() { Fixture fixture = createMixedDepthFixture(); for (int worldY = -64; worldY <= 320; worldY += 17) { - ResolvedCarvingEntry legacyRoot = fixture.legacyRootEntry(worldY); + ResolvedCarvingEntry referenceRoot = fixture.referenceRootEntry(worldY); ResolvedCarvingEntry root = fixture.resolver.rootEntryAtWorldY(worldY); - assertSame("mixed root mismatch at worldY=" + worldY, legacyRoot, root); + assertSame("mixed root mismatch at worldY=" + worldY, referenceRoot, root); for (int worldX = -640; worldX <= 640; worldX += 79) { for (int worldZ = -640; worldZ <= 640; worldZ += 83) { - ResolvedCarvingEntry legacyResolved = fixture.legacyResolveFromRoot(legacyRoot, worldX, worldZ); + ResolvedCarvingEntry referenceResolved = fixture.referenceResolveFromRoot(referenceRoot, worldX, worldZ); ResolvedCarvingEntry resolved = fixture.resolver.resolveFromRoot(root, worldX, worldZ); - assertSame("mixed entry mismatch at worldY=" + worldY + " worldX=" + worldX + " worldZ=" + worldZ, legacyResolved, resolved); + assertSame("mixed entry mismatch at worldY=" + worldY + " worldX=" + worldX + " worldZ=" + worldZ, referenceResolved, resolved); } } } } + @Test + public void aParentLeftOutOfItsChildrenNeverKeepsTheSpot() { + CarveTestWorld world = new CarveTestWorld().carveSeed(77_031L).biome("parent").biome("only-child"); + Fixture fixture = new Fixture(world, List.of( + buildEntry("parent", "parent", Range.of(-64, 320), 1, List.of(child("only-child", 1))), + buildEntry("only-child", "only-child", Range.of(-4096, -2048), 1, List.of()))); + ResolvedCarvingEntry root = fixture.resolver.rootEntryAtWorldY(80); + + for (int worldX = -256; worldX <= 256; worldX += 37) { + for (int worldZ = -256; worldZ <= 256; worldZ += 41) { + assertSame(fixture.resolver.index().get("only-child"), fixture.resolver.resolveFromRoot(root, worldX, worldZ)); + } + } + } + + @Test + public void aParentListedAmongItsChildrenKeepsTheSpotWhereItsEntryReaches() { + CarveTestWorld world = new CarveTestWorld().carveSeed(77_031L).biome("parent").biome("child"); + Fixture fixture = new Fixture(world, List.of( + buildEntry("parent", "parent", Range.of(-64, 320), 1, List.of(child("child", 1), child("parent", 1))), + buildEntry("child", "child", Range.of(-4096, -2048), 1, List.of()))); + ResolvedCarvingEntry root = fixture.resolver.rootEntryAtWorldY(80); + + List resolved = new ArrayList<>(); + for (int worldX = -512; worldX <= 512; worldX += 37) { + for (int worldZ = -512; worldZ <= 512; worldZ += 41) { + resolved.add(fixture.resolver.resolveFromRoot(root, worldX, worldZ)); + } + } + + assertTrue("some spots stay the parent", resolved.contains(root)); + assertTrue("some spots become the child", resolved.contains(fixture.resolver.index().get("child"))); + } + @Test public void columnAnchoredChunkPlanResolutionIsStableAcrossRepeatedBuilds() { Fixture fixture = createMixedDepthFixture(); - ResolvedCarvingEntry root = fixture.legacyRootEntry(80); + ResolvedCarvingEntry root = fixture.referenceRootEntry(80); for (int chunkX = -24; chunkX <= 24; chunkX += 6) { for (int chunkZ = -24; chunkZ <= 24; chunkZ += 6) { @@ -94,8 +131,8 @@ public class CarvingResolverParityTest { Fixture first = createFixture(); Fixture second = createMixedDepthFixture(); - ResolvedCarvingEntry firstExpected = first.legacyRootEntry(80); - ResolvedCarvingEntry secondExpected = second.legacyRootEntry(80); + ResolvedCarvingEntry firstExpected = first.referenceRootEntry(80); + ResolvedCarvingEntry secondExpected = second.referenceRootEntry(80); assertSame(firstExpected, first.resolver.rootEntryAtWorldY(80)); assertSame(secondExpected, second.resolver.rootEntryAtWorldY(80)); @@ -105,7 +142,7 @@ public class CarvingResolverParityTest { @Test public void aWorldReadsItsBandsFromTheDimensionsSettings() { - CarveTestWorld world = new CarveTestWorld().biome("root-low", 6) + CarveTestWorld world = new CarveTestWorld().biome("root-low") .dimension(new CarvingSettings(List.of(buildEntry("root-low", "root-low", Range.of(-64, 120), 4, List.of())))); CarvingResolver resolver = CarvingResolver.of(world); @@ -115,31 +152,41 @@ public class CarvingResolverParityTest { assertNull(resolver.rootEntryAtWorldY(121)); } + @Test + public void childrenKeepTheWeightsTheyAreWrittenWith() { + CarvingEntry entry = buildEntry("parent", "parent", Range.of(-64, 320), 1, List.of(child("a", 3), child("parent", 1))); + + assertEquals(2, entry.children().size()); + assertEquals("a", entry.children().get(0).id()); + assertEquals(3, entry.children().get(0).weight()); + assertEquals(1, entry.children().get(1).weight()); + } + private Fixture createFixture() { CarveTestWorld world = new CarveTestWorld().carveSeed(913_531_771L) - .biome("root-low", 6).biome("root-high", 4).biome("child-a", 2).biome("child-b", 5).biome("child-c", 1); + .biome("root-low").biome("root-high").biome("child-a").biome("child-b").biome("child-c"); return new Fixture(world, List.of( - buildEntry("root-low", "root-low", Range.of(-64, 120), 4, List.of("child-a", "child-b")), - buildEntry("root-high", "root-high", Range.of(121, 320), 3, List.of("child-b", "child-c")), - buildEntry("child-a", "child-a", Range.of(-2048, -1024), 3, List.of("child-b")), - buildEntry("child-b", "child-b", Range.of(-2048, -1024), 2, List.of("child-c", "child-a")), + buildEntry("root-low", "root-low", Range.of(-64, 120), 4, List.of(child("child-a", 2), child("child-b", 3), child("root-low", 1))), + buildEntry("root-high", "root-high", Range.of(121, 320), 3, List.of(child("child-b", 1), child("child-c", 2), child("root-high", 4))), + buildEntry("child-a", "child-a", Range.of(-2048, -1024), 3, List.of(child("child-b", 1), child("child-a", 2))), + buildEntry("child-b", "child-b", Range.of(-2048, -1024), 2, List.of(child("child-c", 1), child("child-a", 1), child("child-b", 3))), buildEntry("child-c", "child-c", Range.of(-2048, -1024), 1, List.of()))); } private Fixture createMixedDepthFixture() { CarveTestWorld world = new CarveTestWorld().carveSeed(4_627_991_643L) - .biome("root-low", 7).biome("root-high", 5).biome("child-a", 2).biome("child-b", 3).biome("child-c", 6) - .biome("child-d", 1).biome("child-e", 4).biome("child-f", 8).biome("child-g", 2); + .biome("root-low").biome("root-high").biome("child-a").biome("child-b").biome("child-c") + .biome("child-d").biome("child-e").biome("child-f").biome("child-g"); return new Fixture(world, List.of( - buildEntry("root-low", "root-low", Range.of(-64, 120), 7, List.of("child-a", "child-d", "child-e")), - buildEntry("root-high", "root-high", Range.of(121, 320), 6, List.of("child-b", "child-c", "child-f")), - buildEntry("child-a", "child-a", Range.of(-4096, 4096), 5, List.of("child-b", "child-g")), - buildEntry("child-b", "child-b", Range.of(-4096, 4096), 1, List.of("child-c")), + buildEntry("root-low", "root-low", Range.of(-64, 120), 7, List.of(child("child-a", 2), child("child-d", 5), child("child-e", 1), child("root-low", 3))), + buildEntry("root-high", "root-high", Range.of(121, 320), 6, List.of(child("child-b", 1), child("child-c", 1), child("child-f", 4), child("root-high", 2))), + buildEntry("child-a", "child-a", Range.of(-4096, 4096), 5, List.of(child("child-b", 3), child("child-g", 2), child("child-a", 1))), + buildEntry("child-b", "child-b", Range.of(-4096, 4096), 1, List.of(child("child-c", 1), child("child-b", 1))), buildEntry("child-c", "child-c", Range.of(-4096, 4096), 0, List.of()), - buildEntry("child-d", "child-d", Range.of(-4096, 4096), 6, List.of("child-e", "child-f")), - buildEntry("child-e", "child-e", Range.of(-4096, 4096), 2, List.of("child-a")), - buildEntry("child-f", "child-f", Range.of(-4096, 4096), 8, List.of("child-g", "child-c")), - buildEntry("child-g", "child-g", Range.of(-4096, 4096), 3, List.of("child-d")))); + buildEntry("child-d", "child-d", Range.of(-4096, 4096), 6, List.of(child("child-e", 2), child("child-f", 1))), + buildEntry("child-e", "child-e", Range.of(-4096, 4096), 2, List.of(child("child-a", 1), child("child-e", 5))), + buildEntry("child-f", "child-f", Range.of(-4096, 4096), 8, List.of(child("child-g", 1), child("child-c", 1), child("child-f", 2))), + buildEntry("child-g", "child-g", Range.of(-4096, 4096), 3, List.of(child("child-d", 1))))); } private ResolvedCarvingEntry[] buildColumnPlan(CarvingResolver resolver, ResolvedCarvingEntry rootEntry, int chunkX, int chunkZ) { @@ -154,7 +201,14 @@ public class CarvingResolverParityTest { return plan; } - private static CarvingEntry buildEntry(String id, String biome, Range worldRange, int depth, List children) { + private static JsonObject child(String id, int weight) { + JsonObject json = new JsonObject(); + json.addProperty("id", id); + json.addProperty("weight", weight); + return json; + } + + private static CarvingEntry buildEntry(String id, String biome, Range worldRange, int depth, List children) { JsonObject json = new JsonObject(); json.addProperty("id", id); json.addProperty("biome", biome); @@ -163,7 +217,9 @@ public class CarvingResolverParityTest { range.addProperty("max", worldRange.max()); json.add("worldYRange", range); json.addProperty("childRecursionDepth", depth); - json.add("children", new Gson().toJsonTree(children)); + JsonArray listed = new JsonArray(); + children.forEach(listed::add); + json.add("children", listed); return new Gson().fromJson(json, CarvingEntry.class); } @@ -174,7 +230,7 @@ public class CarvingResolverParityTest { return Math.min(depth, MAX_CHILD_DEPTH); } - /** The module's resolver, and the band code as it was, over the same entries and world. */ + /** The module's resolver, and the band code as a plain walk, over the same entries and world. */ private static final class Fixture { private final CarveTestWorld world; private final CarvingResolver resolver; @@ -186,7 +242,7 @@ public class CarvingResolverParityTest { entries.forEach(entry -> settingsById.put(entry.id(), entry)); } - private ResolvedCarvingEntry legacyRootEntry(int worldY) { + private ResolvedCarvingEntry referenceRootEntry(int worldY) { ResolvedCarvingEntry resolved = null; for (ResolvedCarvingEntry entry : resolver.entries()) { if (!entry.enabled()) { @@ -204,7 +260,7 @@ public class CarvingResolverParityTest { return resolved; } - private ResolvedCarvingEntry legacyResolveFromRoot(ResolvedCarvingEntry rootEntry, int worldX, int worldZ) { + private ResolvedCarvingEntry referenceResolveFromRoot(ResolvedCarvingEntry rootEntry, int worldX, int worldZ) { if (rootEntry == null || resolver.entryBiome(rootEntry) == null) { return null; } @@ -217,7 +273,7 @@ public class CarvingResolverParityTest { ResolvedCarvingEntry current = rootEntry; int depth = remainingDepth; while (depth > 0) { - ResolvedCarvingEntry selected = legacySelectChild(current, worldX, worldZ); + ResolvedCarvingEntry selected = referenceSelectChild(current, worldX, worldZ); if (selected == null || selected == current) { break; } @@ -233,49 +289,38 @@ public class CarvingResolverParityTest { return current; } - private ResolvedCarvingEntry legacySelectChild(ResolvedCarvingEntry parent, int worldX, int worldZ) { - List children = parent.children(); - if (children.isEmpty()) { - return parent; - } - if (resolver.entryBiome(parent) == null) { - return parent; - } - - KList options = new KList<>(); - for (String childId : children) { - if (childId == null || childId.isBlank()) { + private ResolvedCarvingEntry referenceSelectChild(ResolvedCarvingEntry parent, int worldX, int worldZ) { + List entries = new ArrayList<>(); + List weights = new ArrayList<>(); + int totalWeight = 0; + for (var listed : parent.children()) { + ResolvedCarvingEntry entry = resolver.index().get(listed.id().trim()); + if (entry == null || !entry.enabled() || resolver.entryBiome(entry) == null) { continue; } - ResolvedCarvingEntry child = resolver.index().get(childId.trim()); - if (child == null || !child.enabled() || resolver.entryBiome(child) == null) { - continue; - } - - options.add(new LegacyCarvingChoice(child, rarity(child))); + entries.add(entry); + weights.add(listed.weight()); + totalWeight += listed.weight(); } - - options.add(new LegacyCarvingChoice(parent, rarity(parent))); - if (options.size() <= 1) { + if (entries.isEmpty()) { return parent; } long seed = world.seed(IrisSeedPurposes.CARVE) ^ CHILD_SEED_SALT; - LegacyCarvingChoice selected = legacyChildrenGenerator(parent, seed).fitRarity(options, worldX, worldZ); - if (selected == null || selected.entry == null) { - return parent; + double position = referenceChildrenGenerator(parent, seed).noiseFast2D(worldX, worldZ) * totalWeight; + int weightUpToHere = 0; + for (int index = 0; index < entries.size(); index++) { + weightUpToHere += weights.get(index); + if (position < weightUpToHere) { + return entries.get(index); + } } - - return selected.entry; - } - - private int rarity(ResolvedCarvingEntry entry) { - return Math.max(resolver.entryBiome(entry).rarity(), 1); + return entries.getLast(); } /** The generator of an entry's children as Iris built it: its style created from the entry's seed, then scaled by the shrink factor. */ - private CNG legacyChildrenGenerator(ResolvedCarvingEntry parent, long seed) { + private CNG referenceChildrenGenerator(ResolvedCarvingEntry parent, long seed) { CarvingEntry settings = settingsById.get(parent.id()); long idHash = settings.id().trim().hashCode(); long generatorSeed = seed ^ (idHash << 32) ^ CHILD_GENERATOR_SALT; @@ -285,19 +330,4 @@ public class CarvingResolverParityTest { .bake().scale(scale).bake(); } } - - private static final class LegacyCarvingChoice implements IRare { - private final ResolvedCarvingEntry entry; - private final int rarity; - - private LegacyCarvingChoice(ResolvedCarvingEntry entry, int rarity) { - this.entry = entry; - this.rarity = rarity; - } - - @Override - public int getRarity() { - return rarity; - } - } } 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 94f124883..2db0fab52 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 @@ -50,7 +50,7 @@ public class ResolvedFloatingChildCarvingResolutionTest { when(resources.idOf(anyString())).thenAnswer(invocation -> ResourceId.ofPackKey(NAMESPACE, invocation.getArgument(0, String.class))); when(resources.find(eq(PackResources.BIOMES), any())).thenAnswer(invocation -> { ResourceId id = invocation.getArgument(1); - return biomes.containsValue(id) ? Optional.of(new PackBiome(id, id.path(), id, 1, List.of())) : Optional.empty(); + return biomes.containsValue(id) ? Optional.of(new PackBiome(id, id.path(), id, List.of())) : Optional.empty(); }); return new FloatingWorld(resources, null, 0L, 0L, 0, dimensionCarving); } diff --git a/core/src/test/java/art/arcane/iris/engine/object/world/RemovedDeadFieldsTest.java b/core/src/test/java/art/arcane/iris/engine/object/world/RemovedDeadFieldsTest.java index 3e3b29759..2f14069c5 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/world/RemovedDeadFieldsTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/world/RemovedDeadFieldsTest.java @@ -3,6 +3,7 @@ package art.arcane.iris.engine.object.world; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.TreeOverride; 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.world.region.IrisRegion; import art.arcane.iris.core.IrisSettings; @@ -19,6 +20,8 @@ public class RemovedDeadFieldsTest { assertThrows(NoSuchFieldException.class, () -> IrisDimension.class.getDeclaredField("forceConvertTo320Height")); assertThrows(NoSuchFieldException.class, () -> IrisDimension.class.getDeclaredField("rockZoom")); assertThrows(NoSuchFieldException.class, () -> IrisDimension.class.getDeclaredField("disableExplorerMaps")); + assertThrows(NoSuchFieldException.class, () -> IrisRegion.class.getDeclaredField("rarity")); + assertThrows(NoSuchFieldException.class, () -> IrisBiome.class.getDeclaredField("rarity")); assertThrows(NoSuchFieldException.class, () -> IrisRegion.class.getDeclaredField("riverStyle")); assertThrows(NoSuchFieldException.class, () -> IrisRegion.class.getDeclaredField("lakeStyle")); assertThrows(NoSuchFieldException.class, () -> IrisRegion.class.getDeclaredField("riverGen")); diff --git a/core/src/test/java/art/arcane/iris/engine/object/world/biome/IrisBiomeWeightedChildrenTest.java b/core/src/test/java/art/arcane/iris/engine/object/world/biome/IrisBiomeWeightedChildrenTest.java new file mode 100644 index 000000000..06a4df06b --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/object/world/biome/IrisBiomeWeightedChildrenTest.java @@ -0,0 +1,106 @@ +/* + * 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.biome; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.loader.ResourceLoader; +import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.engine.object.world.region.IrisRegionEntry; +import art.arcane.volmlib.util.collection.KList; +import com.google.gson.Gson; +import com.volmit.world.Weighted; +import org.junit.Test; + +import java.util.List; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** Lists of biomes and regions are weighted entries in the order the pack writes them; a parent is itself only where its own entry is listed. */ +public class IrisBiomeWeightedChildrenTest { + @Test + @SuppressWarnings("unchecked") + public void childOptionsKeepTheListOrderTheWeightsAndTheParentEntry() { + IrisBiome plains = biome("plains"); + IrisBiome meadow = biome("meadow"); + IrisBiome glade = biome("glade"); + plains.setChildren(new KList<>(List.of( + new IrisBiomeEntry("meadow", 1), new IrisBiomeEntry("plains", 4), new IrisBiomeEntry("missing", 2), new IrisBiomeEntry("glade", 3)))); + ResourceLoader loader = mock(ResourceLoader.class); + when(loader.load("plains")).thenReturn(plains); + when(loader.load("meadow")).thenReturn(meadow); + when(loader.load("glade")).thenReturn(glade); + IrisData data = mock(IrisData.class); + when(data.getBiomeLoader()).thenReturn(loader); + + KList> options = plains.getChildOptions(() -> data); + + assertEquals(List.of("meadow", "plains", "glade"), options.stream().map(option -> option.value().getLoadKey()).toList()); + assertEquals(List.of(1, 4, 3), options.stream().map(Weighted::weight).toList()); + assertSame("the parent entry is the parent", plains, options.get(1).value()); + } + + @Test + public void childKeysLeaveOutTheParentItself() { + IrisBiome plains = biome("plains"); + plains.setChildren(new KList<>(List.of(new IrisBiomeEntry("meadow", 1), new IrisBiomeEntry("plains", 4), new IrisBiomeEntry("glade", 3)))); + + assertEquals(List.of("meadow", "glade"), plains.getChildKeys()); + } + + @Test + public void aBiomeWithoutChildrenHasNoOptions() { + IrisBiome plains = biome("plains"); + IrisData data = mock(IrisData.class); + + assertEquals(List.of(), plains.getChildOptions(() -> data)); + } + + @Test + public void entriesReadTheKeyAndTheWeightPacksWrite() { + IrisRegion region = new Gson().fromJson("{\"name\": \"Temperate\", \"landBiomes\": [{\"biome\": \"plains\", \"weight\": 3}, {\"biome\": \"forest\"}]}", IrisRegion.class); + + assertEquals(List.of(new IrisBiomeEntry("plains", 3), new IrisBiomeEntry("forest", 1)), region.getLandBiomes()); + assertEquals(Set.of("plains", "forest"), region.getAllBiomeIds()); + } + + @Test + @SuppressWarnings("unchecked") + public void regionEntriesLeaveOutRegionsThatDoNotLoad() { + IrisRegion temperate = new IrisRegion(); + ResourceLoader loader = mock(ResourceLoader.class); + when(loader.load("temperate")).thenReturn(temperate); + + KList> loaded = IrisRegionEntry.load( + List.of(new IrisRegionEntry("missing", 2), new IrisRegionEntry("temperate", 5)), loader); + + assertEquals(1, loaded.size()); + assertSame(temperate, loaded.getFirst().value()); + assertEquals(5, loaded.getFirst().weight()); + } + + private static IrisBiome biome(String key) { + IrisBiome biome = new IrisBiome(); + biome.setLoadKey(key); + return biome; + } +} 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 47ecd19f1..f57262a0c 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 @@ -3,6 +3,8 @@ package art.arcane.iris.engine.object.world.dimension; import art.arcane.iris.modules.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.biome.IrisBiomeEntry; +import art.arcane.iris.engine.object.world.region.IrisRegionEntry; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.modules.carve.CarvingBiomeSettings; import art.arcane.iris.modules.carve.CarvingEntry; @@ -37,28 +39,28 @@ public class IrisDimensionReachableBiomesTest { 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")); + IrisDimension dimension = new IrisDimension().setRegions(regions("reachable", "missing")); dimension.setModuleSettings(BuiltInPack.settings(new CarvingSettings(List.of(deepBand, disabledBand, floatingCarvingEntry)))); IrisRegion reachable = new IrisRegion() - .setLandBiomes(new KList<>("parent", "shared")) - .setSeaBiomes(new KList<>("shared")); + .setLandBiomes(biomes("parent", "shared")) + .setSeaBiomes(biomes("shared")); 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")); + .setChildren(biomes("child", "shared")); + IrisBiome child = biome("child").setChildren(biomes("parent")); IrisBiome shared = biome("shared"); IrisBiome carve = biome("carve"); IrisBiome floatingTarget = biome("floating-target", carvingBiome("floating-carve")) - .setChildren(new KList<>("floating-child")); + .setChildren(biomes("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", floatingChildren(floating("parent"))); - IrisBiome deepRoot = biome("deep-root").setChildren(new KList<>("deep-child")); + IrisBiome deepRoot = biome("deep-root").setChildren(biomes("deep-child")); 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 deepFloating = biome("deep-floating").setChildren(biomes("deep-root")); IrisBiome disabledDeep = biome("disabled-deep"); IrisBiome unused = biome("unused"); @@ -103,13 +105,13 @@ public class IrisDimensionReachableBiomesTest { @Test(timeout = 1000L) @SuppressWarnings("unchecked") public void terminatesMixedDependencyCyclesWithoutReloadingBiomes() { - IrisDimension dimension = new IrisDimension().setRegions(new KList<>("reachable")); - IrisRegion reachable = new IrisRegion().setLandBiomes(new KList<>("a")); - IrisBiome a = biome("a").setChildren(new KList<>("b")); + IrisDimension dimension = new IrisDimension().setRegions(regions("reachable")); + IrisRegion reachable = new IrisRegion().setLandBiomes(biomes("a")); + IrisBiome a = biome("a").setChildren(biomes("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")); + .setChildren(biomes("a")); IrisPackResources resources = PackResourceFixture.empty(new File("pack")); IrisData data = mock(IrisData.class); @@ -135,6 +137,22 @@ public class IrisDimensionReachableBiomesTest { verify(biomeLoader, times(1)).load("d"); } + private static KList regions(String... keys) { + KList entries = new KList<>(); + for (String key : keys) { + entries.add(new IrisRegionEntry(key, 1)); + } + return entries; + } + + private static KList biomes(String... keys) { + KList entries = new KList<>(); + for (String key : keys) { + entries.add(new IrisBiomeEntry(key, 1)); + } + return entries; + } + private IrisBiome biome(String loadKey, IrisFeature... settings) { IrisBiome biome = new IrisBiome(); biome.setLoadKey(loadKey); 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 index a67f82d52..9ad874a70 100644 --- 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 @@ -27,6 +27,7 @@ import art.arcane.iris.core.modules.BuiltInPack; import art.arcane.iris.core.modules.IrisPackResources; import art.arcane.iris.core.modules.PackResourceFixture; import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.biome.IrisBiomeEntry; import art.arcane.volmlib.util.collection.KList; import com.google.gson.Gson; import com.volmit.IrisFeature; @@ -46,10 +47,10 @@ public class IrisRegionBiomeTreeTest { @Test @SuppressWarnings("unchecked") public void aBiomesCarvingBiomeJoinsTheRegionAndAFloatingChildDoesNot() { - IrisRegion region = new IrisRegion().setLandBiomes(new KList<>("plains")); + IrisRegion region = new IrisRegion().setLandBiomes(new KList<>(new IrisBiomeEntry("plains", 1))); 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")); + .setChildren(new KList<>(new IrisBiomeEntry("meadow", 1), new IrisBiomeEntry("plains", 1))); IrisBiome meadow = biome("meadow"); IrisBiome mushroom = biome("carving/mushroom", new CarvingBiomeSettings("carving/nested")); IrisBiome nested = biome("carving/nested"); 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 717f179d9..a268eddaf 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 @@ -110,8 +110,8 @@ public class SpawnResourcesTest { private Path spawnPack(String name) throws Exception { File pack = temporaryFolder.newFolder(name); - write(pack.toPath(), "dimensions/main.json", "{\"regions\":[\"region\"]}"); - write(pack.toPath(), "regions/region.json", "{\"landBiomes\":[\"biome\"]}"); + write(pack.toPath(), "dimensions/main.json", "{\"regions\":[{\"region\":\"region\"}]}"); + write(pack.toPath(), "regions/region.json", "{\"landBiomes\":[{\"biome\":\"biome\"}]}"); write(pack.toPath(), "biomes/biome.json", "{\"name\":\"Biome\"}"); write(pack.toPath(), "entities/zombie.json", "{\"type\":\"minecraft:zombie\"}"); write(pack.toPath(), "spawners/camp/zombies.json", "{\"spawns\":[{\"entity\":\"zombie\"}]}"); 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 index a36c777d1..27a078153 100644 --- 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 @@ -1,7 +1,6 @@ { "name": "Tropical Volcanoes", "color": "#8C1E1E", - "rarity": 1, "derivative": "minecraft:the_void", "vanillaDerivative": "minecraft:the_void", "customDerivitives": [{ @@ -12,7 +11,9 @@ "fogColor": "#DD793C", "downfallType": "none" }], - "children": ["tropical/volcanoes-lava"], + "children": [ + {"biome": "tropical/volcanoes", "weight": 1} + ], "generators": [{ "generator": "mountain", "max": 180, 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 index 645d60456..2148a0e0e 100644 --- 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 @@ -170,18 +170,18 @@ }, "regionZoom": 16.15, "regions": [ - "frozen", - "hot", - "terralost", - "mushroom", - "forests", - "tundra", - "magnetics", - "temperate", - "estranged", - "tropical", - "swamp", - "prismatics" + {"region": "frozen", "weight": 1}, + {"region": "hot", "weight": 10}, + {"region": "terralost", "weight": 6}, + {"region": "mushroom", "weight": 2}, + {"region": "forests", "weight": 1}, + {"region": "tundra", "weight": 1}, + {"region": "magnetics", "weight": 1}, + {"region": "temperate", "weight": 1}, + {"region": "estranged", "weight": 1}, + {"region": "tropical", "weight": 1}, + {"region": "swamp", "weight": 15}, + {"region": "prismatics", "weight": 1} ], "seaBiomeStyle": { "style": "SIMPLEX", 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 index 09db28c64..9e0edb04d 100644 --- 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 @@ -1,48 +1,47 @@ { "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" + {"biome": "hot/desert-dunes", "weight": 1}, + {"biome": "hot/small-valley", "weight": 1}, + {"biome": "hot/desert-dunes-red", "weight": 1}, + {"biome": "savanna/savanna", "weight": 1}, + {"biome": "mesa/dark", "weight": 1}, + {"biome": "savanna/plateau", "weight": 1}, + {"biome": "savanna/forest", "weight": 1}, + {"biome": "savanna/acacia-denmyre", "weight": 1}, + {"biome": "mesa/plateau", "weight": 1}, + {"biome": "mesa/valleys", "weight": 1}, + {"biome": "mesa/plateau-high", "weight": 1}, + {"biome": "mesa/valleys", "weight": 1}, + {"biome": "mesa/mesa", "weight": 1}, + {"biome": "hot/mountain-middle", "weight": 1}, + {"biome": "hot/mountain-plains", "weight": 1}, + {"biome": "hot/oasis", "weight": 1}, + {"biome": "vanilla/savanna_plateau", "weight": 1}, + {"biome": "vanilla/windswept_savanna", "weight": 1}, + {"biome": "vanilla/wooded_badlands", "weight": 1} ], "caveBiomes": [ - "carving/sandstone", - "carving/sand-hollows", - "carving/red-sandstone", - "carving/mixed-sandstone", - "carving/volcanic", - "carving/ember-rifts" + {"biome": "carving/sandstone", "weight": 1}, + {"biome": "carving/sand-hollows", "weight": 1}, + {"biome": "carving/red-sandstone", "weight": 1}, + {"biome": "carving/mixed-sandstone", "weight": 1}, + {"biome": "carving/volcanic", "weight": 1}, + {"biome": "carving/ember-rifts", "weight": 1} ], "shoreBiomes": [ - "hot/shore/beach", - "hot/shore/beach-grass", - "mesa/shore/beach", - "savanna/shore/beach" + {"biome": "hot/shore/beach", "weight": 1}, + {"biome": "hot/shore/beach-grass", "weight": 1}, + {"biome": "mesa/shore/beach", "weight": 1}, + {"biome": "savanna/shore/beach", "weight": 1} ], "seaBiomes": [ - "hot/sea/ocean", - "ocean/rich-oceans", - "hot/sea/river", - "mesa/sea/river" + {"biome": "hot/sea/ocean", "weight": 1}, + {"biome": "ocean/rich-oceans", "weight": 1}, + {"biome": "hot/sea/river", "weight": 1}, + {"biome": "mesa/sea/river", "weight": 1} ], "landBiomeZoom": 7, "effects": [ 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 index c53e77e7f..31699834b 100644 --- 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 @@ -1,7 +1,6 @@ { "name": "Mushroom", "color": "#F1C3EF", - "rarity": 15, "objects": [ { "place": [ @@ -53,25 +52,25 @@ } ], "landBiomes": [ - "mushroom/forest", - "mushroom/crimson-forest", - "mushroom/forest-extended", - "mushroom/plains", - "mushroom/warped-forest" + {"biome": "mushroom/forest", "weight": 1}, + {"biome": "mushroom/crimson-forest", "weight": 1}, + {"biome": "mushroom/forest-extended", "weight": 1}, + {"biome": "mushroom/plains", "weight": 1}, + {"biome": "mushroom/warped-forest", "weight": 1} ], "caveBiomes": [ - "carving/mushroom", - "carving/rocky-cavebiome", - "carving/drip-lite", - "carving/moss-pillars", - "carving/crystalized-overgrown" + {"biome": "carving/mushroom", "weight": 1}, + {"biome": "carving/rocky-cavebiome", "weight": 1}, + {"biome": "carving/drip-lite", "weight": 1}, + {"biome": "carving/moss-pillars", "weight": 1}, + {"biome": "carving/crystalized-overgrown", "weight": 1} ], "shoreBiomes": [ - "mushroom/shore/beach" + {"biome": "mushroom/shore/beach", "weight": 1} ], "seaBiomes": [ - "mushroom/sea/ocean", - "mushroom/sea/lake" + {"biome": "mushroom/sea/ocean", "weight": 1}, + {"biome": "mushroom/sea/lake", "weight": 1} ], "blockDrops": [ { 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 index e9deba0ad..a8e8a1893 100644 --- 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 @@ -1,33 +1,32 @@ { "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" + {"biome": "swamp/roofed-forest", "weight": 1}, + {"biome": "swamp/sea/lake", "weight": 1}, + {"biome": "swamp/roofed-wayward", "weight": 1}, + {"biome": "swamp/marsh", "weight": 1}, + {"biome": "swamp/handy-willow-forest", "weight": 1}, + {"biome": "swamp/cambian-drift", "weight": 1}, + {"biome": "swamp/swamp-forest", "weight": 1}, + {"biome": "swamp/willow-forest", "weight": 1}, + {"biome": "swamp/creaks", "weight": 1}, + {"biome": "vanilla/mangrove_swamp", "weight": 1} ], "caveBiomes": [ - "carving/swamp", - "carving/lush", - "carving/drip-lite", - "carving/drip", - "carving/moss-pillars" + {"biome": "carving/swamp", "weight": 1}, + {"biome": "carving/lush", "weight": 1}, + {"biome": "carving/drip-lite", "weight": 1}, + {"biome": "carving/drip", "weight": 1}, + {"biome": "carving/moss-pillars", "weight": 1} ], "shoreBiomes": [ - "swamp/shore/beach" + {"biome": "swamp/shore/beach", "weight": 1} ], "seaBiomes": [ - "swamp/sea/ocean", - "swamp/swamp-mangrove-lake", - "swamp/sea/ocean-tree" + {"biome": "swamp/sea/ocean", "weight": 1}, + {"biome": "swamp/swamp-mangrove-lake", "weight": 1}, + {"biome": "swamp/sea/ocean-tree", "weight": 1} ], "landBiomeZoom": 2, "shoreHeightMin": 1.2, 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 index 0623df194..a800c9030 100644 --- 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 @@ -1,21 +1,20 @@ { "name": "Terralost", "color": "#446600", - "rarity": 5, "landBiomes": [ - "terralost/amethyst-rainforest", - "terralost/ancient-sands", - "terralost/amethyst-canyon", - "terralost/alpine-grove", - "terralost/alpine-highlands", - "dev" + {"biome": "terralost/amethyst-rainforest", "weight": 1}, + {"biome": "terralost/ancient-sands", "weight": 1}, + {"biome": "terralost/amethyst-canyon", "weight": 1}, + {"biome": "terralost/alpine-grove", "weight": 1}, + {"biome": "terralost/alpine-highlands", "weight": 1}, + {"biome": "dev", "weight": 1} ], "landBiomeZoom": 3, "shoreBiomes": [ - "tundra/shore/beach" + {"biome": "tundra/shore/beach", "weight": 1} ], "seaBiomes": [ - "mountain/sea/river" + {"biome": "mountain/sea/river", "weight": 1} ], "shoreHeightMin": 2.2, "shoreHeightMax": 5.2, @@ -29,11 +28,11 @@ ] }, "caveBiomes": [ - "carving/amethyst", - "carving/calcite", - "carving/deepslate", - "carving/deepravine", - "carving/chalk-gardens" + {"biome": "carving/amethyst", "weight": 1}, + {"biome": "carving/calcite", "weight": 1}, + {"biome": "carving/deepslate", "weight": 1}, + {"biome": "carving/deepravine", "weight": 1}, + {"biome": "carving/chalk-gardens", "weight": 1} ], "caveProfile": { "enabled": true, 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 index 9a1c2649c..b149cff46 100644 --- 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 @@ -282,7 +282,7 @@ }, "caveMinDepthBelowSurface": 10, "children": [ - "carving/amethyst-child" + {"biome": "carving/amethyst", "weight": 1} ], "childStyle": { "style": "CELLULAR_IRIS_DOUBLE", diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/biomes/estranged/bloomspire-orchard.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/biomes/estranged/bloomspire-orchard.json index d440caff8..32cae64b1 100644 --- a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/biomes/estranged/bloomspire-orchard.json +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/biomes/estranged/bloomspire-orchard.json @@ -1,7 +1,6 @@ { "name": "Bloomspire Orchard", "color": "#F2B6D6", - "rarity": 3, "derivative": "minecraft:cherry_grove", "vanillaDerivative": "minecraft:cherry_grove", "customDerivitives": [{ 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 index eeb79f2a0..182141b4c 100644 --- 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 @@ -1,7 +1,6 @@ { "name": "Magnetics Plains", "color": "#89C46A", - "rarity": 1, "derivative": "minecraft:plains", "vanillaDerivative": "minecraft:plains", "generators": [ diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/biomes/mesa/red.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/biomes/mesa/red.json index 62c4f1900..1d29fe01e 100644 --- a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/biomes/mesa/red.json +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/biomes/mesa/red.json @@ -1,7 +1,6 @@ { "name": "Mesa Red", "color": "#963D16", - "rarity": 1, "derivative": "minecraft:windswept_savanna", "vanillaDerivative": "minecraft:badlands", "generators": [ diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/dimensions/overworld.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/dimensions/overworld.json index 645d60456..4c4bc79ea 100644 --- a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/dimensions/overworld.json +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/dimensions/overworld.json @@ -170,18 +170,18 @@ }, "regionZoom": 16.15, "regions": [ - "frozen", - "hot", - "terralost", - "mushroom", - "forests", - "tundra", - "magnetics", - "temperate", - "estranged", - "tropical", - "swamp", - "prismatics" + {"region": "frozen", "weight": 1}, + {"region": "hot", "weight": 1}, + {"region": "terralost", "weight": 1}, + {"region": "mushroom", "weight": 1}, + {"region": "forests", "weight": 15}, + {"region": "tundra", "weight": 1}, + {"region": "magnetics", "weight": 1}, + {"region": "temperate", "weight": 1}, + {"region": "estranged", "weight": 1}, + {"region": "tropical", "weight": 1}, + {"region": "swamp", "weight": 1}, + {"region": "prismatics", "weight": 1} ], "seaBiomeStyle": { "style": "SIMPLEX", 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 index eaaad5baa..e24bc2fc9 100644 --- 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 @@ -1,37 +1,36 @@ { "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" + {"biome": "tundra/forest", "weight": 1}, + {"biome": "tundra/autumn", "weight": 1}, + {"biome": "mountain/plains", "weight": 1}, + {"biome": "temperate/reaching-forest-violet", "weight": 1}, + {"biome": "temperate/flower-forest", "weight": 1}, + {"biome": "temperate/birch-tall", "weight": 1}, + {"biome": "temperate/osaka-red-forest", "weight": 1}, + {"biome": "mountain/mountain", "weight": 1}, + {"biome": "temperate/combo-forest", "weight": 1}, + {"biome": "tundra/redwood-forest", "weight": 1}, + {"biome": "vanilla/old_growth_birch_forest", "weight": 1}, + {"biome": "vanilla/old_growth_pine_taiga", "weight": 1}, + {"biome": "vanilla/windswept_forest", "weight": 1} ], "caveBiomes": [ - "carving/rocky-cavebiome", - "carving/lush", - "carving/mountain-caves", - "carving/moss-pillars" + {"biome": "carving/rocky-cavebiome", "weight": 1}, + {"biome": "carving/lush", "weight": 1}, + {"biome": "carving/mountain-caves", "weight": 1}, + {"biome": "carving/moss-pillars", "weight": 1} ], "shoreBiomes": [ - "temperate/shore/beach", - "temperate/shore/oak-beach" + {"biome": "temperate/shore/beach", "weight": 1}, + {"biome": "temperate/shore/oak-beach", "weight": 1} ], "seaBiomeZoom": 6, "seaBiomes": [ - "ocean/deep", - "ocean/dark-depth-ocean", - "ocean/rich-oceans" + {"biome": "ocean/deep", "weight": 1}, + {"biome": "ocean/dark-depth-ocean", "weight": 1}, + {"biome": "ocean/rich-oceans", "weight": 1} ], "shoreBiomeZoom": 0.15, "landBiomeZoom": 3.5, diff --git a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/regions/magnetics.json b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/regions/magnetics.json index 1516e065b..84c8b16b5 100644 --- a/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/regions/magnetics.json +++ b/core/src/test/resources/art/arcane/iris/core/modules/pack-before-the-port/regions/magnetics.json @@ -1,30 +1,29 @@ { "name": "The Magnetics", "color": "#7B9EC9", - "rarity": 15, "landBiomes": [ - "magnetics/plains", - "magnetics/frozen", - "magnetics/dunes", - "magnetics/mycelium", - "magnetics/glass", - "magnetics/noise" + {"biome": "magnetics/plains", "weight": 1}, + {"biome": "magnetics/frozen", "weight": 1}, + {"biome": "magnetics/dunes", "weight": 1}, + {"biome": "magnetics/mycelium", "weight": 1}, + {"biome": "magnetics/glass", "weight": 1}, + {"biome": "magnetics/noise", "weight": 1} ], "caveBiomes": [ - "carving/magnetic-hollows", - "carving/flux-crystal-caverns", - "carving/polarity-grotto" + {"biome": "carving/magnetic-hollows", "weight": 1}, + {"biome": "carving/flux-crystal-caverns", "weight": 1}, + {"biome": "carving/polarity-grotto", "weight": 1} ], "shoreBiomes": [ - "temperate/shore/beach", - "ocean/shore/beach" + {"biome": "temperate/shore/beach", "weight": 1}, + {"biome": "ocean/shore/beach", "weight": 1} ], "seaBiomeZoom": 6, "seaBiomes": [ - "ocean/deep", - "ocean/dark-depth-ocean", - "temperate/sea/ocean", - "temperate/sea/ocean-deep" + {"biome": "ocean/deep", "weight": 1}, + {"biome": "ocean/dark-depth-ocean", "weight": 1}, + {"biome": "temperate/sea/ocean", "weight": 1}, + {"biome": "temperate/sea/ocean-deep", "weight": 1} ], "landBiomeZoom": 3.5, "shoreBiomeZoom": 0.15, 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 index d6ff07e7c..5b53f5543 100644 --- 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 @@ -1,10 +1,11 @@ { "name": "Mesa Yellow", "color": "#83300B", - "rarity": 1, "derivative": "minecraft:windswept_savanna", "vanillaDerivative": "minecraft:badlands", - "children": ["mesa/dark"], + "children": [ + {"biome": "mesa/yellow", "weight": 1} + ], "generators": [ { "min": 50, 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 index 32b137d08..de202e401 100644 --- 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 @@ -1,7 +1,6 @@ { "name": "Mountain Beach", "color": "#365B8F", - "rarity": 1, "derivative": "minecraft:old_growth_spruce_taiga", "vanillaDerivative": "minecraft:old_growth_spruce_taiga", "generators": [{ diff --git a/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java b/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java index 4a598c434..e394298f3 100644 --- a/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java +++ b/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java @@ -19,14 +19,15 @@ package art.arcane.iris.engine.object.terrain.carving; import art.arcane.iris.builtin.IrisSeedPurposes; +import art.arcane.iris.modules.carve.CarvingChild; import art.arcane.iris.modules.carve.CarvingEntry; import art.arcane.iris.modules.carve.CarvingSettings; import com.volmit.ModuleLog; import com.volmit.config.Range; -import com.volmit.noise.NoiseSampler; import com.volmit.resource.PackResources; import com.volmit.world.PackBiome; import com.volmit.world.PackWorld; +import com.volmit.world.Weighted; import java.util.ArrayList; import java.util.HashMap; @@ -43,6 +44,7 @@ import java.util.concurrent.ConcurrentHashMap; * one a noise pattern selects at a column. */ public final class CarvingResolver { + private static final Weighted.Edge CHILD_EDGE = Weighted.Edge.LATER; private static final int MAX_CHILD_DEPTH = 32; private static final long CHILD_SEED_SALT = 0x9E3779B97F4A7C15L; @@ -53,7 +55,7 @@ public final class CarvingResolver { private final List entries; private final Map index; private final Map> rootEntriesByWorldY = new ConcurrentHashMap<>(); - private final Map selectionPlans = new ConcurrentHashMap<>(); + private final Map>> childOptions = new ConcurrentHashMap<>(); CarvingResolver(PackWorld world, List declared) { this.resources = world.resources(); @@ -88,7 +90,7 @@ public final class CarvingResolver { return rootEntryAtWorldY(y + minHeight); } - /** The root entry for a world Y as packs write them; null where no enabled entry with a biome holds it. */ + /** The root entry for a world Y as packs write it; null where no enabled entry with a biome holds it. */ public ResolvedCarvingEntry rootEntryAtWorldY(int worldY) { return rootEntriesByWorldY.computeIfAbsent(worldY, this::pickRootEntry).orElse(null); } @@ -156,97 +158,32 @@ public final class CarvingResolver { } private ResolvedCarvingEntry selectChild(ResolvedCarvingEntry parent, int worldX, int worldZ) { - List children = parent.children(); - if (children.isEmpty()) { + List> options = childOptions.computeIfAbsent(parent, this::buildChildOptions); + if (options.isEmpty()) { return parent; } - PackBiome parentBiome = entryBiome(parent); - if (parentBiome == null) { - return parent; - } - - ParentSelectionPlan selectionPlan = selectionPlans.computeIfAbsent(parent, key -> buildSelectionPlan(key, parentBiome)); - if (selectionPlan.parentOnly) { - return parent; - } - - NoiseSampler childGenerator = parent.childrenGenerator(childSeed, resources); - double sample = childGenerator.sample(worldX, worldZ); - int selectedIndex = (int) Math.round(sample * selectionPlan.maxIndex); - CarvingChoice selected = selectionPlan.get(selectedIndex); - if (selected == null || selected.entry == null) { - return parent; - } - - return selected.entry; + double sample = parent.childrenGenerator(childSeed, resources).sample(worldX, worldZ); + return Weighted.pick(options, sample, CHILD_EDGE); } - private ParentSelectionPlan buildSelectionPlan(ResolvedCarvingEntry parent, PackBiome parentBiome) { - List options = new ArrayList<>(); - for (String childId : parent.children()) { - if (childId == null || childId.isBlank()) { - continue; + private List> buildChildOptions(ResolvedCarvingEntry parent) { + List> options = new ArrayList<>(); + for (CarvingChild listed : parent.children()) { + ResolvedCarvingEntry child = listedEntry(parent, listed.id().trim()); + if (child != null && child.enabled() && entryBiome(child) != null) { + options.add(new Weighted<>(child, listed.weight())); } - - ResolvedCarvingEntry child = index.get(childId.trim()); - if (child == null || !child.enabled()) { - continue; - } - - PackBiome childBiome = entryBiome(child); - if (childBiome == null) { - continue; - } - - options.add(new CarvingChoice(child, rarity(childBiome))); } - - options.add(new CarvingChoice(parent, rarity(parentBiome))); - if (options.size() <= 1) { - return ParentSelectionPlan.parentOnly(); - } - - CarvingChoice[] mappedChoices = buildRarityMappedChoices(options); - if (mappedChoices.length == 0) { - return ParentSelectionPlan.parentOnly(); - } - - return new ParentSelectionPlan(mappedChoices); + return List.copyOf(options); } - private static CarvingChoice[] buildRarityMappedChoices(List choices) { - int max = 1; - for (CarvingChoice choice : choices) { - if (choice.rarity > max) { - max = choice.rarity; - } + private ResolvedCarvingEntry listedEntry(ResolvedCarvingEntry parent, String id) { + if (id.isEmpty()) { + return null; } - max++; - List mapped = new ArrayList<>(); - boolean flip = false; - for (CarvingChoice choice : choices) { - int count = max - choice.rarity; - for (int index = 0; index < count; index++) { - flip = !flip; - if (flip) { - mapped.add(choice); - } else { - mapped.add(0, choice); - } - } - } - - return mapped.toArray(new CarvingChoice[0]); - } - - private static int rarity(PackBiome biome) { - if (biome == null) { - return 1; - } - - return Math.max(biome.rarity(), 1); + return id.equals(parent.id().trim()) ? parent : index.get(id); } private static int clampDepth(int depth) { @@ -266,45 +203,4 @@ public final class CarvingResolver { } return Map.copyOf(index); } - - private static final class ParentSelectionPlan { - private final CarvingChoice[] mappedChoices; - private final int maxIndex; - private final boolean parentOnly; - - private ParentSelectionPlan(CarvingChoice[] mappedChoices) { - this.mappedChoices = mappedChoices; - this.maxIndex = mappedChoices.length - 1; - this.parentOnly = false; - } - - private ParentSelectionPlan() { - this.mappedChoices = null; - this.maxIndex = -1; - this.parentOnly = true; - } - - private static ParentSelectionPlan parentOnly() { - return new ParentSelectionPlan(); - } - - private CarvingChoice get(int index) { - if (mappedChoices == null || mappedChoices.length == 0) { - return null; - } - - if (index < 0) { - return mappedChoices[0]; - } - - if (index >= mappedChoices.length) { - return mappedChoices[mappedChoices.length - 1]; - } - - return mappedChoices[index]; - } - } - - private record CarvingChoice(ResolvedCarvingEntry entry, int rarity) { - } } diff --git a/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java b/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java index d47f11e93..fd9854e3c 100644 --- a/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java +++ b/module/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.terrain.carving; +import art.arcane.iris.modules.carve.CarvingChild; import art.arcane.iris.modules.carve.CarvingEntry; import art.arcane.volmlib.util.cache.AtomicCache; import com.volmit.ModuleLog; @@ -64,7 +65,7 @@ public final class ResolvedCarvingEntry { return settings.worldYRange(); } - public List children() { + public List children() { return settings.children(); } diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CarvingChild.java b/module/src/main/java/art/arcane/iris/modules/carve/CarvingChild.java new file mode 100644 index 000000000..993efb0ae --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/carve/CarvingChild.java @@ -0,0 +1,54 @@ +/* + * 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.modules.carve; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.world.Weighted; + +/** A child of a {@link CarvingEntry}: the id of another carving entry and the weight it has in the child noise's pick. */ +@Desc("A carving entry in the list the child noise picks from") +public final class CarvingChild { + @Required + @Desc("The id of the carving entry. List the parent's own id where it should stay itself.") + private String id = ""; + + @MinNumber(Weighted.MIN_WEIGHT) + @MaxNumber(Weighted.MAX_WEIGHT) + @Desc("A weight of two is just as if this entry were listed twice in a row, making it more common. The noise picks along the list in the order it is written.") + private int weight = 1; + + private CarvingChild() { + } + + public CarvingChild(String id, int weight) { + this.id = id; + this.weight = weight; + } + + public String id() { + return id == null ? "" : id; + } + + public int weight() { + return weight; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CarvingEntry.java b/module/src/main/java/art/arcane/iris/modules/carve/CarvingEntry.java index bcca11714..30ba85052 100644 --- a/module/src/main/java/art/arcane/iris/modules/carve/CarvingEntry.java +++ b/module/src/main/java/art/arcane/iris/modules/carve/CarvingEntry.java @@ -60,8 +60,8 @@ public final class CarvingEntry { @Desc("If this carving entry has child carving entries, this controls the shape pattern used to pick them.") private NoiseStyle childStyle = NoiseStyle.of("CELLULAR_IRIS_DOUBLE"); - @Desc("Child carving entry ids. Child ids can point back to parent ids to create cycles; recursion is bounded by childRecursionDepth.") - private List children = List.of(); + @Desc("What portions of this entry turn into: the child noise picks along this list in the order it is written. List this entry's own id where it should stay itself; an entry that is not listed does not stay anywhere. Child ids can point back to parent ids to create cycles; recursion is bounded by childRecursionDepth.") + private List children = List.of(); @Desc("Maximum recursion depth when resolving child carving entries from this entry.") private int childRecursionDepth = DEFAULT_CHILD_RECURSION_DEPTH; @@ -93,7 +93,7 @@ public final class CarvingEntry { return childStyle; } - public List children() { + public List children() { return children == null ? List.of() : Collections.unmodifiableList(children); } From 08f4bffca9a0ceac5863b94fb6fe6b0356b2c2e3 Mon Sep 17 00:00:00 2001 From: piexel Date: Tue, 10 Nov 2026 11:46:25 +0100 Subject: [PATCH 3/4] Add a pack converter from rarity to weighted entries A pack written with rarity needs its dimension regions, region biome lists, biome children and carving children rewritten to weighted entries. Lists that picked by 1 / rarity get the integer weights proportional to it (the least common multiple of the rarities over each, reduced by the greatest common divisor) and a list that would need a weight above 1000 stops the conversion; children keep their old rounded slots as half-slot weights with the parent listed among them. Files are edited as text so comments and formatting stay, and the conversion is all or nothing per pack. Next to the other pack tooling in core, run as PackWeightConverter [--dry-run] . The converter's test checks the fixture packs are already what it would write. v3: 96beb86e0 --- .../arcane/iris/core/pack/PackJsonText.java | 224 ++++++++ .../iris/core/pack/PackWeightConverter.java | 514 ++++++++++++++++++ .../core/pack/PackWeightConverterTest.java | 267 +++++++++ 3 files changed, 1005 insertions(+) create mode 100644 core/src/main/java/art/arcane/iris/core/pack/PackJsonText.java create mode 100644 core/src/main/java/art/arcane/iris/core/pack/PackWeightConverter.java create mode 100644 core/src/test/java/art/arcane/iris/core/pack/PackWeightConverterTest.java diff --git a/core/src/main/java/art/arcane/iris/core/pack/PackJsonText.java b/core/src/main/java/art/arcane/iris/core/pack/PackJsonText.java new file mode 100644 index 000000000..ee4d57af5 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/pack/PackJsonText.java @@ -0,0 +1,224 @@ +/* + * 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 java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +/** + * Positions in the text of a JSON file as Iris reads it, with comments and trailing commas, so a file can be edited + * in place without rewriting the formatting around the edit. + */ +final class PackJsonText { + private PackJsonText() { + } + + /** A member of an object: the key and where its value starts and ends in the text. */ + record Member(String key, int keyStart, int valueStart, int valueEnd) { + } + + /** A value inside an array: where it starts and ends in the text. */ + record Item(int start, int end) { + } + + /** A replacement of the text from {@code start} up to {@code end}. */ + record Edit(int start, int end, String replacement) { + } + + static List members(String text, int objectStart) { + if (text.charAt(objectStart) != '{') { + throw new IllegalArgumentException("An object was expected at " + objectStart); + } + + List members = new ArrayList<>(); + int index = skipBlank(text, objectStart + 1); + while (index < text.length() && text.charAt(index) != '}') { + if (text.charAt(index) == ',') { + index = skipBlank(text, index + 1); + continue; + } + + if (text.charAt(index) != '"') { + throw new IllegalArgumentException("A key was expected at " + index); + } + + int keyEnd = stringEnd(text, index); + int colon = skipBlank(text, keyEnd + 1); + int valueStart = skipBlank(text, colon + 1); + int valueEnd = valueEnd(text, valueStart); + members.add(new Member(text.substring(index + 1, keyEnd), index, valueStart, valueEnd)); + index = skipBlank(text, valueEnd); + } + return members; + } + + static Member member(List members, String key) { + return members.stream().filter(member -> member.key().equals(key)).findFirst().orElse(null); + } + + static List items(String text, int arrayStart) { + if (text.charAt(arrayStart) != '[') { + throw new IllegalArgumentException("An array was expected at " + arrayStart); + } + + List items = new ArrayList<>(); + int index = skipBlank(text, arrayStart + 1); + while (index < text.length() && text.charAt(index) != ']') { + if (text.charAt(index) == ',') { + index = skipBlank(text, index + 1); + continue; + } + + int end = valueEnd(text, index); + items.add(new Item(index, end)); + index = skipBlank(text, end); + } + return items; + } + + /** The text of the file with every edit applied; the edits must not overlap. */ + static String apply(String text, List edits) { + StringBuilder edited = new StringBuilder(text); + edits.stream().sorted(Comparator.comparingInt(Edit::start).reversed()) + .forEach(edit -> edited.replace(edit.start(), edit.end(), edit.replacement())); + return edited.toString(); + } + + /** The edit that takes the member out, together with its comma and, when it stands alone there, its lines. */ + static Edit removal(String text, Member member) { + int start = member.keyStart(); + int end = member.valueEnd(); + int after = skipBlank(text, end); + if (after < text.length() && text.charAt(after) == ',') { + end = after + 1; + } else { + int before = start - 1; + while (before >= 0 && Character.isWhitespace(text.charAt(before))) { + before--; + } + if (before >= 0 && text.charAt(before) == ',') { + start = before; + } + } + + int lineStart = text.lastIndexOf('\n', start - 1) + 1; + int lineEnd = text.indexOf('\n', end); + if (lineEnd < 0) { + lineEnd = text.length(); + } + + boolean alone = text.substring(lineStart, start).isBlank() && text.substring(end, lineEnd).isBlank(); + if (!alone) { + return new Edit(start, end, ""); + } + return new Edit(lineStart, Math.min(lineEnd + 1, text.length()), ""); + } + + /** The whitespace the line holding {@code position} starts with. */ + static String indentAt(String text, int position) { + int lineStart = text.lastIndexOf('\n', position - 1) + 1; + int index = lineStart; + while (index < position && (text.charAt(index) == ' ' || text.charAt(index) == '\t')) { + index++; + } + return text.substring(lineStart, index); + } + + static int skipBlank(String text, int index) { + int position = index; + while (position < text.length()) { + if (Character.isWhitespace(text.charAt(position))) { + position++; + } else if (isComment(text, position)) { + position = commentEnd(text, position); + } else { + break; + } + } + return position; + } + + static int valueEnd(String text, int start) { + char first = text.charAt(start); + if (first == '"') { + return stringEnd(text, start) + 1; + } + + if (first != '[' && first != '{') { + return literalEnd(text, start); + } + + int depth = 0; + int index = start; + while (index < text.length()) { + char current = text.charAt(index); + if (current == '"') { + index = stringEnd(text, index); + } else if (isComment(text, index)) { + index = commentEnd(text, index) - 1; + } else if (current == '[' || current == '{') { + depth++; + } else if (current == ']' || current == '}') { + depth--; + if (depth == 0) { + return index + 1; + } + } + index++; + } + throw new IllegalArgumentException("The value at " + start + " is not closed"); + } + + private static int literalEnd(String text, int start) { + int index = start; + while (index < text.length() && ",]} \t\r\n".indexOf(text.charAt(index)) < 0 && !isComment(text, index)) { + index++; + } + return index; + } + + private static int stringEnd(String text, int quote) { + int index = quote + 1; + while (index < text.length() && text.charAt(index) != '"') { + index += text.charAt(index) == '\\' ? 2 : 1; + } + if (index >= text.length()) { + throw new IllegalArgumentException("The string at " + quote + " is not closed"); + } + return index; + } + + private static boolean isComment(String text, int index) { + return text.startsWith("//", index) || text.startsWith("/*", index); + } + + private static int commentEnd(String text, int start) { + if (text.startsWith("//", start)) { + int lineEnd = text.indexOf('\n', start); + return lineEnd < 0 ? text.length() : lineEnd; + } + + int close = text.indexOf("*/", start + 2); + if (close < 0) { + throw new IllegalArgumentException("The comment at " + start + " is not closed"); + } + return close + 2; + } +} diff --git a/core/src/main/java/art/arcane/iris/core/pack/PackWeightConverter.java b/core/src/main/java/art/arcane/iris/core/pack/PackWeightConverter.java new file mode 100644 index 000000000..fe6c0719f --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/pack/PackWeightConverter.java @@ -0,0 +1,514 @@ +/* + * 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.pack.PackJsonText.Edit; +import art.arcane.iris.core.pack.PackJsonText.Item; +import art.arcane.iris.core.pack.PackJsonText.Member; +import com.google.gson.JsonParser; +import com.volmit.world.Weighted; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeSet; +import java.util.stream.Stream; + +/** + * Converts a pack from rarity to weighted list entries, keeping the share every list entry had in its pick: + *
+ * "landBiomes": [{"biome": "plains", "weight": 3}, ...]        (also seaBiomes, shoreBiomes, caveBiomes)
+ * "regions":    [{"region": "temperate", "weight": 2}, ...]     (in the dimension)
+ * "children":   [{"biome": "forest", "weight": 2}, {"biome": "plains", "weight": 5}, ...]
+ * "carving":    [{"id": "deep", "children": [{"id": "lush", "weight": 2}, {"id": "deep", "weight": 5}]}]
+ * 
+ * Region, biome and dimension lists were picked with a share of 1 / rarity per entry, so an entry's weight is the least + * common multiple of the list's rarities divided by its rarity, reduced by the greatest common divisor. Children were + * picked from rounded slots, the rarer a biome the fewer, alternating from both ends, with the parent among them; the + * parent is listed among its children wherever it kept the spot, in half slots, since the first and last slot only + * held half a slot of noise. A carving entry's children pick the same way by the rarity of the entries' biomes. The + * top-level {@code rarity} of biomes and regions is removed; nested rarities (loot, spawns, objects) stay. + *

+ * Files are edited as text, so formatting elsewhere stays; a rewritten list gets one entry per line. A list that would need + * a weight above {@link Weighted#MAX_WEIGHT} stops the conversion. A pack with lists already converted and lists not yet + * converted cannot be told apart from rarity 1 and is refused. + *

+ * Usage: {@code PackWeightConverter [--dry-run] ...} + */ +public final class PackWeightConverter { + private static final String INDENT_STEP = " "; + private static final String JSON_EXTENSION = ".json"; + private static final int DEFAULT_RARITY = 1; + private static final List BIOME_LISTS = List.of("landBiomes", "seaBiomes", "shoreBiomes", "caveBiomes"); + + /** The files a conversion changed (relative to the pack) and what it could not carry over exactly. */ + public record Result(List changedFiles, List warnings) { + } + + /** A pack the converter cannot convert while keeping every pick. */ + public static final class ConversionException extends RuntimeException { + ConversionException(String message) { + super(message); + } + } + + private record Entry(String key, int weight) { + } + + private record Option(String key, int rarity) { + } + + private record CarvingBand(String biome, boolean enabled) { + } + + private final Path pack; + private final Map biomeRarities; + private final Map regionRarities; + private final TreeSet warnings = new TreeSet<>(); + private String currentFile = ""; + + private PackWeightConverter(Path pack) throws IOException { + this.pack = pack; + this.biomeRarities = rarities("biomes"); + this.regionRarities = rarities("regions"); + } + + public static Result convert(Path pack, boolean dryRun) throws IOException { + PackWeightConverter converter = new PackWeightConverter(pack); + converter.refusePartlyConverted(); + Map converted = new LinkedHashMap<>(); + for (String folder : List.of("biomes", "regions", "dimensions")) { + for (Path file : converter.files(folder)) { + String text = converter.convertFile(folder, file); + if (text != null) { + converted.put(file, text); + } + } + } + + List changed = new ArrayList<>(); + for (Map.Entry file : converted.entrySet()) { + changed.add(relative(pack, file.getKey())); + if (!dryRun) { + Files.writeString(file.getKey(), file.getValue(), StandardCharsets.UTF_8); + } + } + return new Result(changed, List.copyOf(converter.warnings)); + } + + public static void main(String[] arguments) throws IOException { + boolean dryRun = false; + List packs = new ArrayList<>(); + for (String argument : arguments) { + if (argument.equals("--dry-run")) { + dryRun = true; + } else { + packs.add(Path.of(argument)); + } + } + + if (packs.isEmpty()) { + System.err.println("Usage: PackWeightConverter [--dry-run] ..."); + System.exit(2); + } + + for (Path folder : packs) { + try { + Result result = convert(folder, dryRun); + result.changedFiles().forEach(System.out::println); + result.warnings().forEach(warning -> System.out.println("warning: " + warning)); + System.out.println(folder + ": " + result.changedFiles().size() + " files " + (dryRun ? "would change" : "changed")); + } catch (ConversionException refusal) { + System.err.println(folder + ": " + refusal.getMessage()); + System.exit(1); + } + } + } + + /** The converted text of the file; null when nothing in it changes. */ + private String convertFile(String folder, Path file) throws IOException { + currentFile = relative(pack, file); + String text = Files.readString(file, StandardCharsets.UTF_8); + String converted = switch (folder) { + case "biomes" -> convertBiome(keyOf(pack.resolve(folder), file), text); + case "regions" -> convertRegion(text); + default -> convertDimension(text); + }; + if (converted.equals(text)) { + return null; + } + + verifyParses(converted); + return converted; + } + + private static String relative(Path pack, Path file) { + return pack.relativize(file).toString().replace('\\', '/'); + } + + private String convertBiome(String key, String text) { + List members = rootMembers(text); + List edits = new ArrayList<>(); + Member children = PackJsonText.member(members, "children"); + List childKeys = stringItems(text, children); + if (childKeys != null) { + edits.add(replaceList(text, children, "biome", childEntries(key, childKeys))); + } + addRarityRemoval(text, members, edits); + return PackJsonText.apply(text, edits); + } + + private String convertRegion(String text) { + List members = rootMembers(text); + List edits = new ArrayList<>(); + for (String list : BIOME_LISTS) { + Member member = PackJsonText.member(members, list); + List keys = stringItems(text, member); + if (keys != null) { + edits.add(replaceList(text, member, "biome", listEntries(keys, biomeRarities))); + } + } + addRarityRemoval(text, members, edits); + return PackJsonText.apply(text, edits); + } + + private String convertDimension(String text) { + List members = rootMembers(text); + List edits = new ArrayList<>(); + Member regions = PackJsonText.member(members, "regions"); + List regionKeys = stringItems(text, regions); + if (regionKeys != null) { + edits.add(replaceList(text, regions, "region", listEntries(regionKeys, regionRarities))); + } + + Member carving = PackJsonText.member(members, "carving"); + if (carving != null && text.charAt(carving.valueStart()) == '[') { + edits.addAll(convertCarving(text, carving)); + } + return PackJsonText.apply(text, edits); + } + + private List convertCarving(String text, Member carving) { + List> bands = new ArrayList<>(); + for (Item item : PackJsonText.items(text, carving.valueStart())) { + bands.add(text.charAt(item.start()) == '{' ? PackJsonText.members(text, item.start()) : List.of()); + } + + Map bandsById = new HashMap<>(); + for (List members : bands) { + String id = stringValue(text, PackJsonText.member(members, "id")).trim(); + if (!id.isEmpty()) { + bandsById.put(id, carvingBand(text, members)); + } + } + + List edits = new ArrayList<>(); + for (List members : bands) { + Member children = PackJsonText.member(members, "children"); + List childIds = stringItems(text, children); + if (childIds != null) { + edits.add(replaceList(text, children, "id", carvingChildEntries(text, members, childIds, bandsById))); + } + } + return edits; + } + + private CarvingBand carvingBand(String text, List members) { + Member enabled = PackJsonText.member(members, "enabled"); + boolean isEnabled = enabled == null || !text.startsWith("false", enabled.valueStart()); + return new CarvingBand(stringValue(text, PackJsonText.member(members, "biome")).trim(), isEnabled); + } + + private List carvingChildEntries(String text, List members, List childIds, Map bandsById) { + String parentId = stringValue(text, PackJsonText.member(members, "id")).trim(); + if (parentId.isEmpty()) { + throw new ConversionException(currentFile + ": a carving entry with children needs an id, so that it can list itself among them"); + } + + List