From 7a3f5961cc0b5a159e47837eae1cc83d60f6fd14 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 20:45:00 +0200 Subject: [PATCH 1/7] IrisData no longer invalidates module caches by hand Drop StructureGraphCatalog.invalidate and IrisObjectScale.invalidate: the caches follow the pack's resource snapshot and the module world. The scale cache test builds its engine's world state. --- .../art/arcane/iris/core/loader/IrisData.java | 7 -- .../prefab/IrisObjectScaleCacheTest.java | 118 ++++++------------ 2 files changed, 39 insertions(+), 86 deletions(-) diff --git a/core/src/main/java/art/arcane/iris/core/loader/IrisData.java b/core/src/main/java/art/arcane/iris/core/loader/IrisData.java index 28822f017..98c269eab 100644 --- a/core/src/main/java/art/arcane/iris/core/loader/IrisData.java +++ b/core/src/main/java/art/arcane/iris/core/loader/IrisData.java @@ -37,7 +37,6 @@ import art.arcane.iris.core.modules.PackModuleSet; import art.arcane.iris.core.pack.PackDirectoryResolver; import art.arcane.iris.engine.data.cache.AtomicCache; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.structure.StructureGraphCatalog; import art.arcane.iris.core.structure.authoring.StructureRecoveryResult; import art.arcane.iris.core.structure.authoring.StructureTransactionWriter; import art.arcane.iris.engine.object.world.biome.IrisBiome; @@ -45,7 +44,6 @@ import art.arcane.iris.engine.object.material.IrisBlockData; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.entity.IrisEntity; import art.arcane.iris.engine.object.noise.expression.IrisExpression; -import art.arcane.iris.engine.object.prefab.IrisObjectScale; import art.arcane.iris.engine.object.terrain.IrisGenerator; import art.arcane.iris.engine.object.image.IrisImage; import art.arcane.iris.engine.object.image.IrisImageMap; @@ -496,8 +494,6 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory { } public synchronized void hotloaded() { - StructureGraphCatalog.invalidate(this); - IrisObjectScale.invalidate(this); closed = false; dataFolder.mkdirs(); recoverStructureTransactions(); @@ -578,8 +574,6 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory { /** Forgets everything read so far: the loaders' caches and the module resources, which a new snapshot reads again. */ public void dump() { - StructureGraphCatalog.invalidate(this); - IrisObjectScale.invalidate(this); for (ResourceLoader i : loaders.values()) { i.clearCache(); } @@ -588,7 +582,6 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory { /** Reads objects and module resources (structures, jigsaw pools and pieces among them) again after a tool rewrote their files. */ public synchronized void invalidateStructureResources() { - StructureGraphCatalog.invalidate(this); invalidateLoader(objectLoader); reloadModuleResources(); } diff --git a/core/src/test/java/art/arcane/iris/engine/object/prefab/IrisObjectScaleCacheTest.java b/core/src/test/java/art/arcane/iris/engine/object/prefab/IrisObjectScaleCacheTest.java index ca19f171a..b1da1d008 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/prefab/IrisObjectScaleCacheTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/prefab/IrisObjectScaleCacheTest.java @@ -4,9 +4,10 @@ import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectPlacementScaleInterpolator; import art.arcane.iris.engine.object.prefab.IrisObjectScale; import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineGeneration; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.volmlib.util.math.RNG; -import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -20,13 +21,13 @@ import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.LockSupport; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class IrisObjectScaleCacheTest { private static final IrisObjectScale.ScaleRequest REQUEST = new IrisObjectScale.ScaleRequest( @@ -37,55 +38,56 @@ public class IrisObjectScaleCacheTest { IrisObjectPlacementScaleInterpolator.NONE ); + private Engine engine; + @Before public void setUp() { - IrisObjectScale.invalidate(null); + engine = mock(Engine.class); + when(engine.getData()).thenReturn(mock(IrisData.class)); + when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); } - @After - public void tearDown() { - IrisObjectScale.invalidate(null); + private int cacheEntryCount() { + return IrisObjectScale.cacheOf(engine).size(); + } + + private long cacheEstimatedBytes() { + return IrisObjectScale.cacheOf(engine).estimatedBytes(); } @Test - public void mutatedOriginCreatesStableReplacementAndCanBeReleased() { + public void mutatedOriginCreatesStableReplacement() { IrisObject origin = new IrisObject(2, 2, 2); IrisObjectScale scale = new IrisObjectScale().setSize(2D); - IrisObject first = scale.get(new RNG(1L), origin); + IrisObject first = scale.get(new RNG(1L), origin, engine); IrisObjectScale.ScaleCache keyCache = new IrisObjectScale.ScaleCache(10L); IrisObjectScale.CacheKey originalKey = keyCache.key(origin, REQUEST, 0); int originalHash = originalKey.hashCode(); origin.setW(3); - IrisObject second = scale.get(new RNG(1L), origin); + IrisObject second = scale.get(new RNG(1L), origin, engine); assertEquals(originalHash, originalKey.hashCode()); assertNotEquals(originalKey, keyCache.key(origin, REQUEST, 0)); assertNotSame(first, second); assertNotEquals(first.getW(), second.getW()); - assertEquals(2, IrisObjectScale.cacheEntryCount()); - - IrisObjectScale.invalidate(null); - - assertEquals(0, IrisObjectScale.cacheEntryCount()); - assertEquals(0L, IrisObjectScale.cacheEstimatedBytes()); - assertFalse(IrisObjectScale.isOriginCached(origin)); + assertEquals(2, cacheEntryCount()); } @Test public void voxelMutationReplacesCachedVariants() { IrisObject origin = new IrisObject(2, 2, 2); IrisObjectScale scale = new IrisObjectScale().setSize(2D); - IrisObject empty = scale.get(new RNG(1L), origin); + IrisObject empty = scale.get(new RNG(1L), origin, engine); origin.setUnsigned(0, 0, 0, mock(PlatformBlockState.class)); - IrisObject populated = scale.get(new RNG(1L), origin); + IrisObject populated = scale.get(new RNG(1L), origin, engine); assertEquals(0, empty.getBlocks().size()); assertTrue(populated.getBlocks().size() > 0); assertNotSame(empty, populated); - assertEquals(2, IrisObjectScale.cacheEntryCount()); + assertEquals(2, cacheEntryCount()); } @Test @@ -97,18 +99,18 @@ public class IrisObjectScaleCacheTest { .setMaximumScale(2D); SequenceRng rng = new SequenceRng(); - IrisObject first = scale.get(rng, origin); - IrisObject second = scale.get(rng, origin); - IrisObject third = scale.get(rng, origin); - IrisObject fourth = scale.get(rng, origin); - IrisObject repeated = scale.get(rng, origin); + IrisObject first = scale.get(rng, origin, engine); + IrisObject second = scale.get(rng, origin, engine); + IrisObject third = scale.get(rng, origin, engine); + IrisObject fourth = scale.get(rng, origin, engine); + IrisObject repeated = scale.get(rng, origin, engine); assertSame(first, repeated); assertNotEquals(first.getW(), second.getW()); assertNotEquals(second.getW(), third.getW()); assertNotEquals(third.getW(), fourth.getW()); - assertEquals(4, IrisObjectScale.cacheEntryCount()); - assertTrue(IrisObjectScale.cacheEstimatedBytes() > 0L); + assertEquals(4, cacheEntryCount()); + assertTrue(cacheEstimatedBytes() > 0L); } @Test @@ -116,12 +118,12 @@ public class IrisObjectScaleCacheTest { OverweightScaleObject origin = new OverweightScaleObject(); IrisObjectScale scale = new IrisObjectScale().setSize(2D); - IrisObject result = scale.get(new RNG(1L), origin); + IrisObject result = scale.get(new RNG(1L), origin, engine); assertEquals(1_000, result.getW()); assertEquals(1, origin.scaleCalls.get()); - assertEquals(0, IrisObjectScale.cacheEntryCount()); - assertEquals(0L, IrisObjectScale.cacheEstimatedBytes()); + assertEquals(0, cacheEntryCount()); + assertEquals(0L, cacheEstimatedBytes()); } @Test @@ -133,12 +135,12 @@ public class IrisObjectScaleCacheTest { AtomicReference secondThread = new AtomicReference<>(); try { - Future first = executor.submit(() -> scale.get(new RNG(1L), origin)); + Future first = executor.submit(() -> scale.get(new RNG(1L), origin, engine)); assertTrue(origin.firstScaleEntered.await(5L, TimeUnit.SECONDS)); Future second = executor.submit(() -> { secondThread.set(Thread.currentThread()); secondInvoked.countDown(); - return scale.get(new RNG(1L), origin); + return scale.get(new RNG(1L), origin, engine); }); assertTrue(secondInvoked.await(5L, TimeUnit.SECONDS)); @@ -171,15 +173,15 @@ public class IrisObjectScaleCacheTest { put(cache, firstKey, new IrisObject(1, 1, 1), 4L); put(cache, secondKey, new IrisObject(1, 1, 1), 4L); - assertTrue(cache.lookup(firstKey).variant() != null); + assertTrue(cache.lookup(firstKey) != null); put(cache, thirdKey, new IrisObject(1, 1, 1), 4L); assertEquals(2, cache.size()); assertEquals(8L, cache.estimatedBytes()); assertTrue(cache.estimatedBytes() <= cache.maximumEstimatedBytes()); - assertTrue(cache.lookup(firstKey).variant() != null); - assertNull(cache.lookup(secondKey).variant()); - assertTrue(cache.lookup(thirdKey).variant() != null); + assertTrue(cache.lookup(firstKey) != null); + assertNull(cache.lookup(secondKey)); + assertTrue(cache.lookup(thirdKey) != null); } @Test @@ -188,55 +190,14 @@ public class IrisObjectScaleCacheTest { IrisObject origin = new IrisObject(1, 1, 1); IrisObjectScale.CacheKey key = key(origin); IrisObject variant = new IrisObject(1, 1, 1); - IrisObjectScale.CacheLookup lookup = cache.lookup(key); - IrisObject result = cache.putIfCurrent(key, variant, 11L, lookup.generation()); + IrisObject result = cache.putIfAbsent(key, variant, 11L); assertSame(variant, result); assertEquals(0, cache.size()); assertEquals(0L, cache.estimatedBytes()); } - @Test - public void invalidationReleasesOnlyTheRequestedRuntime() { - IrisObjectScale.ScaleCache cache = new IrisObjectScale.ScaleCache(20L); - IrisData firstOwner = mock(IrisData.class); - IrisData secondOwner = mock(IrisData.class); - IrisObject firstOrigin = new IrisObject(1, 1, 1); - IrisObject secondOrigin = new IrisObject(1, 1, 1); - firstOrigin.setLoader(firstOwner); - secondOrigin.setLoader(secondOwner); - IrisObjectScale.CacheKey firstKey = key(firstOrigin); - IrisObjectScale.CacheKey secondKey = key(secondOrigin); - - put(cache, firstKey, new IrisObject(1, 1, 1), 5L); - put(cache, secondKey, new IrisObject(1, 1, 1), 5L); - - cache.invalidate(firstOwner); - - assertNull(cache.lookup(firstKey).variant()); - assertTrue(cache.lookup(secondKey).variant() != null); - assertEquals(1, cache.size()); - assertEquals(5L, cache.estimatedBytes()); - } - - @Test - public void invalidationRejectsAnInFlightStaleInsertion() { - IrisObjectScale.ScaleCache cache = new IrisObjectScale.ScaleCache(10L); - IrisData owner = mock(IrisData.class); - IrisObject origin = new IrisObject(1, 1, 1); - origin.setLoader(owner); - IrisObjectScale.CacheKey key = key(origin); - IrisObjectScale.CacheLookup lookup = cache.lookup(key); - - cache.invalidate(owner); - cache.putIfCurrent(key, new IrisObject(1, 1, 1), 5L, lookup.generation()); - - assertEquals(0, cache.size()); - assertEquals(0L, cache.estimatedBytes()); - assertNull(cache.lookup(key).variant()); - } - @Test public void collectedOriginReleasesScaledValueWithOwnerReference() { IrisObjectScale.ScaleCache cache = new IrisObjectScale.ScaleCache(20L); @@ -261,8 +222,7 @@ public class IrisObjectScaleCacheTest { private static void put(IrisObjectScale.ScaleCache cache, IrisObjectScale.CacheKey key, IrisObject variant, long estimatedBytes) { - IrisObjectScale.CacheLookup lookup = cache.lookup(key); - cache.putIfCurrent(key, variant, estimatedBytes, lookup.generation()); + cache.putIfAbsent(key, variant, estimatedBytes); } private static final class BlockingScaleObject extends IrisObject { From 8137f6dba99667ad1d166933957e4d12acc1aaf3 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 20:51:05 +0200 Subject: [PATCH 2/7] HintedLocator asks the ObjectsAt services which biomes and regions place an object The object search plan no longer reads IrisObjectPlacement: it builds its coarse sampler from the layout entries the modules name and the biome tree it owns. --- .../iris/core/modules/ModuleServices.java | 13 +++++++++ .../iris/engine/framework/HintedLocator.java | 29 +++++++------------ .../iris/core/modules/ModuleServicesTest.java | 20 ++++++++++++- .../engine/framework/HintedLocatorTest.java | 12 ++++++++ 4 files changed, 55 insertions(+), 19 deletions(-) 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 44a94b2c3..e368506d0 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 @@ -49,6 +49,19 @@ public final class ModuleServices { return keys; } + /** The biomes and regions of the engine's layout that every module says place the object {@code objectKey}. */ + public static ObjectsAt.PlacedBy objectPlacers(Engine engine, String objectKey) { + PackWorld world = engine.getGeneration().world(); + Set biomes = new LinkedHashSet<>(); + Set regions = new LinkedHashSet<>(); + for (ObjectsAt provider : catalog(engine.getData()).services(ObjectsAt.class)) { + ObjectsAt.PlacedBy placedBy = provider.placedBy(world, objectKey); + biomes.addAll(placedBy.biomes()); + regions.addAll(placedBy.regions()); + } + return new ObjectsAt.PlacedBy(biomes, regions); + } + /** 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/framework/HintedLocator.java b/core/src/main/java/art/arcane/iris/engine/framework/HintedLocator.java index ad9b118ce..bf6f22d5d 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 @@ -18,14 +18,15 @@ package art.arcane.iris.engine.framework; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; 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.region.IrisRegion; import art.arcane.iris.util.common.parallel.BurstExecutor; import art.arcane.iris.util.common.parallel.MultiBurst; import art.arcane.iris.util.project.context.IrisContext; +import com.volmit.service.ObjectsAt; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KMap; import art.arcane.volmlib.util.collection.KSet; @@ -33,6 +34,7 @@ import art.arcane.volmlib.util.math.Position2; import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; import java.util.ArrayDeque; +import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; @@ -389,6 +391,7 @@ public final class HintedLocator implements Locator { } IrisComplex complex = engine.getComplex(); + ObjectsAt.PlacedBy placers = ModuleServices.objectPlacers(engine, objectKey); BiomeSource source = new BiomeSource(engine); KSet landHosts = new KSet<>(); KSet seaHosts = new KSet<>(); @@ -401,28 +404,28 @@ public final class HintedLocator implements Locator { continue; } - if (placesObject(region.getSurfaceObjects(), objectKey)) { + if (placers.regions().contains(region.getLoadKey())) { directRegions.add(region.getLoadKey()); } boolean hosted = false; for (String root : region.getLandBiomes()) { - if (source.closurePlacesObject(root, objectKey)) { + if (source.closureContainsAny(root, placers.biomes())) { landHosts.add(root); hosted = true; } } for (String root : region.getSeaBiomes()) { - if (source.closurePlacesObject(root, objectKey)) { + if (source.closureContainsAny(root, placers.biomes())) { seaHosts.add(root); hosted = true; } } for (String root : region.getShoreBiomes()) { - if (source.closurePlacesObject(root, objectKey)) { + if (source.closureContainsAny(root, placers.biomes())) { shoreHosts.add(root); hosted = true; } @@ -502,16 +505,6 @@ public final class HintedLocator implements Locator { }; } - private static boolean placesObject(KList placements, String objectKey) { - for (IrisObjectPlacement placement : placements) { - if (placement != null && placement.getPlace().contains(objectKey)) { - return true; - } - } - - return false; - } - private static final class BiomeSource { private final Engine engine; private final KMap cache = new KMap<>(); @@ -576,8 +569,8 @@ public final class HintedLocator implements Locator { return false; } - private boolean closurePlacesObject(String rootKey, String objectKey) { - if (rootKey == null || objectKey == null) { + private boolean closureContainsAny(String rootKey, Set targetKeys) { + if (rootKey == null || targetKeys.isEmpty()) { return false; } @@ -598,7 +591,7 @@ public final class HintedLocator implements Locator { continue; } - if (placesObject(biome.getSurfaceObjects(), objectKey)) { + if (targetKeys.contains(biome.getLoadKey())) { return true; } diff --git a/core/src/test/java/art/arcane/iris/core/modules/ModuleServicesTest.java b/core/src/test/java/art/arcane/iris/core/modules/ModuleServicesTest.java index a66468a83..72c8d8f01 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/ModuleServicesTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/ModuleServicesTest.java @@ -87,7 +87,17 @@ public class ModuleServicesTest { @Override public void register(FeatureRegistry registry) { - registry.registerService(ObjectsAt.class, (world, chunkX, chunkZ) -> Set.of(object + "@" + chunkX + "," + chunkZ)); + registry.registerService(ObjectsAt.class, new ObjectsAt() { + @Override + public Set objectsAt(PackWorld world, int chunkX, int chunkZ) { + return Set.of(object + "@" + chunkX + "," + chunkZ); + } + + @Override + public PlacedBy placedBy(PackWorld world, String objectKey) { + return new PlacedBy(Set.of(object + "-biome"), Set.of(id + "-region")); + } + }); registry.registerService(StructureLocator.class, new StructureLocator() { @Override public Set structures(PackResources resources) { @@ -141,6 +151,14 @@ public class ModuleServicesTest { assertEquals(List.of("tree@3,-4", "bush@3,-4", "rock@3,-4"), List.copyOf(ModuleServices.objectsAt(engine, 3, -4))); } + @Test + public void objectPlacersCombineTheBiomesAndRegionsOfEveryModule() { + ObjectsAt.PlacedBy placers = ModuleServices.objectPlacers(engine, "trees/oak"); + + assertEquals(Set.of("rock-biome", "tree-biome", "bush-biome"), placers.biomes()); + assertEquals(Set.of("test:zeta-region", "test:alpha-region", "test:beta-region"), placers.regions()); + } + @Test public void structureListsCombineEveryModule() { assertEquals(Set.of("tower", "castle"), ModuleServices.locatableStructures(engine)); 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 d7fe7c9b9..eecfdfe87 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 @@ -4,6 +4,8 @@ import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.ResourceLoader; +import art.arcane.iris.core.modules.ModuleResourceFixture; +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.dimension.IrisDimension; @@ -92,6 +94,9 @@ public class HintedLocatorTest { when(engine.isClosed()).thenReturn(false); when(engine.acquireGenerationLease(any(String.class))).thenReturn(GenerationSessionLease.noop()); when(data.getBiomeLoader()).thenReturn(biomeLoader); + ModuleResourceFixture.serveModules(data, new ObjectModule()); + when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); + stubReachableBiomes(); } private static IrisBiome biome(String key) { @@ -137,6 +142,10 @@ public class HintedLocatorTest { when(biomeLoader.load(biome.getLoadKey())).thenReturn(biome); } + private void stubReachableBiomes(IrisBiome... biomes) { + when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>(biomes)); + } + @Test public void appendRingZeroAddsOnlyOrigin() { KList batch = new KList<>(); @@ -285,6 +294,7 @@ public class HintedLocatorTest { placements.add(placement); host.setObjects(placements); stubBiome(host); + stubReachableBiomes(host); stubRegions(regionA); when(complex.getRegionStream()).thenReturn(constantStream(regionA)); @@ -326,6 +336,7 @@ public class HintedLocatorTest { IrisRegion regionA = region("reg_a"); regionA.setLandBiomes(keys("plains")); stubBiome(biome("plains")); + stubReachableBiomes(biome("plains")); stubRegions(regionA); HintedLocator.SearchPlan plan = HintedLocator.objectPlan(engine, "missing/object"); @@ -416,6 +427,7 @@ public class HintedLocatorTest { placements.add(placement); host.setObjects(placements); stubBiome(host); + stubReachableBiomes(host); stubRegions(regionA); when(complex.getRegionStream()).thenReturn(constantStream(regionA)); From 946ad61f7f5068e6793d1a441ed1eb12a876c11e Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 22:02:47 +0200 Subject: [PATCH 3/7] Loot and block drops ask the Loot and BlockDrops services EngineBukkitOps, WorldObjectPlacer and WorldBlockDropRouter no longer read loot classes: the modules name the tables and return resolved ItemDrops, which BukkitItemStacks creates. LootResolver keeps the generic stream helpers; table resolution moved to LootTables in iris:loot. IrisLootEvent carries the Loot sources. --- .../iris/core/commands/CommandStudio.java | 5 +- .../art/arcane/iris/modded/ModdedItem.java | 6 + .../iris/modded/ModdedItemTranslator.java | 5 +- .../arcane/iris/modded/ModdedLootApplier.java | 3 +- .../iris/modded/ModdedLootApplierTest.java | 11 +- .../iris/core/events/IrisLootEvent.java | 12 +- .../iris/core/modules/IrisItemRegistry.java | 59 +++++ .../iris/core/modules/IrisModuleHost.java | 3 +- .../iris/core/modules/IrisPackResources.java | 7 + .../iris/core/modules/ModuleServices.java | 38 +++ .../iris/engine/WorldBlockDropRouter.java | 35 ++- .../iris/engine/framework/LootResolver.java | 121 +--------- .../framework/placer/WorldObjectPlacer.java | 11 +- .../iris/engine/platform/EngineBukkitOps.java | 153 ++++++------ .../platform/bukkit/BukkitAttributes.java | 113 +++++++++ .../iris/platform/bukkit/BukkitItem.java | 5 + .../platform/bukkit/BukkitItemStacks.java | 228 ++++++++++++++++++ .../core/modules/BuiltInServicesTest.java | 10 + .../iris/engine/loot/LootItemsTest.java | 106 ++++++++ .../{framework => loot}/LootResolverTest.java | 29 ++- .../LootTablesClearModeTest.java} | 10 +- .../art/arcane/iris/spi/PlatformItem.java | 5 + 22 files changed, 714 insertions(+), 261 deletions(-) create mode 100644 core/src/main/java/art/arcane/iris/core/modules/IrisItemRegistry.java create mode 100644 core/src/main/java/art/arcane/iris/platform/bukkit/BukkitAttributes.java create mode 100644 core/src/main/java/art/arcane/iris/platform/bukkit/BukkitItemStacks.java create mode 100644 core/src/test/java/art/arcane/iris/engine/loot/LootItemsTest.java rename core/src/test/java/art/arcane/iris/engine/{framework => loot}/LootResolverTest.java (92%) rename core/src/test/java/art/arcane/iris/engine/{framework/LootResolverClearModeTest.java => loot/LootTablesClearModeTest.java} (68%) 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(); } From 8bf4fb0115915deed7ee6b5836300cf047d6405c Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 22:05:41 +0200 Subject: [PATCH 4/7] TreeSVC and TreeDefinitionIndex ask the SaplingGrowth services The module picks the tree placement and places it into a list of blocks; the host reads the world through SaplingGrowth.Surroundings and applies the blocks. Custom (external) blocks in a grown tree are placed as their base block. --- .../iris/core/modules/ModuleServices.java | 26 +++ .../art/arcane/iris/core/service/TreeSVC.java | 220 ++++-------------- .../service/tree/TreeDefinitionIndex.java | 64 +---- .../core/service/TreeSVCFluidHeightTest.java | 22 -- .../service/tree/TreeDefinitionIndexTest.java | 8 + .../mantle/components/TreeGrowingTest.java | 84 +++++++ 6 files changed, 169 insertions(+), 255 deletions(-) delete mode 100644 core/src/test/java/art/arcane/iris/core/service/TreeSVCFluidHeightTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/mantle/components/TreeGrowingTest.java 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 75f3544c1..d25fa6c36 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 @@ -26,6 +26,7 @@ import com.volmit.service.BlockDrops; import com.volmit.service.LocateResult; import com.volmit.service.Loot; import com.volmit.service.ObjectsAt; +import com.volmit.service.SaplingGrowth; import com.volmit.service.StructureLocator; import com.volmit.world.PackWorld; import java.util.ArrayList; @@ -100,6 +101,31 @@ public final class ModuleServices { return new BlockDrops.Result(drops, replacesVanillaDrops); } + /** The tree grown by the first module that grows one for {@code sapling}; empty leaves the growth to the platform. */ + public static Optional growSapling(Engine engine, SaplingGrowth.Sapling sapling, SaplingGrowth.Surroundings surroundings) { + PackWorld world = engine.getGeneration().world(); + for (SaplingGrowth provider : catalog(engine.getData()).services(SaplingGrowth.class)) { + Optional growth = provider.grow(world, sapling, surroundings); + if (growth.isPresent()) { + return growth; + } + } + return Optional.empty(); + } + + /** The objects every module places as trees. */ + public static SaplingGrowth.TreeObjects treeObjects(Engine engine) { + PackWorld world = engine.getGeneration().world(); + Set objects = new LinkedHashSet<>(); + Set procedural = new LinkedHashSet<>(); + for (SaplingGrowth provider : catalog(engine.getData()).services(SaplingGrowth.class)) { + SaplingGrowth.TreeObjects trees = provider.treeObjects(world); + objects.addAll(trees.objects()); + procedural.addAll(trees.procedural()); + } + return new SaplingGrowth.TreeObjects(objects, procedural); + } + /** 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/core/service/TreeSVC.java b/core/src/main/java/art/arcane/iris/core/service/TreeSVC.java index 4d5b54b06..78950cf35 100644 --- a/core/src/main/java/art/arcane/iris/core/service/TreeSVC.java +++ b/core/src/main/java/art/arcane/iris/core/service/TreeSVC.java @@ -18,38 +18,28 @@ package art.arcane.iris.core.service; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.procedural.tree.IrisTreeModes; import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.spi.IrisServices; -import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.core.modules.ModuleServices; +import art.arcane.iris.core.modules.PlatformBlockStates; import art.arcane.iris.core.tools.IrisToolbelt; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.EngineLifecycleTasks; import art.arcane.iris.engine.framework.TreeBlockMaterial; -import art.arcane.iris.engine.object.placement.IObjectPlacer; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.engine.object.placement.IrisTreeSize; -import art.arcane.iris.engine.object.prefab.TileData; import art.arcane.iris.engine.platform.PlatformChunkGenerator; import art.arcane.iris.platform.bukkit.BukkitBlockState; -import art.arcane.iris.spi.PlatformBlockState; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KMap; import art.arcane.volmlib.util.data.Cuboid; -import art.arcane.iris.util.common.data.IrisCustomData; +import com.volmit.placement.PlacedBlock; +import com.volmit.service.SaplingGrowth; import art.arcane.volmlib.util.math.BlockPosition; -import art.arcane.volmlib.util.math.RNG; import art.arcane.iris.util.common.plugin.IrisService; import art.arcane.iris.util.common.scheduling.J; import org.bukkit.Bukkit; import org.bukkit.HeightMap; import org.bukkit.Location; import org.bukkit.Material; -import org.bukkit.TreeType; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockState; @@ -60,7 +50,7 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.world.StructureGrowEvent; import java.util.List; -import java.util.Objects; +import java.util.Optional; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Predicate; @@ -117,134 +107,43 @@ public class TreeSVC implements IrisService { return; } - IrisDimension dimension = engine.getDimension(); - - if (dimension == null) { + if (engine.getDimension() == null) { IrisLogging.debug(this.getClass().getName() + " passed it off to vanilla because could not get Dimension for this world"); IrisLogging.reportError(new NullPointerException(event.getWorld().getName() + " could not be accessed despite being an Iris world")); return; } - if (!dimension.getTreeSettings().isEnabled()) { - IrisLogging.debug(this.getClass().getName() + " cancelled because tree overrides are disabled"); - return; - } - BlockData first = event.getLocation().getBlock().getBlockData().clone(); Cuboid saplingPlane = getSaplings(event.getLocation(), blockData -> blockData instanceof Sapling && blockData.getMaterial().equals(first.getMaterial()), event.getWorld()); IrisLogging.debug("Sapling grew @ " + event.getLocation() + " for " + event.getSpecies().name() + " usedBoneMeal is " + event.isFromBonemeal()); IrisLogging.debug("Sapling plane is: " + saplingPlane.getSizeX() + " by " + saplingPlane.getSizeZ()); - IrisObjectPlacement placement = getObjectPlacement(worldAccess, event.getLocation(), event.getSpecies(), new IrisTreeSize(1, 1)); + int minHeight = event.getWorld().getMinHeight(); + SaplingGrowth.Sapling sapling = new SaplingGrowth.Sapling( + relativePosition(event.getLocation(), minHeight), + relativePosition(saplingPlane.getCenter(), minHeight), + event.getSpecies().name()); + Optional growth = ModuleServices.growSapling(engine, sapling, new WorldSurroundings(event.getWorld(), saplingPlane)); - if (placement == null) { + if (growth.isEmpty()) { IrisLogging.debug(this.getClass().getName() + " had options but did not manage to find objectPlacements for them"); return; } saplingPlane.forEach(block -> block.setType(Material.AIR)); - IrisObject object = worldAccess.getData().getObjectLoader().load(placement.getPlace().getRandom(RNG.r)); - String treeMarker = object.getLoadKey() + "@" + ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); + String treeMarker = growth.get().object() + "@" + ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); List blockStateList = new KList<>(); KMap dataCache = new KMap<>(); - // TODO: REAL CLASSES!!!! - - IObjectPlacer placer = new IObjectPlacer() { - - @Override - public int getHighest(int x, int z, IrisData data) { - return event.getWorld().getHighestBlockYAt(x, z); - } - - @Override - public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) { - return event.getWorld().getHighestBlockYAt(x, z, ignoreFluid ? HeightMap.OCEAN_FLOOR : HeightMap.WORLD_SURFACE); - } - - @Override - public void set(int x, int y, int z, PlatformBlockState s) { - BlockData d = (BlockData) s.nativeHandle(); - Block b = event.getWorld().getBlockAt(x, y, z); - // Listeners get the post-growth tree, per the StructureGrowEvent contract; - // a fresh snapshot here handed every plugin an all-air "tree". - BlockState state = b.getState(); - if (d instanceof IrisCustomData data) - state.setBlockData(data.getBase()); - else state.setBlockData(d); - blockStateList.add(state); - dataCache.put(new Location(event.getWorld(), x, y, z), d); - } - - @Override - public PlatformBlockState get(int x, int y, int z) { - return BukkitBlockState.of(event.getWorld().getBlockAt(x, y, z).getBlockData()); - } - - @Override - public boolean isPreventingDecay() { - return true; - } - - @Override - public boolean isCarved(int x, int y, int z) { - return false; - } - - @Override - public boolean isSurfaceSolid(int x, int y, int z) { - return event.getWorld().getBlockAt(x, y, z).getType().isSolid(); - } - - @Override - public boolean isSolid(int x, int y, int z) { - return event.getWorld().getBlockAt(x, y, z).getBlockData().getMaterial().isSolid(); - } - - @Override - public boolean isUnderwater(int x, int z) { - return false; - } - - @Override - public int getFluidHeight() { - return worldFluidHeight(engine); - } - - @Override - public boolean isDebugSmartBore() { - return false; - } - - @Override - public void setTile(int xx, int yy, int zz, TileData tile) { - - } - - @Override - public void setData(int xx, int yy, int zz, T data) { - - } - - @Override - public T getData(int xx, int yy, int zz, Class t) { - return null; - } - - @Override - public Engine getEngine() { - return engine; - } - }; - - object.place( - saplingPlane.getCenter().getBlockX(), - (saplingPlane.getCenter().getBlockY() + object.getH() / 2), - saplingPlane.getCenter().getBlockZ(), - placer, - placement, - RNG.r, - Objects.requireNonNull(worldAccess).getData() - ); + for (PlacedBlock placed : growth.get().blocks()) { + Block b = event.getWorld().getBlockAt(placed.position().x(), placed.position().y() + minHeight, placed.position().z()); + BlockData d = (BlockData) IrisPlatforms.get().registries().block(placed.state().key()).nativeHandle(); + // Listeners get the post-growth tree, per the StructureGrowEvent contract; + // a fresh snapshot here handed every plugin an all-air "tree". + BlockState state = b.getState(); + state.setBlockData(d); + blockStateList.add(state); + dataCache.put(b.getLocation(), d); + } event.setCancelled(true); @@ -266,10 +165,7 @@ public class TreeSVC implements IrisService { if (d == null) continue; Block block = l.getBlock(); - if (d instanceof IrisCustomData data) { - block.setBlockData(data.getBase(), false); - IrisServices.get(ExternalDataSVC.class).processUpdate(engine, block, data.getCustom()); - } else block.setBlockData(d, false); + block.setBlockData(d, false); int mantleY = block.getY() - event.getWorld().getMinHeight(); // Lease-gated: the grow task can land after the engine started closing, and // an unleased mantle write would race the region flush. @@ -290,58 +186,36 @@ public class TreeSVC implements IrisService { } } - static int worldFluidHeight(Engine engine) { - return engine.getMinHeight() + engine.getDimension().getFluidHeight(); + private static com.volmit.world.BlockPosition relativePosition(Location location, int minHeight) { + return new com.volmit.world.BlockPosition(location.getBlockX(), location.getBlockY() - minHeight, location.getBlockZ()); } - /** - * Finds a single object placement (which may contain more than one object) for the requirements species, location & - * size - * - * @param worldAccess The world to access (check for biome, region, dimension, etc) - * @param location The location of the growth event (For biome/region finding) - * @param type The bukkit TreeType to match - * @param size The size of the sapling area - * @return An object placement which contains the matched tree, or null if none were found / it's disabled. - */ - private IrisObjectPlacement getObjectPlacement(PlatformChunkGenerator worldAccess, Location location, TreeType type, IrisTreeSize size) { + /** The world around the saplings as the modules read it; the saplings that grow count as air, as they are about to. */ + private static final class WorldSurroundings implements SaplingGrowth.Surroundings { + private static final com.volmit.block.BlockState AIR = com.volmit.block.BlockState.parse("minecraft:air"); - KList placements = new KList<>(); - boolean isUseAll = worldAccess.getEngine().getDimension().getTreeSettings().getMode().equals(IrisTreeModes.ALL); + private final World world; + private final Cuboid saplingPlane; - // Retrieve objectPlacements of type `species` from biome - IrisBiome biome = worldAccess.getEngine().getBiome(location.getBlockX(), location.getBlockY()-worldAccess.getTarget().getWorld().minHeight(), location.getBlockZ()); - placements.addAll(matchObjectPlacements(biome.getObjects(), size, type)); - - // Add more or find any in the region - if (isUseAll || placements.isEmpty()) { - IrisRegion region = worldAccess.getEngine().getRegion(location.getBlockX(), location.getBlockZ()); - placements.addAll(matchObjectPlacements(region.getObjects(), size, type)); + private WorldSurroundings(World world, Cuboid saplingPlane) { + this.world = world; + this.saplingPlane = saplingPlane; } - // Check if no matches were found, return a random one if they are - return placements.isNotEmpty() ? placements.getRandom() : null; - } + @Override + public int highest(int x, int z, boolean ignoreFluid) { + int worldY = ignoreFluid ? world.getHighestBlockYAt(x, z, HeightMap.OCEAN_FLOOR) : world.getHighestBlockYAt(x, z); + return worldY - world.getMinHeight(); + } - /** - * Filters out mismatches and returns matches - * - * @param objects The object placements to check - * @param size The size of the sapling area to filter with - * @param type The type of the tree to filter with - * @return A list of objectPlacements that matched. May be empty. - */ - private KList matchObjectPlacements(KList objects, IrisTreeSize size, TreeType type) { - - KList p = new KList<>(); - - for (IrisObjectPlacement i : objects) { - if (i.matches(size, type)) { - p.add(i); + @Override + public com.volmit.block.BlockState blockAt(int x, int y, int z) { + int worldY = y + world.getMinHeight(); + if (saplingPlane.contains(x, worldY, z)) { + return AIR; } + return com.volmit.block.BlockState.parse(PlatformBlockStates.namespaced(BukkitBlockState.of(world.getBlockAt(x, worldY, z).getBlockData()).key())); } - - return p; } /** diff --git a/core/src/main/java/art/arcane/iris/core/service/tree/TreeDefinitionIndex.java b/core/src/main/java/art/arcane/iris/core/service/tree/TreeDefinitionIndex.java index 9ea56358b..a5da07711 100644 --- a/core/src/main/java/art/arcane/iris/core/service/tree/TreeDefinitionIndex.java +++ b/core/src/main/java/art/arcane/iris/core/service/tree/TreeDefinitionIndex.java @@ -1,14 +1,10 @@ package art.arcane.iris.core.service.tree; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.core.modules.ModuleServices; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.StructurePlacementMarker; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.procedural.IrisProceduralObjects; -import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; -import art.arcane.iris.engine.object.world.region.IrisRegion; +import com.volmit.service.SaplingGrowth; -import java.util.HashSet; import java.util.Set; public final class TreeDefinitionIndex { @@ -23,26 +19,8 @@ public final class TreeDefinitionIndex { } public static TreeDefinitionIndex build(Engine engine) { - Set explicitObjectKeys = new HashSet<>(); - Set proceduralTreeKeys = new HashSet<>(); - - for (IrisRegion region : engine.getDimension().getAllRegions(engine)) { - if (region == null) { - continue; - } - collectPlacements(region.getObjects(), explicitObjectKeys); - collectProceduralTrees(region.getProceduralObjects(), proceduralTreeKeys); - } - - for (IrisBiome biome : engine.getDimension().getReachableBiomes(engine)) { - if (biome == null) { - continue; - } - collectPlacements(biome.getObjects(), explicitObjectKeys); - collectProceduralTrees(biome.getProceduralObjects(), proceduralTreeKeys); - } - - return new TreeDefinitionIndex(explicitObjectKeys, proceduralTreeKeys); + SaplingGrowth.TreeObjects trees = ModuleServices.treeObjects(engine); + return new TreeDefinitionIndex(trees.objects(), trees.procedural()); } public boolean isTreeMarker(String marker) { @@ -60,38 +38,4 @@ public final class TreeDefinitionIndex { } return objectKey.startsWith("trees/") || explicitObjectKeys.contains(objectKey); } - - private static void collectPlacements(Iterable placements, Set objectKeys) { - if (placements == null) { - return; - } - for (IrisObjectPlacement placement : placements) { - if (placement == null - || placement.getTrees() == null - || placement.getTrees().isEmpty() - || placement.getPlace() == null) { - continue; - } - for (String objectKey : placement.getPlace()) { - if (objectKey != null && !objectKey.isBlank()) { - objectKeys.add(objectKey); - } - } - } - } - - private static void collectProceduralTrees(IrisProceduralObjects proceduralObjects, Set objectKeys) { - if (proceduralObjects == null || proceduralObjects.getTrees() == null) { - return; - } - for (IrisProceduralTree tree : proceduralObjects.getTrees()) { - if (tree == null || tree.getName() == null || tree.getName().isBlank()) { - continue; - } - int variants = Math.max(1, tree.getVariants()); - for (int index = 0; index < variants; index++) { - objectKeys.add(tree.getVariantLoadKey(index)); - } - } - } } diff --git a/core/src/test/java/art/arcane/iris/core/service/TreeSVCFluidHeightTest.java b/core/src/test/java/art/arcane/iris/core/service/TreeSVCFluidHeightTest.java deleted file mode 100644 index 0c0859d4c..000000000 --- a/core/src/test/java/art/arcane/iris/core/service/TreeSVCFluidHeightTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package art.arcane.iris.core.service; - -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class TreeSVCFluidHeightTest { - @Test - public void liveWorldTreePlacementConvertsLocalFluidHeightToWorldY() { - Engine engine = mock(Engine.class); - IrisDimension dimension = mock(IrisDimension.class); - when(engine.getMinHeight()).thenReturn(-64); - when(engine.getDimension()).thenReturn(dimension); - when(dimension.getFluidHeight()).thenReturn(127); - - assertEquals(63, TreeSVC.worldFluidHeight(engine)); - } -} diff --git a/core/src/test/java/art/arcane/iris/core/service/tree/TreeDefinitionIndexTest.java b/core/src/test/java/art/arcane/iris/core/service/tree/TreeDefinitionIndexTest.java index e55d76dfd..468628996 100644 --- a/core/src/test/java/art/arcane/iris/core/service/tree/TreeDefinitionIndexTest.java +++ b/core/src/test/java/art/arcane/iris/core/service/tree/TreeDefinitionIndexTest.java @@ -10,6 +10,10 @@ import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.engine.object.placement.IrisTree; import art.arcane.volmlib.util.collection.KList; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.ModuleResourceFixture; +import art.arcane.iris.engine.framework.EngineGeneration; +import art.arcane.iris.engine.mantle.components.ObjectModule; import org.junit.Test; import static org.junit.Assert.assertFalse; @@ -38,6 +42,10 @@ public class TreeDefinitionIndexTest { biome.setProceduralObjects(proceduralObjects); when(engine.getDimension()).thenReturn(dimension); + IrisData data = mock(IrisData.class); + when(engine.getData()).thenReturn(data); + ModuleResourceFixture.serveModules(data, new ObjectModule()); + when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); when(dimension.getAllRegions(engine)).thenReturn(new KList().qadd(region)); when(dimension.getReachableBiomes(engine)).thenReturn(new KList().qadd(biome)); diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/TreeGrowingTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/TreeGrowingTest.java new file mode 100644 index 000000000..1b1ebd0fa --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/TreeGrowingTest.java @@ -0,0 +1,84 @@ +/* + * 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.mantle.components; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineGeneration; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.procedural.tree.IrisTreeSettings; +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 com.volmit.service.SaplingGrowth; +import com.volmit.world.BlockPosition; +import com.volmit.world.PackWorld; +import org.junit.Before; +import org.junit.Test; + +import java.util.Optional; + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** Trees only replace the platform's growth when the dimension asks for it and a placement of the area grows that species. */ +public class TreeGrowingTest { + private static final SaplingGrowth.Sapling OAK_SAPLING = new SaplingGrowth.Sapling( + new BlockPosition(10, 70, 20), new BlockPosition(10, 70, 20), "TREE"); + + private Engine engine; + private IrisDimension dimension; + private PackWorld world; + + @Before + public void buildWorld() { + engine = mock(Engine.class); + dimension = mock(IrisDimension.class); + when(engine.getDimension()).thenReturn(dimension); + when(engine.getData()).thenReturn(mock(IrisData.class)); + world = new EngineGeneration(engine).world(); + } + + @Test + public void aDimensionWithoutTreeOverridesLeavesTheGrowthToThePlatform() { + when(dimension.getTreeSettings()).thenReturn(new IrisTreeSettings()); + + Optional growth = new TreeGrowing().grow(world, OAK_SAPLING, mock(SaplingGrowth.Surroundings.class)); + + assertTrue(growth.isEmpty()); + verify(engine, never()).getBiome(anyInt(), anyInt(), anyInt()); + } + + @Test + public void withoutAPlacementThatGrowsTheSpeciesTheGrowthIsLeftToThePlatform() { + when(dimension.getTreeSettings()).thenReturn(new IrisTreeSettings().setEnabled(true)); + IrisBiome biome = new IrisBiome(); + biome.getObjects().add(new IrisObjectPlacement()); + when(engine.getBiome(10, 70, 20)).thenReturn(biome); + when(engine.getRegion(10, 20)).thenReturn(new IrisRegion()); + + Optional growth = new TreeGrowing().grow(world, OAK_SAPLING, mock(SaplingGrowth.Surroundings.class)); + + assertTrue(growth.isEmpty()); + } +} From 406d3e47d322e66fc2b31a2483666fe4e0ce63c4 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 22:16:35 +0200 Subject: [PATCH 5/7] Entity spawning asks the EntitySpawns services WorldEntitySpawner and MarkerSpawnScanner no longer read spawners, entities or markers: modules plan the spawns and describe the entities as EntitySpec, BukkitEntitySpawner creates them and the host checks light, surface and free space. Block-break marker cleanup asks the module what a marker means. --- .../iris/core/commands/CommandStudio.java | 3 +- .../iris/core/modules/IrisModuleHost.java | 3 +- .../iris/core/modules/ModuleServices.java | 45 ++ .../iris/engine/MarkerSpawnScanner.java | 78 ++- .../iris/engine/WorldBlockDropRouter.java | 7 +- .../iris/engine/WorldChunkMaintenance.java | 10 +- .../iris/engine/WorldEntitySpawner.java | 219 ++++----- .../engine/platform/BukkitEntitySpawner.java | 447 ++++++++++++++++++ .../iris/engine/platform/BukkitSurfaces.java | 60 +++ .../common/scheduling/ConsoleCommands.java | 51 ++ .../object/entity/IrisEntitySpawnTest.java | 15 - .../iris/engine/spawn/EntitySpawningTest.java | 179 +++++++ 12 files changed, 933 insertions(+), 184 deletions(-) create mode 100644 core/src/main/java/art/arcane/iris/engine/platform/BukkitEntitySpawner.java create mode 100644 core/src/main/java/art/arcane/iris/engine/platform/BukkitSurfaces.java create mode 100644 core/src/main/java/art/arcane/iris/util/common/scheduling/ConsoleCommands.java delete mode 100644 core/src/test/java/art/arcane/iris/engine/object/entity/IrisEntitySpawnTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/spawn/EntitySpawningTest.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 e32c05851..a034cb182 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 @@ -41,6 +41,7 @@ import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.terrain.IrisBiomePaletteLayer; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.entity.IrisEntity; +import art.arcane.iris.engine.platform.BukkitEntitySpawner; import art.arcane.iris.engine.object.terrain.IrisGenerator; import art.arcane.iris.engine.object.noise.IrisInterpolator; import art.arcane.iris.engine.object.loot.IrisLootTable; @@ -661,7 +662,7 @@ public class CommandStudio implements DirectorExecutor { // Entity creation must run on the thread owning the destination chunk. Location at = new Location(world(), location.getX(), location.getY(), location.getZ()); - if (!J.runAt(at, () -> entity.spawn(spawnEngine, at))) { + if (!J.runAt(at, () -> BukkitEntitySpawner.spawnByKey(spawnEngine, entity.getLoadKey(), at))) { Iris.warn("Could not schedule the entity spawn at " + at.getBlockX() + ", " + at.getBlockY() + ", " + at.getBlockZ() + "."); } } 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 8177d74b0..2ed901252 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 @@ -24,6 +24,7 @@ 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.spawn.SpawnModule; import art.arcane.iris.engine.mantle.components.StructureModule; import art.arcane.iris.engine.modifier.CarveModule; import art.arcane.iris.engine.modifier.CustomModule; @@ -71,7 +72,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 LootModule()); + new PerfectionModule(), new CustomModule(), new LootModule(), new SpawnModule()); } /** 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/ModuleServices.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleServices.java index d25fa6c36..0967cd1b9 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,8 +21,10 @@ 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.entity.EntitySpec; import com.volmit.item.ItemDrop; import com.volmit.service.BlockDrops; +import com.volmit.service.EntitySpawns; import com.volmit.service.LocateResult; import com.volmit.service.Loot; import com.volmit.service.ObjectsAt; @@ -126,6 +128,49 @@ public final class ModuleServices { return new SaplingGrowth.TreeObjects(objects, procedural); } + /** What the first module with something to spawn at {@code site} plans; empty when none does. */ + public static Optional planSpawn(Engine engine, EntitySpawns.Site site) { + PackWorld world = engine.getGeneration().world(); + for (EntitySpawns provider : catalog(engine.getData()).services(EntitySpawns.class)) { + Optional plan = provider.plan(world, site); + if (plan.isPresent()) { + return Optional.of(new PlannedSpawn(provider, world, plan.get())); + } + } + return Optional.empty(); + } + + /** The entity {@code key} as the first module that knows it would spawn it. */ + public static Optional entity(Engine engine, String key) { + PackWorld world = engine.getGeneration().world(); + for (EntitySpawns provider : catalog(engine.getData()).services(EntitySpawns.class)) { + Optional entity = provider.entity(world, key); + if (entity.isPresent()) { + return entity; + } + } + return Optional.empty(); + } + + /** What the first module that knows the marker {@code tag} says it does. */ + public static Optional markerRule(Engine engine, String tag) { + PackWorld world = engine.getGeneration().world(); + for (EntitySpawns provider : catalog(engine.getData()).services(EntitySpawns.class)) { + Optional rule = provider.marker(world, tag); + if (rule.isPresent()) { + return rule; + } + } + return Optional.empty(); + } + + /** A plan and the module that made it, which hears how many of its entities appeared. */ + public record PlannedSpawn(EntitySpawns provider, PackWorld world, EntitySpawns.Plan plan) { + public void spawned(int count) { + provider.spawned(world, plan, count); + } + } + /** 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/MarkerSpawnScanner.java b/core/src/main/java/art/arcane/iris/engine/MarkerSpawnScanner.java index 92c4fc83a..fa5ddb8cd 100644 --- a/core/src/main/java/art/arcane/iris/engine/MarkerSpawnScanner.java +++ b/core/src/main/java/art/arcane/iris/engine/MarkerSpawnScanner.java @@ -19,19 +19,22 @@ package art.arcane.iris.engine; import art.arcane.iris.engine.data.cache.Cache; -import art.arcane.iris.engine.object.marker.IrisMarker; import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; +import art.arcane.iris.core.modules.ModuleServices; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.util.common.plugin.Chunks; import art.arcane.iris.util.common.scheduling.J; import art.arcane.volmlib.util.collection.KMap; import art.arcane.volmlib.util.collection.KSet; +import com.volmit.service.EntitySpawns; import art.arcane.volmlib.util.matter.MatterMarker; import org.bukkit.Chunk; import org.bukkit.World; +import java.util.ArrayList; +import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; @@ -49,8 +52,12 @@ final class MarkerSpawnScanner { this.manager = manager; } - Map> getSpawnersFromMarkers(Chunk c) { - Map> p = new KMap<>(); + /** A spawner a marker names, and the marker. */ + record MarkerSpawner(String marker, String spawner) { + } + + Map> getSpawnersFromMarkers(Chunk c) { + Map> p = new KMap<>(); Set b = new KSet<>(); if (J.isFolia()) { @@ -61,35 +68,20 @@ final class MarkerSpawnScanner { } manager.getMantle().iterateChunk(c.getX(), c.getZ(), MatterMarker.class, (x, y, z, t) -> { - if (t.getTag().equals("cave_floor") || t.getTag().equals("cave_ceiling")) { - return; - } - - IrisMarker mark = manager.getData().getMarkerLoader().load(t.getTag()); - if (mark == null) { + Optional rule = markerRule(t); + if (rule.isEmpty()) { return; } IrisPosition pos = new IrisPosition((c.getX() << 4) + x, y, (c.getZ() << 4) + z); - if (isMarkerObstructed(c, pos, mark.isEmptyAbove())) { + if (isMarkerObstructed(c, pos, rule.get().emptyAbove())) { b.add(pos); return; } - for (String i : mark.getSpawners()) { - IrisSpawner m = manager.getData().getSpawnerLoader().load(i); - if (m == null) { - IrisLogging.error("Cannot load spawner: " + i + " for marker on " + manager.getName()); - continue; - } - m.setReferenceMarker(mark); - - // This is so fucking incorrect its a joke - //noinspection ConstantConditions - if (m != null) { - p.computeIfAbsent(pos, (k) -> new KSet<>()).add(m); - } + for (String spawner : rule.get().spawners()) { + addOnce(p.computeIfAbsent(pos, (k) -> new ArrayList<>()), new MarkerSpawner(t.getTag(), spawner)); } }); @@ -100,7 +92,15 @@ final class MarkerSpawnScanner { return p; } - void forEachMarkerSpawner(Chunk c, BiConsumer> consumer) { + /** What the modules say the marker means; empty for the cave markers Iris keeps for itself and for markers no module knows. */ + private Optional markerRule(MatterMarker marker) { + if (marker.getTag().equals("cave_floor") || marker.getTag().equals("cave_ceiling")) { + return Optional.empty(); + } + return ModuleServices.markerRule(manager.getEngine(), marker.getTag()); + } + + void forEachMarkerSpawner(Chunk c, BiConsumer> consumer) { if (c == null || consumer == null) { return; } @@ -160,30 +160,26 @@ final class MarkerSpawnScanner { }, () -> markerScanQueue.remove(key))); } + private static void addOnce(List spawners, MarkerSpawner spawner) { + if (!spawners.contains(spawner)) { + spawners.add(spawner); + } + } + private Map collectMarkerSpawnData(int chunkX, int chunkZ) { Map markerData = new KMap<>(); manager.getMantle().iterateChunk(chunkX, chunkZ, MatterMarker.class, (x, y, z, t) -> { - if (t.getTag().equals("cave_floor") || t.getTag().equals("cave_ceiling")) { - return; - } - - IrisMarker mark = manager.getData().getMarkerLoader().load(t.getTag()); - if (mark == null) { + Optional rule = markerRule(t); + if (rule.isEmpty()) { return; } IrisPosition position = new IrisPosition((chunkX << 4) + x, y, (chunkZ << 4) + z); MarkerSpawnData data = markerData.computeIfAbsent(position, k -> new MarkerSpawnData()); - data.requiresEmptyAbove = data.requiresEmptyAbove || mark.isEmptyAbove(); + data.requiresEmptyAbove = data.requiresEmptyAbove || rule.get().emptyAbove(); - for (String i : mark.getSpawners()) { - IrisSpawner spawner = manager.getData().getSpawnerLoader().load(i); - if (spawner == null) { - IrisLogging.error("Cannot load spawner: " + i + " for marker on " + manager.getName()); - continue; - } - spawner.setReferenceMarker(mark); - data.spawners.add(spawner); + for (String spawner : rule.get().spawners()) { + addOnce(data.spawners, new MarkerSpawner(t.getTag(), spawner)); } }); @@ -218,7 +214,7 @@ final class MarkerSpawnScanner { } private static final class MarkerSpawnData { - private final KSet spawners = new KSet<>(); + private final List spawners = new ArrayList<>(); private boolean requiresEmptyAbove; } } 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 3ecd6134d..af0f6da70 100644 --- a/core/src/main/java/art/arcane/iris/engine/WorldBlockDropRouter.java +++ b/core/src/main/java/art/arcane/iris/engine/WorldBlockDropRouter.java @@ -19,7 +19,6 @@ package art.arcane.iris.engine; import art.arcane.iris.core.service.tree.BlockDropRouter; -import art.arcane.iris.engine.object.marker.IrisMarker; import art.arcane.iris.core.modules.ModuleServices; import art.arcane.iris.core.modules.PlatformBlockStates; import art.arcane.iris.platform.bukkit.BukkitBlockState; @@ -36,8 +35,10 @@ import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.inventory.ItemStack; import com.volmit.block.BlockState; import com.volmit.service.BlockDrops; +import com.volmit.service.EntitySpawns; import com.volmit.world.BlockPosition; +import java.util.Optional; import java.util.function.Consumer; /** @@ -79,8 +80,8 @@ final class WorldBlockDropRouter { return; } - IrisMarker mark = manager.getData().getMarkerLoader().load(marker.getTag()); - if (mark == null || mark.isRemoveOnChange()) { + Optional rule = ModuleServices.markerRule(manager.getEngine(), marker.getTag()); + if (rule.isEmpty() || rule.get().removeOnChange()) { manager.getMantle().remove(blockX, mantleY, blockZ, MatterMarker.class); } })); diff --git a/core/src/main/java/art/arcane/iris/engine/WorldChunkMaintenance.java b/core/src/main/java/art/arcane/iris/engine/WorldChunkMaintenance.java index e6dcbe2cb..09e2f82ae 100644 --- a/core/src/main/java/art/arcane/iris/engine/WorldChunkMaintenance.java +++ b/core/src/main/java/art/arcane/iris/engine/WorldChunkMaintenance.java @@ -20,7 +20,6 @@ package art.arcane.iris.engine; import art.arcane.iris.core.IrisSettings; import art.arcane.iris.engine.data.cache.Cache; -import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; import art.arcane.iris.engine.platform.EngineBukkitOps; import art.arcane.iris.platform.bukkit.BukkitWorldBinding; import art.arcane.iris.spi.IrisLogging; @@ -303,13 +302,8 @@ final class WorldChunkMaintenance { }), delay); Chunk markerChunk = world.getChunkAt(chunkX, chunkZ); - manager.markerScanner.forEachMarkerSpawner(markerChunk, (block, spawners) -> { - IrisSpawner s = new KList<>(spawners).getRandom(); - if (s == null) { - return; - } - manager.entitySpawner.spawn(block, s, true); - }); + manager.markerScanner.forEachMarkerSpawner(markerChunk, (block, spawners) -> + manager.entitySpawner.spawnAtMarker(block, spawners.get(RNG.r.nextInt(spawners.size())), true)); }); } diff --git a/core/src/main/java/art/arcane/iris/engine/WorldEntitySpawner.java b/core/src/main/java/art/arcane/iris/engine/WorldEntitySpawner.java index e61d0a967..ea92c6f4c 100644 --- a/core/src/main/java/art/arcane/iris/engine/WorldEntitySpawner.java +++ b/core/src/main/java/art/arcane/iris/engine/WorldEntitySpawner.java @@ -19,40 +19,41 @@ package art.arcane.iris.engine; import art.arcane.iris.core.IrisSettings; +import art.arcane.iris.core.modules.ModuleServices; +import art.arcane.iris.engine.platform.BukkitEntitySpawner; +import art.arcane.iris.engine.platform.BukkitSurfaces; +import art.arcane.iris.platform.bukkit.BukkitPlatform; +import art.arcane.iris.util.common.format.C; +import art.arcane.volmlib.util.math.Vector3d; +import art.arcane.volmlib.util.matter.MatterMarker; +import com.volmit.entity.EntitySpec; +import com.volmit.service.EntitySpawns; +import com.volmit.world.BlockPosition; import art.arcane.iris.core.gui.PregeneratorJob; import art.arcane.iris.core.tools.IrisToolbelt; -import art.arcane.iris.engine.object.value.IRare; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.entity.IrisEntitySpawn; import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; -import art.arcane.iris.engine.platform.EngineBukkitOps; import art.arcane.iris.platform.bukkit.BukkitWorldBinding; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.util.common.plugin.Chunks; import art.arcane.iris.util.common.scheduling.J; import art.arcane.volmlib.util.bukkit.WorldIdentity; -import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.format.Form; -import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; import art.arcane.volmlib.util.math.Position2; import art.arcane.volmlib.util.math.RNG; -import lombok.Data; import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; -import java.util.List; +import java.util.Arrays; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Predicate; -import java.util.stream.Collectors; -import java.util.stream.Stream; /** * Ambient and marker entity spawning for a Bukkit Iris world. Every count and spawn hops onto the @@ -281,16 +282,12 @@ final class WorldEntitySpawner { if (IrisSettings.get().getWorld().isMarkerEntitySpawningSystem()) { manager.markerScanner.forEachMarkerSpawner(c, (block, spawners) -> { - IrisSpawner s = new KList<>(spawners).getRandom(); - if (s == null) { - return; - } - - spawn(block, s, false); + MarkerSpawnScanner.MarkerSpawner s = spawners.get(RNG.r.nextInt(spawners.size())); + spawnAtMarker(block, s, false); J.runRegion(c.getWorld(), c.getX(), c.getZ(), manager.managedTask( "bukkit_world_manager_marker_spawn_followup", () -> manager.chunkMaintenance.raiseInitialSpawnMarkerFlag(c.getWorld(), c.getX(), c.getZ(), - () -> spawn(block, s, true)))); + () -> spawnAtMarker(block, s, true)))); }); } @@ -298,87 +295,106 @@ final class WorldEntitySpawner { return; } - //@builder - Predicate filter = i -> i.canSpawn(manager.getEngine(), c.getX(), c.getZ()); - ChunkCounter counter = new ChunkCounter(c.getEntities()); - - IrisBiome biome = EngineBukkitOps.getSurfaceBiome(manager.getEngine(), c); - IrisEntitySpawn v = spawnRandomly(Stream.concat(manager.getData().getSpawnerLoader() - .loadAll(manager.getDimension().getEntitySpawners()) - .shuffleCopy(RNG.r) - .stream() - .filter(filter) - .filter((i) -> i.isValid(biome)), - Stream.concat(manager.getData() - .getSpawnerLoader() - .loadAll(manager.getEngine().getRegion(PowerOfTwoCoordinates.chunkToBlock(c.getX()), PowerOfTwoCoordinates.chunkToBlock(c.getZ())).getEntitySpawners()) - .shuffleCopy(RNG.r) - .stream() - .filter(filter), - manager.getData().getSpawnerLoader() - .loadAll(manager.getEngine().getSurfaceBiome(PowerOfTwoCoordinates.chunkToBlock(c.getX()), PowerOfTwoCoordinates.chunkToBlock(c.getZ())).getEntitySpawners()) - .shuffleCopy(RNG.r) - .stream() - .filter(filter))) - .filter(counter) - .flatMap((i) -> stream(i, initial)) - .collect(Collectors.toList())) - .getRandom(); - //@done - if (v == null || v.getReferenceSpawner() == null) - return; - - spawn(c, v); + int livingEntities = (int) Arrays.stream(c.getEntities()).filter(LivingEntity.class::isInstance).count(); + ModuleServices.planSpawn(manager.getEngine(), new EntitySpawns.Chunk(c.getX(), c.getZ(), livingEntities, initial)) + .ifPresent(planned -> spawn(c.getWorld(), planned)); } - private void spawn(Chunk c, IrisEntitySpawn i) { - IrisSpawner ref = i.getReferenceSpawner(); - int s = i.spawn(manager.getEngine(), c, RNG.r); - actuallySpawned.addAndGet(s); - if (s > 0) { - ref.spawn(manager.getEngine(), c.getX(), c.getZ()); + /** Spawns at a marker: the spawner of the marker the caller picked, with its initial spawns or its ordinary ones. */ + void spawnAtMarker(IrisPosition block, MarkerSpawnScanner.MarkerSpawner spawner, boolean initial) { + if (manager.getEngine().isClosed() || !BukkitWorldBinding.tryBind(manager.getEngine().getWorld())) { + return; + } + + BlockPosition position = new BlockPosition(block.getX(), block.getY() - manager.getEngine().getWorld().minHeight(), block.getZ()); + EntitySpawns.Marker site = new EntitySpawns.Marker(position, spawner.marker(), spawner.spawner(), initial); + ModuleServices.planSpawn(manager.getEngine(), site).ifPresent(planned -> { + if (planned.plan().exhaustsMarker()) { + removeExhaustedMarker(block); + } + spawn(BukkitWorldBinding.world(manager.getEngine().getWorld()), planned); + }); + } + + private void removeExhaustedMarker(IrisPosition marker) { + int relativeY = marker.getY() - manager.getEngine().getWorld().minHeight(); + Runnable remove = () -> manager.getEngine().getMantle().getMantle().remove(marker.getX(), relativeY, marker.getZ(), MatterMarker.class); + if (J.isFolia()) { + J.a(remove); + return; + } + remove.run(); + } + + private void spawn(World world, ModuleServices.PlannedSpawn planned) { + int spawned = 0; + for (EntitySpawns.Attempt attempt : planned.plan().attempts()) { + if (spawnIfAllowed(world, attempt)) { + spawned++; + } + } + actuallySpawned.addAndGet(spawned); + planned.spawned(spawned); + } + + /** Spawns the attempt's entity unless the light, the surface below or the space around it forbid it. */ + private boolean spawnIfAllowed(World world, EntitySpawns.Attempt attempt) { + EntitySpec entity = attempt.entity(); + try { + Location l = new Location(world, attempt.at().x(), attempt.at().y() + world.getMinHeight(), attempt.at().z()); + if (attempt.restrictsLight() && !lightAllows(l, attempt)) { + return false; + } + + if (attempt.checkSurface() && !surfaceAllows(l, attempt)) { + return false; + } + + Entity e = BukkitEntitySpawner.spawn(manager.getEngine(), entity, l.add(0.5, 0.5, 0.5)); + if (e != null) { + IrisLogging.debug("Spawned " + C.DARK_AQUA + "Entity<" + entity.type() + "> " + C.GREEN + e.getType() + C.LIGHT_PURPLE + " @ " + C.GRAY + e.getLocation().getX() + ", " + e.getLocation().getY() + ", " + e.getLocation().getZ()); + } + return e != null; + } catch (Throwable e) { + IrisLogging.reportError(e); + IrisLogging.error(" Failed to retrieve real entity @ " + attempt.at() + " (entity: " + entity.type() + ")"); + return false; } } - private void spawn(IrisPosition pos, IrisEntitySpawn i) { - IrisSpawner ref = i.getReferenceSpawner(); - if (!ref.canSpawn(manager.getEngine(), PowerOfTwoCoordinates.blockToChunkFloor(pos.getX()), PowerOfTwoCoordinates.blockToChunkFloor(pos.getZ()))) - return; - - int s = i.spawn(manager.getEngine(), pos, RNG.r); - actuallySpawned.addAndGet(s); - if (s > 0) { - ref.spawn(manager.getEngine(), PowerOfTwoCoordinates.blockToChunkFloor(pos.getX()), PowerOfTwoCoordinates.blockToChunkFloor(pos.getZ())); - } + private static boolean lightAllows(Location l, EntitySpawns.Attempt attempt) { + int light = l.getBlock().getLightLevel(); + return light >= attempt.minLight() && light <= attempt.maxLight(); } - void spawn(IrisPosition block, IrisSpawner spawner, boolean initial) { - if (manager.getEngine().isClosed()) { - return; + private static boolean surfaceAllows(Location l, EntitySpawns.Attempt attempt) { + if (!BukkitSurfaces.matches(attempt.surface(), l.clone().subtract(0, 1, 0).getBlock())) { + return false; } - if (spawner == null) { - return; - } - - KList s = initial ? spawner.getInitialSpawns() : spawner.getSpawns(); - if (s.isEmpty()) { - return; - } - - IrisEntitySpawn ss = spawnRandomly(s).getRandom(); - ss.setReferenceSpawner(spawner); - ss.setReferenceMarker(spawner.getReferenceMarker()); - spawn(block, ss); + Vector3d boundingBox = BukkitPlatform.entityBoundingBox(BukkitEntitySpawner.bukkitType(attempt.entity())); + return boundingBox == null || isAreaClearForSpawn(l, boundingBox); } - private Stream stream(IrisSpawner s, boolean initial) { - for (IrisEntitySpawn i : initial ? s.getInitialSpawns() : s.getSpawns()) { - i.setReferenceSpawner(s); - i.setReferenceMarker(s.getReferenceMarker()); - } + private static boolean isAreaClearForSpawn(Location center, Vector3d boundingBox) { + World world = center.getWorld(); + int startX = center.getBlockX() - (int) (boundingBox.x / 2); + int endX = center.getBlockX() + (int) (boundingBox.x / 2); + int startY = center.getBlockY(); + int endY = center.getBlockY() + (int) boundingBox.y; + int startZ = center.getBlockZ() - (int) (boundingBox.z / 2); + int endZ = center.getBlockZ() + (int) (boundingBox.z / 2); - return (initial ? s.getInitialSpawns() : s.getSpawns()).stream(); + for (int x = startX; x <= endX; x++) { + for (int y = startY; y <= endY; y++) { + for (int z = startZ; z <= endZ; z++) { + if (world.getBlockAt(x, y, z).getType() != Material.AIR) { + return false; + } + } + } + } + return true; } boolean isEntitySpawningEnabledForCurrentWorld() { @@ -388,31 +404,4 @@ final class WorldEntitySpawner { return IrisSettings.get().getStudio().isEntitySpawning(); } - - private KList spawnRandomly(List types) { - return IRare.expandWeighted(types); - } - - @Data - private static class ChunkCounter implements Predicate { - private final Entity[] entities; - private transient int index = 0; - private transient int count = 0; - - @Override - public boolean test(IrisSpawner spawner) { - int max = spawner.getMaxEntitiesPerChunk(); - if (max <= count) - return false; - - while (index < entities.length) { - if (entities[index++] instanceof LivingEntity) { - if (++count >= max) - return false; - } - } - - return true; - } - } } diff --git a/core/src/main/java/art/arcane/iris/engine/platform/BukkitEntitySpawner.java b/core/src/main/java/art/arcane/iris/engine/platform/BukkitEntitySpawner.java new file mode 100644 index 000000000..c4f418e37 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/platform/BukkitEntitySpawner.java @@ -0,0 +1,447 @@ +/* + * 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.platform; + +import art.arcane.iris.core.IrisSettings; +import art.arcane.iris.core.link.Identifier; +import art.arcane.iris.core.modules.ModuleServices; +import art.arcane.iris.core.service.EntityRiseSVC; +import art.arcane.iris.core.service.ExternalDataSVC; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.platform.bukkit.BukkitAttributes; +import art.arcane.iris.platform.bukkit.BukkitItemStacks; +import art.arcane.iris.platform.bukkit.BukkitPlatform; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.spi.IrisServices; +import art.arcane.iris.util.common.data.registry.RegistryUtil; +import art.arcane.iris.util.common.format.C; +import art.arcane.iris.util.common.plugin.Chunks; +import art.arcane.iris.util.common.scheduling.ConsoleCommands; +import art.arcane.iris.util.common.scheduling.J; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.M; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; +import com.volmit.entity.EntitySpec; +import com.volmit.item.ItemAttribute; +import com.volmit.service.Loot; +import com.volmit.world.BlockPosition; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.NamespacedKey; +import org.bukkit.Particle; +import org.bukkit.Sound; +import org.bukkit.attribute.Attributable; +import org.bukkit.entity.Ageable; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Mob; +import org.bukkit.entity.Panda; +import org.bukkit.entity.Panda.Gene; +import org.bukkit.entity.Villager; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.loot.LootContext; +import org.bukkit.loot.LootTable; +import org.bukkit.loot.Lootable; +import org.bukkit.util.Vector; + +import java.util.Collection; +import java.util.List; +import java.util.Locale; +import java.util.Random; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static art.arcane.iris.util.common.data.registry.Particles.ITEM; + +/** + * Creates the entities a module planned ({@link EntitySpec}) on a Bukkit server: the entity itself, then everything the + * spec sets on it. Every random choice was made by the module; this class only acts on the platform. + */ +public final class BukkitEntitySpawner { + private static final long RISE_START_DEPTH_BLOCKS = 5; + private static final int RISE_MAX_TICKS = 100; + private static final int RISE_NO_DAMAGE_TICKS = 100000; + private static final double RISE_STEP_BLOCKS = 0.1; + private static final double RISE_SOUND_CHANCE = 0.2; + private static final int SPAWN_WAIT_SLEEP_MS = 25; + private static final int SPAWN_WAIT_LIMIT_MS = 500; + private static final String LOOT_TABLE_NAMESPACE = "iris"; + + private BukkitEntitySpawner() { + } + + /** Spawns the pack's entity {@code key} at {@code at}, as a command asks for; null when the pack has no such entity or the spawn fails. */ + public static Entity spawnByKey(Engine gen, String key, Location at) { + return ModuleServices.entity(gen, key).map(spec -> spawn(gen, spec, at)).orElse(null); + } + + public static Entity spawn(Engine gen, EntitySpec spec, Location at) { + if (!Chunks.isSafe(at)) { + return null; + } + if (spec.riseOutOfGround()) { + at = startBelowGroundWhenWatched(at); + } + + Entity ee = doSpawn(spec, at); + + if (ee == null && !Chunks.isSafe(at)) { + return null; + } + + if (spec.isSpecial() && !spec.applySettingsToSpecial()) { + return ee; + } + + if (ee == null) { + return null; + } + + Entity e = ee; + applyFlags(e, spec); + addPassengers(gen, e, spec, at); + + if (e instanceof Attributable attributable) { + for (ItemAttribute attribute : spec.attributes()) { + BukkitAttributes.apply(attribute, attributable); + } + } + + if (e instanceof Lootable lootable && !spec.lootTables().isEmpty()) { + bindLoot(spec, gen, lootable, at); + } + + if (e instanceof LivingEntity living) { + applyLivingState(gen, living, spec, at); + } + + if (e instanceof Ageable ageable && spec.flags().baby()) { + ageable.setBaby(); + } + + if (e instanceof Panda panda) { + panda.setMainGene(resolveGene(spec.pandaMainGene())); + panda.setHiddenGene(resolveGene(spec.pandaHiddenGene())); + } + + if (e instanceof Villager villager) { + villager.setRemoveWhenFarAway(false); + villager.setPersistent(true); + } + + if (e instanceof Mob mob) { + mob.setAware(spec.flags().aware()); + } + + if (spec.spawnEffect() != null) { + showSpawnEffect(e, spec.spawnEffect()); + } + + runCommands(spec, at); + + Location riseFrom = at; + J.runEntity(e, () -> { + if (spec.riseOutOfGround() && e instanceof LivingEntity living && Chunks.hasPlayersNearby(riseFrom)) { + riseOutOfGround(e, living, riseFrom); + } + }); + + return e; + } + + /** Players watching an entity that rises out of the ground see it start five blocks below the spot. */ + private static Location startBelowGroundWhenWatched(Location at) { + AtomicReference start = new AtomicReference<>(at); + try { + J.sfut(() -> { + if (Chunks.hasPlayersNearby(start.get())) { + Location b = start.get().clone(); + start.set(new Location(b.getWorld(), b.getX(), b.getY() - RISE_START_DEPTH_BLOCKS, b.getZ())); + } + }).get(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + IrisLogging.reportError("Iris entity spawn preparation was interrupted.", e); + } catch (ExecutionException e) { + IrisLogging.reportError("Iris entity spawn preparation failed.", e); + } + return start.get(); + } + + private static void applyFlags(Entity e, EntitySpec spec) { + EntitySpec.Flags flags = spec.flags(); + e.setCustomName(spec.customName() != null ? C.translateAlternateColorCodes('&', spec.customName()) : null); + e.setCustomNameVisible(flags.customNameVisible()); + e.setGlowing(flags.glowing()); + e.setGravity(flags.gravity()); + e.setInvulnerable(flags.invulnerable()); + e.setSilent(flags.silent()); + e.setPersistent(flags.keepEntity() || IrisSettings.get().getWorld().isForcePersistEntities()); + } + + private static void addPassengers(Engine gen, Entity e, EntitySpec spec, Location at) { + for (EntitySpec passengerSpec : spec.passengers()) { + Entity passenger = spawn(gen, passengerSpec, at); + if (passenger == null) { + continue; + } + + if (Bukkit.isPrimaryThread()) { + e.addPassenger(passenger); + } else { + J.runEntity(e, () -> e.addPassenger(passenger)); + } + } + } + + private static void applyLivingState(Engine gen, LivingEntity l, EntitySpec spec, Location at) { + l.setAI(spec.flags().ai()); + l.setCanPickupItems(spec.flags().pickupItems()); + + if (spec.leashHolder() != null) { + l.setLeashHolder(spawn(gen, spec.leashHolder(), at)); + } + + l.setRemoveWhenFarAway(spec.flags().removable()); + + EntitySpec.Equipment equipment = spec.equipment(); + if (equipment.helmet() != null) { + l.getEquipment().setHelmet(BukkitItemStacks.create(equipment.helmet())); + } + if (equipment.chestplate() != null) { + l.getEquipment().setChestplate(BukkitItemStacks.create(equipment.chestplate())); + } + if (equipment.leggings() != null) { + l.getEquipment().setLeggings(BukkitItemStacks.create(equipment.leggings())); + } + if (equipment.boots() != null) { + l.getEquipment().setBoots(BukkitItemStacks.create(equipment.boots())); + } + if (equipment.mainHand() != null) { + l.getEquipment().setItemInMainHand(BukkitItemStacks.create(equipment.mainHand())); + } + if (equipment.offHand() != null) { + l.getEquipment().setItemInOffHand(BukkitItemStacks.create(equipment.offHand())); + } + } + + private static void runCommands(EntitySpec spec, Location at) { + for (EntitySpec.Command command : spec.commands()) { + ConsoleCommands.run(command.commands(), command.delay(), command.repeat(), command.repeatDelay(), + at.getBlockX(), at.getBlockY(), at.getBlockZ()); + } + } + + private static void riseOutOfGround(Entity e, LivingEntity living, Location from) { + Location start = from.clone(); + boolean originalInvulnerable = e.isInvulnerable(); + boolean originalAi = living.hasAI(); + boolean originalCollidable = living.isCollidable(); + int originalNoDamageTicks = living.getNoDamageTicks(); + EntityRiseSVC.stamp(e, originalInvulnerable, originalAi, originalCollidable); + e.setInvulnerable(true); + living.setAI(false); + living.setCollidable(false); + living.setNoDamageTicks(RISE_NO_DAMAGE_TICKS); + Runnable restore = () -> restoreRiseState(e, living, originalInvulnerable, originalAi, + originalCollidable, originalNoDamageTicks); + AtomicInteger t = new AtomicInteger(0); + Runnable[] loop = new Runnable[1]; + loop[0] = () -> { + if (t.get() > RISE_MAX_TICKS || e.isDead()) { + restore.run(); + return; + } + + t.incrementAndGet(); + if (e.getLocation().getBlock().getType().isSolid() || living.getEyeLocation().getBlock().getType().isSolid()) { + e.teleport(start.add(new Vector(0, RISE_STEP_BLOCKS, 0))); + ItemStack itemCrackData = new ItemStack(living.getEyeLocation().clone().subtract(0, 2, 0).getBlock().getBlockData().getMaterial()); + e.getWorld().spawnParticle(ITEM, living.getEyeLocation(), 6, 0.2, 0.4, 0.2, 0.06f, itemCrackData); + if (M.r(RISE_SOUND_CHANCE)) { + e.getWorld().playSound(e.getLocation(), Sound.BLOCK_CHORUS_FLOWER_GROW, 0.8f, 0.1f); + } + if (!J.runEntity(e, loop[0], 1, restore)) { + restore.run(); + } + } else { + restore.run(); + } + }; + if (!J.runEntity(e, loop[0], 0, restore)) { + restore.run(); + } + } + + private static void restoreRiseState(Entity entity, LivingEntity living, boolean invulnerable, + boolean ai, boolean collidable, int noDamageTicks) { + living.setNoDamageTicks(noDamageTicks); + living.setCollidable(collidable); + living.setAI(ai); + entity.setInvulnerable(invulnerable); + EntityRiseSVC.clearStamp(entity); + } + + private static Entity doSpawn(EntitySpec spec, Location at) { + if (!Chunks.isSafe(at)) { + return null; + } + + if (EntityType.UNKNOWN.equals(bukkitType(spec)) && !spec.isSpecial()) { + return null; + } + + if (!Bukkit.isPrimaryThread()) { + // Someone called spawn (worldedit maybe?) on a non server thread + // Due to the structure of iris, we will call it sync and busy wait until it's done. + AtomicReference ae = new AtomicReference<>(); + + try { + if (!J.runAt(at, () -> ae.set(doSpawn(spec, at)))) { + return null; + } + } catch (Throwable e) { + return null; + } + PrecisionStopwatch p = PrecisionStopwatch.start(); + + while (ae.get() == null) { + J.sleep(SPAWN_WAIT_SLEEP_MS); + + if (p.getMilliseconds() > SPAWN_WAIT_LIMIT_MS) { + return null; + } + } + + return ae.get(); + } + + if (spec.isSpecial()) { + return IrisServices.get(ExternalDataSVC.class).spawnMob(at, Identifier.fromString(spec.specialType())); + } + + return BukkitPlatform.spawnEntity(at, bukkitType(spec), bukkitReason(spec)); + } + + /** The platform's entity type of the spec, unknown when it names none. */ + public static EntityType bukkitType(EntitySpec spec) { + if (spec.type().isBlank()) { + return EntityType.UNKNOWN; + } + + NamespacedKey key = NamespacedKey.fromString(spec.type().trim().toLowerCase(Locale.ROOT)); + if (key == null) { + return EntityType.UNKNOWN; + } + + EntityType entityType = RegistryUtil.lookup(EntityType.class).get(key); + return entityType == null ? EntityType.UNKNOWN : entityType; + } + + private static CreatureSpawnEvent.SpawnReason bukkitReason(EntitySpec spec) { + if (spec.reason() == null || spec.reason().isBlank()) { + return CreatureSpawnEvent.SpawnReason.NATURAL; + } + + try { + return CreatureSpawnEvent.SpawnReason.valueOf(spec.reason().trim().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { + return CreatureSpawnEvent.SpawnReason.NATURAL; + } + } + + private static Gene resolveGene(String gene) { + if (gene == null || gene.isBlank()) { + return Gene.NORMAL; + } + + try { + return Gene.valueOf(gene.trim().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { + return Gene.NORMAL; + } + } + + private static void showSpawnEffect(Entity p, EntitySpec.SpawnEffect fx) { + J.runEntity(p, () -> { + Sound soundType = fx.sound() == null ? null : resolveKeyed(Sound.class, fx.sound()); + Particle particleType = fx.particle() == null ? null : resolveKeyed(Particle.class, fx.particle()); + if (soundType != null) { + Location part = p.getLocation().clone().add(RNG.r.i(-fx.soundDistance(), fx.soundDistance()), RNG.r.i(-fx.soundDistance(), fx.soundDistance()), RNG.r.i(-fx.soundDistance(), fx.soundDistance())); + p.getWorld().playSound(part, soundType, (float) fx.volume(), (float) RNG.r.d(fx.minPitch(), fx.maxPitch())); + } + + if (particleType != null) { + Location part = p.getLocation().clone().add(0, 0.25, 0).add(new Vector(1, 1, 1).multiply(RNG.r.d())).subtract(new Vector(1, 1, 1).multiply(RNG.r.d())); + part.add(RNG.r.d(), 0, RNG.r.d()); + double motionX = fx.randomAltX() ? RNG.r.d(-fx.altX(), fx.altX()) : fx.altX(); + double motionY = fx.randomAltY() ? RNG.r.d(-fx.altY(), fx.altY()) : fx.altY(); + double motionZ = fx.randomAltZ() ? RNG.r.d(-fx.altZ(), fx.altZ()) : fx.altZ(); + if (fx.extra() != 0) { + p.getWorld().spawnParticle(particleType, part.getX(), part.getY() + RNG.r.i(fx.particleOffset()), part.getZ(), + fx.particleCount(), motionX, motionY, motionZ, fx.extra()); + } else { + p.getWorld().spawnParticle(particleType, part.getX(), part.getY() + RNG.r.i(fx.particleOffset()), part.getZ(), + fx.particleCount(), motionX, motionY, motionZ); + } + } + }); + } + + private static T resolveKeyed(Class type, String key) { + NamespacedKey namespacedKey = NamespacedKey.fromString(key); + return namespacedKey == null ? null : RegistryUtil.lookup(type).get(namespacedKey); + } + + private static void bindLoot(EntitySpec spec, Engine gen, Lootable lootable, Location finalAt) { + lootable.setLootTable(new LootTable() { + @Override + public NamespacedKey getKey() { + return new NamespacedKey(LOOT_TABLE_NAMESPACE, "loot-" + spec.hashCode()); + } + + @Override + public Collection populateLoot(Random random, LootContext context) { + BlockPosition position = new BlockPosition(finalAt.getBlockX(), finalAt.getBlockY() - gen.getMinHeight(), finalAt.getBlockZ()); + Loot.Site site = new Loot.Site(position, null, false, gen.isStudio()); + KList items = new KList<>(); + + for (String table : spec.lootTables()) { + items.addAll(BukkitItemStacks.createAll(ModuleServices.lootItems(gen, site, table))); + } + + return items; + } + + @Override + public void fillInventory(Inventory inventory, Random random, LootContext context) { + for (ItemStack i : populateLoot(random, context)) { + inventory.addItem(i); + } + + EngineBukkitOps.scramble(gen, inventory, new RNG(spec.lootShuffleSeed())); + } + }); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/platform/BukkitSurfaces.java b/core/src/main/java/art/arcane/iris/engine/platform/BukkitSurfaces.java new file mode 100644 index 000000000..b3541fb15 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/platform/BukkitSurfaces.java @@ -0,0 +1,60 @@ +/* + * 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.platform; + +import com.volmit.service.EntitySpawns; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.data.Waterlogged; + +/** Whether a block is the kind of ground or fluid an entity spawns on. */ +public final class BukkitSurfaces { + private BukkitSurfaces() { + } + + /** Whether {@code block} suits an entity that wants {@code surface} below it. */ + public static boolean matches(EntitySpawns.Surface surface, Block block) { + Material type = block.getType(); + if (type.isSolid()) { + return surface == EntitySpawns.Surface.LAND || surface == EntitySpawns.Surface.OVERWORLD + || (surface == EntitySpawns.Surface.ANIMAL && isAnimalGround(type)); + } + if (type == Material.LAVA) { + return surface == EntitySpawns.Surface.LAVA; + } + if (isWater(type, block)) { + return surface == EntitySpawns.Surface.WATER || surface == EntitySpawns.Surface.OVERWORLD; + } + return false; + } + + private static boolean isAnimalGround(Material type) { + return type == Material.GRASS_BLOCK || type == Material.DIRT + || type == Material.DIRT_PATH || type == Material.COARSE_DIRT + || type == Material.ROOTED_DIRT || type == Material.PODZOL + || type == Material.MYCELIUM || type == Material.SNOW_BLOCK; + } + + private static boolean isWater(Material type, Block block) { + return type == Material.WATER || type == Material.SEAGRASS + || type == Material.TALL_SEAGRASS || type == Material.KELP_PLANT + || type == Material.KELP + || (block.getBlockData() instanceof Waterlogged waterlogged && waterlogged.isWaterlogged()); + } +} diff --git a/core/src/main/java/art/arcane/iris/util/common/scheduling/ConsoleCommands.java b/core/src/main/java/art/arcane/iris/util/common/scheduling/ConsoleCommands.java new file mode 100644 index 000000000..2d5e6f154 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/util/common/scheduling/ConsoleCommands.java @@ -0,0 +1,51 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.util.common.scheduling; + +import art.arcane.iris.spi.IrisPlatforms; + +import java.util.List; + +/** Runs console commands for the pack: once or for ever, after a delay, with {@code {x}}, {@code {y}} and {@code {z}} filled in. */ +public final class ConsoleCommands { + private ConsoleCommands() { + } + + /** + * @param commands the commands, with an optional leading slash + * @param delay server ticks before the commands run + * @param repeat whether to run them again every {@code repeatDelay} ticks until the server stops + * @param repeatDelay server ticks between repeats + */ + public static void run(List commands, long delay, boolean repeat, long repeatDelay, int x, int y, int z) { + for (String command : commands) { + String filled = (command.startsWith("/") ? command.replaceFirst("/", "") : command) + .replaceAll("\\Q{x}\\E", String.valueOf(x)) + .replaceAll("\\Q{y}\\E", String.valueOf(y)) + .replaceAll("\\Q{z}\\E", String.valueOf(z)); + int safeDelay = (int) Math.max(0, Math.min(Integer.MAX_VALUE, delay)); + if (repeat) { + int safeRepeatDelay = (int) Math.max(1, Math.min(Integer.MAX_VALUE, repeatDelay)); + J.s(() -> J.sr(() -> IrisPlatforms.get().dispatchConsoleCommand(filled), safeRepeatDelay), safeDelay); + } else { + J.s(() -> IrisPlatforms.get().dispatchConsoleCommand(filled), safeDelay); + } + } + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/object/entity/IrisEntitySpawnTest.java b/core/src/test/java/art/arcane/iris/engine/object/entity/IrisEntitySpawnTest.java deleted file mode 100644 index b197804d4..000000000 --- a/core/src/test/java/art/arcane/iris/engine/object/entity/IrisEntitySpawnTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package art.arcane.iris.engine.object.entity; - -import art.arcane.iris.engine.object.entity.IrisEntitySpawn; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; -import org.junit.Test; - -import static org.junit.Assert.assertNull; - -public class IrisEntitySpawnTest { - @Test - public void caveSpawnWithoutSafeMarkerIsSkipped() { - assertNull(IrisEntitySpawn.selectCaveSpawnLocation(new KList<>(), null, new RNG(1L))); - } -} diff --git a/core/src/test/java/art/arcane/iris/engine/spawn/EntitySpawningTest.java b/core/src/test/java/art/arcane/iris/engine/spawn/EntitySpawningTest.java new file mode 100644 index 000000000..6f706a5c9 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/spawn/EntitySpawningTest.java @@ -0,0 +1,179 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.spawn; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.loader.ResourceLoader; +import art.arcane.iris.core.modules.ModuleResourceFixture; +import art.arcane.iris.engine.UsableBlockPlatform; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineGeneration; +import art.arcane.iris.engine.framework.SeedManager; +import art.arcane.iris.engine.mantle.EngineMantle; +import art.arcane.iris.engine.object.entity.IrisEntity; +import art.arcane.iris.engine.object.entity.IrisEntitySpawn; +import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; +import art.arcane.iris.engine.object.marker.IrisMarker; +import art.arcane.iris.engine.object.world.IrisWorld; +import art.arcane.iris.spi.PlatformWorld; +import art.arcane.volmlib.util.collection.KList; +import com.volmit.entity.EntitySpec; +import com.volmit.item.ItemRegistry; +import com.volmit.service.EntitySpawns; +import com.volmit.world.BlockPosition; +import com.volmit.world.PackWorld; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** What the spawn module plans for markers, and what its markers mean. */ +public class EntitySpawningTest { + private static final BlockPosition MARKER_BLOCK = new BlockPosition(40, 70, -12); + + private Engine engine; + private ResourceLoader spawners; + private ResourceLoader markers; + private ResourceLoader entities; + private PackWorld world; + + @BeforeClass + public static void bindPlatform() { + UsableBlockPlatform.bind(); + } + + @AfterClass + public static void unbindPlatform() { + UsableBlockPlatform.unbind(); + } + + @Before + @SuppressWarnings("unchecked") + public void buildWorld() { + engine = mock(Engine.class); + IrisData data = mock(IrisData.class); + spawners = (ResourceLoader) mock(ResourceLoader.class); + markers = (ResourceLoader) mock(ResourceLoader.class); + entities = (ResourceLoader) mock(ResourceLoader.class); + when(engine.getData()).thenReturn(data); + when(data.getSpawnerLoader()).thenReturn(spawners); + when(data.getMarkerLoader()).thenReturn(markers); + when(data.getEntityLoader()).thenReturn(entities); + ModuleResourceFixture.serve(data); + when(data.getPackResources().items()).thenReturn(mock(ItemRegistry.class)); + IrisWorld engineWorld = mock(IrisWorld.class); + when(engineWorld.platformWorld()).thenReturn(mock(PlatformWorld.class)); + when(engine.getWorld()).thenReturn(engineWorld); + SeedManager seeds = mock(SeedManager.class); + when(seeds.getEntity()).thenReturn(11L); + when(engine.getSeedManager()).thenReturn(seeds); + world = new EngineGeneration(engine).world(); + } + + @Test + public void aCaveWithoutFloorMarkersHasNowhereToSpawn() { + EngineMantle mantle = mock(EngineMantle.class); + when(engine.getMantle()).thenReturn(mantle); + when(mantle.findMarkers(2, 3, art.arcane.volmlib.util.matter.slices.MarkerMatter.CAVE_FLOOR)).thenReturn(new KList<>()); + + assertNull(EntitySpawning.caveSpawnPosition(engine, 2, 3)); + } + + @Test + public void aMarkerMeansItsSpawnersAndWhetherItGoesAwayWhenItsBlockChanges() { + IrisMarker marker = new IrisMarker(); + marker.setSpawners(new KList<>("zombies", "missing")).setEmptyAbove(true).setRemoveOnChange(false); + when(markers.load("camp")).thenReturn(marker); + when(spawners.load("zombies")).thenReturn(new IrisSpawner()); + + EntitySpawns.MarkerRule rule = new EntitySpawning().marker(world, "camp").orElseThrow(); + + assertEquals(List.of("zombies"), rule.spawners()); + assertTrue(rule.emptyAbove()); + assertFalse(rule.removeOnChange()); + } + + @Test + public void markersNoModuleKnowsAndTheCaveMarkersMeanNothing() { + assertTrue(new EntitySpawning().marker(world, "unknown").isEmpty()); + assertTrue(new EntitySpawning().marker(world, "cave_floor").isEmpty()); + } + + @Test + public void aMarkerSpawnPlansEntitiesOneBlockAboveTheMarkerWithoutSurfaceChecks() { + IrisSpawner spawner = new IrisSpawner(); + spawner.setLoadKey("camp/zombies"); + spawner.getSpawns().add(new IrisEntitySpawn().setEntity("zombie").setMinSpawns(2).setMaxSpawns(2)); + when(spawners.load("camp/zombies")).thenReturn(spawner); + IrisMarker marker = new IrisMarker(); + marker.setExhaustionChance(2); + when(markers.load("camp")).thenReturn(marker); + IrisEntity zombie = new IrisEntity(); + zombie.setType("minecraft:zombie"); + when(entities.load("zombie")).thenReturn(zombie); + when(engine.getMinHeight()).thenReturn(-64); + + EntitySpawns.Plan plan = new EntitySpawning() + .plan(world, new EntitySpawns.Marker(MARKER_BLOCK, "camp", "camp/zombies", false)) + .orElseThrow(); + + assertEquals("camp/zombies", plan.spawner()); + assertTrue("an exhaustion chance above 1 always uses the marker up", plan.exhaustsMarker()); + assertEquals(2, plan.attempts().size()); + for (EntitySpawns.Attempt attempt : plan.attempts()) { + assertEquals(new BlockPosition(40, 71, -12), attempt.at()); + assertFalse(attempt.checkSurface()); + assertEquals("minecraft:zombie", attempt.entity().type()); + } + } + + @Test + public void aSpawnerThatCannotFireOrHasNoEntitiesPlansNothing() { + IrisSpawner empty = new IrisSpawner(); + when(spawners.load("empty")).thenReturn(empty); + + Optional plan = new EntitySpawning().plan(world, new EntitySpawns.Marker(MARKER_BLOCK, "camp", "empty", false)); + + assertTrue(plan.isEmpty()); + } + + @Test + public void anEntityOfThePackResolvesToTheSpecTheHostSpawns() { + IrisEntity entity = new IrisEntity(); + entity.setType("minecraft:cow").setCustomName("&6Bessie").setBaby(true); + when(entities.load("cow")).thenReturn(entity); + + EntitySpec spec = new EntitySpawning().entity(world, "cow").orElseThrow(); + + assertEquals("minecraft:cow", spec.type()); + assertEquals("&6Bessie", spec.customName()); + assertTrue(spec.flags().baby()); + assertTrue(new EntitySpawning().entity(world, "nothing").isEmpty()); + } +} From e120991ad3cb539c1ea663e37b4017aef1330a58 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 22:24:20 +0200 Subject: [PATCH 6/7] Iris has no loaders for loot tables, spawners, entities and markers any more Callers read them through LootResources and SpawnResources; the pack's loot check moved to iris:loot. RegistryMatter asks its subclass how to load a key, the entity command handler lists entities through the module kind. --- .../iris/modded/ModdedBlockBreakHandler.java | 3 +- .../arcane/iris/modded/ModdedDeathLoot.java | 3 +- .../arcane/iris/modded/ModdedLootApplier.java | 3 +- .../iris/modded/ModdedWorldManager.java | 11 +- .../modded/command/ModdedStudioCommands.java | 22 +- .../art/arcane/iris/core/loader/IrisData.java | 33 +-- .../iris/core/pack/PackIntegerChecks.java | 68 +++++ .../iris/core/pack/PackJsonFieldChecks.java | 6 +- .../iris/core/pack/PackLootValidator.java | 255 ------------------ .../pack/PackStructurePlacementValidator.java | 4 +- .../arcane/iris/core/pack/PackValidator.java | 4 - .../core/project/IrisPackageCompiler.java | 22 +- .../util/common/data/registry/Particles.java | 6 +- .../director/handlers/EntityHandler.java | 15 ++ .../specialhandlers/RegistrantHandler.java | 9 +- .../project/matter/slices/RegistryMatter.java | 14 +- .../project/matter/slices/SpawnerMatter.java | 7 + .../structure/StructureResourcesTest.java | 10 +- .../iris/engine/loot/LootResourcesTest.java | 113 ++++++++ .../loot/LootValidatorTest.java} | 46 ++-- .../iris/engine/spawn/EntitySpawningTest.java | 28 +- .../iris/engine/spawn/SpawnResourcesTest.java | 104 +++++++ .../purity/PackTypeBukkitPurityGateTest.java | 18 +- .../matter/RegistryMatterContextTest.java | 13 +- 24 files changed, 423 insertions(+), 394 deletions(-) create mode 100644 core/src/main/java/art/arcane/iris/core/pack/PackIntegerChecks.java delete mode 100644 core/src/main/java/art/arcane/iris/core/pack/PackLootValidator.java create mode 100644 core/src/test/java/art/arcane/iris/engine/loot/LootResourcesTest.java rename core/src/test/java/art/arcane/iris/{core/pack/PackValidatorLootTest.java => engine/loot/LootValidatorTest.java} (86%) create mode 100644 core/src/test/java/art/arcane/iris/engine/spawn/SpawnResourcesTest.java diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedBlockBreakHandler.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedBlockBreakHandler.java index c88c82ae7..d2382d541 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedBlockBreakHandler.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedBlockBreakHandler.java @@ -18,6 +18,7 @@ package art.arcane.iris.modded; +import art.arcane.iris.engine.spawn.SpawnResources; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.LootResolver; @@ -235,7 +236,7 @@ public final class ModdedBlockBreakHandler { if ("cave_floor".equals(tag) || "cave_ceiling".equals(tag)) { return; } - IrisMarker configured = engine.getData().getMarkerLoader().load(tag); + IrisMarker configured = SpawnResources.marker(engine.getData(), tag); if (configured == null || configured.isRemoveOnChange()) { engine.getMantle().getMantle().remove(position.getX(), mantleY, position.getZ(), MatterMarker.class); } diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedDeathLoot.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedDeathLoot.java index 2f4236b74..51a5b493b 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedDeathLoot.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedDeathLoot.java @@ -18,6 +18,7 @@ package art.arcane.iris.modded; +import art.arcane.iris.engine.loot.LootResources; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.loot.InventorySlotType; import art.arcane.iris.engine.object.loot.IrisLootTable; @@ -104,7 +105,7 @@ public final class ModdedDeathLoot { private static KList resolve(Engine engine, ServerLevel level, LootBinding binding) { KList drops = new KList<>(); for (String key : binding.tableKeys()) { - IrisLootTable table = engine.getData().getLootLoader().load(key); + IrisLootTable table = LootResources.table(engine.getData(), key); if (table == null) { if (WARNED_TABLES.add(key)) { IrisLogging.warn("Iris death loot: unknown loot table '" + key + "'"); 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 ffa64a300..5ea3ab45c 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedLootApplier.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedLootApplier.java @@ -18,6 +18,7 @@ package art.arcane.iris.modded; +import art.arcane.iris.engine.loot.LootResources; import art.arcane.iris.engine.object.loot.IrisObjectLoot; import art.arcane.iris.engine.object.loot.IrisObjectVanillaLoot; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; @@ -144,7 +145,7 @@ public final class ModdedLootApplier { if (loot == null || loot.getWeight() <= 0) { continue; } - IrisLootTable table = engine.getData().getLootLoader().load(loot.getName()); + IrisLootTable table = LootResources.table(engine.getData(), loot.getName()); if (table == null) { IrisLogging.warn("Couldn't find loot table " + loot.getName()); continue; diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedWorldManager.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedWorldManager.java index 602792f54..9688ed336 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedWorldManager.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedWorldManager.java @@ -18,6 +18,7 @@ package art.arcane.iris.modded; +import art.arcane.iris.engine.spawn.SpawnResources; import art.arcane.iris.core.IrisSettings; import art.arcane.iris.core.gui.PregeneratorJob; import art.arcane.iris.engine.IrisComplex; @@ -396,7 +397,7 @@ public final class ModdedWorldManager implements EngineWorldManager { if (tag.equals("cave_floor") || tag.equals("cave_ceiling")) { return; } - IrisMarker resolved = engine.getData().getMarkerLoader().load(tag); + IrisMarker resolved = SpawnResources.marker(engine.getData(), tag); if (resolved == null) { return; } @@ -429,7 +430,7 @@ public final class ModdedWorldManager implements EngineWorldManager { private KList resolveMarkerSpawners(IrisMarker marker) { KList spawners = new KList<>(); for (String key : marker.getSpawners()) { - IrisSpawner spawner = engine.getData().getSpawnerLoader().load(key); + IrisSpawner spawner = SpawnResources.spawner(engine.getData(), key); if (spawner == null) { IrisLogging.error("Cannot load spawner: " + key + " for marker on " + engine.getName()); continue; @@ -478,9 +479,9 @@ public final class ModdedWorldManager implements EngineWorldManager { int chunkMobs = countChunkLivingEntities(level, chunkX, chunkZ); KList pool = new KList<>(); - collectSpawns(pool, engine.getData().getSpawnerLoader().loadAll(engine.getDimension().getEntitySpawners()), biome, chunkX, chunkZ, chunkMobs, initial); - collectSpawns(pool, engine.getData().getSpawnerLoader().loadAll(region.getEntitySpawners()), null, chunkX, chunkZ, chunkMobs, initial); - collectSpawns(pool, engine.getData().getSpawnerLoader().loadAll(biome.getEntitySpawners()), null, chunkX, chunkZ, chunkMobs, initial); + collectSpawns(pool, SpawnResources.spawners(engine.getData(), engine.getDimension().getEntitySpawners()), biome, chunkX, chunkZ, chunkMobs, initial); + collectSpawns(pool, SpawnResources.spawners(engine.getData(), region.getEntitySpawners()), null, chunkX, chunkZ, chunkMobs, initial); + collectSpawns(pool, SpawnResources.spawners(engine.getData(), biome.getEntitySpawners()), null, chunkX, chunkZ, chunkMobs, initial); if (pool.isEmpty()) { return; } 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 5078c11bc..a7de7a58f 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java @@ -18,6 +18,9 @@ package art.arcane.iris.modded.command; +import art.arcane.iris.core.loader.IrisRegistrant; +import art.arcane.iris.engine.spawn.SpawnResources; +import art.arcane.iris.engine.loot.LootResources; import art.arcane.iris.modded.ModdedIrisLog; import art.arcane.iris.core.IrisSettings; import art.arcane.iris.core.gui.GuiHost; @@ -935,14 +938,14 @@ public final class ModdedStudioCommands { markerKeys.addAll(PackExportClosure.collectMarkerKeys(biome.getObjects())); } for (String markerKey : markerKeys) { - IrisMarker marker = dm.getMarkerLoader().load(markerKey); + IrisMarker marker = SpawnResources.marker(dm, markerKey); if (marker == null) { continue; } spawnerKeys.addAll(marker.getSpawners()); } for (String spawnerKey : spawnerKeys) { - IrisSpawner spawner = dm.getSpawnerLoader().load(spawnerKey); + IrisSpawner spawner = SpawnResources.spawner(dm, spawnerKey); if (spawner == null) { continue; } @@ -950,7 +953,7 @@ public final class ModdedStudioCommands { spawner.getInitialSpawns().forEach((IrisEntitySpawn spawn) -> entityKeys.add(spawn.getEntity())); } for (String entityKey : entityKeys) { - IrisEntity entity = dm.getEntityLoader().load(entityKey); + IrisEntity entity = SpawnResources.entity(dm, entityKey); if (entity == null) { continue; } @@ -988,16 +991,16 @@ public final class ModdedStudioCommands { hashes.append(copyJson(folder, "biomes", key, dm.getBiomeLoader().findFile(key))); } for (String key : entityKeys) { - hashes.append(copyJson(folder, "entities", key, dm.getEntityLoader().findFile(key))); + hashes.append(copyJson(folder, "entities", key, loadFile(SpawnResources.entity(dm, key)))); } for (String key : lootKeys) { - hashes.append(copyJson(folder, "loot", key, dm.getLootLoader().findFile(key))); + hashes.append(copyJson(folder, "loot", key, loadFile(LootResources.table(dm, key)))); } for (String key : spawnerKeys) { - hashes.append(copyJson(folder, "spawners", key, dm.getSpawnerLoader().findFile(key))); + hashes.append(copyJson(folder, "spawners", key, loadFile(SpawnResources.spawner(dm, key)))); } for (String key : markerKeys) { - hashes.append(copyJson(folder, "markers", key, dm.getMarkerLoader().findFile(key))); + hashes.append(copyJson(folder, "markers", key, loadFile(SpawnResources.marker(dm, key)))); } JSONObject meta = new JSONObject(); @@ -1088,4 +1091,9 @@ public final class ModdedStudioCommands { thread.start(); return 1; } + + /** The file a resource was read from, or null when the pack has no such resource. */ + private static File loadFile(IrisRegistrant resource) { + return resource == null ? null : resource.getLoadFile(); + } } diff --git a/core/src/main/java/art/arcane/iris/core/loader/IrisData.java b/core/src/main/java/art/arcane/iris/core/loader/IrisData.java index 98c269eab..f048c794a 100644 --- a/core/src/main/java/art/arcane/iris/core/loader/IrisData.java +++ b/core/src/main/java/art/arcane/iris/core/loader/IrisData.java @@ -42,17 +42,13 @@ import art.arcane.iris.core.structure.authoring.StructureTransactionWriter; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.material.IrisBlockData; import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.entity.IrisEntity; import art.arcane.iris.engine.object.noise.expression.IrisExpression; import art.arcane.iris.engine.object.terrain.IrisGenerator; import art.arcane.iris.engine.object.image.IrisImage; import art.arcane.iris.engine.object.image.IrisImageMap; -import art.arcane.iris.engine.object.loot.IrisLootTable; -import art.arcane.iris.engine.object.marker.IrisMarker; import art.arcane.iris.engine.object.mod.IrisMod; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; import art.arcane.iris.engine.object.annotations.Snippet; import art.arcane.iris.engine.object.prefab.matter.IrisMatterObject; import art.arcane.volmlib.util.collection.KList; @@ -103,9 +99,8 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory { private static final Set ENGINE_HOLDERS = Collections.synchronizedSet(Collections.newSetFromMap(new IdentityHashMap<>())); /** Every resource type Iris loads itself for generation, studio and validation; module resource kinds come on top. */ - private static final List> RUNTIME_RESOURCE_TYPES = List.of(IrisLootTable.class, - IrisSpawner.class, IrisEntity.class, IrisRegion.class, IrisBiome.class, IrisMod.class, IrisDimension.class, - IrisGenerator.class, IrisMarker.class, IrisBlockData.class, IrisExpression.class, IrisObject.class, IrisImage.class, + private static final List> RUNTIME_RESOURCE_TYPES = List.of(IrisRegion.class, IrisBiome.class, IrisMod.class, IrisDimension.class, + IrisGenerator.class, IrisBlockData.class, IrisExpression.class, IrisObject.class, IrisImage.class, IrisImageMap.class, IrisMatterObject.class); /** Pack folders Iris reads that hold no resources of its loaders: snippets and module jars. */ private static final List OTHER_OWN_FOLDERS = List.of("snippet", "modules"); @@ -118,13 +113,9 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory { @ToString.Exclude private volatile IrisPackResources packResources; private ResourceLoader biomeLoader; - private ResourceLoader lootLoader; private ResourceLoader regionLoader; private ResourceLoader dimensionLoader; private ResourceLoader generatorLoader; - private ResourceLoader entityLoader; - private ResourceLoader markerLoader; - private ResourceLoader spawnerLoader; private ResourceLoader modLoader; private ResourceLoader blockLoader; private ResourceLoader expressionLoader; @@ -254,30 +245,14 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory { return loadAny(IrisMod.class, key, nearest); } - public static IrisEntity loadAnyEntity(String key, @Nullable IrisData nearest) { - return loadAny(IrisEntity.class, key, nearest); - } - - public static IrisLootTable loadAnyLootTable(String key, @Nullable IrisData nearest) { - return loadAny(IrisLootTable.class, key, nearest); - } - public static IrisBlockData loadAnyBlock(String key, @Nullable IrisData nearest) { return loadAny(IrisBlockData.class, key, nearest); } - public static IrisSpawner loadAnySpaner(String key, @Nullable IrisData nearest) { - return loadAny(IrisSpawner.class, key, nearest); - } - public static IrisRegion loadAnyRegion(String key, @Nullable IrisData nearest) { return loadAny(IrisRegion.class, key, nearest); } - public static IrisMarker loadAnyMarker(String key, @Nullable IrisData nearest) { - return loadAny(IrisMarker.class, key, nearest); - } - public static IrisImage loadAnyImage(String key, @Nullable IrisData nearest) { return loadAny(IrisImage.class, key, nearest); } @@ -521,15 +496,11 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory { .registerTypeAdapter(MantleFlag.class, new MantleFlagAdapter()) .setPrettyPrinting(); KMap, ResourceLoader> replacement = new KMap<>(); - this.lootLoader = registerLoader(IrisLootTable.class, replacement); - this.spawnerLoader = registerLoader(IrisSpawner.class, replacement); - this.entityLoader = registerLoader(IrisEntity.class, replacement); this.regionLoader = registerLoader(IrisRegion.class, replacement); this.biomeLoader = registerLoader(IrisBiome.class, replacement); this.modLoader = registerLoader(IrisMod.class, replacement); this.dimensionLoader = registerLoader(IrisDimension.class, replacement); this.generatorLoader = registerLoader(IrisGenerator.class, replacement); - this.markerLoader = registerLoader(IrisMarker.class, replacement); this.blockLoader = registerLoader(IrisBlockData.class, replacement); this.expressionLoader = registerLoader(IrisExpression.class, replacement); this.objectLoader = registerLoader(IrisObject.class, replacement); diff --git a/core/src/main/java/art/arcane/iris/core/pack/PackIntegerChecks.java b/core/src/main/java/art/arcane/iris/core/pack/PackIntegerChecks.java new file mode 100644 index 000000000..217a6349f --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/pack/PackIntegerChecks.java @@ -0,0 +1,68 @@ +/* + * 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.volmlib.util.json.JSONObject; + +import java.util.List; + +/** Checks of integer fields in the JSON of pack files, which add what is wrong to a list of messages. */ +public final class PackIntegerChecks { + private PackIntegerChecks() { + } + + /** The integer in {@code field}, {@code defaultValue} when it is absent, or null (with a message) when it is not an integer. */ + public static Integer integerField(JSONObject object, String field, int defaultValue, + String path, List blockingErrors) { + if (!object.has(field)) { + return defaultValue; + } + Object rawValue = object.opt(field); + if (!(rawValue instanceof Number number) + || !Double.isFinite(number.doubleValue()) + || number.doubleValue() != Math.rint(number.doubleValue()) + || number.longValue() < Integer.MIN_VALUE + || number.longValue() > Integer.MAX_VALUE) { + blockingErrors.add(path + "." + field + " must be an integer."); + return null; + } + return number.intValue(); + } + + public static void requireMinimum(String fieldPath, Integer value, int minimum, + List blockingErrors) { + if (value != null && value < minimum) { + blockingErrors.add(fieldPath + " must be at least " + minimum + "."); + } + } + + public static void requireMaximum(String fieldPath, Integer value, int maximum, + List blockingErrors) { + if (value != null && value > maximum) { + blockingErrors.add(fieldPath + " must be at most " + maximum + "."); + } + } + + public static void requireOrdered(String minimumPath, Integer minimum, String maximumPath, + Integer maximum, List blockingErrors) { + if (minimum != null && maximum != null && minimum > maximum) { + blockingErrors.add(minimumPath + " must not exceed " + maximumPath + "."); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/core/pack/PackJsonFieldChecks.java b/core/src/main/java/art/arcane/iris/core/pack/PackJsonFieldChecks.java index c397a5890..cbbd6e3ed 100644 --- a/core/src/main/java/art/arcane/iris/core/pack/PackJsonFieldChecks.java +++ b/core/src/main/java/art/arcane/iris/core/pack/PackJsonFieldChecks.java @@ -62,9 +62,9 @@ final class PackJsonFieldChecks { if (!object.has(field) || object.opt(field) == JSONObject.NULL) { return; } - Integer value = PackLootValidator.lootInteger(object, field, minimum, path, blockingErrors); - PackLootValidator.requireMinimum(path + "." + field, value, minimum, blockingErrors); - PackLootValidator.requireMaximum(path + "." + field, value, maximum, blockingErrors); + Integer value = PackIntegerChecks.integerField(object, field, minimum, path, blockingErrors); + PackIntegerChecks.requireMinimum(path + "." + field, value, minimum, blockingErrors); + PackIntegerChecks.requireMaximum(path + "." + field, value, maximum, blockingErrors); } static void validateOptionalDoubleRange(String path, JSONObject object, String field, diff --git a/core/src/main/java/art/arcane/iris/core/pack/PackLootValidator.java b/core/src/main/java/art/arcane/iris/core/pack/PackLootValidator.java deleted file mode 100644 index 8e6092ad7..000000000 --- a/core/src/main/java/art/arcane/iris/core/pack/PackLootValidator.java +++ /dev/null @@ -1,255 +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.core.pack; - -import art.arcane.iris.engine.object.loot.IrisLoot; -import art.arcane.iris.engine.object.loot.IrisLootReference; -import art.arcane.iris.engine.object.loot.IrisLootTable; -import art.arcane.volmlib.util.json.JSONArray; -import art.arcane.volmlib.util.json.JSONObject; - -import java.io.File; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Set; - -final class PackLootValidator { - private PackLootValidator() { - } - - record LootGraphIssues(List errors, List warnings) { - LootGraphIssues { - errors = List.copyOf(errors); - warnings = List.copyOf(warnings); - } - } - - static LootGraphIssues validateLootGraph(File packFolder) { - List blockingErrors = new ArrayList<>(); - List warnings = new ArrayList<>(); - if (packFolder == null || !packFolder.isDirectory()) { - return new LootGraphIssues(blockingErrors, warnings); - } - - File lootFolder = new File(packFolder, PackValidator.LOOT_FOLDER); - Set lootKeys = ContentKeyValidator.deriveRegistrantKeysExact(lootFolder); - if (lootFolder.isDirectory()) { - List lootFiles = PackValidationIo.listJsonRecursive(lootFolder); - lootFiles.sort(Comparator.comparing(File::getPath)); - for (File lootFile : lootFiles) { - String lootKey = PackValidationIo.deriveKey(lootFolder, lootFile); - JSONObject table = PackStructurePlacementValidator.readGraphJson( - lootFile, "Loot table", lootKey, blockingErrors); - if (table != null) { - validateLootTable(lootKey, table, blockingErrors); - } - } - } - - for (String folderName : PackValidator.STRUCTURE_HOST_FOLDERS) { - File resourceFolder = new File(packFolder, folderName); - if (!resourceFolder.isDirectory()) { - continue; - } - List resourceFiles = PackValidationIo.listJsonRecursive(resourceFolder); - resourceFiles.sort(Comparator.comparing(File::getPath)); - for (File resourceFile : resourceFiles) { - JSONObject resource = PackValidationIo.readJson(resourceFile); - if (resource == null || !resource.has("loot")) { - continue; - } - String resourceType = PackStructurePlacementValidator.structureHostType(folderName); - String resourceKey = PackValidationIo.deriveKey(resourceFolder, resourceFile); - validateLootReference(resourceType, resourceKey, resource.opt("loot"), lootKeys, blockingErrors, warnings); - } - } - return new LootGraphIssues(blockingErrors, warnings); - } - - private static void validateLootTable(String lootKey, JSONObject table, List blockingErrors) { - String path = "Loot table '" + lootKey + "'"; - Integer rarity = lootInteger(table, "rarity", 1, path, blockingErrors); - Integer minimumPicked = lootInteger(table, "minPicked", 1, path, blockingErrors); - Integer maximumPicked = lootInteger(table, "maxPicked", 5, path, blockingErrors); - Integer maximumTries = lootInteger(table, "maxTries", 10, path, blockingErrors); - requireMinimum(path + ".rarity", rarity, 1, blockingErrors); - requireMinimum(path + ".minPicked", minimumPicked, 0, blockingErrors); - requireMinimum(path + ".maxPicked", maximumPicked, 1, blockingErrors); - requireMinimum(path + ".maxTries", maximumTries, 1, blockingErrors); - requireMaximum(path + ".minPicked", minimumPicked, IrisLootTable.MAX_PICKED, blockingErrors); - requireMaximum(path + ".maxPicked", maximumPicked, IrisLootTable.MAX_PICKED, blockingErrors); - requireMaximum(path + ".maxTries", maximumTries, IrisLootTable.MAX_TRIES, blockingErrors); - requireOrdered(path + ".minPicked", minimumPicked, path + ".maxPicked", maximumPicked, blockingErrors); - - JSONArray entries = table.optJSONArray("loot"); - if (entries == null || entries.length() == 0) { - blockingErrors.add(path + ".loot must be a non-empty array."); - return; - } - for (int entryIndex = 0; entryIndex < entries.length(); entryIndex++) { - JSONObject entry = entries.optJSONObject(entryIndex); - String entryPath = path + ".loot[" + entryIndex + "]"; - if (entry == null) { - blockingErrors.add(entryPath + " must be an object."); - continue; - } - String type = entry.optString("type", "").trim(); - if (type.isEmpty()) { - blockingErrors.add(entryPath + ".type must not be blank."); - } - Integer entryRarity = lootInteger(entry, "rarity", 1, entryPath, blockingErrors); - Integer minimumAmount = lootInteger(entry, "minAmount", 1, entryPath, blockingErrors); - Integer maximumAmount = lootInteger(entry, "maxAmount", 1, entryPath, blockingErrors); - requireMinimum(entryPath + ".rarity", entryRarity, 1, blockingErrors); - requireMinimum(entryPath + ".minAmount", minimumAmount, 1, blockingErrors); - requireMinimum(entryPath + ".maxAmount", maximumAmount, 1, blockingErrors); - requireMaximum(entryPath + ".minAmount", minimumAmount, IrisLoot.MAX_AMOUNT, blockingErrors); - requireMaximum(entryPath + ".maxAmount", maximumAmount, IrisLoot.MAX_AMOUNT, blockingErrors); - requireOrdered(entryPath + ".minAmount", minimumAmount, - entryPath + ".maxAmount", maximumAmount, blockingErrors); - validateLootEnchantments(entryPath, entry.opt("enchantments"), blockingErrors); - } - } - - private static void validateLootEnchantments(String entryPath, Object rawEnchantments, - List blockingErrors) { - if (rawEnchantments == null || rawEnchantments == JSONObject.NULL) { - return; - } - if (!(rawEnchantments instanceof JSONArray enchantments)) { - blockingErrors.add(entryPath + ".enchantments must be an array."); - return; - } - for (int enchantmentIndex = 0; enchantmentIndex < enchantments.length(); enchantmentIndex++) { - JSONObject enchantment = enchantments.optJSONObject(enchantmentIndex); - String enchantmentPath = entryPath + ".enchantments[" + enchantmentIndex + "]"; - if (enchantment == null) { - blockingErrors.add(enchantmentPath + " must be an object."); - continue; - } - if (enchantment.optString("enchantment", "").isBlank()) { - blockingErrors.add(enchantmentPath + ".enchantment must not be blank."); - } - Integer minimumLevel = lootInteger(enchantment, "minLevel", 1, enchantmentPath, blockingErrors); - Integer maximumLevel = lootInteger(enchantment, "maxLevel", 1, enchantmentPath, blockingErrors); - requireMinimum(enchantmentPath + ".minLevel", minimumLevel, 1, blockingErrors); - requireMinimum(enchantmentPath + ".maxLevel", maximumLevel, 1, blockingErrors); - requireOrdered(enchantmentPath + ".minLevel", minimumLevel, - enchantmentPath + ".maxLevel", maximumLevel, blockingErrors); - if (enchantment.has("chance")) { - Object rawChance = enchantment.opt("chance"); - if (!(rawChance instanceof Number number) - || !Double.isFinite(number.doubleValue()) - || number.doubleValue() < 0D - || number.doubleValue() > 1D) { - blockingErrors.add(enchantmentPath + ".chance must be a finite number from 0 to 1."); - } - } - } - } - - private static void validateLootReference(String resourceType, String resourceKey, Object rawLoot, - Set lootKeys, List blockingErrors, List warnings) { - String path = resourceType + " '" + resourceKey + "'.loot"; - if (!(rawLoot instanceof JSONObject reference)) { - blockingErrors.add(path + " must be an object."); - return; - } - boolean clearMode = false; - if (reference.has("mode")) { - Object rawMode = reference.opt("mode"); - if (!(rawMode instanceof String mode) - || !Set.of("ADD", "CLEAR", "REPLACE", "FALLBACK").contains(mode)) { - blockingErrors.add(path + ".mode must be ADD, CLEAR, REPLACE, or FALLBACK."); - } else { - clearMode = "CLEAR".equals(mode); - } - } - if (reference.has("multiplier")) { - Object rawMultiplier = reference.opt("multiplier"); - if (!(rawMultiplier instanceof Number multiplier) - || !Double.isFinite(multiplier.doubleValue()) - || multiplier.doubleValue() < 0D - || multiplier.doubleValue() > IrisLootReference.MAX_MULTIPLIER) { - blockingErrors.add(path + ".multiplier must be a finite number from 0 to " - + (int) IrisLootReference.MAX_MULTIPLIER + "."); - } - } - if (!reference.has("tables")) { - return; - } - JSONArray tables = reference.optJSONArray("tables"); - if (tables == null) { - blockingErrors.add(path + ".tables must be an array."); - return; - } - if (clearMode && tables.length() > 0) { - warnings.add(path + " uses mode CLEAR and lists " + tables.length() - + " table(s); CLEAR clears parent tables and contributes no tables of its own, so these entries are dead. Use REPLACE to substitute them."); - } - for (int tableIndex = 0; tableIndex < tables.length(); tableIndex++) { - Object rawTableKey = tables.opt(tableIndex); - if (!(rawTableKey instanceof String tableKey) || tableKey.isBlank()) { - blockingErrors.add(path + ".tables[" + tableIndex + "] must name a loot table."); - } else if (!lootKeys.contains(tableKey)) { - blockingErrors.add(path + ".tables[" + tableIndex - + "] references missing loot table '" + tableKey + "'."); - } - } - } - - static Integer lootInteger(JSONObject object, String field, int defaultValue, - String path, List blockingErrors) { - if (!object.has(field)) { - return defaultValue; - } - Object rawValue = object.opt(field); - if (!(rawValue instanceof Number number) - || !Double.isFinite(number.doubleValue()) - || number.doubleValue() != Math.rint(number.doubleValue()) - || number.longValue() < Integer.MIN_VALUE - || number.longValue() > Integer.MAX_VALUE) { - blockingErrors.add(path + "." + field + " must be an integer."); - return null; - } - return number.intValue(); - } - - static void requireMinimum(String fieldPath, Integer value, int minimum, - List blockingErrors) { - if (value != null && value < minimum) { - blockingErrors.add(fieldPath + " must be at least " + minimum + "."); - } - } - - static void requireMaximum(String fieldPath, Integer value, int maximum, - List blockingErrors) { - if (value != null && value > maximum) { - blockingErrors.add(fieldPath + " must be at most " + maximum + "."); - } - } - - static void requireOrdered(String minimumPath, Integer minimum, String maximumPath, - Integer maximum, List blockingErrors) { - if (minimum != null && maximum != null && minimum > maximum) { - blockingErrors.add(minimumPath + " must not exceed " + maximumPath + "."); - } - } -} diff --git a/core/src/main/java/art/arcane/iris/core/pack/PackStructurePlacementValidator.java b/core/src/main/java/art/arcane/iris/core/pack/PackStructurePlacementValidator.java index 4d95b5e4a..801d17f42 100644 --- a/core/src/main/java/art/arcane/iris/core/pack/PackStructurePlacementValidator.java +++ b/core/src/main/java/art/arcane/iris/core/pack/PackStructurePlacementValidator.java @@ -395,8 +395,8 @@ final class PackStructurePlacementValidator { if (!structureKey.isEmpty() && !sourceKeys.add(structureKey.toLowerCase(Locale.ROOT))) { blockingErrors.add(sourcePath + ".structure duplicates native source '" + structureKey + "'."); } - Integer weight = PackLootValidator.lootInteger(source, "weight", 1, sourcePath, blockingErrors); - PackLootValidator.requireMinimum(sourcePath + ".weight", weight, 1, blockingErrors); + Integer weight = PackIntegerChecks.integerField(source, "weight", 1, sourcePath, blockingErrors); + PackIntegerChecks.requireMinimum(sourcePath + ".weight", weight, 1, blockingErrors); if (weight != null && weight > 0) { totalWeight += weight; } diff --git a/core/src/main/java/art/arcane/iris/core/pack/PackValidator.java b/core/src/main/java/art/arcane/iris/core/pack/PackValidator.java index c6d662bdb..ce9d978a6 100644 --- a/core/src/main/java/art/arcane/iris/core/pack/PackValidator.java +++ b/core/src/main/java/art/arcane/iris/core/pack/PackValidator.java @@ -36,7 +36,6 @@ public final class PackValidator { static final String DATAPACKS_FOLDER = "datapacks"; static final String CACHE_FOLDER = "cache"; static final String OBJECTS_FOLDER = "objects"; - static final String LOOT_FOLDER = "loot"; static final String DIMENSIONS_FOLDER = "dimensions"; static final String STRUCTURES_FOLDER = "structures"; static final String JIGSAW_POOLS_FOLDER = "jigsaw-pools"; @@ -90,9 +89,6 @@ public final class PackValidator { addDistinct(blockingErrors, imageMaps.errors()); addDistinct(warnings, imageMaps.warnings()); blockingErrors.addAll(PackCaveProfileValidator.validateLegacyFields(packFolder)); - PackLootValidator.LootGraphIssues lootIssues = PackLootValidator.validateLootGraph(packFolder); - addDistinct(blockingErrors, lootIssues.errors()); - addDistinct(warnings, lootIssues.warnings()); blockingErrors.addAll(PackObjectSurfaceValidator.validateRemovedWorldgenFields(packFolder)); blockingErrors.addAll(PackObjectSurfaceValidator.validateObjectSurfaceSupport(packFolder)); blockingErrors.addAll(PackObjectSurfaceValidator.validateUnsupportedStructureTransforms(packFolder)); diff --git a/core/src/main/java/art/arcane/iris/core/project/IrisPackageCompiler.java b/core/src/main/java/art/arcane/iris/core/project/IrisPackageCompiler.java index bfae34b3d..241f811e2 100644 --- a/core/src/main/java/art/arcane/iris/core/project/IrisPackageCompiler.java +++ b/core/src/main/java/art/arcane/iris/core/project/IrisPackageCompiler.java @@ -18,6 +18,8 @@ package art.arcane.iris.core.project; +import art.arcane.iris.engine.spawn.SpawnResources; +import art.arcane.iris.engine.loot.LootResources; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import com.google.gson.Gson; import art.arcane.iris.core.loader.IrisData; @@ -120,29 +122,29 @@ public class IrisPackageCompiler { } dimension.getAllRegions(() -> dm).forEach((region) -> addIfPresent(regions, region)); - dimension.getLoot().getTables().forEach((i) -> addIfPresent(loot, dm.getLootLoader().load(i))); + dimension.getLoot().getTables().forEach((i) -> addIfPresent(loot, LootResources.table(dm, i))); regions.forEach((i) -> biomes.addAll(i.getAllBiomes(() -> dm))); dimension.getReachableBiomes(() -> dm).forEach((biome) -> addIfPresent(biomes, biome)); - regions.forEach((r) -> r.getLoot().getTables().forEach((i) -> addIfPresent(loot, dm.getLootLoader().load(i)))); - regions.forEach((r) -> r.getEntitySpawners().forEach((sp) -> addIfPresent(spawners, dm.getSpawnerLoader().load(sp)))); - dimension.getEntitySpawners().forEach((sp) -> addIfPresent(spawners, dm.getSpawnerLoader().load(sp))); + regions.forEach((r) -> r.getLoot().getTables().forEach((i) -> addIfPresent(loot, LootResources.table(dm, i)))); + regions.forEach((r) -> r.getEntitySpawners().forEach((sp) -> addIfPresent(spawners, SpawnResources.spawner(dm, sp)))); + dimension.getEntitySpawners().forEach((sp) -> addIfPresent(spawners, SpawnResources.spawner(dm, sp))); biomes.forEach((i) -> i.getGenerators().forEach((j) -> addIfPresent(generators, j.getCachedGenerator(() -> dm)))); - biomes.forEach((r) -> r.getLoot().getTables().forEach((i) -> addIfPresent(loot, dm.getLootLoader().load(i)))); - biomes.forEach((r) -> r.getEntitySpawners().forEach((sp) -> addIfPresent(spawners, dm.getSpawnerLoader().load(sp)))); + biomes.forEach((r) -> r.getLoot().getTables().forEach((i) -> addIfPresent(loot, LootResources.table(dm, i)))); + biomes.forEach((r) -> r.getEntitySpawners().forEach((sp) -> addIfPresent(spawners, SpawnResources.spawner(dm, sp)))); KList allPlacements = new KList<>(); regions.forEach((r) -> allPlacements.addAll(r.getObjects())); biomes.forEach((i) -> allPlacements.addAll(i.getObjects())); KSet markers = new KSet<>(); for (String markerKey : PackExportClosure.collectMarkerKeys(allPlacements)) { - IrisMarker marker = dm.getMarkerLoader().load(markerKey); + IrisMarker marker = SpawnResources.marker(dm, markerKey); if (marker == null) { continue; } markers.add(marker); - marker.getSpawners().forEach((sp) -> addIfPresent(spawners, dm.getSpawnerLoader().load(sp))); + marker.getSpawners().forEach((sp) -> addIfPresent(spawners, SpawnResources.spawner(dm, sp))); } - collectSpawnerEntityKeys(spawners).forEach((i) -> addIfPresent(entities, dm.getEntityLoader().load(i))); - entities.forEach((e) -> e.getLoot().getTables().forEach((i) -> addIfPresent(loot, dm.getLootLoader().load(i)))); + collectSpawnerEntityKeys(spawners).forEach((i) -> addIfPresent(entities, SpawnResources.entity(dm, i))); + entities.forEach((e) -> e.getLoot().getTables().forEach((i) -> addIfPresent(loot, LootResources.table(dm, i)))); Set structureKeys = new LinkedHashSet<>(); collectStructureKeys(structureKeys, dimension.getStructures()); regions.forEach((region) -> collectStructureKeys(structureKeys, region.getStructures())); diff --git a/core/src/main/java/art/arcane/iris/util/common/data/registry/Particles.java b/core/src/main/java/art/arcane/iris/util/common/data/registry/Particles.java index be18db1cd..e30c1ba88 100644 --- a/core/src/main/java/art/arcane/iris/util/common/data/registry/Particles.java +++ b/core/src/main/java/art/arcane/iris/util/common/data/registry/Particles.java @@ -1,14 +1,12 @@ package art.arcane.iris.util.common.data.registry; -import art.arcane.iris.engine.object.entity.IrisEntity; import org.bukkit.Particle; import static art.arcane.iris.util.common.data.registry.RegistryUtil.find; /** - * Bukkit particle constants. Statically imported by {@code IrisEntity} (a Gson-registered pack - * type), so this class is reachable from core on the modded loaders. The resolution below is - * therefore guarded against the absent Bukkit class: without the guard the class initializer dies + * Bukkit particle constants, used by the Bukkit entity spawner. Core code can reach this class on the modded + * loaders, so the resolution below is guarded against the absent Bukkit class: without the guard the class initializer dies * with a NoClassDefFoundError and the class stays permanently erroneous for the rest of the JVM's * life. On Bukkit a genuinely missing registry key still throws, exactly as before. */ diff --git a/core/src/main/java/art/arcane/iris/util/common/director/handlers/EntityHandler.java b/core/src/main/java/art/arcane/iris/util/common/director/handlers/EntityHandler.java index df12a7e0b..1844516e5 100644 --- a/core/src/main/java/art/arcane/iris/util/common/director/handlers/EntityHandler.java +++ b/core/src/main/java/art/arcane/iris/util/common/director/handlers/EntityHandler.java @@ -18,7 +18,10 @@ package art.arcane.iris.util.common.director.handlers; +import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.object.entity.IrisEntity; +import art.arcane.iris.engine.spawn.SpawnResources; +import art.arcane.volmlib.util.collection.KList; import art.arcane.iris.util.common.director.specialhandlers.RegistrantHandler; public class EntityHandler extends RegistrantHandler { @@ -27,6 +30,18 @@ public class EntityHandler extends RegistrantHandler { super(IrisEntity.class, false); } + @Override + protected KList loadAll(IrisData data) { + KList entities = new KList<>(); + for (String key : SpawnResources.entityKeys(data)) { + IrisEntity entity = SpawnResources.entity(data, key); + if (entity != null) { + entities.add(entity); + } + } + return entities; + } + @Override public String getRandomDefault() { return "entity"; diff --git a/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/RegistrantHandler.java b/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/RegistrantHandler.java index c11a99aff..b9d7ecad4 100644 --- a/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/RegistrantHandler.java +++ b/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/RegistrantHandler.java @@ -29,7 +29,7 @@ public abstract class RegistrantHandler implements Dir Set known = new HashSet<>(); IrisData data = data(); if (data != null) { - for (T j : data.getLoader(type).loadAll(data.getLoader(type).getPossibleKeys())) { + for (T j : loadAll(data)) { known.add(j.getLoadKey()); p.add(j); } @@ -38,7 +38,7 @@ public abstract class RegistrantHandler implements Dir for (File i : PackDirectoryResolver.listVisiblePackDirectories( IrisPlatforms.get().packsFolder())) { data = IrisData.get(i); - for (T j : data.getLoader(type).loadAll(data.getLoader(type).getPossibleKeys())) { + for (T j : loadAll(data)) { if (known.add(j.getLoadKey())) p.add(j); } @@ -47,6 +47,11 @@ public abstract class RegistrantHandler implements Dir return p; } + /** Every resource of this handler's type that {@code data}'s pack has. */ + protected KList loadAll(IrisData data) { + return data.getLoader(type).loadAll(data.getLoader(type).getPossibleKeys()); + } + @Override public String toString(T t) { return t != null ? t.getLoadKey() : "null"; diff --git a/core/src/main/java/art/arcane/iris/util/project/matter/slices/RegistryMatter.java b/core/src/main/java/art/arcane/iris/util/project/matter/slices/RegistryMatter.java index 780e55617..229e1f11b 100644 --- a/core/src/main/java/art/arcane/iris/util/project/matter/slices/RegistryMatter.java +++ b/core/src/main/java/art/arcane/iris/util/project/matter/slices/RegistryMatter.java @@ -20,7 +20,6 @@ package art.arcane.iris.util.project.matter.slices; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.core.loader.ResourceLoader; import art.arcane.iris.util.project.matter.IrisMatterContext; import art.arcane.volmlib.util.data.palette.Palette; import art.arcane.volmlib.util.matter.slices.RawMatter; @@ -29,7 +28,7 @@ import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; -public class RegistryMatter extends RawMatter { +public abstract class RegistryMatter extends RawMatter { public RegistryMatter(int width, int height, int depth, Class c, T e) { super(width, height, depth, c); } @@ -46,12 +45,9 @@ public class RegistryMatter extends RawMatter { @Override public T readNode(DataInputStream din) throws IOException { - String key = din.readUTF(); - IrisData data = IrisMatterContext.require(); - ResourceLoader loader = data.getLoaders().get(getType()); - if (loader == null) { - throw new IOException("No Iris registry loader is available for matter type " + getType().getName() + " while reading key " + key + "."); - } - return (T) loader.load(key); + return load(IrisMatterContext.require(), din.readUTF()); } + + /** The resource of the pack {@code data} named by {@code key}, or null when the pack has none. */ + protected abstract T load(IrisData data, String key); } diff --git a/core/src/main/java/art/arcane/iris/util/project/matter/slices/SpawnerMatter.java b/core/src/main/java/art/arcane/iris/util/project/matter/slices/SpawnerMatter.java index 0c7040ecb..0cd4eb21b 100644 --- a/core/src/main/java/art/arcane/iris/util/project/matter/slices/SpawnerMatter.java +++ b/core/src/main/java/art/arcane/iris/util/project/matter/slices/SpawnerMatter.java @@ -18,7 +18,9 @@ package art.arcane.iris.util.project.matter.slices; +import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; +import art.arcane.iris.engine.spawn.SpawnResources; import art.arcane.volmlib.util.matter.Sliced; @Sliced @@ -30,4 +32,9 @@ public class SpawnerMatter extends RegistryMatter { public SpawnerMatter(int width, int height, int depth) { super(width, height, depth, IrisSpawner.class, new IrisSpawner()); } + + @Override + protected IrisSpawner load(IrisData data, String key) { + return SpawnResources.spawner(data, key); + } } diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureResourcesTest.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureResourcesTest.java index 2c6a07efb..139a0f3b4 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 @@ -44,10 +44,11 @@ public class StructureResourcesTest { try { var catalog = data.getModules().pack().catalog(); + var kinds = catalog.resourceKinds().stream().map(ResourceKindRegistration::kind) + .filter(kind -> kind.id().toString().startsWith("iris:structure/")).toList(); assertEquals(List.of("iris:structure/piece", "iris:structure/pool", "iris:structure/structure"), - catalog.resourceKinds().stream().map(registration -> registration.kind().id().toString()).toList()); - assertEquals(List.of("jigsaw-pieces", "jigsaw-pools", "structures"), - catalog.resourceKinds().stream().map(ResourceKindRegistration::kind).map(kind -> kind.folder()).toList()); + kinds.stream().map(kind -> kind.id().toString()).toList()); + assertEquals(List.of("jigsaw-pieces", "jigsaw-pools", "structures"), kinds.stream().map(kind -> kind.folder()).toList()); assertTrue(catalog.validators().stream().map(ValidatorRegistration::validator).anyMatch(StructureValidator.class::isInstance)); assertFalse(data.getLoaders().containsKey(IrisStructure.class)); assertFalse(data.getLoaders().containsKey(IrisJigsawPool.class)); @@ -146,7 +147,8 @@ public class StructureResourcesTest { List entries = ModuleResourceSchemas.entries(data, true); assertEquals(List.of("./.iris/schema/jigsaw-pieces-schema.json", "./.iris/schema/jigsaw-pools-schema.json", - "./.iris/schema/structures-schema.json"), entries.stream().map(entry -> entry.getString("url")).toList()); + "./.iris/schema/structures-schema.json"), + entries.stream().map(entry -> entry.getString("url")).filter(url -> url.contains("jigsaw") || url.contains("structures-")).toList()); JSONObject structures = new JSONObject(Files.readString(pack.resolve(".iris/schema/structures-schema.json"))); JSONObject startPool = structures.getJSONObject("properties").getJSONObject("startPool"); assertEquals("#/definitions/erzjigsaw-pools", startPool.getString("$ref")); 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 new file mode 100644 index 000000000..a1e0d4029 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/loot/LootResourcesTest.java @@ -0,0 +1,113 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.loot; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.project.ModuleResourceSchemas; +import art.arcane.iris.core.project.SchemaTestPlatform; +import art.arcane.iris.engine.object.loot.IrisLootTable; +import art.arcane.volmlib.util.json.JSONObject; +import com.volmit.host.ValidatorRegistration; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +/** Loot tables are a resource kind of module {@code iris:loot}, read from the folder packs have always had. */ +public class LootResourcesTest { + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Test + public void theLootModuleOwnsTheKindAndItsValidator() throws Exception { + IrisData data = IrisData.openValidation(lootPack("owned").toFile()); + try { + var catalog = data.getModules().pack().catalog(); + + assertEquals(List.of("iris:loot/table"), catalog.resourceKinds().stream().map(registration -> registration.kind().id().toString()) + .filter(id -> id.startsWith("iris:loot/")).toList()); + assertTrue(catalog.validators().stream().map(ValidatorRegistration::validator).anyMatch(LootValidator.class::isInstance)); + assertFalse(data.getLoaders().containsKey(IrisLootTable.class)); + } finally { + data.close(); + } + } + + @Test + public void tablesAreReadThroughPackResourcesAndReadAgainAfterAReload() throws Exception { + Path pack = lootPack("tables"); + IrisData data = IrisData.openValidation(pack.toFile()); + try { + IrisLootTable table = LootResources.table(data, "dungeon/chest"); + + assertEquals("Chest", table.getName()); + assertEquals("dungeon/chest", table.getLoadKey()); + assertEquals(pack.resolve("loot/dungeon/chest.json").toFile(), table.getLoadFile()); + assertEquals(List.of("dungeon/chest"), LootResources.tableKeys(data)); + assertEquals(List.of(table), LootResources.tables(data, List.of("dungeon/chest", "missing"))); + assertNull(LootResources.table(data, "missing")); + assertNull(LootResources.table(data, " ")); + + write(pack, "loot/dungeon/chest.json", "{\"name\":\"Renamed\"}"); + data.dump(); + assertEquals("Renamed", LootResources.table(data, "dungeon/chest").getName()); + } finally { + data.close(); + } + } + + @Test + public void studioDescribesLootTablesAsIrisDoes() throws Exception { + Path pack = lootPack("studio"); + IrisData data = IrisData.openValidation(pack.toFile()); + try (SchemaTestPlatform ignored = SchemaTestPlatform.bind(temporaryFolder.getRoot())) { + List entries = ModuleResourceSchemas.entries(data, true); + + assertTrue(entries.stream().anyMatch(entry -> entry.getString("url").equals("./.iris/schema/loot-schema.json"))); + assertTrue(Files.exists(pack.resolve(".iris/schema/loot-schema.json"))); + } finally { + data.close(); + } + } + + 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(), "biomes/biome.json", "{\"name\":\"Biome\"}"); + write(pack.toPath(), "loot/dungeon/chest.json", "{\"name\":\"Chest\",\"loot\":[{\"type\":\"stick\"}]}"); + return pack.toPath(); + } + + private static void write(Path root, String relative, String content) throws Exception { + Path path = root.resolve(relative); + Files.createDirectories(path.getParent()); + Files.writeString(path, content, StandardCharsets.UTF_8); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/pack/PackValidatorLootTest.java b/core/src/test/java/art/arcane/iris/engine/loot/LootValidatorTest.java similarity index 86% rename from core/src/test/java/art/arcane/iris/core/pack/PackValidatorLootTest.java rename to core/src/test/java/art/arcane/iris/engine/loot/LootValidatorTest.java index ac435304e..b27b04f32 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/PackValidatorLootTest.java +++ b/core/src/test/java/art/arcane/iris/engine/loot/LootValidatorTest.java @@ -1,8 +1,10 @@ -package art.arcane.iris.core.pack; +package art.arcane.iris.engine.loot; import art.arcane.iris.engine.object.loot.IrisLoot; import art.arcane.iris.engine.object.loot.IrisLootTable; import art.arcane.iris.engine.object.annotations.MaxNumber; +import com.volmit.validation.Problem; +import com.volmit.validation.Severity; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -16,7 +18,7 @@ import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -public class PackValidatorLootTest { +public class LootValidatorTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @@ -28,7 +30,7 @@ public class PackValidatorLootTest { write(pack, "dimensions/main.json", "{\"loot\":{\"mode\":\"FALLBACK\",\"multiplier\":0.5," + "\"tables\":[\"global/clutter\"]}}"); - assertTrue(PackLootValidator.validateLootGraph(pack).errors().isEmpty()); + assertTrue(errors(pack).isEmpty()); } @Test @@ -37,7 +39,7 @@ public class PackValidatorLootTest { write(pack, "dimensions/main.json", "{\"loot\":{\"tables\":[\"missing\"]}}"); assertEquals(List.of("Dimension 'main'.loot.tables[0] references missing loot table 'missing'."), - PackLootValidator.validateLootGraph(pack).errors()); + errors(pack)); } @Test @@ -47,7 +49,7 @@ public class PackValidatorLootTest { + "\"loot\":[{\"type\":\"\",\"rarity\":0,\"minAmount\":3,\"maxAmount\":1," + "\"enchantments\":[{\"enchantment\":\"\",\"minLevel\":4,\"maxLevel\":2,\"chance\":2}]}]}"); - List errors = PackLootValidator.validateLootGraph(pack).errors(); + List errors = errors(pack); assertTrue(errors.stream().anyMatch(error -> error.contains(".rarity must be at least 1"))); assertTrue(errors.stream().anyMatch(error -> error.contains(".minPicked must not exceed"))); @@ -63,7 +65,7 @@ public class PackValidatorLootTest { File pack = temporaryFolder.newFolder("pack"); write(pack, "dimensions/main.json", "{\"loot\":{\"mode\":\"MERGE\",\"multiplier\":-1,\"tables\":[]}}"); - List errors = PackLootValidator.validateLootGraph(pack).errors(); + List errors = errors(pack); assertEquals(2, errors.size()); assertTrue(errors.get(0).contains(".mode must be")); @@ -74,12 +76,12 @@ public class PackValidatorLootTest { public void enforcesPublishedLootMultiplierCap() throws Exception { File acceptedPack = temporaryFolder.newFolder("accepted-pack"); write(acceptedPack, "dimensions/main.json", "{\"loot\":{\"multiplier\":16,\"tables\":[]}}"); - assertTrue(PackLootValidator.validateLootGraph(acceptedPack).errors().isEmpty()); + assertTrue(errors(acceptedPack).isEmpty()); File rejectedPack = temporaryFolder.newFolder("rejected-pack"); write(rejectedPack, "dimensions/main.json", "{\"loot\":{\"multiplier\":16.01,\"tables\":[]}}"); assertEquals(List.of("Dimension 'main'.loot.multiplier must be a finite number from 0 to 16."), - PackLootValidator.validateLootGraph(rejectedPack).errors()); + errors(rejectedPack)); } @Test @@ -88,7 +90,7 @@ public class PackValidatorLootTest { write(pack, "loot/boundary.json", "{\"minPicked\":64,\"maxPicked\":64,\"maxTries\":256," + "\"loot\":[{\"type\":\"stone\",\"minAmount\":64,\"maxAmount\":64}]}"); - assertTrue(PackLootValidator.validateLootGraph(pack).errors().isEmpty()); + assertTrue(errors(pack).isEmpty()); } @Test @@ -97,7 +99,7 @@ public class PackValidatorLootTest { write(pack, "loot/excessive.json", "{\"minPicked\":65,\"maxPicked\":65,\"maxTries\":257," + "\"loot\":[{\"type\":\"stone\",\"minAmount\":65,\"maxAmount\":65}]}"); - List errors = PackLootValidator.validateLootGraph(pack).errors(); + List errors = errors(pack); assertTrue(errors.contains("Loot table 'excessive'.minPicked must be at most 64.")); assertTrue(errors.contains("Loot table 'excessive'.maxPicked must be at most 64.")); @@ -127,12 +129,11 @@ public class PackValidatorLootTest { write(pack, "loot/t.json", "{\"loot\":[{\"type\":\"minecraft:stone\"}]}"); write(pack, "biomes/x.json", "{\"loot\":{\"mode\":\"CLEAR\",\"tables\":[\"t\"]}}"); - PackLootValidator.LootGraphIssues issues = PackLootValidator.validateLootGraph(pack); - - assertTrue(issues.errors().isEmpty()); + + assertTrue(errors(pack).isEmpty()); assertEquals(List.of("Biome 'x'.loot uses mode CLEAR and lists 1 table(s); CLEAR clears parent tables" + " and contributes no tables of its own, so these entries are dead. Use REPLACE to substitute them."), - issues.warnings()); + warnings(pack)); } @Test @@ -140,12 +141,23 @@ public class PackValidatorLootTest { File pack = temporaryFolder.newFolder("clear-dangling"); write(pack, "biomes/x.json", "{\"loot\":{\"mode\":\"CLEAR\",\"tables\":[\"missing\"]}}"); - PackLootValidator.LootGraphIssues issues = PackLootValidator.validateLootGraph(pack); - - assertTrue(issues.errors().contains( + + assertTrue(errors(pack).contains( "Biome 'x'.loot.tables[0] references missing loot table 'missing'.")); } + private static List errors(File pack) { + return messages(pack, Severity.ERROR); + } + + private static List warnings(File pack) { + return messages(pack, Severity.WARNING); + } + + private static List messages(File pack, Severity severity) { + return LootValidator.check(pack).stream().filter(problem -> problem.severity() == severity).map(Problem::message).toList(); + } + private void write(File root, String relative, String content) throws Exception { File file = new File(root, relative); Files.createDirectories(file.toPath().getParent()); diff --git a/core/src/test/java/art/arcane/iris/engine/spawn/EntitySpawningTest.java b/core/src/test/java/art/arcane/iris/engine/spawn/EntitySpawningTest.java index 6f706a5c9..b66829125 100644 --- a/core/src/test/java/art/arcane/iris/engine/spawn/EntitySpawningTest.java +++ b/core/src/test/java/art/arcane/iris/engine/spawn/EntitySpawningTest.java @@ -19,7 +19,6 @@ package art.arcane.iris.engine.spawn; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.loader.ResourceLoader; import art.arcane.iris.core.modules.ModuleResourceFixture; import art.arcane.iris.engine.UsableBlockPlatform; import art.arcane.iris.engine.framework.Engine; @@ -58,9 +57,7 @@ public class EntitySpawningTest { private static final BlockPosition MARKER_BLOCK = new BlockPosition(40, 70, -12); private Engine engine; - private ResourceLoader spawners; - private ResourceLoader markers; - private ResourceLoader entities; + private ModuleResourceFixture fixture; private PackWorld world; @BeforeClass @@ -74,18 +71,11 @@ public class EntitySpawningTest { } @Before - @SuppressWarnings("unchecked") public void buildWorld() { engine = mock(Engine.class); IrisData data = mock(IrisData.class); - spawners = (ResourceLoader) mock(ResourceLoader.class); - markers = (ResourceLoader) mock(ResourceLoader.class); - entities = (ResourceLoader) mock(ResourceLoader.class); when(engine.getData()).thenReturn(data); - when(data.getSpawnerLoader()).thenReturn(spawners); - when(data.getMarkerLoader()).thenReturn(markers); - when(data.getEntityLoader()).thenReturn(entities); - ModuleResourceFixture.serve(data); + fixture = ModuleResourceFixture.serve(data); when(data.getPackResources().items()).thenReturn(mock(ItemRegistry.class)); IrisWorld engineWorld = mock(IrisWorld.class); when(engineWorld.platformWorld()).thenReturn(mock(PlatformWorld.class)); @@ -109,8 +99,8 @@ public class EntitySpawningTest { public void aMarkerMeansItsSpawnersAndWhetherItGoesAwayWhenItsBlockChanges() { IrisMarker marker = new IrisMarker(); marker.setSpawners(new KList<>("zombies", "missing")).setEmptyAbove(true).setRemoveOnChange(false); - when(markers.load("camp")).thenReturn(marker); - when(spawners.load("zombies")).thenReturn(new IrisSpawner()); + fixture.resource(SpawnResources.MARKERS, "camp", marker); + fixture.resource(SpawnResources.SPAWNERS, "zombies", new IrisSpawner()); EntitySpawns.MarkerRule rule = new EntitySpawning().marker(world, "camp").orElseThrow(); @@ -130,13 +120,13 @@ public class EntitySpawningTest { IrisSpawner spawner = new IrisSpawner(); spawner.setLoadKey("camp/zombies"); spawner.getSpawns().add(new IrisEntitySpawn().setEntity("zombie").setMinSpawns(2).setMaxSpawns(2)); - when(spawners.load("camp/zombies")).thenReturn(spawner); + fixture.resource(SpawnResources.SPAWNERS, "camp/zombies", spawner); IrisMarker marker = new IrisMarker(); marker.setExhaustionChance(2); - when(markers.load("camp")).thenReturn(marker); + fixture.resource(SpawnResources.MARKERS, "camp", marker); IrisEntity zombie = new IrisEntity(); zombie.setType("minecraft:zombie"); - when(entities.load("zombie")).thenReturn(zombie); + fixture.resource(SpawnResources.ENTITIES, "zombie", zombie); when(engine.getMinHeight()).thenReturn(-64); EntitySpawns.Plan plan = new EntitySpawning() @@ -156,7 +146,7 @@ public class EntitySpawningTest { @Test public void aSpawnerThatCannotFireOrHasNoEntitiesPlansNothing() { IrisSpawner empty = new IrisSpawner(); - when(spawners.load("empty")).thenReturn(empty); + fixture.resource(SpawnResources.SPAWNERS, "empty", empty); Optional plan = new EntitySpawning().plan(world, new EntitySpawns.Marker(MARKER_BLOCK, "camp", "empty", false)); @@ -167,7 +157,7 @@ public class EntitySpawningTest { public void anEntityOfThePackResolvesToTheSpecTheHostSpawns() { IrisEntity entity = new IrisEntity(); entity.setType("minecraft:cow").setCustomName("&6Bessie").setBaby(true); - when(entities.load("cow")).thenReturn(entity); + fixture.resource(SpawnResources.ENTITIES, "cow", entity); EntitySpec spec = new EntitySpawning().entity(world, "cow").orElseThrow(); 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 new file mode 100644 index 000000000..13e7d542e --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/spawn/SpawnResourcesTest.java @@ -0,0 +1,104 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.spawn; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.object.entity.IrisEntity; +import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; +import art.arcane.iris.engine.object.marker.IrisMarker; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; + +/** Spawners, entities and markers are resource kinds of module {@code iris:spawn}, read from the folders packs have always had. */ +public class SpawnResourcesTest { + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Test + public void theSpawnModuleOwnsTheKinds() throws Exception { + IrisData data = IrisData.openValidation(spawnPack("owned").toFile()); + try { + var catalog = data.getModules().pack().catalog(); + + var kinds = catalog.resourceKinds().stream().map(registration -> registration.kind()) + .filter(kind -> kind.id().toString().startsWith("iris:spawn/")).toList(); + assertEquals(List.of("iris:spawn/entity", "iris:spawn/marker", "iris:spawn/spawner"), kinds.stream().map(kind -> kind.id().toString()).toList()); + assertEquals(List.of("entities", "markers", "spawners"), kinds.stream().map(kind -> kind.folder()).toList()); + assertFalse(data.getLoaders().containsKey(IrisSpawner.class)); + assertFalse(data.getLoaders().containsKey(IrisEntity.class)); + assertFalse(data.getLoaders().containsKey(IrisMarker.class)); + } finally { + data.close(); + } + } + + @Test + public void spawnersEntitiesAndMarkersAreReadThroughPackResources() throws Exception { + Path pack = spawnPack("spawns"); + IrisData data = IrisData.openValidation(pack.toFile()); + try { + IrisSpawner spawner = SpawnResources.spawner(data, "camp/zombies"); + + assertEquals("camp/zombies", spawner.getLoadKey()); + assertEquals(pack.resolve("spawners/camp/zombies.json").toFile(), spawner.getLoadFile()); + assertEquals("minecraft:zombie", SpawnResources.entity(data, "zombie").getType()); + assertEquals(List.of("camp/zombies"), SpawnResources.marker(data, "camp").getSpawners()); + assertEquals(List.of(spawner), SpawnResources.spawners(data, List.of("camp/zombies", "missing"))); + assertEquals(List.of("zombie"), SpawnResources.entityKeys(data)); + assertEquals(List.of("camp"), SpawnResources.markerKeys(data)); + assertEquals(List.of("camp/zombies"), SpawnResources.spawnerKeys(data)); + assertNull(SpawnResources.spawner(data, "missing")); + assertNull(SpawnResources.entity(data, " ")); + + write(pack, "entities/zombie.json", "{\"type\":\"minecraft:husk\"}"); + data.dump(); + assertEquals("minecraft:husk", SpawnResources.entity(data, "zombie").getType()); + } finally { + data.close(); + } + } + + 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(), "biomes/biome.json", "{\"name\":\"Biome\"}"); + write(pack.toPath(), "entities/zombie.json", "{\"type\":\"minecraft:zombie\"}"); + write(pack.toPath(), "spawners/camp/zombies.json", "{\"spawns\":[{\"entity\":\"zombie\"}]}"); + write(pack.toPath(), "markers/camp.json", "{\"spawners\":[\"camp/zombies\"]}"); + return pack.toPath(); + } + + private static void write(Path root, String relative, String content) throws Exception { + Path path = root.resolve(relative); + Files.createDirectories(path.getParent()); + Files.writeString(path, content, StandardCharsets.UTF_8); + } +} diff --git a/core/src/test/java/art/arcane/iris/purity/PackTypeBukkitPurityGateTest.java b/core/src/test/java/art/arcane/iris/purity/PackTypeBukkitPurityGateTest.java index 13dc6934e..fc680340a 100644 --- a/core/src/test/java/art/arcane/iris/purity/PackTypeBukkitPurityGateTest.java +++ b/core/src/test/java/art/arcane/iris/purity/PackTypeBukkitPurityGateTest.java @@ -89,8 +89,7 @@ import static org.junit.Assert.fail; * deleted) and {@code Particles} (Bukkit registry lookups in a static initializer). *

* Deliberately not asserted: method and constructor descriptors. These classes legitimately - * expose a Bukkit-typed edge that only the Bukkit adapter calls - {@code IrisEntity.spawn(Engine, - * Location)}, {@code IrisLoot.get(...) -> ItemStack}, {@code IrisObjectRotation.rotate(BlockData, + * expose a Bukkit-typed edge that only the Bukkit adapter calls - {@code IrisObjectRotation.rotate(BlockData, * ...)}, {@code TileData.toBukkit(Block)} and ~60 more. Method descriptors are resolved at * invocation, never at class load, field walk or equals/hashCode/toString, so they are not a modded * boot hazard. Fields and supertypes are, and both are asserted hard below. @@ -110,15 +109,11 @@ public class PackTypeBukkitPurityGateTest { * #registeredRootListMatchesIrisData()} fails if the source drifts away from it. */ private static final List GSON_REGISTERED_ROOTS = List.of( - "art.arcane.iris.engine.object.loot.IrisLootTable", - "art.arcane.iris.engine.object.entity.spawn.IrisSpawner", - "art.arcane.iris.engine.object.entity.IrisEntity", "art.arcane.iris.engine.object.world.region.IrisRegion", "art.arcane.iris.engine.object.world.biome.IrisBiome", "art.arcane.iris.engine.object.mod.IrisMod", "art.arcane.iris.engine.object.world.dimension.IrisDimension", "art.arcane.iris.engine.object.terrain.IrisGenerator", - "art.arcane.iris.engine.object.marker.IrisMarker", "art.arcane.iris.engine.object.material.IrisBlockData", "art.arcane.iris.engine.object.noise.expression.IrisExpression", "art.arcane.iris.engine.object.prefab.IrisObject", @@ -133,7 +128,11 @@ public class PackTypeBukkitPurityGateTest { private static final List MODULE_RESOURCE_ROOTS = List.of( "art.arcane.iris.engine.object.structure.IrisStructure", "art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool", - "art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece"); + "art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece", + "art.arcane.iris.engine.object.loot.IrisLootTable", + "art.arcane.iris.engine.object.entity.spawn.IrisSpawner", + "art.arcane.iris.engine.object.entity.IrisEntity", + "art.arcane.iris.engine.object.marker.IrisMarker"); /** * Types reachable from a pack that are not roots and carry no {@code @Snippet}, but are @@ -145,8 +144,9 @@ public class PackTypeBukkitPurityGateTest { "art.arcane.iris.engine.object.loot.IrisVanillaLootTable"); /** - * Bukkit-registry constant holders that a core pack type references, so their class initializer - * runs on the modded loaders too. {@code Particles} is statically imported by {@code IrisEntity}. + * Bukkit-registry constant holders that a core pack type may reference, so their class initializer + * must run on the modded loaders too. {@code Particles} is used by the Bukkit entity spawner now; it stays in the + * gate so that a pack type importing it again keeps working. * ({@code Materials} and {@code Attributes} have the same shape but are only reachable from the * Bukkit adapter, so they stay out of the gate.) */ diff --git a/core/src/test/java/art/arcane/iris/util/project/matter/RegistryMatterContextTest.java b/core/src/test/java/art/arcane/iris/util/project/matter/RegistryMatterContextTest.java index cd32792d9..7e6271aba 100644 --- a/core/src/test/java/art/arcane/iris/util/project/matter/RegistryMatterContextTest.java +++ b/core/src/test/java/art/arcane/iris/util/project/matter/RegistryMatterContextTest.java @@ -1,11 +1,10 @@ package art.arcane.iris.util.project.matter; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.core.loader.ResourceLoader; +import art.arcane.iris.core.modules.ModuleResourceFixture; +import art.arcane.iris.engine.spawn.SpawnResources; import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; import art.arcane.iris.util.project.matter.slices.SpawnerMatter; -import art.arcane.volmlib.util.collection.KMap; import org.junit.Test; import java.io.ByteArrayInputStream; @@ -18,7 +17,6 @@ import java.util.concurrent.Future; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; public class RegistryMatterContextTest { @Test @@ -49,14 +47,9 @@ public class RegistryMatterContextTest { } } - @SuppressWarnings("unchecked") private IrisData dataReturning(IrisSpawner resolved) { - ResourceLoader loader = mock(ResourceLoader.class); - when(loader.load("test-spawner")).thenReturn(resolved); - KMap, ResourceLoader> loaders = new KMap<>(); - loaders.put(IrisSpawner.class, loader); IrisData data = mock(IrisData.class); - when(data.getLoaders()).thenReturn(loaders); + ModuleResourceFixture.serve(data).resource(SpawnResources.SPAWNERS, "test-spawner", resolved); return data; } } From 7ae605a4e43ef2446e456279c68c1a49bb753ac2 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 22:26:05 +0200 Subject: [PATCH 7/7] Purity ratchet: the Bukkit code that moved out of the loot and entity classes is allowlisted, the classes that lost it are not Custom item durability asks the external data service. --- core/purity-allowlist.txt | 12 ++++-------- .../arcane/iris/core/modules/IrisItemRegistry.java | 5 +---- .../arcane/iris/core/service/ExternalDataSVC.java | 7 +++++++ 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/core/purity-allowlist.txt b/core/purity-allowlist.txt index 1cd8e2fc5..50a4d26c9 100644 --- a/core/purity-allowlist.txt +++ b/core/purity-allowlist.txt @@ -101,28 +101,20 @@ art/arcane/iris/engine/framework/placer/WorldObjectPlacer.java art/arcane/iris/engine/mantle/MantleWriter.java art/arcane/iris/engine/object/material/BlockDataMergeSupport.java art/arcane/iris/engine/object/placement/IPostBlockAccess.java -art/arcane/iris/engine/object/entity/IrisAttributeModifier.java art/arcane/iris/engine/object/world/biome/IrisBiome.java art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomParticle.java art/arcane/iris/engine/object/world/biome/IrisBiomeDerivatives.java art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomSpawn.java -art/arcane/iris/engine/object/loot/IrisBlockDrops.java art/arcane/iris/engine/object/marker/IrisCommandRegistry.java art/arcane/iris/engine/object/compatibility/IrisCompat.java art/arcane/iris/engine/object/compatibility/IrisCompatabilityBlockFilter.java art/arcane/iris/engine/object/compatibility/IrisCompatabilityItemFilter.java art/arcane/iris/engine/object/value/IrisDirection.java art/arcane/iris/engine/object/entity/IrisEffect.java -art/arcane/iris/engine/object/loot/IrisEnchantment.java -art/arcane/iris/engine/object/entity/IrisEntity.java -art/arcane/iris/engine/object/entity/IrisEntitySpawn.java -art/arcane/iris/engine/object/loot/IrisLoot.java -art/arcane/iris/engine/object/loot/IrisLootTable.java art/arcane/iris/engine/object/prefab/IrisObject.java art/arcane/iris/engine/object/placement/IrisObjectPlacement.java art/arcane/iris/engine/object/prefab/IrisObjectRotation.java art/arcane/iris/engine/object/entity/IrisPotionEffect.java -art/arcane/iris/engine/object/entity/spawn/IrisSurface.java art/arcane/iris/engine/object/placement/IrisTree.java art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java art/arcane/iris/engine/object/prefab/LegacyTileData.java @@ -187,3 +179,7 @@ art/arcane/iris/util/project/matter/IrisMatterSupport.java art/arcane/iris/util/project/matter/WorldMatter.java art/arcane/iris/util/project/matter/slices/EntityMatter.java art/arcane/iris/util/project/matter/slices/TileMatter.java +art/arcane/iris/engine/platform/BukkitEntitySpawner.java +art/arcane/iris/engine/platform/BukkitSurfaces.java +art/arcane/iris/platform/bukkit/BukkitAttributes.java +art/arcane/iris/platform/bukkit/BukkitItemStacks.java 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 index 8d2d4f6b0..9a5cc623b 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisItemRegistry.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisItemRegistry.java @@ -24,9 +24,7 @@ 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; /** @@ -53,7 +51,6 @@ public final class IrisItemRegistry implements ItemRegistry { } 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()); + return IrisServices.get(ExternalDataSVC.class).maxDurability(Identifier.fromString(key)); } } diff --git a/core/src/main/java/art/arcane/iris/core/service/ExternalDataSVC.java b/core/src/main/java/art/arcane/iris/core/service/ExternalDataSVC.java index 00b291701..fe5fc0e4e 100644 --- a/core/src/main/java/art/arcane/iris/core/service/ExternalDataSVC.java +++ b/core/src/main/java/art/arcane/iris/core/service/ExternalDataSVC.java @@ -45,6 +45,7 @@ import java.util.List; import java.util.MissingResourceException; import java.util.Objects; import java.util.Optional; +import java.util.OptionalInt; import java.util.stream.Collectors; public class ExternalDataSVC implements IrisService { @@ -159,6 +160,12 @@ public class ExternalDataSVC implements IrisService { } } + /** The most damage the custom item {@code key} takes before it breaks, 0 if it cannot be damaged; empty when no provider has the item. */ + public OptionalInt maxDurability(Identifier key) { + Optional stack = getItemStack(key, null); + return stack.isEmpty() ? OptionalInt.empty() : OptionalInt.of(stack.get().getType().getMaxDurability()); + } + public void processUpdate(Engine engine, Block block, Identifier blockId) { Optional provider = activeProviders.stream().filter(p -> p.isValidProvider(blockId, DataType.BLOCK)).findFirst(); if (provider.isEmpty()) {