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 19f5014fd..e32c05851 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 @@ -298,11 +298,10 @@ public class CommandStudio implements DirectorExecutor { ) { if (noStudio()) return; - KList tables = EngineBukkitOps.getLootTables(engine(), RNG.r, player().getLocation().getBlock()); Inventory inv = Bukkit.createInventory(null, 27 * 2); try { - EngineBukkitOps.addItems(engine(), true, inv, tables, InventorySlotType.STORAGE, player().getWorld(), player().getLocation().getBlockX(), player().getLocation().getBlockY(), player().getLocation().getBlockZ()); + EngineBukkitOps.addLootOf(engine(), true, inv, player().getLocation()); } catch (Throwable e) { Iris.reportError(e); sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_CANNOT_ADD_ITEMS_VIRTUAL_INVENTORY_BECAUSE, MessageArgument.untrusted("value", String.valueOf(e.getMessage())))); @@ -329,7 +328,7 @@ public class CommandStudio implements DirectorExecutor { inv.clear(); } - EngineBukkitOps.addItems(engine, true, inv, tables, InventorySlotType.STORAGE, player.getWorld(), player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()); + EngineBukkitOps.addLootOf(engine, true, inv, player.getLocation()); }, fast ? 5 : 35)); sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_INVENTORY_NOW)); diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedItem.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedItem.java index b2f5d7414..781d02936 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedItem.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedItem.java @@ -20,6 +20,7 @@ package art.arcane.iris.modded; import art.arcane.iris.spi.PlatformItem; import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; import java.util.concurrent.ConcurrentHashMap; @@ -55,4 +56,9 @@ public final class ModdedItem implements PlatformItem { public Object nativeHandle() { return item; } + + @Override + public int maxDurability() { + return new ItemStack(item).getMaxDamage(); + } } diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedItemTranslator.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedItemTranslator.java index 3efb324a9..690e25d8d 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedItemTranslator.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedItemTranslator.java @@ -19,6 +19,7 @@ package art.arcane.iris.modded; import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.engine.loot.LootTables; import art.arcane.iris.engine.object.loot.InventorySlotType; import art.arcane.iris.engine.object.entity.IrisAttributeModifier; import art.arcane.iris.engine.object.loot.IrisEnchantment; @@ -80,7 +81,7 @@ public final class ModdedItemTranslator { return out; } - RNG rng = LootResolver.tableRng(lootSeed, table, x, y, z); + RNG rng = LootTables.rng(lootSeed, table, x, y, z); int m = 0; int c = 0; int mx = Math.max(0, LootResolver.inclusive(rng, table.getMinPicked(), table.getMaxPicked())); @@ -118,7 +119,7 @@ public final class ModdedItemTranslator { public static ItemStack item(IrisLoot loot, IrisLootTable table, RNG rng, long lootSeed, int entryIndex, ServerLevel level, int x, int y, int z) { long combinedRarity = LootResolver.combinedRarity(loot.getRarity(), table.getRarity()); - if (!LootResolver.spatialOneIn(lootSeed, table, entryIndex, x, y, z, combinedRarity)) { + if (!LootTables.spatialOneIn(lootSeed, table, entryIndex, x, y, z, combinedRarity)) { return null; } diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedLootApplier.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedLootApplier.java index a8611cf12..ffa64a300 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedLootApplier.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedLootApplier.java @@ -23,6 +23,7 @@ import art.arcane.iris.engine.object.loot.IrisObjectVanillaLoot; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.engine.loot.LootTables; import art.arcane.iris.engine.framework.PlacedObject; import art.arcane.iris.engine.object.loot.IObjectLoot; import art.arcane.iris.engine.object.loot.InventorySlotType; @@ -121,7 +122,7 @@ public final class ModdedLootApplier { } } - LootResolver.resolveEnvironmentSources( + LootTables.resolveEnvironmentSources( sources, engine, rng, diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedLootApplierTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedLootApplierTest.java index 56665f239..75fec1946 100644 --- a/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedLootApplierTest.java +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedLootApplierTest.java @@ -1,6 +1,7 @@ package art.arcane.iris.modded; import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.engine.loot.LootTables; import art.arcane.iris.engine.object.loot.IrisLootMode; import art.arcane.volmlib.util.math.RNG; import net.minecraft.resources.Identifier; @@ -30,7 +31,7 @@ public class ModdedLootApplierTest { public void addAppendsSourcesInOrder() { List sources = new ArrayList<>(List.of("placement-native")); - LootResolver.injectSources(sources, List.of("dimension-iris", "region-iris"), IrisLootMode.ADD, false); + LootTables.injectSources(sources, List.of("dimension-iris", "region-iris"), IrisLootMode.ADD, false); assertEquals(List.of("placement-native", "dimension-iris", "region-iris"), sources); } @@ -39,7 +40,7 @@ public class ModdedLootApplierTest { public void clearRemovesEverythingAndContributesNothing() { List sources = new ArrayList<>(List.of("placement-native", "dimension-iris")); - LootResolver.injectSources(sources, List.of("biome-iris"), IrisLootMode.CLEAR, false); + LootTables.injectSources(sources, List.of("biome-iris"), IrisLootMode.CLEAR, false); assertEquals(List.of(), sources); } @@ -48,7 +49,7 @@ public class ModdedLootApplierTest { public void replaceRemovesNativeAndIrisSourcesBeforeAdding() { List sources = new ArrayList<>(List.of("placement-native", "dimension-iris")); - LootResolver.injectSources(sources, List.of("biome-iris"), IrisLootMode.REPLACE, false); + LootTables.injectSources(sources, List.of("biome-iris"), IrisLootMode.REPLACE, false); assertEquals(List.of("biome-iris"), sources); } @@ -63,7 +64,7 @@ public class ModdedLootApplierTest { public void fallbackDoesNotOverrideExistingNativeOrIrisSources() { List sources = new ArrayList<>(List.of("placement-native", "dimension-iris")); - LootResolver.injectSources(sources, List.of("fallback-iris"), IrisLootMode.FALLBACK, false); + LootTables.injectSources(sources, List.of("fallback-iris"), IrisLootMode.FALLBACK, false); assertEquals(List.of("placement-native", "dimension-iris"), sources); } @@ -72,7 +73,7 @@ public class ModdedLootApplierTest { public void fallbackAddsSourcesWhenPlacementIsEmpty() { List sources = new ArrayList<>(); - LootResolver.injectSources(sources, List.of("fallback-iris"), IrisLootMode.FALLBACK, true); + LootTables.injectSources(sources, List.of("fallback-iris"), IrisLootMode.FALLBACK, true); assertEquals(List.of("fallback-iris"), sources); } diff --git a/core/src/main/java/art/arcane/iris/core/events/IrisLootEvent.java b/core/src/main/java/art/arcane/iris/core/events/IrisLootEvent.java index d0286b3c0..87576d982 100644 --- a/core/src/main/java/art/arcane/iris/core/events/IrisLootEvent.java +++ b/core/src/main/java/art/arcane/iris/core/events/IrisLootEvent.java @@ -1,8 +1,6 @@ package art.arcane.iris.core.events; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.loot.InventorySlotType; -import art.arcane.iris.engine.object.loot.IrisLootTable; import art.arcane.iris.platform.bukkit.BukkitPlatform; import art.arcane.iris.spi.IrisLogging; import art.arcane.volmlib.util.collection.KList; @@ -17,6 +15,7 @@ import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import org.bukkit.event.world.LootGenerateEvent; +import com.volmit.service.Loot; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; @@ -52,21 +51,18 @@ public class IrisLootEvent extends Event { private final Engine engine; private final Block block; - private final InventorySlotType slot; - private final KList tables; + private final KList tables; /** * Constructor for IrisLootEvent with mode selection. * * @param engine The engine instance. * @param block The block associated with the event. - * @param slot The inventory slot type. - * @param tables The list of IrisLootTables. (mutable*) + * @param tables The loot tables the container draws from, as the pack's modules named them. (mutable*) */ - public IrisLootEvent(Engine engine, Block block, InventorySlotType slot, KList tables) { + public IrisLootEvent(Engine engine, Block block, KList tables) { this.engine = engine; this.block = block; - this.slot = slot; this.tables = tables; } diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisItemRegistry.java b/core/src/main/java/art/arcane/iris/core/modules/IrisItemRegistry.java new file mode 100644 index 000000000..8d2d4f6b0 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisItemRegistry.java @@ -0,0 +1,59 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.modules; + +import art.arcane.iris.core.link.Identifier; +import art.arcane.iris.core.service.ExternalDataSVC; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.IrisServices; +import art.arcane.iris.spi.PlatformItem; +import com.volmit.item.ItemRegistry; +import org.bukkit.inventory.ItemStack; + +import java.util.Optional; +import java.util.OptionalInt; + +/** + * IrisApi's view of the bound platform's items: the platform's registry for plain keys, and the item providers of + * Iris's external data service for keys with a namespace of their own ({@code itemsadder:ruby}), which is how packs name + * custom items. + */ +public final class IrisItemRegistry implements ItemRegistry { + private static final String MINECRAFT_PREFIX = "minecraft:"; + private static final char NAMESPACE_SEPARATOR = ':'; + + @Override + public OptionalInt maxDurability(String key) { + if (isCustomItem(key)) { + return customItemDurability(key); + } + PlatformItem item = IrisPlatforms.get().registries().item(key); + return item == null ? OptionalInt.empty() : OptionalInt.of(item.maxDurability()); + } + + /** Whether {@code key} names an item of an external provider, which resolves it, rather than of the platform. */ + public static boolean isCustomItem(String key) { + return !key.startsWith(MINECRAFT_PREFIX) && key.indexOf(NAMESPACE_SEPARATOR) >= 0; + } + + private static OptionalInt customItemDurability(String key) { + Optional stack = IrisServices.get(ExternalDataSVC.class).getItemStack(Identifier.fromString(key), null); + return stack.isEmpty() ? OptionalInt.empty() : OptionalInt.of(stack.get().getType().getMaxDurability()); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisModuleHost.java b/core/src/main/java/art/arcane/iris/core/modules/IrisModuleHost.java index 54eebface..8177d74b0 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisModuleHost.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisModuleHost.java @@ -22,6 +22,7 @@ import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.actuator.BiomeModule; import art.arcane.iris.engine.actuator.DecorantModule; import art.arcane.iris.engine.actuator.TerrainModule; +import art.arcane.iris.engine.loot.LootModule; import art.arcane.iris.engine.mantle.components.ObjectModule; import art.arcane.iris.engine.mantle.components.StructureModule; import art.arcane.iris.engine.modifier.CarveModule; @@ -70,7 +71,7 @@ public final class IrisModuleHost { private static List generationModules() { return List.of(new BiomeModule(), new TerrainModule(), new CarveModule(), new ObjectModule(), new StructureModule(), new PostModule(), new FloatingModule(), new DepositModule(), new MatterModule(), new DecorantModule(), - new PerfectionModule(), new CustomModule()); + new PerfectionModule(), new CustomModule(), new LootModule()); } /** Whether {@code type} is one of Iris's own classes that built-in settings may hold. */ 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 988ef5161..2259f5040 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.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.region.IrisRegion; import com.volmit.block.BlockRegistry; import com.volmit.host.ResourceKindRegistration; +import com.volmit.item.ItemRegistry; import com.volmit.noise.NoiseFactory; import com.volmit.object.GeneratedObject; import com.volmit.resource.PackResources; @@ -69,6 +70,7 @@ public final class IrisPackResources implements PackResources { private final PackResourceIds ids; private final UUID snapshotId = UUID.randomUUID(); private final BlockRegistry blocks; + private final ItemRegistry items = new IrisItemRegistry(); private final NoiseFactory noise; private final Map, Kind> irisKinds; private final Supplier>> moduleKindList; @@ -122,6 +124,11 @@ public final class IrisPackResources implements PackResources { return blocks; } + @Override + public ItemRegistry items() { + return items; + } + @Override public NoiseFactory noise() { return noise; diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleServices.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleServices.java index e368506d0..75f3544c1 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleServices.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleServices.java @@ -21,11 +21,16 @@ package art.arcane.iris.core.modules; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.Engine; import com.volmit.host.FeatureCatalog; +import com.volmit.item.ItemDrop; +import com.volmit.service.BlockDrops; import com.volmit.service.LocateResult; +import com.volmit.service.Loot; import com.volmit.service.ObjectsAt; import com.volmit.service.StructureLocator; import com.volmit.world.PackWorld; +import java.util.ArrayList; import java.util.LinkedHashSet; +import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.Set; @@ -62,6 +67,39 @@ public final class ModuleServices { return new ObjectsAt.PlacedBy(biomes, regions); } + /** The loot tables the modules say the container at {@code site} draws from, in module order. */ + public static List lootTables(Engine engine, Loot.Site site) { + PackWorld world = engine.getGeneration().world(); + List tables = new ArrayList<>(); + for (Loot provider : catalog(engine.getData()).services(Loot.class)) { + tables.addAll(provider.tables(world, site)); + } + return tables; + } + + /** The items loot table {@code key} gives at {@code site}, from the module that knows the table. */ + public static List lootItems(Engine engine, Loot.Site site, String key) { + PackWorld world = engine.getGeneration().world(); + List items = new ArrayList<>(); + for (Loot provider : catalog(engine.getData()).services(Loot.class)) { + items.addAll(provider.items(world, site, key)); + } + return items; + } + + /** What the modules drop for the broken block, put together. */ + public static BlockDrops.Result blockDrops(Engine engine, BlockDrops.Broken broken) { + PackWorld world = engine.getGeneration().world(); + List drops = new ArrayList<>(); + boolean replacesVanillaDrops = false; + for (BlockDrops provider : catalog(engine.getData()).services(BlockDrops.class)) { + BlockDrops.Result result = provider.drops(world, broken); + drops.addAll(result.drops()); + replacesVanillaDrops |= result.replacesVanillaDrops(); + } + return new BlockDrops.Result(drops, replacesVanillaDrops); + } + /** Every structure key the pack's modules know, placed or not. */ public static Set structureKeys(IrisData data) { Set keys = new LinkedHashSet<>(); diff --git a/core/src/main/java/art/arcane/iris/engine/WorldBlockDropRouter.java b/core/src/main/java/art/arcane/iris/engine/WorldBlockDropRouter.java index c3949a283..3ecd6134d 100644 --- a/core/src/main/java/art/arcane/iris/engine/WorldBlockDropRouter.java +++ b/core/src/main/java/art/arcane/iris/engine/WorldBlockDropRouter.java @@ -18,13 +18,12 @@ package art.arcane.iris.engine; -import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.service.tree.BlockDropRouter; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.loot.IrisBlockDrops; import art.arcane.iris.engine.object.marker.IrisMarker; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.engine.platform.EngineBukkitOps; +import art.arcane.iris.core.modules.ModuleServices; +import art.arcane.iris.core.modules.PlatformBlockStates; +import art.arcane.iris.platform.bukkit.BukkitBlockState; +import art.arcane.iris.platform.bukkit.BukkitItemStacks; import art.arcane.iris.platform.bukkit.BukkitWorldBinding; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.util.common.scheduling.J; @@ -35,8 +34,10 @@ import org.bukkit.World; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.inventory.ItemStack; +import com.volmit.block.BlockState; +import com.volmit.service.BlockDrops; +import com.volmit.world.BlockPosition; -import java.util.List; import java.util.function.Consumer; /** @@ -57,19 +58,10 @@ final class WorldBlockDropRouter { int mantleY = toMantleY(e.getBlock().getY(), manager.getEngine().getWorld().minHeight()); int blockZ = e.getBlock().getZ(); - KList d = new KList<>(); - IrisBiome b = EngineBukkitOps.getBiome(manager.getEngine(), e.getBlock().getLocation()); - List dropProviders = filterDrops(b.getBlockDrops(), e, manager.getData()); + BlockDrops.Result result = ModuleServices.blockDrops(manager.getEngine(), brokenBlock(e)); + KList d = BukkitItemStacks.createAll(result.drops()); - if (dropProviders.stream().noneMatch(IrisBlockDrops::isSkipParents)) { - IrisRegion r = EngineBukkitOps.getRegion(manager.getEngine(), e.getBlock().getLocation()); - dropProviders.addAll(filterDrops(r.getBlockDrops(), e, manager.getData())); - dropProviders.addAll(filterDrops(manager.getEngine().getDimension().getBlockDrops(), e, manager.getData())); - } - - dropProviders.forEach(provider -> provider.fillDrops(false, d)); - - if (dropProviders.stream().anyMatch(IrisBlockDrops::isReplaceVanillaDrops)) { + if (result.replacesVanillaDrops()) { e.setDropItems(false); } @@ -128,7 +120,10 @@ final class WorldBlockDropRouter { return mantleY + minHeight; } - private List filterDrops(KList drops, BlockBreakEvent e, IrisData data) { - return new KList<>(drops.stream().filter(d -> d.shouldDropFor(e.getBlock().getBlockData(), data)).toList()); + private BlockDrops.Broken brokenBlock(BlockBreakEvent e) { + int relativeY = toMantleY(e.getBlock().getY(), manager.getEngine().getWorld().minHeight()); + BlockPosition position = new BlockPosition(e.getBlock().getX(), relativeY, e.getBlock().getZ()); + BlockState block = BlockState.parse(PlatformBlockStates.namespaced(BukkitBlockState.of(e.getBlock().getBlockData()).key())); + return new BlockDrops.Broken(position, block); } } diff --git a/core/src/main/java/art/arcane/iris/engine/framework/LootResolver.java b/core/src/main/java/art/arcane/iris/engine/framework/LootResolver.java index 300e8339b..560e8e314 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/LootResolver.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/LootResolver.java @@ -18,18 +18,10 @@ package art.arcane.iris.engine.framework; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.loot.IrisLootMode; -import art.arcane.iris.engine.object.loot.IrisLootReference; -import art.arcane.iris.engine.object.loot.IrisLootTable; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; import java.util.ArrayList; import java.util.List; -import java.util.Objects; -import java.util.function.Function; import java.util.function.ToIntFunction; public final class LootResolver { @@ -52,17 +44,18 @@ public final class LootResolver { return mix(seed ^ ((long) z * 0x8CB92BA72F3D8DD7L)); } - public static RNG tableRng(long lootSeed, IrisLootTable table, int x, int y, int z) { - return new RNG(tableSeed(lootSeed, table, x, y, z)); + /** The random stream of one loot table at one position; {@code tableIdentity} names the table (its key, else its name). */ + public static RNG tableRng(long lootSeed, String tableIdentity, int x, int y, int z) { + return new RNG(tableSeed(lootSeed, tableIdentity, x, y, z)); } - public static long tableSeed(long lootSeed, IrisLootTable table, int x, int y, int z) { - return mix(containerSeed(lootSeed, x, y, z) ^ stableHash(tableIdentity(table)) ^ TABLE_SALT); + public static long tableSeed(long lootSeed, String tableIdentity, int x, int y, int z) { + return mix(containerSeed(lootSeed, x, y, z) ^ stableHash(tableIdentity) ^ TABLE_SALT); } public static boolean spatialOneIn( long lootSeed, - IrisLootTable table, + String tableIdentity, int entryIndex, int x, int y, @@ -72,7 +65,7 @@ public final class LootResolver { if (rarity <= 1L) { return true; } - long roll = mix(tableSeed(lootSeed, table, x, y, z) ^ ((long) entryIndex * ENTRY_SALT)); + long roll = mix(tableSeed(lootSeed, tableIdentity, x, y, z) ^ ((long) entryIndex * ENTRY_SALT)); return new RNG(roll).nextLong(rarity) == 0L; } @@ -119,63 +112,6 @@ public final class LootResolver { return null; } - public static void resolveEnvironmentSources( - List sources, - Engine engine, - RNG rng, - int x, - int relativeY, - int z, - boolean objectLootDefined, - Function mapper - ) { - IrisRegion region = engine.getComplex().getRegionStream().get(x, z); - IrisBiome surfaceBiome = engine.getComplex().getTrueBiomeStream().get(x, z); - double terrainHeight = engine.getComplex().getHeightStream().get(x, z); - IrisBiome contextualBiome = relativeY < terrainHeight - ? engine.getCaveBiome(x, relativeY, z) - : surfaceBiome; - if (contextualBiome == null) { - contextualBiome = surfaceBiome; - } - - boolean distinctContextualBiome = !sameBiome(surfaceBiome, contextualBiome); - double multiplier = engine.getDimension().getLoot().getMultiplier() - * region.getLoot().getMultiplier() - * surfaceBiome.getLoot().getMultiplier(); - if (distinctContextualBiome) { - multiplier *= contextualBiome.getLoot().getMultiplier(); - } - - boolean fallback = !objectLootDefined; - injectReference(sources, engine.getDimension().getLoot(), engine, mapper, fallback); - injectReference(sources, region.getLoot(), engine, mapper, fallback); - injectReference(sources, surfaceBiome.getLoot(), engine, mapper, fallback); - if (distinctContextualBiome) { - injectReference(sources, contextualBiome.getLoot(), engine, mapper, fallback); - } - scaleSources(sources, multiplier, rng); - } - - public static void injectSources( - List sources, - List additions, - IrisLootMode mode, - boolean fallback - ) { - if (mode == IrisLootMode.FALLBACK && !fallback) { - return; - } - if (mode == IrisLootMode.CLEAR) { - sources.clear(); - return; - } - if (mode == IrisLootMode.REPLACE) { - sources.clear(); - } - sources.addAll(additions); - } - public static void scaleSources(List sources, double multiplier, RNG rng) { if (!Double.isFinite(multiplier) || multiplier < 0D) { throw new IllegalArgumentException("Effective loot source multiplier must be finite and non-negative, got " @@ -206,49 +142,6 @@ public final class LootResolver { expandSources(sources, original, order, target, rng); } - static boolean sameBiome(IrisBiome first, IrisBiome second) { - if (first == second) { - return true; - } - if (first == null || second == null) { - return false; - } - return Objects.equals(first.getLoadKey(), second.getLoadKey()); - } - - static String tableIdentity(IrisLootTable table) { - if (table == null) { - return ""; - } - String loadKey = table.getLoadKey(); - if (loadKey != null && !loadKey.isBlank()) { - return loadKey; - } - String name = table.getName(); - return name == null ? "" : name; - } - - private static void injectReference( - List sources, - IrisLootReference reference, - Engine engine, - Function mapper, - boolean fallback - ) { - KList tables = reference.getLootTables(engine.getComplex()); - KList additions = new KList<>(); - for (IrisLootTable table : tables) { - if (table == null) { - continue; - } - T source = mapper.apply(table); - if (source != null) { - additions.add(source); - } - } - injectSources(sources, additions, reference.getMode(), fallback); - } - private static void shrinkSources(List sources, List original, int[] order, int target, RNG rng) { shuffleOrder(order, rng); boolean[] selected = new boolean[original.size()]; diff --git a/core/src/main/java/art/arcane/iris/engine/framework/placer/WorldObjectPlacer.java b/core/src/main/java/art/arcane/iris/engine/framework/placer/WorldObjectPlacer.java index fb9a6b9ac..2b9e0ba64 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/placer/WorldObjectPlacer.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/placer/WorldObjectPlacer.java @@ -5,20 +5,18 @@ import art.arcane.iris.platform.bukkit.BukkitBlockResolution; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.tools.IrisToolbelt; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.LootResolver; import art.arcane.iris.core.events.IrisLootEvent; import art.arcane.iris.engine.mantle.EngineMantle; import art.arcane.iris.engine.platform.EngineBukkitOps; import art.arcane.iris.engine.platform.PlatformChunkGenerator; import art.arcane.iris.engine.object.placement.IObjectPlacer; -import art.arcane.iris.engine.object.loot.InventorySlotType; -import art.arcane.iris.engine.object.loot.IrisLootTable; import art.arcane.iris.engine.object.prefab.TileData; import art.arcane.iris.platform.bukkit.BukkitBlockState; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.scheduling.J; import art.arcane.volmlib.util.collection.KList; +import com.volmit.service.Loot; import art.arcane.iris.util.common.data.IrisCustomData; import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.matter.MatterCavern; @@ -85,16 +83,15 @@ public class WorldObjectPlacer implements IObjectPlacer { int x = block.getX(); int y = block.getY(); int z = block.getZ(); - RNG rng = LootResolver.containerRng(engine.getSeedManager().getLoot(), x, y, z); - KList tables = EngineBukkitOps.getLootTables(engine, rng, block); + KList tables = EngineBukkitOps.getLootTables(engine, block); try { - Bukkit.getPluginManager().callEvent(new IrisLootEvent(engine, block, InventorySlotType.STORAGE, tables)); + Bukkit.getPluginManager().callEvent(new IrisLootEvent(engine, block, tables)); if (tables.isEmpty()) { return; } InventoryHolder holder = (InventoryHolder) block.getState(); - EngineBukkitOps.addItems(engine, false, holder.getInventory(), tables, InventorySlotType.STORAGE, world, x, y, z); + EngineBukkitOps.addItems(engine, false, holder.getInventory(), tables, world, x, y, z); } catch (Throwable e) { IrisLogging.reportError(e); } diff --git a/core/src/main/java/art/arcane/iris/engine/platform/EngineBukkitOps.java b/core/src/main/java/art/arcane/iris/engine/platform/EngineBukkitOps.java index 2de919e08..53690d89b 100644 --- a/core/src/main/java/art/arcane/iris/engine/platform/EngineBukkitOps.java +++ b/core/src/main/java/art/arcane/iris/engine/platform/EngineBukkitOps.java @@ -25,12 +25,12 @@ import art.arcane.iris.core.service.ExternalDataSVC; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.GenerationSessionLease; import art.arcane.iris.engine.framework.Locator; +import art.arcane.iris.core.modules.ModuleServices; +import art.arcane.iris.core.modules.PlatformBlockStates; import art.arcane.iris.engine.framework.LootResolver; -import art.arcane.iris.engine.framework.PlacedObject; +import art.arcane.iris.platform.bukkit.BukkitItemStacks; import art.arcane.iris.engine.framework.WrongEngineBroException; -import art.arcane.iris.engine.object.loot.InventorySlotType; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.loot.IrisLootTable; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.engine.object.prefab.TileData; import art.arcane.iris.platform.bukkit.BukkitBlockResolution; @@ -63,6 +63,10 @@ import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.NamespacedKey; +import org.bukkit.loot.LootContext; +import org.bukkit.loot.LootTable; +import com.volmit.service.Loot; +import com.volmit.world.BlockPosition; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; @@ -76,6 +80,7 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.loot.Lootable; import java.lang.reflect.Method; +import java.util.List; import java.util.UUID; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; @@ -162,14 +167,14 @@ public final class EngineBukkitOps { if (grid[x][z] == Integer.MIN_VALUE) { continue; } - update(engine, x, grid[x][z], z, c, chunk); + update(engine, x, grid[x][z], z, c); } } chunk.iterate(MatterUpdate.class, (x, yf, z, v) -> { int y = yf + engine.getWorld().minHeight(); if (v != null && v.isUpdate()) { - update(engine, x, y, z, c, chunk); + update(engine, x, y, z, c); } }); chunk.deleteSlices(MatterUpdate.class); @@ -274,7 +279,7 @@ public final class EngineBukkitOps { } } - public static void update(Engine engine, int x, int y, int z, Chunk c, MantleChunk mc) { + public static void update(Engine engine, int x, int y, int z, Chunk c) { World world = c.getWorld(); if (y < world.getMinHeight() || y >= world.getMaxHeight()) { return; @@ -283,30 +288,8 @@ public final class EngineBukkitOps { BlockData data = block.getBlockData(); engine.blockUpdatedMetric(); if (BukkitBlockResolution.isStorage(data)) { - InventorySlotType slot = null; - if (BukkitBlockResolution.isStorageChest(data)) { - slot = InventorySlotType.STORAGE; - } - - if (slot != null) { - if (!isCanonicalContainer(block)) { - return; - } - int worldX = block.getX(); - int worldZ = block.getZ(); - RNG rx = LootResolver.containerRng(engine.getSeedManager().getLoot(), worldX, y, worldZ); - KList tables = getLootTables(engine, rx, block, mc, hasNativeLootTable(block)); - - try { - Bukkit.getPluginManager().callEvent(new IrisLootEvent(engine, block, slot, tables)); - if (tables.isEmpty()) return; - InventoryHolder m = (InventoryHolder) block.getState(); - addItems(engine, false, m.getInventory(), tables, slot, c.getWorld(), worldX, y, worldZ); - - } catch (Throwable e) { - IrisLogging.reportError(e); - } + fillStorageChest(engine, block, y, c); } } else { block.setType(Material.AIR, false); @@ -314,6 +297,23 @@ public final class EngineBukkitOps { } } + private static void fillStorageChest(Engine engine, Block block, int y, Chunk c) { + if (!isCanonicalContainer(block)) { + return; + } + KList tables = new KList<>(getLootTables(engine, block, hasNativeLootTable(block))); + + try { + Bukkit.getPluginManager().callEvent(new IrisLootEvent(engine, block, tables)); + if (tables.isEmpty()) return; + InventoryHolder m = (InventoryHolder) block.getState(); + addItems(engine, false, m.getInventory(), tables, c.getWorld(), block.getX(), y, block.getZ()); + + } catch (Throwable e) { + IrisLogging.reportError(e); + } + } + public static boolean isCanonicalContainer(Block block) { if (!(block.getBlockData() instanceof Chest chest) || chest.getType() == Chest.Type.SINGLE) { return true; @@ -407,66 +407,32 @@ public final class EngineBukkitOps { inventory.setContents(nitems); } - public static KList getLootTables(Engine engine, RNG rng, Block b) { - MantleChunk mc = engine.getMantle().getMantle().getChunk(b.getChunk()).use(); - try { - return getLootTables(engine, rng, b, mc, hasNativeLootTable(b)); - } finally { - mc.release(); - } + /** The loot tables the modules say the container at {@code b} draws from, in the order their items are added. */ + public static KList getLootTables(Engine engine, Block b) { + return new KList<>(getLootTables(engine, b, hasNativeLootTable(b))); } - public static KList getLootTables(Engine engine, RNG rng, Block b, MantleChunk mc) { - return getLootTables(engine, rng, b, mc, hasNativeLootTable(b)); + private static List getLootTables(Engine engine, Block b, boolean nativeLootDefined) { + return ModuleServices.lootTables(engine, lootSite(engine, b, nativeLootDefined)); } - public static KList getLootTables(Engine engine, RNG rng, Block b, MantleChunk mc, boolean nativeLootDefined) { - int rx = b.getX(); - int rz = b.getZ(); - int ry = b.getY() - engine.getWorld().minHeight(); - KList tables = new KList<>(); - boolean objectLootDefined = nativeLootDefined; - - PlacedObject po = engine.getObjectPlacement(rx, ry, rz, mc); - if (po != null && po.getPlacement() != null) { - if (BukkitBlockResolution.isStorageChest(b.getBlockData())) { - objectLootDefined = objectLootDefined - || po.getPlacement().getLoot().isNotEmpty() - || po.getPlacement().getVanillaLoot().isNotEmpty(); - IrisLootTable table = po.getPlacement().getTable( - BukkitBlockState.of(b.getBlockData()), engine.getData(), rng); - if (table != null) { - tables.add(table); - if (po.getPlacement().isOverrideGlobalLoot()) { - return new KList<>(table); - } - } - } - } - - LootResolver.resolveEnvironmentSources( - tables, - engine, - rng, - rx, - ry, - rz, - objectLootDefined, - table -> table - ); - - return tables; + private static Loot.Site lootSite(Engine engine, Block b, boolean nativeLootDefined) { + BlockPosition position = new BlockPosition(b.getX(), b.getY() - engine.getMinHeight(), b.getZ()); + BlockData data = b.getBlockData(); + com.volmit.block.BlockState container = BukkitBlockResolution.isStorageChest(data) + ? com.volmit.block.BlockState.parse(PlatformBlockStates.namespaced(BukkitBlockState.of(data).key())) + : null; + return new Loot.Site(position, container, nativeLootDefined, false); } - public static void addItems(Engine engine, boolean debug, Inventory inv, KList tables, InventorySlotType slot, World world, int x, int y, int z) { - KList items = new KList<>(); + /** Adds the loot a container at {@code at} would hold to {@code inv}; {@code debug} makes the items say where they came from. */ + public static void addLootOf(Engine engine, boolean debug, Inventory inv, Location at) { + addItems(engine, debug, inv, getLootTables(engine, at.getBlock()), at.getWorld(), at.getBlockX(), at.getBlockY(), at.getBlockZ()); + } - for (IrisLootTable i : tables) { - if (i == null) - continue; - items.addAll(i.getLoot(debug, engine.getSeedManager().getLoot(), slot, world, x, y, z)); - } - if (IrisLootEvent.callLootEvent(items, inv, world, x, y, z)) + public static void addItems(Engine engine, boolean debug, Inventory inv, List tables, World world, int x, int y, int z) { + List items = lootItems(engine, debug, tables, world, x, y, z); + if (IrisLootEvent.callLootEvent(new KList<>(items), inv, world, x, y, z)) return; if (PaperLib.isPaper() && engine.getWorld().hasPlatformWorld()) { @@ -504,6 +470,29 @@ public final class EngineBukkitOps { } } + /** The items of {@code tables} at the spot, in the tables' order: the modules' for pack tables, the platform's own for platform tables. */ + private static List lootItems(Engine engine, boolean debug, List tables, World world, int x, int y, int z) { + Loot.Site site = new Loot.Site(new BlockPosition(x, y - engine.getMinHeight(), z), null, false, debug); + List items = new KList<>(); + for (Loot.Source source : tables) { + switch (source) { + case Loot.Table table -> items.addAll(BukkitItemStacks.createAll(ModuleServices.lootItems(engine, site, table.key()))); + case Loot.PlatformTable table -> items.addAll(platformLoot(table, world, x, y, z)); + } + } + return items; + } + + private static List platformLoot(Loot.PlatformTable table, World world, int x, int y, int z) { + NamespacedKey key = NamespacedKey.fromString(table.key()); + LootTable platformTable = key == null ? null : Bukkit.getLootTable(key); + if (platformTable == null) { + IrisLogging.warn("Unknown vanilla loot table " + table.key()); + return List.of(); + } + return new KList<>(platformTable.populateLoot(new RNG(table.seed()), new LootContext.Builder(new Location(world, x, y, z)).build())); + } + static boolean dispatchLootMutation( LootMutationTask task, boolean folia, diff --git a/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitAttributes.java b/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitAttributes.java new file mode 100644 index 000000000..fd58564ea --- /dev/null +++ b/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitAttributes.java @@ -0,0 +1,113 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.platform.bukkit; + +import art.arcane.iris.spi.IrisLogging; +import com.volmit.item.ItemAttribute; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; +import org.bukkit.attribute.Attributable; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeInstance; +import org.bukkit.attribute.AttributeModifier; +import org.bukkit.inventory.EquipmentSlotGroup; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.Locale; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** Applies the attribute modifiers a module decided on to Bukkit items and entities. */ +public final class BukkitAttributes { + private static final Set WARNED_ATTRIBUTES = ConcurrentHashMap.newKeySet(); + private static final String GENERIC_UNDERSCORE = "generic_"; + private static final String GENERIC_DOT = "generic."; + private static final int MAX_NAME_LENGTH = 32; + private static final String DEFAULT_NAME = "modifier"; + + private BukkitAttributes() { + } + + public static void apply(ItemAttribute modifier, ItemMeta meta) { + Attribute attribute = resolveAttribute(modifier); + if (attribute != null) { + meta.addAttributeModifier(attribute, create(modifier)); + } + } + + public static void apply(ItemAttribute modifier, Attributable target) { + Attribute attribute = resolveAttribute(modifier); + if (attribute == null) { + return; + } + AttributeInstance instance = target.getAttribute(attribute); + if (instance != null) { + instance.addModifier(create(modifier)); + } + } + + private static Attribute resolveAttribute(ItemAttribute modifier) { + String value = modifier.attribute().trim().toLowerCase(Locale.ROOT); + Attribute resolved; + if (value.contains(":")) { + NamespacedKey key = NamespacedKey.fromString(value); + resolved = key == null ? null : Registry.ATTRIBUTE.get(key); + } else { + resolved = Registry.ATTRIBUTE.get(NamespacedKey.minecraft(value)); + if (resolved == null && value.startsWith(GENERIC_UNDERSCORE)) { + resolved = Registry.ATTRIBUTE.get(NamespacedKey.minecraft(value.substring(GENERIC_UNDERSCORE.length()))); + } + if (resolved == null && value.startsWith(GENERIC_DOT)) { + resolved = Registry.ATTRIBUTE.get(NamespacedKey.minecraft(value.substring(GENERIC_DOT.length()))); + } + } + if (resolved == null && WARNED_ATTRIBUTES.add(value)) { + IrisLogging.warn("Unknown attribute '" + modifier.attribute() + "' in attribute-modifier '" + modifier.name() + "'"); + } + return resolved; + } + + private static AttributeModifier create(ItemAttribute modifier) { + NamespacedKey key = NamespacedKey.minecraft(uniqueKey(modifier.name())); + return new AttributeModifier(key, modifier.amount(), resolveOperation(modifier.operation()), EquipmentSlotGroup.ANY); + } + + private static AttributeModifier.Operation resolveOperation(String operation) { + if (operation.isBlank()) { + return AttributeModifier.Operation.ADD_NUMBER; + } + try { + return AttributeModifier.Operation.valueOf(operation.trim().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { + return AttributeModifier.Operation.ADD_NUMBER; + } + } + + private static String uniqueKey(String name) { + String normalized = name.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9/._-]", "_"); + if (normalized.isBlank()) { + normalized = DEFAULT_NAME; + } + if (normalized.length() > MAX_NAME_LENGTH) { + normalized = normalized.substring(0, MAX_NAME_LENGTH); + } + return normalized + "_" + UUID.randomUUID().toString().replace("-", ""); + } +} diff --git a/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitItem.java b/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitItem.java index f98b0ed1b..b914275d6 100644 --- a/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitItem.java +++ b/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitItem.java @@ -59,4 +59,9 @@ public final class BukkitItem implements PlatformItem { public Object nativeHandle() { return material; } + + @Override + public int maxDurability() { + return material.getMaxDurability(); + } } diff --git a/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitItemStacks.java b/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitItemStacks.java new file mode 100644 index 000000000..39331c6de --- /dev/null +++ b/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitItemStacks.java @@ -0,0 +1,228 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.platform.bukkit; + +import art.arcane.iris.core.link.Identifier; +import art.arcane.iris.core.modules.IrisItemRegistry; +import art.arcane.iris.core.service.ExternalDataSVC; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.spi.IrisServices; +import art.arcane.iris.util.common.format.C; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.collection.KMap; +import art.arcane.volmlib.util.format.Form; +import com.volmit.item.ItemAttribute; +import com.volmit.item.ItemDrop; +import com.volmit.item.ItemEnchantment; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.Damageable; +import org.bukkit.inventory.meta.EnchantmentStorageMeta; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.LeatherArmorMeta; +import org.bukkit.inventory.meta.components.CustomModelDataComponent; +import org.bukkit.material.Colorable; + +import java.awt.Color; +import java.util.List; +import java.util.Locale; +import java.util.Optional; + +/** Creates the Bukkit item stacks that module {@link ItemDrop}s describe. */ +public final class BukkitItemStacks { + private static final int LORE_WRAP_WIDTH = 24; + private static final String LORE_RULE = C.GRAY + "--------------------"; + private static final int CHANCE_DIGITS = 5; + + private BukkitItemStacks() { + } + + /** The stack {@code drop} describes; an air stack when the item cannot be made. */ + public static ItemStack create(ItemDrop drop) { + try { + ItemStack stack = baseStack(drop); + if (stack == null || stack.getType() == Material.AIR) { + return new ItemStack(Material.AIR); + } + stack.setItemMeta(applyProperties(stack, drop)); + return BukkitPlatform.applyCustomNbt(stack, drop.customNbt().isEmpty() ? null : new KMap<>(drop.customNbt())); + } catch (Throwable e) { + IrisLogging.reportError(e); + return new ItemStack(Material.AIR); + } + } + + /** The non-air stacks of {@code drops}, in order. */ + public static KList createAll(List drops) { + KList stacks = new KList<>(); + for (ItemDrop drop : drops) { + ItemStack stack = create(drop); + if (stack.getType() != Material.AIR) { + stacks.add(stack); + } + } + return stacks; + } + + private static ItemStack baseStack(ItemDrop drop) { + if (IrisItemRegistry.isCustomItem(drop.item())) { + Optional custom = IrisServices.get(ExternalDataSVC.class) + .getItemStack(Identifier.fromString(drop.item()), drop.customNbt().isEmpty() ? null : new KMap<>(drop.customNbt())); + if (custom.isEmpty()) { + IrisLogging.warn("Unknown Material: " + drop.item()); + return null; + } + ItemStack stack = custom.get(); + stack.setAmount(drop.amount()); + return stack; + } + return new ItemStack(BukkitBlockResolution.getMaterial(drop.item()), drop.amount()); + } + + private static ItemMeta applyProperties(ItemStack stack, ItemDrop drop) { + ItemMeta meta = stack.getItemMeta(); + if (meta == null) { + return null; + } + + drop.enchantments().forEach(enchantment -> enchant(meta, enchantment)); + for (ItemAttribute attribute : drop.attributes()) { + BukkitAttributes.apply(attribute, meta); + } + + meta.setUnbreakable(drop.unbreakable()); + flags(drop).forEach(meta::addItemFlags); + + if (drop.customModel() != null) { + CustomModelDataComponent customModelData = meta.getCustomModelDataComponent(); + customModelData.setFloats(List.of(drop.customModel().floatValue())); + meta.setCustomModelDataComponent(customModelData); + } + + int maxDurability = stack.getType().getMaxDurability(); + if (drop.damage() != null && maxDurability > 0 && meta instanceof Damageable damageable) { + damageable.setDamage((int) Math.round(Math.max(0, Math.min(maxDurability, drop.damage() * maxDurability)))); + } + + if (drop.leatherColor() != null && meta instanceof LeatherArmorMeta leather) { + Color c = Color.decode(drop.leatherColor()); + leather.setColor(org.bukkit.Color.fromRGB(c.getRed(), c.getGreen(), c.getBlue())); + } + + DyeColor dye = dyeColor(drop); + if (dye != null && meta instanceof Colorable colorable) { + colorable.setColor(dye); + } + + if (drop.displayName() != null) { + meta.setDisplayName(C.translateAlternateColorCodes('&', drop.displayName())); + } + + meta.setLore(lore(drop)); + return meta; + } + + private static void enchant(ItemMeta meta, ItemEnchantment enchantment) { + try { + Enchantment resolved = resolveEnchantment(enchantment.key()); + if (resolved == null) { + IrisLogging.warn("Unknown Enchantment: " + enchantment.key()); + return; + } + if (meta instanceof EnchantmentStorageMeta storage) { + storage.addStoredEnchant(resolved, enchantment.level(), true); + return; + } + meta.addEnchant(resolved, enchantment.level(), true); + } catch (Throwable e) { + IrisLogging.reportError(e); + } + } + + /** A bare path ({@code sharpness}) or a full namespaced key ({@code mymod:vorpal}), as the modded resolver accepts. */ + private static Enchantment resolveEnchantment(String raw) { + if (raw.isBlank()) { + return null; + } + String value = raw.trim().toLowerCase(Locale.ROOT).replace(' ', '_'); + NamespacedKey key = value.indexOf(':') >= 0 ? NamespacedKey.fromString(value) : NamespacedKey.minecraft(value); + return key == null ? null : Registry.ENCHANTMENT.get(key); + } + + private static List flags(ItemDrop drop) { + KList resolved = new KList<>(); + for (String flag : drop.flags()) { + if (flag == null) { + continue; + } + try { + resolved.add(ItemFlag.valueOf(flag)); + } catch (IllegalArgumentException ignored) { + } + } + return resolved; + } + + private static DyeColor dyeColor(ItemDrop drop) { + if (drop.dyeColor() == null) { + return null; + } + try { + return DyeColor.valueOf(drop.dyeColor()); + } catch (IllegalArgumentException e) { + return null; + } + } + + private static KList lore(ItemDrop drop) { + KList lore = new KList<>(); + for (String line : drop.lore()) { + String colored = C.translateAlternateColorCodes('&', line); + if (colored.length() > LORE_WRAP_WIDTH) { + for (String wrapped : Form.wrapWords(colored, LORE_WRAP_WIDTH).split("\\Q\n\\E")) { + lore.add(wrapped.trim()); + } + } else { + lore.add(colored); + } + } + if (drop.source() != null) { + addSourceLore(lore, drop.source()); + } + return lore; + } + + private static void addSourceLore(KList lore, ItemDrop.Source source) { + if (lore.isNotEmpty()) { + lore.add(LORE_RULE); + } + if (source.table() == null) { + lore.add(C.GRAY + "1 in " + source.entryRarity() + " Chance (" + Form.pc(1D / source.entryRarity(), CHANCE_DIGITS) + ")"); + return; + } + long combined = (long) source.tableRarity() * source.entryRarity(); + lore.add(C.GRAY + "From: " + source.table() + " (" + Form.pc(1D / source.tableRarity(), CHANCE_DIGITS) + ")"); + lore.add(C.GRAY + "1 in " + combined + " Chance (" + Form.pc(1D / combined, CHANCE_DIGITS) + ")"); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/modules/BuiltInServicesTest.java b/core/src/test/java/art/arcane/iris/core/modules/BuiltInServicesTest.java index 8c95aa41b..9258cd9fa 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/BuiltInServicesTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/BuiltInServicesTest.java @@ -19,10 +19,13 @@ package art.arcane.iris.core.modules; import art.arcane.iris.engine.framework.structure.StructureLocating; +import art.arcane.iris.engine.loot.LootGiving; import art.arcane.iris.engine.mantle.components.StructureModule; import com.volmit.IrisModule; import com.volmit.host.FeatureCatalog; import com.volmit.host.LifecycleRegistration; +import com.volmit.service.BlockDrops; +import com.volmit.service.Loot; import com.volmit.service.ObjectsAt; import com.volmit.service.StructureLocator; import org.junit.Test; @@ -41,6 +44,13 @@ public class BuiltInServicesTest { assertEquals(1, BUILT_INS.services(ObjectsAt.class).size()); } + @Test + public void lootAndBlockDropsComeFromTheLootModule() { + assertEquals(1, BUILT_INS.services(Loot.class).size()); + assertEquals(1, BUILT_INS.services(BlockDrops.class).size()); + assertTrue(BUILT_INS.services(Loot.class).getFirst() instanceof LootGiving); + } + @Test public void structuresAreFoundThroughTheStructureModule() { List locators = BUILT_INS.services(StructureLocator.class); diff --git a/core/src/test/java/art/arcane/iris/engine/loot/LootItemsTest.java b/core/src/test/java/art/arcane/iris/engine/loot/LootItemsTest.java new file mode 100644 index 000000000..314d70878 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/loot/LootItemsTest.java @@ -0,0 +1,106 @@ +package art.arcane.iris.engine.loot; + +import art.arcane.iris.engine.object.entity.IrisAttributeModifier; +import art.arcane.iris.engine.object.loot.IrisEnchantment; +import art.arcane.iris.engine.object.loot.IrisLoot; +import art.arcane.iris.engine.object.loot.IrisLootTable; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.item.ItemDrop; +import com.volmit.item.ItemRegistry; +import org.junit.Before; +import org.junit.Test; + +import java.util.List; +import java.util.OptionalInt; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** Loot entries turn into items with the random choices made in Iris's order: amount, enchantments, attributes, damage. */ +public class LootItemsTest { + private static final long LOOT_SEED = 77L; + + private ItemRegistry registry; + + @Before + public void knowTheItems() { + registry = mock(ItemRegistry.class); + when(registry.maxDurability(anyString())).thenReturn(OptionalInt.empty()); + when(registry.maxDurability("diamond_sword")).thenReturn(OptionalInt.of(1561)); + when(registry.maxDurability("diamond")).thenReturn(OptionalInt.of(0)); + } + + @Test + public void anEntryDrawsAmountEnchantmentsAttributesAndDamageFromOneStreamInThatOrder() { + IrisLoot entry = new IrisLoot().setType("diamond_sword").setMinAmount(1).setMaxAmount(3) + .setMinDurability(0.25).setMaxDurability(0.75) + .setEnchantments(new KList<>(new IrisEnchantment("sharpness", 1, 5, 1D))) + .setAttributes(new KList<>(new IrisAttributeModifier("max_health", "bonus", "ADD_NUMBER", 2, 6, 1D))); + RNG expected = new RNG(5L); + int amount = (int) (1 + expected.nextLong(3)); + expected.nextDouble(); + int level = (int) (1 + expected.nextLong(5)); + expected.nextDouble(); + double bonus = expected.d(2, 6); + double damage = 1D - expected.d(0.25, 0.75); + + ItemDrop drop = new LootItems(registry, false).give(entry, new RNG(5L)); + + assertEquals(amount, drop.amount()); + assertEquals(level, drop.enchantments().getFirst().level()); + assertEquals(bonus, drop.attributes().getFirst().amount(), 0D); + assertEquals(damage, drop.damage(), 0D); + } + + @Test + public void anItemThatCannotBeDamagedDrawsNoDamageAndKeepsTheStreamAligned() { + IrisLoot entry = new IrisLoot().setType("diamond").setMinAmount(2).setMaxAmount(2); + RNG rng = new RNG(9L); + RNG untouched = new RNG(9L); + + ItemDrop drop = new LootItems(registry, false).give(entry, rng); + + assertEquals(2, drop.amount()); + assertNull(drop.damage()); + assertEquals(untouched.nextLong(), rng.nextLong()); + } + + @Test + public void anItemThePlatformDoesNotKnowIsNotGivenAndDrawsNothing() { + RNG rng = new RNG(9L); + RNG untouched = new RNG(9L); + + assertNull(new LootItems(registry, false).give(new IrisLoot().setType("not_an_item"), rng)); + assertNull(new LootItems(registry, false).give(new IrisLoot().setType("air"), rng)); + assertEquals(untouched.nextLong(), rng.nextLong()); + } + + @Test + public void debugItemsSayWhereTheyCameFrom() { + IrisLootTable table = new IrisLootTable().setName("dungeon").setRarity(4); + table.setLoot(new KList<>(new IrisLoot().setType("diamond").setRarity(3))); + table.setMinPicked(1).setMaxPicked(1); + + List drops = new LootItems(registry, true).draw(table, LOOT_SEED, 0, 64, 0); + + for (ItemDrop drop : drops) { + assertEquals(new ItemDrop.Source("dungeon", 4, 3), drop.source()); + } + assertTrue(new LootItems(registry, false).draw(table, LOOT_SEED, 0, 64, 0).stream().allMatch(drop -> drop.source() == null)); + } + + @Test + public void aTableGivesTheSameItemsAtTheSameSpotAndSeed() { + IrisLootTable table = new IrisLootTable().setName("tools").setMinPicked(2).setMaxPicked(4); + table.setLoot(new KList<>(new IrisLoot().setType("diamond").setMaxAmount(5), new IrisLoot().setType("diamond_sword"))); + + LootItems items = new LootItems(registry, false); + + assertEquals(items.draw(table, LOOT_SEED, 10, 64, -30), items.draw(table, LOOT_SEED, 10, 64, -30)); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/framework/LootResolverTest.java b/core/src/test/java/art/arcane/iris/engine/loot/LootResolverTest.java similarity index 92% rename from core/src/test/java/art/arcane/iris/engine/framework/LootResolverTest.java rename to core/src/test/java/art/arcane/iris/engine/loot/LootResolverTest.java index 51a01a7bb..f80ba209b 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/LootResolverTest.java +++ b/core/src/test/java/art/arcane/iris/engine/loot/LootResolverTest.java @@ -1,7 +1,9 @@ -package art.arcane.iris.engine.framework; +package art.arcane.iris.engine.loot; + +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.LootResolver; import art.arcane.iris.engine.IrisComplex; -import art.arcane.iris.engine.object.loot.InventorySlotType; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.loot.IrisLootMode; @@ -12,6 +14,7 @@ import art.arcane.iris.engine.object.annotations.Desc; import art.arcane.iris.engine.object.annotations.MaxNumber; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; +import com.volmit.item.ItemRegistry; import org.junit.Test; import java.lang.reflect.Field; @@ -70,12 +73,12 @@ public class LootResolverTest { IrisLootTable first = new IrisLootTable().setName("first"); IrisLootTable second = new IrisLootTable().setName("second"); - long baseline = LootResolver.tableSeed(41L, first, 0, 64, 0); + long baseline = LootTables.seed(41L, first, 0, 64, 0); - assertEquals(baseline, LootResolver.tableSeed(41L, first, 0, 64, 0)); - assertNotEquals(baseline, LootResolver.tableSeed(42L, first, 0, 64, 0)); - assertNotEquals(baseline, LootResolver.tableSeed(41L, second, 0, 64, 0)); - assertNotEquals(baseline, LootResolver.tableSeed(41L, first, 16, 64, 0)); + assertEquals(baseline, LootTables.seed(41L, first, 0, 64, 0)); + assertNotEquals(baseline, LootTables.seed(42L, first, 0, 64, 0)); + assertNotEquals(baseline, LootTables.seed(41L, second, 0, 64, 0)); + assertNotEquals(baseline, LootTables.seed(41L, first, 16, 64, 0)); } @Test @@ -84,7 +87,7 @@ public class LootResolverTest { int successes = 0; for (int x = 0; x < 65_536; x++) { - if (LootResolver.spatialOneIn(91L, table, 3, x, 40, x * 31, 8L)) { + if (LootTables.spatialOneIn(91L, table, 3, x, 40, x * 31, 8L)) { successes++; } } @@ -92,8 +95,8 @@ public class LootResolverTest { assertTrue(successes > 7_600); assertTrue(successes < 8_800); assertEquals( - LootResolver.spatialOneIn(91L, table, 3, 112, 40, 992, 8L), - LootResolver.spatialOneIn(91L, table, 3, 112, 40, 992, 8L) + LootTables.spatialOneIn(91L, table, 3, 112, 40, 992, 8L), + LootTables.spatialOneIn(91L, table, 3, 112, 40, 992, 8L) ); } @@ -102,7 +105,7 @@ public class LootResolverTest { ResolutionFixture fixture = new ResolutionFixture(); List sources = new ArrayList<>(); - LootResolver.resolveEnvironmentSources( + LootTables.resolveEnvironmentSources( sources, fixture.engine, new RNG(19L), @@ -121,7 +124,7 @@ public class LootResolverTest { ResolutionFixture fixture = new ResolutionFixture(); List sources = new ArrayList<>(); - LootResolver.resolveEnvironmentSources( + LootTables.resolveEnvironmentSources( sources, fixture.engine, new RNG(19L), @@ -247,7 +250,7 @@ public class LootResolverTest { public void emptyLootTableReturnsNoItems() { IrisLootTable table = new IrisLootTable().setName("empty"); - assertTrue(table.getLoot(false, 7L, InventorySlotType.STORAGE, null, 0, 64, 0).isEmpty()); + assertTrue(new LootItems(mock(ItemRegistry.class), false).draw(table, 7L, 0, 64, 0).isEmpty()); } @Test diff --git a/core/src/test/java/art/arcane/iris/engine/framework/LootResolverClearModeTest.java b/core/src/test/java/art/arcane/iris/engine/loot/LootTablesClearModeTest.java similarity index 68% rename from core/src/test/java/art/arcane/iris/engine/framework/LootResolverClearModeTest.java rename to core/src/test/java/art/arcane/iris/engine/loot/LootTablesClearModeTest.java index f498763b9..64f4a4eca 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/LootResolverClearModeTest.java +++ b/core/src/test/java/art/arcane/iris/engine/loot/LootTablesClearModeTest.java @@ -1,4 +1,4 @@ -package art.arcane.iris.engine.framework; +package art.arcane.iris.engine.loot; import art.arcane.iris.engine.object.loot.IrisLootMode; import org.junit.Test; @@ -9,22 +9,22 @@ import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -public class LootResolverClearModeTest { +public class LootTablesClearModeTest { @Test public void clearSuppressesItsOwnTablesAndReplaceDoesNot() { List cleared = new ArrayList<>(List.of("placement", "dimension")); - LootResolver.injectSources(cleared, List.of("biome"), IrisLootMode.CLEAR, false); + LootTables.injectSources(cleared, List.of("biome"), IrisLootMode.CLEAR, false); assertTrue("CLEAR must clear parents and contribute nothing", cleared.isEmpty()); List replaced = new ArrayList<>(List.of("placement", "dimension")); - LootResolver.injectSources(replaced, List.of("biome"), IrisLootMode.REPLACE, false); + LootTables.injectSources(replaced, List.of("biome"), IrisLootMode.REPLACE, false); assertEquals(List.of("biome"), replaced); } @Test public void clearIgnoresTheFallbackFlag() { List sources = new ArrayList<>(List.of("placement")); - LootResolver.injectSources(sources, List.of("biome"), IrisLootMode.CLEAR, true); + LootTables.injectSources(sources, List.of("biome"), IrisLootMode.CLEAR, true); assertTrue(sources.isEmpty()); } } diff --git a/spi/src/main/java/art/arcane/iris/spi/PlatformItem.java b/spi/src/main/java/art/arcane/iris/spi/PlatformItem.java index ff86970c6..2b4896834 100644 --- a/spi/src/main/java/art/arcane/iris/spi/PlatformItem.java +++ b/spi/src/main/java/art/arcane/iris/spi/PlatformItem.java @@ -42,4 +42,9 @@ public interface PlatformItem { * on a mod loader. Never null. Only code inside the owning adapter may cast it. */ Object nativeHandle(); + + /** + * The damage a stack of this item takes before it breaks, 0 for an item that cannot be damaged. + */ + int maxDurability(); }