Merge branch 'wave2/d' into feat/irisapi-host

This commit is contained in:
piexel committed 2026-10-09 22:33:42 +02:00
commit 0b303eb937
63 files changed
+2319 -1185

No files matched your search

@@ -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.terrain.IrisBiomePaletteLayer;
import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.entity.IrisEntity; 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.terrain.IrisGenerator;
import art.arcane.iris.engine.object.noise.IrisInterpolator; import art.arcane.iris.engine.object.noise.IrisInterpolator;
import art.arcane.iris.engine.object.loot.IrisLootTable; import art.arcane.iris.engine.object.loot.IrisLootTable;
@@ -298,11 +299,10 @@ public class CommandStudio implements DirectorExecutor {
) { ) {
if (noStudio()) return; if (noStudio()) return;
KList<IrisLootTable> tables = EngineBukkitOps.getLootTables(engine(), RNG.r, player().getLocation().getBlock());
Inventory inv = Bukkit.createInventory(null, 27 * 2); Inventory inv = Bukkit.createInventory(null, 27 * 2);
try { 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) { } catch (Throwable e) {
Iris.reportError(e); Iris.reportError(e);
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_CANNOT_ADD_ITEMS_VIRTUAL_INVENTORY_BECAUSE, MessageArgument.untrusted("value", String.valueOf(e.getMessage())))); sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_CANNOT_ADD_ITEMS_VIRTUAL_INVENTORY_BECAUSE, MessageArgument.untrusted("value", String.valueOf(e.getMessage()))));
@@ -329,7 +329,7 @@ public class CommandStudio implements DirectorExecutor {
inv.clear(); 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)); }, fast ? 5 : 35));
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_INVENTORY_NOW)); sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_INVENTORY_NOW));
@@ -662,7 +662,7 @@ public class CommandStudio implements DirectorExecutor {
// Entity creation must run on the thread owning the destination chunk. // Entity creation must run on the thread owning the destination chunk.
Location at = new Location(world(), location.getX(), location.getY(), location.getZ()); 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() + "."); Iris.warn("Could not schedule the entity spawn at " + at.getBlockX() + ", " + at.getBlockY() + ", " + at.getBlockZ() + ".");
} }
} }
@@ -18,6 +18,7 @@
package art.arcane.iris.modded; package art.arcane.iris.modded;
import art.arcane.iris.engine.spawn.SpawnResources;
import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.LootResolver; import art.arcane.iris.engine.framework.LootResolver;
@@ -235,7 +236,7 @@ public final class ModdedBlockBreakHandler {
if ("cave_floor".equals(tag) || "cave_ceiling".equals(tag)) { if ("cave_floor".equals(tag) || "cave_ceiling".equals(tag)) {
return; return;
} }
IrisMarker configured = engine.getData().getMarkerLoader().load(tag); IrisMarker configured = SpawnResources.marker(engine.getData(), tag);
if (configured == null || configured.isRemoveOnChange()) { if (configured == null || configured.isRemoveOnChange()) {
engine.getMantle().getMantle().remove(position.getX(), mantleY, position.getZ(), MatterMarker.class); engine.getMantle().getMantle().remove(position.getX(), mantleY, position.getZ(), MatterMarker.class);
} }
@@ -18,6 +18,7 @@
package art.arcane.iris.modded; package art.arcane.iris.modded;
import art.arcane.iris.engine.loot.LootResources;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.object.loot.InventorySlotType; import art.arcane.iris.engine.object.loot.InventorySlotType;
import art.arcane.iris.engine.object.loot.IrisLootTable; import art.arcane.iris.engine.object.loot.IrisLootTable;
@@ -104,7 +105,7 @@ public final class ModdedDeathLoot {
private static KList<ItemStack> resolve(Engine engine, ServerLevel level, LootBinding binding) { private static KList<ItemStack> resolve(Engine engine, ServerLevel level, LootBinding binding) {
KList<ItemStack> drops = new KList<>(); KList<ItemStack> drops = new KList<>();
for (String key : binding.tableKeys()) { for (String key : binding.tableKeys()) {
IrisLootTable table = engine.getData().getLootLoader().load(key); IrisLootTable table = LootResources.table(engine.getData(), key);
if (table == null) { if (table == null) {
if (WARNED_TABLES.add(key)) { if (WARNED_TABLES.add(key)) {
IrisLogging.warn("Iris death loot: unknown loot table '" + key + "'"); IrisLogging.warn("Iris death loot: unknown loot table '" + key + "'");
@@ -20,6 +20,7 @@ package art.arcane.iris.modded;
import art.arcane.iris.spi.PlatformItem; import art.arcane.iris.spi.PlatformItem;
import net.minecraft.world.item.Item; import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@@ -55,4 +56,9 @@ public final class ModdedItem implements PlatformItem {
public Object nativeHandle() { public Object nativeHandle() {
return item; return item;
} }
@Override
public int maxDurability() {
return new ItemStack(item).getMaxDamage();
}
} }
@@ -19,6 +19,7 @@
package art.arcane.iris.modded; package art.arcane.iris.modded;
import art.arcane.iris.engine.framework.LootResolver; 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.loot.InventorySlotType;
import art.arcane.iris.engine.object.entity.IrisAttributeModifier; import art.arcane.iris.engine.object.entity.IrisAttributeModifier;
import art.arcane.iris.engine.object.loot.IrisEnchantment; import art.arcane.iris.engine.object.loot.IrisEnchantment;
@@ -80,7 +81,7 @@ public final class ModdedItemTranslator {
return out; return out;
} }
RNG rng = LootResolver.tableRng(lootSeed, table, x, y, z); RNG rng = LootTables.rng(lootSeed, table, x, y, z);
int m = 0; int m = 0;
int c = 0; int c = 0;
int mx = Math.max(0, LootResolver.inclusive(rng, table.getMinPicked(), table.getMaxPicked())); 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) { 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()); 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; return null;
} }
@@ -18,11 +18,13 @@
package art.arcane.iris.modded; 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.IrisObjectLoot;
import art.arcane.iris.engine.object.loot.IrisObjectVanillaLoot; import art.arcane.iris.engine.object.loot.IrisObjectVanillaLoot;
import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.LootResolver; 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.framework.PlacedObject;
import art.arcane.iris.engine.object.loot.IObjectLoot; import art.arcane.iris.engine.object.loot.IObjectLoot;
import art.arcane.iris.engine.object.loot.InventorySlotType; import art.arcane.iris.engine.object.loot.InventorySlotType;
@@ -121,7 +123,7 @@ public final class ModdedLootApplier {
} }
} }
LootResolver.resolveEnvironmentSources( LootTables.resolveEnvironmentSources(
sources, sources,
engine, engine,
rng, rng,
@@ -143,7 +145,7 @@ public final class ModdedLootApplier {
if (loot == null || loot.getWeight() <= 0) { if (loot == null || loot.getWeight() <= 0) {
continue; continue;
} }
IrisLootTable table = engine.getData().getLootLoader().load(loot.getName()); IrisLootTable table = LootResources.table(engine.getData(), loot.getName());
if (table == null) { if (table == null) {
IrisLogging.warn("Couldn't find loot table " + loot.getName()); IrisLogging.warn("Couldn't find loot table " + loot.getName());
continue; continue;
@@ -18,6 +18,7 @@
package art.arcane.iris.modded; package art.arcane.iris.modded;
import art.arcane.iris.engine.spawn.SpawnResources;
import art.arcane.iris.core.IrisSettings; import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.core.gui.PregeneratorJob; import art.arcane.iris.core.gui.PregeneratorJob;
import art.arcane.iris.engine.IrisComplex; 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")) { if (tag.equals("cave_floor") || tag.equals("cave_ceiling")) {
return; return;
} }
IrisMarker resolved = engine.getData().getMarkerLoader().load(tag); IrisMarker resolved = SpawnResources.marker(engine.getData(), tag);
if (resolved == null) { if (resolved == null) {
return; return;
} }
@@ -429,7 +430,7 @@ public final class ModdedWorldManager implements EngineWorldManager {
private KList<IrisSpawner> resolveMarkerSpawners(IrisMarker marker) { private KList<IrisSpawner> resolveMarkerSpawners(IrisMarker marker) {
KList<IrisSpawner> spawners = new KList<>(); KList<IrisSpawner> spawners = new KList<>();
for (String key : marker.getSpawners()) { for (String key : marker.getSpawners()) {
IrisSpawner spawner = engine.getData().getSpawnerLoader().load(key); IrisSpawner spawner = SpawnResources.spawner(engine.getData(), key);
if (spawner == null) { if (spawner == null) {
IrisLogging.error("Cannot load spawner: " + key + " for marker on " + engine.getName()); IrisLogging.error("Cannot load spawner: " + key + " for marker on " + engine.getName());
continue; continue;
@@ -478,9 +479,9 @@ public final class ModdedWorldManager implements EngineWorldManager {
int chunkMobs = countChunkLivingEntities(level, chunkX, chunkZ); int chunkMobs = countChunkLivingEntities(level, chunkX, chunkZ);
KList<IrisEntitySpawn> pool = new KList<>(); KList<IrisEntitySpawn> pool = new KList<>();
collectSpawns(pool, engine.getData().getSpawnerLoader().loadAll(engine.getDimension().getEntitySpawners()), biome, chunkX, chunkZ, chunkMobs, initial); collectSpawns(pool, SpawnResources.spawners(engine.getData(), engine.getDimension().getEntitySpawners()), biome, chunkX, chunkZ, chunkMobs, initial);
collectSpawns(pool, engine.getData().getSpawnerLoader().loadAll(region.getEntitySpawners()), null, chunkX, chunkZ, chunkMobs, initial); collectSpawns(pool, SpawnResources.spawners(engine.getData(), 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(), biome.getEntitySpawners()), null, chunkX, chunkZ, chunkMobs, initial);
if (pool.isEmpty()) { if (pool.isEmpty()) {
return; return;
} }
@@ -18,6 +18,9 @@
package art.arcane.iris.modded.command; 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.modded.ModdedIrisLog;
import art.arcane.iris.core.IrisSettings; import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.core.gui.GuiHost; import art.arcane.iris.core.gui.GuiHost;
@@ -935,14 +938,14 @@ public final class ModdedStudioCommands {
markerKeys.addAll(PackExportClosure.collectMarkerKeys(biome.getObjects())); markerKeys.addAll(PackExportClosure.collectMarkerKeys(biome.getObjects()));
} }
for (String markerKey : markerKeys) { for (String markerKey : markerKeys) {
IrisMarker marker = dm.getMarkerLoader().load(markerKey); IrisMarker marker = SpawnResources.marker(dm, markerKey);
if (marker == null) { if (marker == null) {
continue; continue;
} }
spawnerKeys.addAll(marker.getSpawners()); spawnerKeys.addAll(marker.getSpawners());
} }
for (String spawnerKey : spawnerKeys) { for (String spawnerKey : spawnerKeys) {
IrisSpawner spawner = dm.getSpawnerLoader().load(spawnerKey); IrisSpawner spawner = SpawnResources.spawner(dm, spawnerKey);
if (spawner == null) { if (spawner == null) {
continue; continue;
} }
@@ -950,7 +953,7 @@ public final class ModdedStudioCommands {
spawner.getInitialSpawns().forEach((IrisEntitySpawn spawn) -> entityKeys.add(spawn.getEntity())); spawner.getInitialSpawns().forEach((IrisEntitySpawn spawn) -> entityKeys.add(spawn.getEntity()));
} }
for (String entityKey : entityKeys) { for (String entityKey : entityKeys) {
IrisEntity entity = dm.getEntityLoader().load(entityKey); IrisEntity entity = SpawnResources.entity(dm, entityKey);
if (entity == null) { if (entity == null) {
continue; continue;
} }
@@ -988,16 +991,16 @@ public final class ModdedStudioCommands {
hashes.append(copyJson(folder, "biomes", key, dm.getBiomeLoader().findFile(key))); hashes.append(copyJson(folder, "biomes", key, dm.getBiomeLoader().findFile(key)));
} }
for (String key : entityKeys) { 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) { 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) { 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) { 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(); JSONObject meta = new JSONObject();
@@ -1088,4 +1091,9 @@ public final class ModdedStudioCommands {
thread.start(); thread.start();
return 1; 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();
}
} }
@@ -1,6 +1,7 @@
package art.arcane.iris.modded; package art.arcane.iris.modded;
import art.arcane.iris.engine.framework.LootResolver; import art.arcane.iris.engine.framework.LootResolver;
import art.arcane.iris.engine.loot.LootTables;
import art.arcane.iris.engine.object.loot.IrisLootMode; import art.arcane.iris.engine.object.loot.IrisLootMode;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import net.minecraft.resources.Identifier; import net.minecraft.resources.Identifier;
@@ -30,7 +31,7 @@ public class ModdedLootApplierTest {
public void addAppendsSourcesInOrder() { public void addAppendsSourcesInOrder() {
List<String> sources = new ArrayList<>(List.of("placement-native")); List<String> 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); assertEquals(List.of("placement-native", "dimension-iris", "region-iris"), sources);
} }
@@ -39,7 +40,7 @@ public class ModdedLootApplierTest {
public void clearRemovesEverythingAndContributesNothing() { public void clearRemovesEverythingAndContributesNothing() {
List<String> sources = new ArrayList<>(List.of("placement-native", "dimension-iris")); List<String> 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); assertEquals(List.of(), sources);
} }
@@ -48,7 +49,7 @@ public class ModdedLootApplierTest {
public void replaceRemovesNativeAndIrisSourcesBeforeAdding() { public void replaceRemovesNativeAndIrisSourcesBeforeAdding() {
List<String> sources = new ArrayList<>(List.of("placement-native", "dimension-iris")); List<String> 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); assertEquals(List.of("biome-iris"), sources);
} }
@@ -63,7 +64,7 @@ public class ModdedLootApplierTest {
public void fallbackDoesNotOverrideExistingNativeOrIrisSources() { public void fallbackDoesNotOverrideExistingNativeOrIrisSources() {
List<String> sources = new ArrayList<>(List.of("placement-native", "dimension-iris")); List<String> 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); assertEquals(List.of("placement-native", "dimension-iris"), sources);
} }
@@ -72,7 +73,7 @@ public class ModdedLootApplierTest {
public void fallbackAddsSourcesWhenPlacementIsEmpty() { public void fallbackAddsSourcesWhenPlacementIsEmpty() {
List<String> sources = new ArrayList<>(); List<String> 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); assertEquals(List.of("fallback-iris"), sources);
} }
+4 -8
View File
@@ -101,28 +101,20 @@ art/arcane/iris/engine/framework/placer/WorldObjectPlacer.java
art/arcane/iris/engine/mantle/MantleWriter.java art/arcane/iris/engine/mantle/MantleWriter.java
art/arcane/iris/engine/object/material/BlockDataMergeSupport.java art/arcane/iris/engine/object/material/BlockDataMergeSupport.java
art/arcane/iris/engine/object/placement/IPostBlockAccess.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/IrisBiome.java
art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomParticle.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/IrisBiomeDerivatives.java
art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomSpawn.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/marker/IrisCommandRegistry.java
art/arcane/iris/engine/object/compatibility/IrisCompat.java art/arcane/iris/engine/object/compatibility/IrisCompat.java
art/arcane/iris/engine/object/compatibility/IrisCompatabilityBlockFilter.java art/arcane/iris/engine/object/compatibility/IrisCompatabilityBlockFilter.java
art/arcane/iris/engine/object/compatibility/IrisCompatabilityItemFilter.java art/arcane/iris/engine/object/compatibility/IrisCompatabilityItemFilter.java
art/arcane/iris/engine/object/value/IrisDirection.java art/arcane/iris/engine/object/value/IrisDirection.java
art/arcane/iris/engine/object/entity/IrisEffect.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/prefab/IrisObject.java
art/arcane/iris/engine/object/placement/IrisObjectPlacement.java art/arcane/iris/engine/object/placement/IrisObjectPlacement.java
art/arcane/iris/engine/object/prefab/IrisObjectRotation.java art/arcane/iris/engine/object/prefab/IrisObjectRotation.java
art/arcane/iris/engine/object/entity/IrisPotionEffect.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/placement/IrisTree.java
art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java
art/arcane/iris/engine/object/prefab/LegacyTileData.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/WorldMatter.java
art/arcane/iris/util/project/matter/slices/EntityMatter.java art/arcane/iris/util/project/matter/slices/EntityMatter.java
art/arcane/iris/util/project/matter/slices/TileMatter.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
@@ -1,8 +1,6 @@
package art.arcane.iris.core.events; package art.arcane.iris.core.events;
import art.arcane.iris.engine.framework.Engine; 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.platform.bukkit.BukkitPlatform;
import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisLogging;
import art.arcane.volmlib.util.collection.KList; 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.HandlerList;
import org.bukkit.event.world.LootGenerateEvent; import org.bukkit.event.world.LootGenerateEvent;
import com.volmit.service.Loot;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@@ -52,21 +51,18 @@ public class IrisLootEvent extends Event {
private final Engine engine; private final Engine engine;
private final Block block; private final Block block;
private final InventorySlotType slot; private final KList<Loot.Source> tables;
private final KList<IrisLootTable> tables;
/** /**
* Constructor for IrisLootEvent with mode selection. * Constructor for IrisLootEvent with mode selection.
* *
* @param engine The engine instance. * @param engine The engine instance.
* @param block The block associated with the event. * @param block The block associated with the event.
* @param slot The inventory slot type. * @param tables The loot tables the container draws from, as the pack's modules named them. (mutable*)
* @param tables The list of IrisLootTables. (mutable*)
*/ */
public IrisLootEvent(Engine engine, Block block, InventorySlotType slot, KList<IrisLootTable> tables) { public IrisLootEvent(Engine engine, Block block, KList<Loot.Source> tables) {
this.engine = engine; this.engine = engine;
this.block = block; this.block = block;
this.slot = slot;
this.tables = tables; this.tables = tables;
} }
@@ -37,24 +37,18 @@ import art.arcane.iris.core.modules.PackModuleSet;
import art.arcane.iris.core.pack.PackDirectoryResolver; import art.arcane.iris.core.pack.PackDirectoryResolver;
import art.arcane.iris.engine.data.cache.AtomicCache; import art.arcane.iris.engine.data.cache.AtomicCache;
import art.arcane.iris.engine.framework.Engine; 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.StructureRecoveryResult;
import art.arcane.iris.core.structure.authoring.StructureTransactionWriter; import art.arcane.iris.core.structure.authoring.StructureTransactionWriter;
import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.material.IrisBlockData; import art.arcane.iris.engine.object.material.IrisBlockData;
import art.arcane.iris.engine.object.world.dimension.IrisDimension; 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.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.terrain.IrisGenerator;
import art.arcane.iris.engine.object.image.IrisImage; import art.arcane.iris.engine.object.image.IrisImage;
import art.arcane.iris.engine.object.image.IrisImageMap; 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.mod.IrisMod;
import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.world.region.IrisRegion; 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.annotations.Snippet;
import art.arcane.iris.engine.object.prefab.matter.IrisMatterObject; import art.arcane.iris.engine.object.prefab.matter.IrisMatterObject;
import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KList;
@@ -105,9 +99,8 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
private static final Set<IrisData> ENGINE_HOLDERS = private static final Set<IrisData> ENGINE_HOLDERS =
Collections.synchronizedSet(Collections.newSetFromMap(new IdentityHashMap<>())); Collections.synchronizedSet(Collections.newSetFromMap(new IdentityHashMap<>()));
/** Every resource type Iris loads itself for generation, studio and validation; module resource kinds come on top. */ /** Every resource type Iris loads itself for generation, studio and validation; module resource kinds come on top. */
private static final List<Class<? extends IrisRegistrant>> RUNTIME_RESOURCE_TYPES = List.of(IrisLootTable.class, private static final List<Class<? extends IrisRegistrant>> RUNTIME_RESOURCE_TYPES = List.of(IrisRegion.class, IrisBiome.class, IrisMod.class, IrisDimension.class,
IrisSpawner.class, IrisEntity.class, IrisRegion.class, IrisBiome.class, IrisMod.class, IrisDimension.class, IrisGenerator.class, IrisBlockData.class, IrisExpression.class, IrisObject.class, IrisImage.class,
IrisGenerator.class, IrisMarker.class, IrisBlockData.class, IrisExpression.class, IrisObject.class, IrisImage.class,
IrisImageMap.class, IrisMatterObject.class); IrisImageMap.class, IrisMatterObject.class);
/** Pack folders Iris reads that hold no resources of its loaders: snippets and module jars. */ /** Pack folders Iris reads that hold no resources of its loaders: snippets and module jars. */
private static final List<String> OTHER_OWN_FOLDERS = List.of("snippet", "modules"); private static final List<String> OTHER_OWN_FOLDERS = List.of("snippet", "modules");
@@ -120,13 +113,9 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
@ToString.Exclude @ToString.Exclude
private volatile IrisPackResources packResources; private volatile IrisPackResources packResources;
private ResourceLoader<IrisBiome> biomeLoader; private ResourceLoader<IrisBiome> biomeLoader;
private ResourceLoader<IrisLootTable> lootLoader;
private ResourceLoader<IrisRegion> regionLoader; private ResourceLoader<IrisRegion> regionLoader;
private ResourceLoader<IrisDimension> dimensionLoader; private ResourceLoader<IrisDimension> dimensionLoader;
private ResourceLoader<IrisGenerator> generatorLoader; private ResourceLoader<IrisGenerator> generatorLoader;
private ResourceLoader<IrisEntity> entityLoader;
private ResourceLoader<IrisMarker> markerLoader;
private ResourceLoader<IrisSpawner> spawnerLoader;
private ResourceLoader<IrisMod> modLoader; private ResourceLoader<IrisMod> modLoader;
private ResourceLoader<IrisBlockData> blockLoader; private ResourceLoader<IrisBlockData> blockLoader;
private ResourceLoader<IrisExpression> expressionLoader; private ResourceLoader<IrisExpression> expressionLoader;
@@ -256,30 +245,14 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
return loadAny(IrisMod.class, key, nearest); 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) { public static IrisBlockData loadAnyBlock(String key, @Nullable IrisData nearest) {
return loadAny(IrisBlockData.class, key, 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) { public static IrisRegion loadAnyRegion(String key, @Nullable IrisData nearest) {
return loadAny(IrisRegion.class, key, 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) { public static IrisImage loadAnyImage(String key, @Nullable IrisData nearest) {
return loadAny(IrisImage.class, key, nearest); return loadAny(IrisImage.class, key, nearest);
} }
@@ -496,8 +469,6 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
} }
public synchronized void hotloaded() { public synchronized void hotloaded() {
StructureGraphCatalog.invalidate(this);
IrisObjectScale.invalidate(this);
closed = false; closed = false;
dataFolder.mkdirs(); dataFolder.mkdirs();
recoverStructureTransactions(); recoverStructureTransactions();
@@ -525,15 +496,11 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
.registerTypeAdapter(MantleFlag.class, new MantleFlagAdapter()) .registerTypeAdapter(MantleFlag.class, new MantleFlagAdapter())
.setPrettyPrinting(); .setPrettyPrinting();
KMap<Class<? extends IrisRegistrant>, ResourceLoader<? extends IrisRegistrant>> replacement = new KMap<>(); KMap<Class<? extends IrisRegistrant>, ResourceLoader<? extends IrisRegistrant>> 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.regionLoader = registerLoader(IrisRegion.class, replacement);
this.biomeLoader = registerLoader(IrisBiome.class, replacement); this.biomeLoader = registerLoader(IrisBiome.class, replacement);
this.modLoader = registerLoader(IrisMod.class, replacement); this.modLoader = registerLoader(IrisMod.class, replacement);
this.dimensionLoader = registerLoader(IrisDimension.class, replacement); this.dimensionLoader = registerLoader(IrisDimension.class, replacement);
this.generatorLoader = registerLoader(IrisGenerator.class, replacement); this.generatorLoader = registerLoader(IrisGenerator.class, replacement);
this.markerLoader = registerLoader(IrisMarker.class, replacement);
this.blockLoader = registerLoader(IrisBlockData.class, replacement); this.blockLoader = registerLoader(IrisBlockData.class, replacement);
this.expressionLoader = registerLoader(IrisExpression.class, replacement); this.expressionLoader = registerLoader(IrisExpression.class, replacement);
this.objectLoader = registerLoader(IrisObject.class, replacement); this.objectLoader = registerLoader(IrisObject.class, replacement);
@@ -578,8 +545,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. */ /** Forgets everything read so far: the loaders' caches and the module resources, which a new snapshot reads again. */
public void dump() { public void dump() {
StructureGraphCatalog.invalidate(this);
IrisObjectScale.invalidate(this);
for (ResourceLoader<?> i : loaders.values()) { for (ResourceLoader<?> i : loaders.values()) {
i.clearCache(); i.clearCache();
} }
@@ -588,7 +553,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. */ /** Reads objects and module resources (structures, jigsaw pools and pieces among them) again after a tool rewrote their files. */
public synchronized void invalidateStructureResources() { public synchronized void invalidateStructureResources() {
StructureGraphCatalog.invalidate(this);
invalidateLoader(objectLoader); invalidateLoader(objectLoader);
reloadModuleResources(); reloadModuleResources();
} }
@@ -0,0 +1,56 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
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 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) {
return IrisServices.get(ExternalDataSVC.class).maxDurability(Identifier.fromString(key));
}
}
@@ -22,7 +22,9 @@ import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.actuator.BiomeModule; import art.arcane.iris.engine.actuator.BiomeModule;
import art.arcane.iris.engine.actuator.DecorantModule; import art.arcane.iris.engine.actuator.DecorantModule;
import art.arcane.iris.engine.actuator.TerrainModule; 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.ObjectModule;
import art.arcane.iris.engine.spawn.SpawnModule;
import art.arcane.iris.engine.mantle.components.StructureModule; import art.arcane.iris.engine.mantle.components.StructureModule;
import art.arcane.iris.engine.modifier.CarveModule; import art.arcane.iris.engine.modifier.CarveModule;
import art.arcane.iris.engine.modifier.CustomModule; import art.arcane.iris.engine.modifier.CustomModule;
@@ -70,7 +72,7 @@ public final class IrisModuleHost {
private static List<IrisModule> generationModules() { private static List<IrisModule> generationModules() {
return List.of(new BiomeModule(), new TerrainModule(), new CarveModule(), new ObjectModule(), new StructureModule(), return List.of(new BiomeModule(), new TerrainModule(), new CarveModule(), new ObjectModule(), new StructureModule(),
new PostModule(), new FloatingModule(), new DepositModule(), new MatterModule(), new DecorantModule(), new PostModule(), new FloatingModule(), new DepositModule(), new MatterModule(), new DecorantModule(),
new PerfectionModule(), new CustomModule()); new PerfectionModule(), new CustomModule(), new LootModule(), new SpawnModule());
} }
/** Whether {@code type} is one of Iris's own classes that built-in settings may hold. */ /** Whether {@code type} is one of Iris's own classes that built-in settings may hold. */
@@ -26,6 +26,7 @@ import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.engine.object.world.region.IrisRegion;
import com.volmit.block.BlockRegistry; import com.volmit.block.BlockRegistry;
import com.volmit.host.ResourceKindRegistration; import com.volmit.host.ResourceKindRegistration;
import com.volmit.item.ItemRegistry;
import com.volmit.noise.NoiseFactory; import com.volmit.noise.NoiseFactory;
import com.volmit.object.GeneratedObject; import com.volmit.object.GeneratedObject;
import com.volmit.resource.PackResources; import com.volmit.resource.PackResources;
@@ -69,6 +70,7 @@ public final class IrisPackResources implements PackResources {
private final PackResourceIds ids; private final PackResourceIds ids;
private final UUID snapshotId = UUID.randomUUID(); private final UUID snapshotId = UUID.randomUUID();
private final BlockRegistry blocks; private final BlockRegistry blocks;
private final ItemRegistry items = new IrisItemRegistry();
private final NoiseFactory noise; private final NoiseFactory noise;
private final Map<Class<?>, Kind<?>> irisKinds; private final Map<Class<?>, Kind<?>> irisKinds;
private final Supplier<List<ResourceKind<?>>> moduleKindList; private final Supplier<List<ResourceKind<?>>> moduleKindList;
@@ -122,6 +124,11 @@ public final class IrisPackResources implements PackResources {
return blocks; return blocks;
} }
@Override
public ItemRegistry items() {
return items;
}
@Override @Override
public NoiseFactory noise() { public NoiseFactory noise() {
return noise; return noise;
@@ -21,11 +21,19 @@ package art.arcane.iris.core.modules;
import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.Engine;
import com.volmit.host.FeatureCatalog; 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.LocateResult;
import com.volmit.service.Loot;
import com.volmit.service.ObjectsAt; import com.volmit.service.ObjectsAt;
import com.volmit.service.SaplingGrowth;
import com.volmit.service.StructureLocator; import com.volmit.service.StructureLocator;
import com.volmit.world.PackWorld; import com.volmit.world.PackWorld;
import java.util.ArrayList;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
@@ -49,6 +57,120 @@ public final class ModuleServices {
return keys; 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<String> biomes = new LinkedHashSet<>();
Set<String> 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);
}
/** The loot tables the modules say the container at {@code site} draws from, in module order. */
public static List<Loot.Source> lootTables(Engine engine, Loot.Site site) {
PackWorld world = engine.getGeneration().world();
List<Loot.Source> 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<ItemDrop> lootItems(Engine engine, Loot.Site site, String key) {
PackWorld world = engine.getGeneration().world();
List<ItemDrop> 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<ItemDrop> 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);
}
/** The tree grown by the first module that grows one for {@code sapling}; empty leaves the growth to the platform. */
public static Optional<SaplingGrowth.Growth> growSapling(Engine engine, SaplingGrowth.Sapling sapling, SaplingGrowth.Surroundings surroundings) {
PackWorld world = engine.getGeneration().world();
for (SaplingGrowth provider : catalog(engine.getData()).services(SaplingGrowth.class)) {
Optional<SaplingGrowth.Growth> 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<String> objects = new LinkedHashSet<>();
Set<String> 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);
}
/** What the first module with something to spawn at {@code site} plans; empty when none does. */
public static Optional<PlannedSpawn> planSpawn(Engine engine, EntitySpawns.Site site) {
PackWorld world = engine.getGeneration().world();
for (EntitySpawns provider : catalog(engine.getData()).services(EntitySpawns.class)) {
Optional<EntitySpawns.Plan> 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<EntitySpec> entity(Engine engine, String key) {
PackWorld world = engine.getGeneration().world();
for (EntitySpawns provider : catalog(engine.getData()).services(EntitySpawns.class)) {
Optional<EntitySpec> 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<EntitySpawns.MarkerRule> markerRule(Engine engine, String tag) {
PackWorld world = engine.getGeneration().world();
for (EntitySpawns provider : catalog(engine.getData()).services(EntitySpawns.class)) {
Optional<EntitySpawns.MarkerRule> 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. */ /** Every structure key the pack's modules know, placed or not. */
public static Set<String> structureKeys(IrisData data) { public static Set<String> structureKeys(IrisData data) {
Set<String> keys = new LinkedHashSet<>(); Set<String> keys = new LinkedHashSet<>();
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<String> 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<String> 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<String> 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<String> blockingErrors) {
if (minimum != null && maximum != null && minimum > maximum) {
blockingErrors.add(minimumPath + " must not exceed " + maximumPath + ".");
}
}
}
@@ -62,9 +62,9 @@ final class PackJsonFieldChecks {
if (!object.has(field) || object.opt(field) == JSONObject.NULL) { if (!object.has(field) || object.opt(field) == JSONObject.NULL) {
return; return;
} }
Integer value = PackLootValidator.lootInteger(object, field, minimum, path, blockingErrors); Integer value = PackIntegerChecks.integerField(object, field, minimum, path, blockingErrors);
PackLootValidator.requireMinimum(path + "." + field, value, minimum, blockingErrors); PackIntegerChecks.requireMinimum(path + "." + field, value, minimum, blockingErrors);
PackLootValidator.requireMaximum(path + "." + field, value, maximum, blockingErrors); PackIntegerChecks.requireMaximum(path + "." + field, value, maximum, blockingErrors);
} }
static void validateOptionalDoubleRange(String path, JSONObject object, String field, static void validateOptionalDoubleRange(String path, JSONObject object, String field,
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<String> errors, List<String> warnings) {
LootGraphIssues {
errors = List.copyOf(errors);
warnings = List.copyOf(warnings);
}
}
static LootGraphIssues validateLootGraph(File packFolder) {
List<String> blockingErrors = new ArrayList<>();
List<String> warnings = new ArrayList<>();
if (packFolder == null || !packFolder.isDirectory()) {
return new LootGraphIssues(blockingErrors, warnings);
}
File lootFolder = new File(packFolder, PackValidator.LOOT_FOLDER);
Set<String> lootKeys = ContentKeyValidator.deriveRegistrantKeysExact(lootFolder);
if (lootFolder.isDirectory()) {
List<File> 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<File> 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<String> 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<String> 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<String> lootKeys, List<String> blockingErrors, List<String> 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<String> 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<String> blockingErrors) {
if (value != null && value < minimum) {
blockingErrors.add(fieldPath + " must be at least " + minimum + ".");
}
}
static void requireMaximum(String fieldPath, Integer value, int maximum,
List<String> 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<String> blockingErrors) {
if (minimum != null && maximum != null && minimum > maximum) {
blockingErrors.add(minimumPath + " must not exceed " + maximumPath + ".");
}
}
}
@@ -395,8 +395,8 @@ final class PackStructurePlacementValidator {
if (!structureKey.isEmpty() && !sourceKeys.add(structureKey.toLowerCase(Locale.ROOT))) { if (!structureKey.isEmpty() && !sourceKeys.add(structureKey.toLowerCase(Locale.ROOT))) {
blockingErrors.add(sourcePath + ".structure duplicates native source '" + structureKey + "'."); blockingErrors.add(sourcePath + ".structure duplicates native source '" + structureKey + "'.");
} }
Integer weight = PackLootValidator.lootInteger(source, "weight", 1, sourcePath, blockingErrors); Integer weight = PackIntegerChecks.integerField(source, "weight", 1, sourcePath, blockingErrors);
PackLootValidator.requireMinimum(sourcePath + ".weight", weight, 1, blockingErrors); PackIntegerChecks.requireMinimum(sourcePath + ".weight", weight, 1, blockingErrors);
if (weight != null && weight > 0) { if (weight != null && weight > 0) {
totalWeight += weight; totalWeight += weight;
} }
@@ -36,7 +36,6 @@ public final class PackValidator {
static final String DATAPACKS_FOLDER = "datapacks"; static final String DATAPACKS_FOLDER = "datapacks";
static final String CACHE_FOLDER = "cache"; static final String CACHE_FOLDER = "cache";
static final String OBJECTS_FOLDER = "objects"; static final String OBJECTS_FOLDER = "objects";
static final String LOOT_FOLDER = "loot";
static final String DIMENSIONS_FOLDER = "dimensions"; static final String DIMENSIONS_FOLDER = "dimensions";
static final String STRUCTURES_FOLDER = "structures"; static final String STRUCTURES_FOLDER = "structures";
static final String JIGSAW_POOLS_FOLDER = "jigsaw-pools"; static final String JIGSAW_POOLS_FOLDER = "jigsaw-pools";
@@ -90,9 +89,6 @@ public final class PackValidator {
addDistinct(blockingErrors, imageMaps.errors()); addDistinct(blockingErrors, imageMaps.errors());
addDistinct(warnings, imageMaps.warnings()); addDistinct(warnings, imageMaps.warnings());
blockingErrors.addAll(PackCaveProfileValidator.validateLegacyFields(packFolder)); 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.validateRemovedWorldgenFields(packFolder));
blockingErrors.addAll(PackObjectSurfaceValidator.validateObjectSurfaceSupport(packFolder)); blockingErrors.addAll(PackObjectSurfaceValidator.validateObjectSurfaceSupport(packFolder));
blockingErrors.addAll(PackObjectSurfaceValidator.validateUnsupportedStructureTransforms(packFolder)); blockingErrors.addAll(PackObjectSurfaceValidator.validateUnsupportedStructureTransforms(packFolder));
@@ -18,6 +18,8 @@
package art.arcane.iris.core.project; 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 art.arcane.iris.engine.object.placement.IrisObjectPlacement;
import com.google.gson.Gson; import com.google.gson.Gson;
import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.IrisData;
@@ -120,29 +122,29 @@ public class IrisPackageCompiler {
} }
dimension.getAllRegions(() -> dm).forEach((region) -> addIfPresent(regions, region)); 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))); regions.forEach((i) -> biomes.addAll(i.getAllBiomes(() -> dm)));
dimension.getReachableBiomes(() -> dm).forEach((biome) -> addIfPresent(biomes, biome)); 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.getLoot().getTables().forEach((i) -> addIfPresent(loot, LootResources.table(dm, i))));
regions.forEach((r) -> r.getEntitySpawners().forEach((sp) -> addIfPresent(spawners, dm.getSpawnerLoader().load(sp)))); regions.forEach((r) -> r.getEntitySpawners().forEach((sp) -> addIfPresent(spawners, SpawnResources.spawner(dm, sp))));
dimension.getEntitySpawners().forEach((sp) -> addIfPresent(spawners, dm.getSpawnerLoader().load(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((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.getLoot().getTables().forEach((i) -> addIfPresent(loot, LootResources.table(dm, i))));
biomes.forEach((r) -> r.getEntitySpawners().forEach((sp) -> addIfPresent(spawners, dm.getSpawnerLoader().load(sp)))); biomes.forEach((r) -> r.getEntitySpawners().forEach((sp) -> addIfPresent(spawners, SpawnResources.spawner(dm, sp))));
KList<IrisObjectPlacement> allPlacements = new KList<>(); KList<IrisObjectPlacement> allPlacements = new KList<>();
regions.forEach((r) -> allPlacements.addAll(r.getObjects())); regions.forEach((r) -> allPlacements.addAll(r.getObjects()));
biomes.forEach((i) -> allPlacements.addAll(i.getObjects())); biomes.forEach((i) -> allPlacements.addAll(i.getObjects()));
KSet<IrisMarker> markers = new KSet<>(); KSet<IrisMarker> markers = new KSet<>();
for (String markerKey : PackExportClosure.collectMarkerKeys(allPlacements)) { for (String markerKey : PackExportClosure.collectMarkerKeys(allPlacements)) {
IrisMarker marker = dm.getMarkerLoader().load(markerKey); IrisMarker marker = SpawnResources.marker(dm, markerKey);
if (marker == null) { if (marker == null) {
continue; continue;
} }
markers.add(marker); 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))); collectSpawnerEntityKeys(spawners).forEach((i) -> addIfPresent(entities, SpawnResources.entity(dm, i)));
entities.forEach((e) -> e.getLoot().getTables().forEach((i) -> addIfPresent(loot, dm.getLootLoader().load(i)))); entities.forEach((e) -> e.getLoot().getTables().forEach((i) -> addIfPresent(loot, LootResources.table(dm, i))));
Set<String> structureKeys = new LinkedHashSet<>(); Set<String> structureKeys = new LinkedHashSet<>();
collectStructureKeys(structureKeys, dimension.getStructures()); collectStructureKeys(structureKeys, dimension.getStructures());
regions.forEach((region) -> collectStructureKeys(structureKeys, region.getStructures())); regions.forEach((region) -> collectStructureKeys(structureKeys, region.getStructures()));
@@ -45,6 +45,7 @@ import java.util.List;
import java.util.MissingResourceException; import java.util.MissingResourceException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.OptionalInt;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class ExternalDataSVC implements IrisService { 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<ItemStack> stack = getItemStack(key, null);
return stack.isEmpty() ? OptionalInt.empty() : OptionalInt.of(stack.get().getType().getMaxDurability());
}
public void processUpdate(Engine engine, Block block, Identifier blockId) { public void processUpdate(Engine engine, Block block, Identifier blockId) {
Optional<ExternalDataProvider> provider = activeProviders.stream().filter(p -> p.isValidProvider(blockId, DataType.BLOCK)).findFirst(); Optional<ExternalDataProvider> provider = activeProviders.stream().filter(p -> p.isValidProvider(blockId, DataType.BLOCK)).findFirst();
if (provider.isEmpty()) { if (provider.isEmpty()) {
@@ -18,38 +18,28 @@
package art.arcane.iris.core.service; 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.IrisLogging;
import art.arcane.iris.spi.IrisServices; import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.core.loader.IrisData; 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.core.tools.IrisToolbelt;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineLifecycleTasks; import art.arcane.iris.engine.framework.EngineLifecycleTasks;
import art.arcane.iris.engine.framework.TreeBlockMaterial; 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.engine.platform.PlatformChunkGenerator;
import art.arcane.iris.platform.bukkit.BukkitBlockState; 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.KList;
import art.arcane.volmlib.util.collection.KMap; import art.arcane.volmlib.util.collection.KMap;
import art.arcane.volmlib.util.data.Cuboid; 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.BlockPosition;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.iris.util.common.plugin.IrisService; import art.arcane.iris.util.common.plugin.IrisService;
import art.arcane.iris.util.common.scheduling.J; import art.arcane.iris.util.common.scheduling.J;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.HeightMap; import org.bukkit.HeightMap;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.TreeType;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
@@ -60,7 +50,7 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.world.StructureGrowEvent; import org.bukkit.event.world.StructureGrowEvent;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Predicate; import java.util.function.Predicate;
@@ -117,134 +107,43 @@ public class TreeSVC implements IrisService {
return; return;
} }
IrisDimension dimension = engine.getDimension(); if (engine.getDimension() == null) {
if (dimension == null) {
IrisLogging.debug(this.getClass().getName() + " passed it off to vanilla because could not get Dimension for this world"); 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")); IrisLogging.reportError(new NullPointerException(event.getWorld().getName() + " could not be accessed despite being an Iris world"));
return; return;
} }
if (!dimension.getTreeSettings().isEnabled()) {
IrisLogging.debug(this.getClass().getName() + " cancelled because tree overrides are disabled");
return;
}
BlockData first = event.getLocation().getBlock().getBlockData().clone(); BlockData first = event.getLocation().getBlock().getBlockData().clone();
Cuboid saplingPlane = getSaplings(event.getLocation(), blockData -> blockData instanceof Sapling && blockData.getMaterial().equals(first.getMaterial()), event.getWorld()); 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 grew @ " + event.getLocation() + " for " + event.getSpecies().name() + " usedBoneMeal is " + event.isFromBonemeal());
IrisLogging.debug("Sapling plane is: " + saplingPlane.getSizeX() + " by " + saplingPlane.getSizeZ()); 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<SaplingGrowth.Growth> 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"); IrisLogging.debug(this.getClass().getName() + " had options but did not manage to find objectPlacements for them");
return; return;
} }
saplingPlane.forEach(block -> block.setType(Material.AIR)); saplingPlane.forEach(block -> block.setType(Material.AIR));
IrisObject object = worldAccess.getData().getObjectLoader().load(placement.getPlace().getRandom(RNG.r)); String treeMarker = growth.get().object() + "@" + ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE);
String treeMarker = object.getLoadKey() + "@" + ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE);
List<BlockState> blockStateList = new KList<>(); List<BlockState> blockStateList = new KList<>();
KMap<Location, BlockData> dataCache = new KMap<>(); KMap<Location, BlockData> dataCache = new KMap<>();
// TODO: REAL CLASSES!!!! for (PlacedBlock placed : growth.get().blocks()) {
Block b = event.getWorld().getBlockAt(placed.position().x(), placed.position().y() + minHeight, placed.position().z());
IObjectPlacer placer = new IObjectPlacer() { BlockData d = (BlockData) IrisPlatforms.get().registries().block(placed.state().key()).nativeHandle();
// Listeners get the post-growth tree, per the StructureGrowEvent contract;
@Override // a fresh snapshot here handed every plugin an all-air "tree".
public int getHighest(int x, int z, IrisData data) { BlockState state = b.getState();
return event.getWorld().getHighestBlockYAt(x, z); state.setBlockData(d);
} blockStateList.add(state);
dataCache.put(b.getLocation(), d);
@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 <T> void setData(int xx, int yy, int zz, T data) {
}
@Override
public <T> T getData(int xx, int yy, int zz, Class<T> 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()
);
event.setCancelled(true); event.setCancelled(true);
@@ -266,10 +165,7 @@ public class TreeSVC implements IrisService {
if (d == null) continue; if (d == null) continue;
Block block = l.getBlock(); Block block = l.getBlock();
if (d instanceof IrisCustomData data) { block.setBlockData(d, false);
block.setBlockData(data.getBase(), false);
IrisServices.get(ExternalDataSVC.class).processUpdate(engine, block, data.getCustom());
} else block.setBlockData(d, false);
int mantleY = block.getY() - event.getWorld().getMinHeight(); int mantleY = block.getY() - event.getWorld().getMinHeight();
// Lease-gated: the grow task can land after the engine started closing, and // Lease-gated: the grow task can land after the engine started closing, and
// an unleased mantle write would race the region flush. // an unleased mantle write would race the region flush.
@@ -290,58 +186,36 @@ public class TreeSVC implements IrisService {
} }
} }
static int worldFluidHeight(Engine engine) { private static com.volmit.world.BlockPosition relativePosition(Location location, int minHeight) {
return engine.getMinHeight() + engine.getDimension().getFluidHeight(); return new com.volmit.world.BlockPosition(location.getBlockX(), location.getBlockY() - minHeight, location.getBlockZ());
} }
/** /** The world around the saplings as the modules read it; the saplings that grow count as air, as they are about to. */
* Finds a single object placement (which may contain more than one object) for the requirements species, location & private static final class WorldSurroundings implements SaplingGrowth.Surroundings {
* size private static final com.volmit.block.BlockState AIR = com.volmit.block.BlockState.parse("minecraft:air");
*
* @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) {
KList<IrisObjectPlacement> placements = new KList<>(); private final World world;
boolean isUseAll = worldAccess.getEngine().getDimension().getTreeSettings().getMode().equals(IrisTreeModes.ALL); private final Cuboid saplingPlane;
// Retrieve objectPlacements of type `species` from biome private WorldSurroundings(World world, Cuboid saplingPlane) {
IrisBiome biome = worldAccess.getEngine().getBiome(location.getBlockX(), location.getBlockY()-worldAccess.getTarget().getWorld().minHeight(), location.getBlockZ()); this.world = world;
placements.addAll(matchObjectPlacements(biome.getObjects(), size, type)); this.saplingPlane = saplingPlane;
// 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));
} }
// Check if no matches were found, return a random one if they are @Override
return placements.isNotEmpty() ? placements.getRandom() : null; 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();
}
/** @Override
* Filters out mismatches and returns matches public com.volmit.block.BlockState blockAt(int x, int y, int z) {
* int worldY = y + world.getMinHeight();
* @param objects The object placements to check if (saplingPlane.contains(x, worldY, z)) {
* @param size The size of the sapling area to filter with return AIR;
* @param type The type of the tree to filter with
* @return A list of objectPlacements that matched. May be empty.
*/
private KList<IrisObjectPlacement> matchObjectPlacements(KList<IrisObjectPlacement> objects, IrisTreeSize size, TreeType type) {
KList<IrisObjectPlacement> p = new KList<>();
for (IrisObjectPlacement i : objects) {
if (i.matches(size, type)) {
p.add(i);
} }
return com.volmit.block.BlockState.parse(PlatformBlockStates.namespaced(BukkitBlockState.of(world.getBlockAt(x, worldY, z).getBlockData()).key()));
} }
return p;
} }
/** /**
@@ -1,14 +1,10 @@
package art.arcane.iris.core.service.tree; 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.Engine;
import art.arcane.iris.engine.framework.StructurePlacementMarker; import art.arcane.iris.engine.framework.StructurePlacementMarker;
import art.arcane.iris.engine.object.world.biome.IrisBiome; import com.volmit.service.SaplingGrowth;
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 java.util.HashSet;
import java.util.Set; import java.util.Set;
public final class TreeDefinitionIndex { public final class TreeDefinitionIndex {
@@ -23,26 +19,8 @@ public final class TreeDefinitionIndex {
} }
public static TreeDefinitionIndex build(Engine engine) { public static TreeDefinitionIndex build(Engine engine) {
Set<String> explicitObjectKeys = new HashSet<>(); SaplingGrowth.TreeObjects trees = ModuleServices.treeObjects(engine);
Set<String> proceduralTreeKeys = new HashSet<>(); return new TreeDefinitionIndex(trees.objects(), trees.procedural());
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);
} }
public boolean isTreeMarker(String marker) { public boolean isTreeMarker(String marker) {
@@ -60,38 +38,4 @@ public final class TreeDefinitionIndex {
} }
return objectKey.startsWith("trees/") || explicitObjectKeys.contains(objectKey); return objectKey.startsWith("trees/") || explicitObjectKeys.contains(objectKey);
} }
private static void collectPlacements(Iterable<IrisObjectPlacement> placements, Set<String> 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<String> 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));
}
}
}
} }
@@ -19,19 +19,22 @@
package art.arcane.iris.engine; package art.arcane.iris.engine;
import art.arcane.iris.engine.data.cache.Cache; 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.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.spi.IrisLogging;
import art.arcane.iris.util.common.plugin.Chunks; import art.arcane.iris.util.common.plugin.Chunks;
import art.arcane.iris.util.common.scheduling.J; import art.arcane.iris.util.common.scheduling.J;
import art.arcane.volmlib.util.collection.KMap; import art.arcane.volmlib.util.collection.KMap;
import art.arcane.volmlib.util.collection.KSet; import art.arcane.volmlib.util.collection.KSet;
import com.volmit.service.EntitySpawns;
import art.arcane.volmlib.util.matter.MatterMarker; import art.arcane.volmlib.util.matter.MatterMarker;
import org.bukkit.Chunk; import org.bukkit.Chunk;
import org.bukkit.World; import org.bukkit.World;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
@@ -49,8 +52,12 @@ final class MarkerSpawnScanner {
this.manager = manager; this.manager = manager;
} }
Map<IrisPosition, KSet<IrisSpawner>> getSpawnersFromMarkers(Chunk c) { /** A spawner a marker names, and the marker. */
Map<IrisPosition, KSet<IrisSpawner>> p = new KMap<>(); record MarkerSpawner(String marker, String spawner) {
}
Map<IrisPosition, List<MarkerSpawner>> getSpawnersFromMarkers(Chunk c) {
Map<IrisPosition, List<MarkerSpawner>> p = new KMap<>();
Set<IrisPosition> b = new KSet<>(); Set<IrisPosition> b = new KSet<>();
if (J.isFolia()) { if (J.isFolia()) {
@@ -61,35 +68,20 @@ final class MarkerSpawnScanner {
} }
manager.getMantle().iterateChunk(c.getX(), c.getZ(), MatterMarker.class, (x, y, z, t) -> { manager.getMantle().iterateChunk(c.getX(), c.getZ(), MatterMarker.class, (x, y, z, t) -> {
if (t.getTag().equals("cave_floor") || t.getTag().equals("cave_ceiling")) { Optional<EntitySpawns.MarkerRule> rule = markerRule(t);
return; if (rule.isEmpty()) {
}
IrisMarker mark = manager.getData().getMarkerLoader().load(t.getTag());
if (mark == null) {
return; return;
} }
IrisPosition pos = new IrisPosition((c.getX() << 4) + x, y, (c.getZ() << 4) + z); 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); b.add(pos);
return; return;
} }
for (String i : mark.getSpawners()) { for (String spawner : rule.get().spawners()) {
IrisSpawner m = manager.getData().getSpawnerLoader().load(i); addOnce(p.computeIfAbsent(pos, (k) -> new ArrayList<>()), new MarkerSpawner(t.getTag(), spawner));
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);
}
} }
}); });
@@ -100,7 +92,15 @@ final class MarkerSpawnScanner {
return p; return p;
} }
void forEachMarkerSpawner(Chunk c, BiConsumer<IrisPosition, KSet<IrisSpawner>> 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<EntitySpawns.MarkerRule> 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<IrisPosition, List<MarkerSpawner>> consumer) {
if (c == null || consumer == null) { if (c == null || consumer == null) {
return; return;
} }
@@ -160,30 +160,26 @@ final class MarkerSpawnScanner {
}, () -> markerScanQueue.remove(key))); }, () -> markerScanQueue.remove(key)));
} }
private static void addOnce(List<MarkerSpawner> spawners, MarkerSpawner spawner) {
if (!spawners.contains(spawner)) {
spawners.add(spawner);
}
}
private Map<IrisPosition, MarkerSpawnData> collectMarkerSpawnData(int chunkX, int chunkZ) { private Map<IrisPosition, MarkerSpawnData> collectMarkerSpawnData(int chunkX, int chunkZ) {
Map<IrisPosition, MarkerSpawnData> markerData = new KMap<>(); Map<IrisPosition, MarkerSpawnData> markerData = new KMap<>();
manager.getMantle().iterateChunk(chunkX, chunkZ, MatterMarker.class, (x, y, z, t) -> { manager.getMantle().iterateChunk(chunkX, chunkZ, MatterMarker.class, (x, y, z, t) -> {
if (t.getTag().equals("cave_floor") || t.getTag().equals("cave_ceiling")) { Optional<EntitySpawns.MarkerRule> rule = markerRule(t);
return; if (rule.isEmpty()) {
}
IrisMarker mark = manager.getData().getMarkerLoader().load(t.getTag());
if (mark == null) {
return; return;
} }
IrisPosition position = new IrisPosition((chunkX << 4) + x, y, (chunkZ << 4) + z); IrisPosition position = new IrisPosition((chunkX << 4) + x, y, (chunkZ << 4) + z);
MarkerSpawnData data = markerData.computeIfAbsent(position, k -> new MarkerSpawnData()); 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()) { for (String spawner : rule.get().spawners()) {
IrisSpawner spawner = manager.getData().getSpawnerLoader().load(i); addOnce(data.spawners, new MarkerSpawner(t.getTag(), spawner));
if (spawner == null) {
IrisLogging.error("Cannot load spawner: " + i + " for marker on " + manager.getName());
continue;
}
spawner.setReferenceMarker(mark);
data.spawners.add(spawner);
} }
}); });
@@ -218,7 +214,7 @@ final class MarkerSpawnScanner {
} }
private static final class MarkerSpawnData { private static final class MarkerSpawnData {
private final KSet<IrisSpawner> spawners = new KSet<>(); private final List<MarkerSpawner> spawners = new ArrayList<>();
private boolean requiresEmptyAbove; private boolean requiresEmptyAbove;
} }
} }
@@ -18,13 +18,11 @@
package art.arcane.iris.engine; package art.arcane.iris.engine;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.service.tree.BlockDropRouter; import art.arcane.iris.core.service.tree.BlockDropRouter;
import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.core.modules.ModuleServices;
import art.arcane.iris.engine.object.loot.IrisBlockDrops; import art.arcane.iris.core.modules.PlatformBlockStates;
import art.arcane.iris.engine.object.marker.IrisMarker; import art.arcane.iris.platform.bukkit.BukkitBlockState;
import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.platform.bukkit.BukkitItemStacks;
import art.arcane.iris.engine.platform.EngineBukkitOps;
import art.arcane.iris.platform.bukkit.BukkitWorldBinding; import art.arcane.iris.platform.bukkit.BukkitWorldBinding;
import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.util.common.scheduling.J; import art.arcane.iris.util.common.scheduling.J;
@@ -35,8 +33,12 @@ import org.bukkit.World;
import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.inventory.ItemStack; 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.List; import java.util.Optional;
import java.util.function.Consumer; import java.util.function.Consumer;
/** /**
@@ -57,19 +59,10 @@ final class WorldBlockDropRouter {
int mantleY = toMantleY(e.getBlock().getY(), manager.getEngine().getWorld().minHeight()); int mantleY = toMantleY(e.getBlock().getY(), manager.getEngine().getWorld().minHeight());
int blockZ = e.getBlock().getZ(); int blockZ = e.getBlock().getZ();
KList<ItemStack> d = new KList<>(); BlockDrops.Result result = ModuleServices.blockDrops(manager.getEngine(), brokenBlock(e));
IrisBiome b = EngineBukkitOps.getBiome(manager.getEngine(), e.getBlock().getLocation()); KList<ItemStack> d = BukkitItemStacks.createAll(result.drops());
List<IrisBlockDrops> dropProviders = filterDrops(b.getBlockDrops(), e, manager.getData());
if (dropProviders.stream().noneMatch(IrisBlockDrops::isSkipParents)) { if (result.replacesVanillaDrops()) {
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)) {
e.setDropItems(false); e.setDropItems(false);
} }
@@ -87,8 +80,8 @@ final class WorldBlockDropRouter {
return; return;
} }
IrisMarker mark = manager.getData().getMarkerLoader().load(marker.getTag()); Optional<EntitySpawns.MarkerRule> rule = ModuleServices.markerRule(manager.getEngine(), marker.getTag());
if (mark == null || mark.isRemoveOnChange()) { if (rule.isEmpty() || rule.get().removeOnChange()) {
manager.getMantle().remove(blockX, mantleY, blockZ, MatterMarker.class); manager.getMantle().remove(blockX, mantleY, blockZ, MatterMarker.class);
} }
})); }));
@@ -128,7 +121,10 @@ final class WorldBlockDropRouter {
return mantleY + minHeight; return mantleY + minHeight;
} }
private List<IrisBlockDrops> filterDrops(KList<IrisBlockDrops> drops, BlockBreakEvent e, IrisData data) { private BlockDrops.Broken brokenBlock(BlockBreakEvent e) {
return new KList<>(drops.stream().filter(d -> d.shouldDropFor(e.getBlock().getBlockData(), data)).toList()); 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);
} }
} }
@@ -20,7 +20,6 @@ package art.arcane.iris.engine;
import art.arcane.iris.core.IrisSettings; import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.engine.data.cache.Cache; 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.engine.platform.EngineBukkitOps;
import art.arcane.iris.platform.bukkit.BukkitWorldBinding; import art.arcane.iris.platform.bukkit.BukkitWorldBinding;
import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisLogging;
@@ -303,13 +302,8 @@ final class WorldChunkMaintenance {
}), delay); }), delay);
Chunk markerChunk = world.getChunkAt(chunkX, chunkZ); Chunk markerChunk = world.getChunkAt(chunkX, chunkZ);
manager.markerScanner.forEachMarkerSpawner(markerChunk, (block, spawners) -> { manager.markerScanner.forEachMarkerSpawner(markerChunk, (block, spawners) ->
IrisSpawner s = new KList<>(spawners).getRandom(); manager.entitySpawner.spawnAtMarker(block, spawners.get(RNG.r.nextInt(spawners.size())), true));
if (s == null) {
return;
}
manager.entitySpawner.spawn(block, s, true);
});
}); });
} }
@@ -19,40 +19,41 @@
package art.arcane.iris.engine; package art.arcane.iris.engine;
import art.arcane.iris.core.IrisSettings; 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.gui.PregeneratorJob;
import art.arcane.iris.core.tools.IrisToolbelt; 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.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.platform.bukkit.BukkitWorldBinding;
import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.util.common.plugin.Chunks; import art.arcane.iris.util.common.plugin.Chunks;
import art.arcane.iris.util.common.scheduling.J; import art.arcane.iris.util.common.scheduling.J;
import art.arcane.volmlib.util.bukkit.WorldIdentity; 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.format.Form;
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
import art.arcane.volmlib.util.math.Position2; import art.arcane.volmlib.util.math.Position2;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import lombok.Data;
import org.bukkit.Chunk; import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity; import org.bukkit.entity.LivingEntity;
import java.util.List; import java.util.Arrays;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger; 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 * 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()) { if (IrisSettings.get().getWorld().isMarkerEntitySpawningSystem()) {
manager.markerScanner.forEachMarkerSpawner(c, (block, spawners) -> { manager.markerScanner.forEachMarkerSpawner(c, (block, spawners) -> {
IrisSpawner s = new KList<>(spawners).getRandom(); MarkerSpawnScanner.MarkerSpawner s = spawners.get(RNG.r.nextInt(spawners.size()));
if (s == null) { spawnAtMarker(block, s, false);
return;
}
spawn(block, s, false);
J.runRegion(c.getWorld(), c.getX(), c.getZ(), manager.managedTask( J.runRegion(c.getWorld(), c.getX(), c.getZ(), manager.managedTask(
"bukkit_world_manager_marker_spawn_followup", "bukkit_world_manager_marker_spawn_followup",
() -> manager.chunkMaintenance.raiseInitialSpawnMarkerFlag(c.getWorld(), c.getX(), c.getZ(), () -> 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; return;
} }
//@builder int livingEntities = (int) Arrays.stream(c.getEntities()).filter(LivingEntity.class::isInstance).count();
Predicate<IrisSpawner> filter = i -> i.canSpawn(manager.getEngine(), c.getX(), c.getZ()); ModuleServices.planSpawn(manager.getEngine(), new EntitySpawns.Chunk(c.getX(), c.getZ(), livingEntities, initial))
ChunkCounter counter = new ChunkCounter(c.getEntities()); .ifPresent(planned -> spawn(c.getWorld(), planned));
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);
} }
private void spawn(Chunk c, IrisEntitySpawn i) { /** Spawns at a marker: the spawner of the marker the caller picked, with its initial spawns or its ordinary ones. */
IrisSpawner ref = i.getReferenceSpawner(); void spawnAtMarker(IrisPosition block, MarkerSpawnScanner.MarkerSpawner spawner, boolean initial) {
int s = i.spawn(manager.getEngine(), c, RNG.r); if (manager.getEngine().isClosed() || !BukkitWorldBinding.tryBind(manager.getEngine().getWorld())) {
actuallySpawned.addAndGet(s); return;
if (s > 0) { }
ref.spawn(manager.getEngine(), c.getX(), c.getZ());
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) { private static boolean lightAllows(Location l, EntitySpawns.Attempt attempt) {
IrisSpawner ref = i.getReferenceSpawner(); int light = l.getBlock().getLightLevel();
if (!ref.canSpawn(manager.getEngine(), PowerOfTwoCoordinates.blockToChunkFloor(pos.getX()), PowerOfTwoCoordinates.blockToChunkFloor(pos.getZ()))) return light >= attempt.minLight() && light <= attempt.maxLight();
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()));
}
} }
void spawn(IrisPosition block, IrisSpawner spawner, boolean initial) { private static boolean surfaceAllows(Location l, EntitySpawns.Attempt attempt) {
if (manager.getEngine().isClosed()) { if (!BukkitSurfaces.matches(attempt.surface(), l.clone().subtract(0, 1, 0).getBlock())) {
return; return false;
} }
if (spawner == null) { Vector3d boundingBox = BukkitPlatform.entityBoundingBox(BukkitEntitySpawner.bukkitType(attempt.entity()));
return; return boundingBox == null || isAreaClearForSpawn(l, boundingBox);
}
KList<IrisEntitySpawn> 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);
} }
private Stream<IrisEntitySpawn> stream(IrisSpawner s, boolean initial) { private static boolean isAreaClearForSpawn(Location center, Vector3d boundingBox) {
for (IrisEntitySpawn i : initial ? s.getInitialSpawns() : s.getSpawns()) { World world = center.getWorld();
i.setReferenceSpawner(s); int startX = center.getBlockX() - (int) (boundingBox.x / 2);
i.setReferenceMarker(s.getReferenceMarker()); 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() { boolean isEntitySpawningEnabledForCurrentWorld() {
@@ -388,31 +404,4 @@ final class WorldEntitySpawner {
return IrisSettings.get().getStudio().isEntitySpawning(); return IrisSettings.get().getStudio().isEntitySpawning();
} }
private KList<IrisEntitySpawn> spawnRandomly(List<IrisEntitySpawn> types) {
return IRare.expandWeighted(types);
}
@Data
private static class ChunkCounter implements Predicate<IrisSpawner> {
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;
}
}
} }
@@ -18,14 +18,15 @@
package art.arcane.iris.engine.framework; 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.IrisSettings;
import art.arcane.iris.core.modules.ModuleServices;
import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.IrisComplex;
import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.util.common.parallel.BurstExecutor; import art.arcane.iris.util.common.parallel.BurstExecutor;
import art.arcane.iris.util.common.parallel.MultiBurst; import art.arcane.iris.util.common.parallel.MultiBurst;
import art.arcane.iris.util.project.context.IrisContext; 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.KList;
import art.arcane.volmlib.util.collection.KMap; import art.arcane.volmlib.util.collection.KMap;
import art.arcane.volmlib.util.collection.KSet; 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 art.arcane.volmlib.util.scheduling.PrecisionStopwatch;
import java.util.ArrayDeque; import java.util.ArrayDeque;
import java.util.Set;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
@@ -389,6 +391,7 @@ public final class HintedLocator<T> implements Locator<T> {
} }
IrisComplex complex = engine.getComplex(); IrisComplex complex = engine.getComplex();
ObjectsAt.PlacedBy placers = ModuleServices.objectPlacers(engine, objectKey);
BiomeSource source = new BiomeSource(engine); BiomeSource source = new BiomeSource(engine);
KSet<String> landHosts = new KSet<>(); KSet<String> landHosts = new KSet<>();
KSet<String> seaHosts = new KSet<>(); KSet<String> seaHosts = new KSet<>();
@@ -401,28 +404,28 @@ public final class HintedLocator<T> implements Locator<T> {
continue; continue;
} }
if (placesObject(region.getSurfaceObjects(), objectKey)) { if (placers.regions().contains(region.getLoadKey())) {
directRegions.add(region.getLoadKey()); directRegions.add(region.getLoadKey());
} }
boolean hosted = false; boolean hosted = false;
for (String root : region.getLandBiomes()) { for (String root : region.getLandBiomes()) {
if (source.closurePlacesObject(root, objectKey)) { if (source.closureContainsAny(root, placers.biomes())) {
landHosts.add(root); landHosts.add(root);
hosted = true; hosted = true;
} }
} }
for (String root : region.getSeaBiomes()) { for (String root : region.getSeaBiomes()) {
if (source.closurePlacesObject(root, objectKey)) { if (source.closureContainsAny(root, placers.biomes())) {
seaHosts.add(root); seaHosts.add(root);
hosted = true; hosted = true;
} }
} }
for (String root : region.getShoreBiomes()) { for (String root : region.getShoreBiomes()) {
if (source.closurePlacesObject(root, objectKey)) { if (source.closureContainsAny(root, placers.biomes())) {
shoreHosts.add(root); shoreHosts.add(root);
hosted = true; hosted = true;
} }
@@ -502,16 +505,6 @@ public final class HintedLocator<T> implements Locator<T> {
}; };
} }
private static boolean placesObject(KList<IrisObjectPlacement> placements, String objectKey) {
for (IrisObjectPlacement placement : placements) {
if (placement != null && placement.getPlace().contains(objectKey)) {
return true;
}
}
return false;
}
private static final class BiomeSource { private static final class BiomeSource {
private final Engine engine; private final Engine engine;
private final KMap<String, IrisBiome> cache = new KMap<>(); private final KMap<String, IrisBiome> cache = new KMap<>();
@@ -576,8 +569,8 @@ public final class HintedLocator<T> implements Locator<T> {
return false; return false;
} }
private boolean closurePlacesObject(String rootKey, String objectKey) { private boolean closureContainsAny(String rootKey, Set<String> targetKeys) {
if (rootKey == null || objectKey == null) { if (rootKey == null || targetKeys.isEmpty()) {
return false; return false;
} }
@@ -598,7 +591,7 @@ public final class HintedLocator<T> implements Locator<T> {
continue; continue;
} }
if (placesObject(biome.getSurfaceObjects(), objectKey)) { if (targetKeys.contains(biome.getLoadKey())) {
return true; return true;
} }
@@ -18,18 +18,10 @@
package art.arcane.iris.engine.framework; 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 art.arcane.volmlib.util.math.RNG;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.ToIntFunction; import java.util.function.ToIntFunction;
public final class LootResolver { public final class LootResolver {
@@ -52,17 +44,18 @@ public final class LootResolver {
return mix(seed ^ ((long) z * 0x8CB92BA72F3D8DD7L)); return mix(seed ^ ((long) z * 0x8CB92BA72F3D8DD7L));
} }
public static RNG tableRng(long lootSeed, IrisLootTable table, int x, int y, int z) { /** The random stream of one loot table at one position; {@code tableIdentity} names the table (its key, else its name). */
return new RNG(tableSeed(lootSeed, table, x, y, z)); 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) { public static long tableSeed(long lootSeed, String tableIdentity, int x, int y, int z) {
return mix(containerSeed(lootSeed, x, y, z) ^ stableHash(tableIdentity(table)) ^ TABLE_SALT); return mix(containerSeed(lootSeed, x, y, z) ^ stableHash(tableIdentity) ^ TABLE_SALT);
} }
public static boolean spatialOneIn( public static boolean spatialOneIn(
long lootSeed, long lootSeed,
IrisLootTable table, String tableIdentity,
int entryIndex, int entryIndex,
int x, int x,
int y, int y,
@@ -72,7 +65,7 @@ public final class LootResolver {
if (rarity <= 1L) { if (rarity <= 1L) {
return true; 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; return new RNG(roll).nextLong(rarity) == 0L;
} }
@@ -119,63 +112,6 @@ public final class LootResolver {
return null; return null;
} }
public static <T> void resolveEnvironmentSources(
List<T> sources,
Engine engine,
RNG rng,
int x,
int relativeY,
int z,
boolean objectLootDefined,
Function<IrisLootTable, T> 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 <T> void injectSources(
List<T> sources,
List<? extends T> 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 <T> void scaleSources(List<T> sources, double multiplier, RNG rng) { public static <T> void scaleSources(List<T> sources, double multiplier, RNG rng) {
if (!Double.isFinite(multiplier) || multiplier < 0D) { if (!Double.isFinite(multiplier) || multiplier < 0D) {
throw new IllegalArgumentException("Effective loot source multiplier must be finite and non-negative, got " 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); 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 <T> void injectReference(
List<T> sources,
IrisLootReference reference,
Engine engine,
Function<IrisLootTable, T> mapper,
boolean fallback
) {
KList<IrisLootTable> tables = reference.getLootTables(engine.getComplex());
KList<T> 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 <T> void shrinkSources(List<T> sources, List<T> original, int[] order, int target, RNG rng) { private static <T> void shrinkSources(List<T> sources, List<T> original, int[] order, int target, RNG rng) {
shuffleOrder(order, rng); shuffleOrder(order, rng);
boolean[] selected = new boolean[original.size()]; boolean[] selected = new boolean[original.size()];
@@ -5,20 +5,18 @@ import art.arcane.iris.platform.bukkit.BukkitBlockResolution;
import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.tools.IrisToolbelt; import art.arcane.iris.core.tools.IrisToolbelt;
import art.arcane.iris.engine.framework.Engine; 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.core.events.IrisLootEvent;
import art.arcane.iris.engine.mantle.EngineMantle; import art.arcane.iris.engine.mantle.EngineMantle;
import art.arcane.iris.engine.platform.EngineBukkitOps; import art.arcane.iris.engine.platform.EngineBukkitOps;
import art.arcane.iris.engine.platform.PlatformChunkGenerator; import art.arcane.iris.engine.platform.PlatformChunkGenerator;
import art.arcane.iris.engine.object.placement.IObjectPlacer; 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.engine.object.prefab.TileData;
import art.arcane.iris.platform.bukkit.BukkitBlockState; import art.arcane.iris.platform.bukkit.BukkitBlockState;
import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.util.common.scheduling.J; import art.arcane.iris.util.common.scheduling.J;
import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KList;
import com.volmit.service.Loot;
import art.arcane.iris.util.common.data.IrisCustomData; import art.arcane.iris.util.common.data.IrisCustomData;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.matter.MatterCavern; import art.arcane.volmlib.util.matter.MatterCavern;
@@ -85,16 +83,15 @@ public class WorldObjectPlacer implements IObjectPlacer {
int x = block.getX(); int x = block.getX();
int y = block.getY(); int y = block.getY();
int z = block.getZ(); int z = block.getZ();
RNG rng = LootResolver.containerRng(engine.getSeedManager().getLoot(), x, y, z); KList<Loot.Source> tables = EngineBukkitOps.getLootTables(engine, block);
KList<IrisLootTable> tables = EngineBukkitOps.getLootTables(engine, rng, block);
try { try {
Bukkit.getPluginManager().callEvent(new IrisLootEvent(engine, block, InventorySlotType.STORAGE, tables)); Bukkit.getPluginManager().callEvent(new IrisLootEvent(engine, block, tables));
if (tables.isEmpty()) { if (tables.isEmpty()) {
return; return;
} }
InventoryHolder holder = (InventoryHolder) block.getState(); 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) { } catch (Throwable e) {
IrisLogging.reportError(e); IrisLogging.reportError(e);
} }
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<Location> 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<Entity> 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> T resolveKeyed(Class<T> 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<ItemStack> 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<ItemStack> 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()));
}
});
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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());
}
}
@@ -25,12 +25,12 @@ import art.arcane.iris.core.service.ExternalDataSVC;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.GenerationSessionLease; import art.arcane.iris.engine.framework.GenerationSessionLease;
import art.arcane.iris.engine.framework.Locator; 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.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.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.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.world.region.IrisRegion;
import art.arcane.iris.engine.object.prefab.TileData; import art.arcane.iris.engine.object.prefab.TileData;
import art.arcane.iris.platform.bukkit.BukkitBlockResolution; import art.arcane.iris.platform.bukkit.BukkitBlockResolution;
@@ -63,6 +63,10 @@ import org.bukkit.Chunk;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.NamespacedKey; 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.World;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.BlockFace; import org.bukkit.block.BlockFace;
@@ -76,6 +80,7 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.loot.Lootable; import org.bukkit.loot.Lootable;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CancellationException; import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@@ -162,14 +167,14 @@ public final class EngineBukkitOps {
if (grid[x][z] == Integer.MIN_VALUE) { if (grid[x][z] == Integer.MIN_VALUE) {
continue; 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) -> { chunk.iterate(MatterUpdate.class, (x, yf, z, v) -> {
int y = yf + engine.getWorld().minHeight(); int y = yf + engine.getWorld().minHeight();
if (v != null && v.isUpdate()) { if (v != null && v.isUpdate()) {
update(engine, x, y, z, c, chunk); update(engine, x, y, z, c);
} }
}); });
chunk.deleteSlices(MatterUpdate.class); 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<Matter> mc) { public static void update(Engine engine, int x, int y, int z, Chunk c) {
World world = c.getWorld(); World world = c.getWorld();
if (y < world.getMinHeight() || y >= world.getMaxHeight()) { if (y < world.getMinHeight() || y >= world.getMaxHeight()) {
return; return;
@@ -283,30 +288,8 @@ public final class EngineBukkitOps {
BlockData data = block.getBlockData(); BlockData data = block.getBlockData();
engine.blockUpdatedMetric(); engine.blockUpdatedMetric();
if (BukkitBlockResolution.isStorage(data)) { if (BukkitBlockResolution.isStorage(data)) {
InventorySlotType slot = null;
if (BukkitBlockResolution.isStorageChest(data)) { if (BukkitBlockResolution.isStorageChest(data)) {
slot = InventorySlotType.STORAGE; fillStorageChest(engine, block, y, c);
}
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<IrisLootTable> 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);
}
} }
} else { } else {
block.setType(Material.AIR, false); 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<Loot.Source> 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) { public static boolean isCanonicalContainer(Block block) {
if (!(block.getBlockData() instanceof Chest chest) || chest.getType() == Chest.Type.SINGLE) { if (!(block.getBlockData() instanceof Chest chest) || chest.getType() == Chest.Type.SINGLE) {
return true; return true;
@@ -407,66 +407,32 @@ public final class EngineBukkitOps {
inventory.setContents(nitems); inventory.setContents(nitems);
} }
public static KList<IrisLootTable> getLootTables(Engine engine, RNG rng, Block b) { /** The loot tables the modules say the container at {@code b} draws from, in the order their items are added. */
MantleChunk<Matter> mc = engine.getMantle().getMantle().getChunk(b.getChunk()).use(); public static KList<Loot.Source> getLootTables(Engine engine, Block b) {
try { return new KList<>(getLootTables(engine, b, hasNativeLootTable(b)));
return getLootTables(engine, rng, b, mc, hasNativeLootTable(b));
} finally {
mc.release();
}
} }
public static KList<IrisLootTable> getLootTables(Engine engine, RNG rng, Block b, MantleChunk<Matter> mc) { private static List<Loot.Source> getLootTables(Engine engine, Block b, boolean nativeLootDefined) {
return getLootTables(engine, rng, b, mc, hasNativeLootTable(b)); return ModuleServices.lootTables(engine, lootSite(engine, b, nativeLootDefined));
} }
public static KList<IrisLootTable> getLootTables(Engine engine, RNG rng, Block b, MantleChunk<Matter> mc, boolean nativeLootDefined) { private static Loot.Site lootSite(Engine engine, Block b, boolean nativeLootDefined) {
int rx = b.getX(); BlockPosition position = new BlockPosition(b.getX(), b.getY() - engine.getMinHeight(), b.getZ());
int rz = b.getZ(); BlockData data = b.getBlockData();
int ry = b.getY() - engine.getWorld().minHeight(); com.volmit.block.BlockState container = BukkitBlockResolution.isStorageChest(data)
KList<IrisLootTable> tables = new KList<>(); ? com.volmit.block.BlockState.parse(PlatformBlockStates.namespaced(BukkitBlockState.of(data).key()))
boolean objectLootDefined = nativeLootDefined; : null;
return new Loot.Site(position, container, nativeLootDefined, false);
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;
} }
public static void addItems(Engine engine, boolean debug, Inventory inv, KList<IrisLootTable> tables, InventorySlotType slot, World world, int x, int y, int z) { /** Adds the loot a container at {@code at} would hold to {@code inv}; {@code debug} makes the items say where they came from. */
KList<ItemStack> items = new KList<>(); 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) { public static void addItems(Engine engine, boolean debug, Inventory inv, List<Loot.Source> tables, World world, int x, int y, int z) {
if (i == null) List<ItemStack> items = lootItems(engine, debug, tables, world, x, y, z);
continue; if (IrisLootEvent.callLootEvent(new KList<>(items), inv, world, x, y, z))
items.addAll(i.getLoot(debug, engine.getSeedManager().getLoot(), slot, world, x, y, z));
}
if (IrisLootEvent.callLootEvent(items, inv, world, x, y, z))
return; return;
if (PaperLib.isPaper() && engine.getWorld().hasPlatformWorld()) { 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<ItemStack> lootItems(Engine engine, boolean debug, List<Loot.Source> 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<ItemStack> 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<ItemStack> 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( static boolean dispatchLootMutation(
LootMutationTask task, LootMutationTask task,
boolean folia, boolean folia,
@@ -0,0 +1,113 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.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<String> 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("-", "");
}
}
@@ -59,4 +59,9 @@ public final class BukkitItem implements PlatformItem {
public Object nativeHandle() { public Object nativeHandle() {
return material; return material;
} }
@Override
public int maxDurability() {
return material.getMaxDurability();
}
} }
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<ItemStack> createAll(List<ItemDrop> drops) {
KList<ItemStack> 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<ItemStack> 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<ItemFlag> flags(ItemDrop drop) {
KList<ItemFlag> 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<String> lore(ItemDrop drop) {
KList<String> 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<String> 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) + ")");
}
}
@@ -1,14 +1,12 @@
package art.arcane.iris.util.common.data.registry; package art.arcane.iris.util.common.data.registry;
import art.arcane.iris.engine.object.entity.IrisEntity;
import org.bukkit.Particle; import org.bukkit.Particle;
import static art.arcane.iris.util.common.data.registry.RegistryUtil.find; import static art.arcane.iris.util.common.data.registry.RegistryUtil.find;
/** /**
* Bukkit particle constants. Statically imported by {@code IrisEntity} (a Gson-registered pack * Bukkit particle constants, used by the Bukkit entity spawner. Core code can reach this class on the modded
* type), so this class is reachable from core on the modded loaders. The resolution below is * loaders, so the resolution below is guarded against the absent Bukkit class: without the guard the class initializer dies
* therefore 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 * 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. * life. On Bukkit a genuinely missing registry key still throws, exactly as before.
*/ */
@@ -18,7 +18,10 @@
package art.arcane.iris.util.common.director.handlers; 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.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; import art.arcane.iris.util.common.director.specialhandlers.RegistrantHandler;
public class EntityHandler extends RegistrantHandler<IrisEntity> { public class EntityHandler extends RegistrantHandler<IrisEntity> {
@@ -27,6 +30,18 @@ public class EntityHandler extends RegistrantHandler<IrisEntity> {
super(IrisEntity.class, false); super(IrisEntity.class, false);
} }
@Override
protected KList<IrisEntity> loadAll(IrisData data) {
KList<IrisEntity> entities = new KList<>();
for (String key : SpawnResources.entityKeys(data)) {
IrisEntity entity = SpawnResources.entity(data, key);
if (entity != null) {
entities.add(entity);
}
}
return entities;
}
@Override @Override
public String getRandomDefault() { public String getRandomDefault() {
return "entity"; return "entity";
@@ -29,7 +29,7 @@ public abstract class RegistrantHandler<T extends IrisRegistrant> implements Dir
Set<String> known = new HashSet<>(); Set<String> known = new HashSet<>();
IrisData data = data(); IrisData data = data();
if (data != null) { if (data != null) {
for (T j : data.getLoader(type).loadAll(data.getLoader(type).getPossibleKeys())) { for (T j : loadAll(data)) {
known.add(j.getLoadKey()); known.add(j.getLoadKey());
p.add(j); p.add(j);
} }
@@ -38,7 +38,7 @@ public abstract class RegistrantHandler<T extends IrisRegistrant> implements Dir
for (File i : PackDirectoryResolver.listVisiblePackDirectories( for (File i : PackDirectoryResolver.listVisiblePackDirectories(
IrisPlatforms.get().packsFolder())) { IrisPlatforms.get().packsFolder())) {
data = IrisData.get(i); 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())) if (known.add(j.getLoadKey()))
p.add(j); p.add(j);
} }
@@ -47,6 +47,11 @@ public abstract class RegistrantHandler<T extends IrisRegistrant> implements Dir
return p; return p;
} }
/** Every resource of this handler's type that {@code data}'s pack has. */
protected KList<T> loadAll(IrisData data) {
return data.getLoader(type).loadAll(data.getLoader(type).getPossibleKeys());
}
@Override @Override
public String toString(T t) { public String toString(T t) {
return t != null ? t.getLoadKey() : "null"; return t != null ? t.getLoadKey() : "null";
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<String> 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);
}
}
}
}
@@ -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.IrisData;
import art.arcane.iris.core.loader.IrisRegistrant; 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.iris.util.project.matter.IrisMatterContext;
import art.arcane.volmlib.util.data.palette.Palette; import art.arcane.volmlib.util.data.palette.Palette;
import art.arcane.volmlib.util.matter.slices.RawMatter; import art.arcane.volmlib.util.matter.slices.RawMatter;
@@ -29,7 +28,7 @@ import java.io.DataInputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
public class RegistryMatter<T extends IrisRegistrant> extends RawMatter<T> { public abstract class RegistryMatter<T extends IrisRegistrant> extends RawMatter<T> {
public RegistryMatter(int width, int height, int depth, Class<T> c, T e) { public RegistryMatter(int width, int height, int depth, Class<T> c, T e) {
super(width, height, depth, c); super(width, height, depth, c);
} }
@@ -46,12 +45,9 @@ public class RegistryMatter<T extends IrisRegistrant> extends RawMatter<T> {
@Override @Override
public T readNode(DataInputStream din) throws IOException { public T readNode(DataInputStream din) throws IOException {
String key = din.readUTF(); return load(IrisMatterContext.require(), din.readUTF());
IrisData data = IrisMatterContext.require();
ResourceLoader<? extends IrisRegistrant> 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);
} }
/** 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);
} }
@@ -18,7 +18,9 @@
package art.arcane.iris.util.project.matter.slices; 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.object.entity.spawn.IrisSpawner;
import art.arcane.iris.engine.spawn.SpawnResources;
import art.arcane.volmlib.util.matter.Sliced; import art.arcane.volmlib.util.matter.Sliced;
@Sliced @Sliced
@@ -30,4 +32,9 @@ public class SpawnerMatter extends RegistryMatter<IrisSpawner> {
public SpawnerMatter(int width, int height, int depth) { public SpawnerMatter(int width, int height, int depth) {
super(width, height, depth, IrisSpawner.class, new IrisSpawner()); super(width, height, depth, IrisSpawner.class, new IrisSpawner());
} }
@Override
protected IrisSpawner load(IrisData data, String key) {
return SpawnResources.spawner(data, key);
}
} }
@@ -19,10 +19,13 @@
package art.arcane.iris.core.modules; package art.arcane.iris.core.modules;
import art.arcane.iris.engine.framework.structure.StructureLocating; import art.arcane.iris.engine.framework.structure.StructureLocating;
import art.arcane.iris.engine.loot.LootGiving;
import art.arcane.iris.engine.mantle.components.StructureModule; import art.arcane.iris.engine.mantle.components.StructureModule;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.host.FeatureCatalog; import com.volmit.host.FeatureCatalog;
import com.volmit.host.LifecycleRegistration; import com.volmit.host.LifecycleRegistration;
import com.volmit.service.BlockDrops;
import com.volmit.service.Loot;
import com.volmit.service.ObjectsAt; import com.volmit.service.ObjectsAt;
import com.volmit.service.StructureLocator; import com.volmit.service.StructureLocator;
import org.junit.Test; import org.junit.Test;
@@ -41,6 +44,13 @@ public class BuiltInServicesTest {
assertEquals(1, BUILT_INS.services(ObjectsAt.class).size()); 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 @Test
public void structuresAreFoundThroughTheStructureModule() { public void structuresAreFoundThroughTheStructureModule() {
List<StructureLocator> locators = BUILT_INS.services(StructureLocator.class); List<StructureLocator> locators = BUILT_INS.services(StructureLocator.class);
@@ -87,7 +87,17 @@ public class ModuleServicesTest {
@Override @Override
public void register(FeatureRegistry registry) { 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<String> 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() { registry.registerService(StructureLocator.class, new StructureLocator() {
@Override @Override
public Set<String> structures(PackResources resources) { public Set<String> 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))); 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 @Test
public void structureListsCombineEveryModule() { public void structureListsCombineEveryModule() {
assertEquals(Set.of("tower", "castle"), ModuleServices.locatableStructures(engine)); assertEquals(Set.of("tower", "castle"), ModuleServices.locatableStructures(engine));
@@ -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));
}
}
@@ -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.world.region.IrisRegion;
import art.arcane.iris.engine.object.placement.IrisTree; import art.arcane.iris.engine.object.placement.IrisTree;
import art.arcane.volmlib.util.collection.KList; 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 org.junit.Test;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
@@ -38,6 +42,10 @@ public class TreeDefinitionIndexTest {
biome.setProceduralObjects(proceduralObjects); biome.setProceduralObjects(proceduralObjects);
when(engine.getDimension()).thenReturn(dimension); 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<IrisRegion>().qadd(region)); when(dimension.getAllRegions(engine)).thenReturn(new KList<IrisRegion>().qadd(region));
when(dimension.getReachableBiomes(engine)).thenReturn(new KList<IrisBiome>().qadd(biome)); when(dimension.getReachableBiomes(engine)).thenReturn(new KList<IrisBiome>().qadd(biome));
@@ -4,6 +4,8 @@ import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.loader.ResourceLoader; 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.IrisComplex;
import art.arcane.iris.engine.object.world.biome.IrisBiome; 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.dimension.IrisDimension;
@@ -92,6 +94,9 @@ public class HintedLocatorTest {
when(engine.isClosed()).thenReturn(false); when(engine.isClosed()).thenReturn(false);
when(engine.acquireGenerationLease(any(String.class))).thenReturn(GenerationSessionLease.noop()); when(engine.acquireGenerationLease(any(String.class))).thenReturn(GenerationSessionLease.noop());
when(data.getBiomeLoader()).thenReturn(biomeLoader); when(data.getBiomeLoader()).thenReturn(biomeLoader);
ModuleResourceFixture.serveModules(data, new ObjectModule());
when(engine.getGeneration()).thenReturn(new EngineGeneration(engine));
stubReachableBiomes();
} }
private static IrisBiome biome(String key) { private static IrisBiome biome(String key) {
@@ -137,6 +142,10 @@ public class HintedLocatorTest {
when(biomeLoader.load(biome.getLoadKey())).thenReturn(biome); when(biomeLoader.load(biome.getLoadKey())).thenReturn(biome);
} }
private void stubReachableBiomes(IrisBiome... biomes) {
when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>(biomes));
}
@Test @Test
public void appendRingZeroAddsOnlyOrigin() { public void appendRingZeroAddsOnlyOrigin() {
KList<Position2> batch = new KList<>(); KList<Position2> batch = new KList<>();
@@ -285,6 +294,7 @@ public class HintedLocatorTest {
placements.add(placement); placements.add(placement);
host.setObjects(placements); host.setObjects(placements);
stubBiome(host); stubBiome(host);
stubReachableBiomes(host);
stubRegions(regionA); stubRegions(regionA);
when(complex.getRegionStream()).thenReturn(constantStream(regionA)); when(complex.getRegionStream()).thenReturn(constantStream(regionA));
@@ -326,6 +336,7 @@ public class HintedLocatorTest {
IrisRegion regionA = region("reg_a"); IrisRegion regionA = region("reg_a");
regionA.setLandBiomes(keys("plains")); regionA.setLandBiomes(keys("plains"));
stubBiome(biome("plains")); stubBiome(biome("plains"));
stubReachableBiomes(biome("plains"));
stubRegions(regionA); stubRegions(regionA);
HintedLocator.SearchPlan plan = HintedLocator.objectPlan(engine, "missing/object"); HintedLocator.SearchPlan plan = HintedLocator.objectPlan(engine, "missing/object");
@@ -416,6 +427,7 @@ public class HintedLocatorTest {
placements.add(placement); placements.add(placement);
host.setObjects(placements); host.setObjects(placements);
stubBiome(host); stubBiome(host);
stubReachableBiomes(host);
stubRegions(regionA); stubRegions(regionA);
when(complex.getRegionStream()).thenReturn(constantStream(regionA)); when(complex.getRegionStream()).thenReturn(constantStream(regionA));
@@ -44,10 +44,11 @@ public class StructureResourcesTest {
try { try {
var catalog = data.getModules().pack().catalog(); 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"), assertEquals(List.of("iris:structure/piece", "iris:structure/pool", "iris:structure/structure"),
catalog.resourceKinds().stream().map(registration -> registration.kind().id().toString()).toList()); kinds.stream().map(kind -> kind.id().toString()).toList());
assertEquals(List.of("jigsaw-pieces", "jigsaw-pools", "structures"), assertEquals(List.of("jigsaw-pieces", "jigsaw-pools", "structures"), kinds.stream().map(kind -> kind.folder()).toList());
catalog.resourceKinds().stream().map(ResourceKindRegistration::kind).map(kind -> kind.folder()).toList());
assertTrue(catalog.validators().stream().map(ValidatorRegistration::validator).anyMatch(StructureValidator.class::isInstance)); assertTrue(catalog.validators().stream().map(ValidatorRegistration::validator).anyMatch(StructureValidator.class::isInstance));
assertFalse(data.getLoaders().containsKey(IrisStructure.class)); assertFalse(data.getLoaders().containsKey(IrisStructure.class));
assertFalse(data.getLoaders().containsKey(IrisJigsawPool.class)); assertFalse(data.getLoaders().containsKey(IrisJigsawPool.class));
@@ -146,7 +147,8 @@ public class StructureResourcesTest {
List<JSONObject> entries = ModuleResourceSchemas.entries(data, true); List<JSONObject> entries = ModuleResourceSchemas.entries(data, true);
assertEquals(List.of("./.iris/schema/jigsaw-pieces-schema.json", "./.iris/schema/jigsaw-pools-schema.json", 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 structures = new JSONObject(Files.readString(pack.resolve(".iris/schema/structures-schema.json")));
JSONObject startPool = structures.getJSONObject("properties").getJSONObject("startPool"); JSONObject startPool = structures.getJSONObject("properties").getJSONObject("startPool");
assertEquals("#/definitions/erzjigsaw-pools", startPool.getString("$ref")); assertEquals("#/definitions/erzjigsaw-pools", startPool.getString("$ref"));
@@ -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<ItemDrop> 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));
}
}
@@ -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.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.biome.IrisBiome;
import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.loot.IrisLootMode; 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.iris.engine.object.annotations.MaxNumber;
import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import com.volmit.item.ItemRegistry;
import org.junit.Test; import org.junit.Test;
import java.lang.reflect.Field; import java.lang.reflect.Field;
@@ -70,12 +73,12 @@ public class LootResolverTest {
IrisLootTable first = new IrisLootTable().setName("first"); IrisLootTable first = new IrisLootTable().setName("first");
IrisLootTable second = new IrisLootTable().setName("second"); 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)); assertEquals(baseline, LootTables.seed(41L, first, 0, 64, 0));
assertNotEquals(baseline, LootResolver.tableSeed(42L, first, 0, 64, 0)); assertNotEquals(baseline, LootTables.seed(42L, first, 0, 64, 0));
assertNotEquals(baseline, LootResolver.tableSeed(41L, second, 0, 64, 0)); assertNotEquals(baseline, LootTables.seed(41L, second, 0, 64, 0));
assertNotEquals(baseline, LootResolver.tableSeed(41L, first, 16, 64, 0)); assertNotEquals(baseline, LootTables.seed(41L, first, 16, 64, 0));
} }
@Test @Test
@@ -84,7 +87,7 @@ public class LootResolverTest {
int successes = 0; int successes = 0;
for (int x = 0; x < 65_536; x++) { 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++; successes++;
} }
} }
@@ -92,8 +95,8 @@ public class LootResolverTest {
assertTrue(successes > 7_600); assertTrue(successes > 7_600);
assertTrue(successes < 8_800); assertTrue(successes < 8_800);
assertEquals( assertEquals(
LootResolver.spatialOneIn(91L, table, 3, 112, 40, 992, 8L), LootTables.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)
); );
} }
@@ -102,7 +105,7 @@ public class LootResolverTest {
ResolutionFixture fixture = new ResolutionFixture(); ResolutionFixture fixture = new ResolutionFixture();
List<IrisLootTable> sources = new ArrayList<>(); List<IrisLootTable> sources = new ArrayList<>();
LootResolver.resolveEnvironmentSources( LootTables.resolveEnvironmentSources(
sources, sources,
fixture.engine, fixture.engine,
new RNG(19L), new RNG(19L),
@@ -121,7 +124,7 @@ public class LootResolverTest {
ResolutionFixture fixture = new ResolutionFixture(); ResolutionFixture fixture = new ResolutionFixture();
List<IrisLootTable> sources = new ArrayList<>(); List<IrisLootTable> sources = new ArrayList<>();
LootResolver.resolveEnvironmentSources( LootTables.resolveEnvironmentSources(
sources, sources,
fixture.engine, fixture.engine,
new RNG(19L), new RNG(19L),
@@ -247,7 +250,7 @@ public class LootResolverTest {
public void emptyLootTableReturnsNoItems() { public void emptyLootTableReturnsNoItems() {
IrisLootTable table = new IrisLootTable().setName("empty"); 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 @Test
@@ -0,0 +1,113 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.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<JSONObject> 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);
}
}
@@ -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 art.arcane.iris.engine.object.loot.IrisLootMode;
import org.junit.Test; import org.junit.Test;
@@ -9,22 +9,22 @@ import java.util.List;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
public class LootResolverClearModeTest { public class LootTablesClearModeTest {
@Test @Test
public void clearSuppressesItsOwnTablesAndReplaceDoesNot() { public void clearSuppressesItsOwnTablesAndReplaceDoesNot() {
List<String> cleared = new ArrayList<>(List.of("placement", "dimension")); List<String> 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()); assertTrue("CLEAR must clear parents and contribute nothing", cleared.isEmpty());
List<String> replaced = new ArrayList<>(List.of("placement", "dimension")); List<String> 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); assertEquals(List.of("biome"), replaced);
} }
@Test @Test
public void clearIgnoresTheFallbackFlag() { public void clearIgnoresTheFallbackFlag() {
List<String> sources = new ArrayList<>(List.of("placement")); List<String> 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()); assertTrue(sources.isEmpty());
} }
} }
@@ -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.IrisLoot;
import art.arcane.iris.engine.object.loot.IrisLootTable; import art.arcane.iris.engine.object.loot.IrisLootTable;
import art.arcane.iris.engine.object.annotations.MaxNumber; 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.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.TemporaryFolder; import org.junit.rules.TemporaryFolder;
@@ -16,7 +18,7 @@ import java.util.List;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
public class PackValidatorLootTest { public class LootValidatorTest {
@Rule @Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder(); public TemporaryFolder temporaryFolder = new TemporaryFolder();
@@ -28,7 +30,7 @@ public class PackValidatorLootTest {
write(pack, "dimensions/main.json", "{\"loot\":{\"mode\":\"FALLBACK\",\"multiplier\":0.5," write(pack, "dimensions/main.json", "{\"loot\":{\"mode\":\"FALLBACK\",\"multiplier\":0.5,"
+ "\"tables\":[\"global/clutter\"]}}"); + "\"tables\":[\"global/clutter\"]}}");
assertTrue(PackLootValidator.validateLootGraph(pack).errors().isEmpty()); assertTrue(errors(pack).isEmpty());
} }
@Test @Test
@@ -37,7 +39,7 @@ public class PackValidatorLootTest {
write(pack, "dimensions/main.json", "{\"loot\":{\"tables\":[\"missing\"]}}"); write(pack, "dimensions/main.json", "{\"loot\":{\"tables\":[\"missing\"]}}");
assertEquals(List.of("Dimension 'main'.loot.tables[0] references missing loot table 'missing'."), assertEquals(List.of("Dimension 'main'.loot.tables[0] references missing loot table 'missing'."),
PackLootValidator.validateLootGraph(pack).errors()); errors(pack));
} }
@Test @Test
@@ -47,7 +49,7 @@ public class PackValidatorLootTest {
+ "\"loot\":[{\"type\":\"\",\"rarity\":0,\"minAmount\":3,\"maxAmount\":1," + "\"loot\":[{\"type\":\"\",\"rarity\":0,\"minAmount\":3,\"maxAmount\":1,"
+ "\"enchantments\":[{\"enchantment\":\"\",\"minLevel\":4,\"maxLevel\":2,\"chance\":2}]}]}"); + "\"enchantments\":[{\"enchantment\":\"\",\"minLevel\":4,\"maxLevel\":2,\"chance\":2}]}]}");
List<String> errors = PackLootValidator.validateLootGraph(pack).errors(); List<String> errors = errors(pack);
assertTrue(errors.stream().anyMatch(error -> error.contains(".rarity must be at least 1"))); assertTrue(errors.stream().anyMatch(error -> error.contains(".rarity must be at least 1")));
assertTrue(errors.stream().anyMatch(error -> error.contains(".minPicked must not exceed"))); assertTrue(errors.stream().anyMatch(error -> error.contains(".minPicked must not exceed")));
@@ -63,7 +65,7 @@ public class PackValidatorLootTest {
File pack = temporaryFolder.newFolder("pack"); File pack = temporaryFolder.newFolder("pack");
write(pack, "dimensions/main.json", "{\"loot\":{\"mode\":\"MERGE\",\"multiplier\":-1,\"tables\":[]}}"); write(pack, "dimensions/main.json", "{\"loot\":{\"mode\":\"MERGE\",\"multiplier\":-1,\"tables\":[]}}");
List<String> errors = PackLootValidator.validateLootGraph(pack).errors(); List<String> errors = errors(pack);
assertEquals(2, errors.size()); assertEquals(2, errors.size());
assertTrue(errors.get(0).contains(".mode must be")); assertTrue(errors.get(0).contains(".mode must be"));
@@ -74,12 +76,12 @@ public class PackValidatorLootTest {
public void enforcesPublishedLootMultiplierCap() throws Exception { public void enforcesPublishedLootMultiplierCap() throws Exception {
File acceptedPack = temporaryFolder.newFolder("accepted-pack"); File acceptedPack = temporaryFolder.newFolder("accepted-pack");
write(acceptedPack, "dimensions/main.json", "{\"loot\":{\"multiplier\":16,\"tables\":[]}}"); 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"); File rejectedPack = temporaryFolder.newFolder("rejected-pack");
write(rejectedPack, "dimensions/main.json", "{\"loot\":{\"multiplier\":16.01,\"tables\":[]}}"); 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."), assertEquals(List.of("Dimension 'main'.loot.multiplier must be a finite number from 0 to 16."),
PackLootValidator.validateLootGraph(rejectedPack).errors()); errors(rejectedPack));
} }
@Test @Test
@@ -88,7 +90,7 @@ public class PackValidatorLootTest {
write(pack, "loot/boundary.json", "{\"minPicked\":64,\"maxPicked\":64,\"maxTries\":256," write(pack, "loot/boundary.json", "{\"minPicked\":64,\"maxPicked\":64,\"maxTries\":256,"
+ "\"loot\":[{\"type\":\"stone\",\"minAmount\":64,\"maxAmount\":64}]}"); + "\"loot\":[{\"type\":\"stone\",\"minAmount\":64,\"maxAmount\":64}]}");
assertTrue(PackLootValidator.validateLootGraph(pack).errors().isEmpty()); assertTrue(errors(pack).isEmpty());
} }
@Test @Test
@@ -97,7 +99,7 @@ public class PackValidatorLootTest {
write(pack, "loot/excessive.json", "{\"minPicked\":65,\"maxPicked\":65,\"maxTries\":257," write(pack, "loot/excessive.json", "{\"minPicked\":65,\"maxPicked\":65,\"maxTries\":257,"
+ "\"loot\":[{\"type\":\"stone\",\"minAmount\":65,\"maxAmount\":65}]}"); + "\"loot\":[{\"type\":\"stone\",\"minAmount\":65,\"maxAmount\":65}]}");
List<String> errors = PackLootValidator.validateLootGraph(pack).errors(); List<String> errors = errors(pack);
assertTrue(errors.contains("Loot table 'excessive'.minPicked must be at most 64.")); assertTrue(errors.contains("Loot table 'excessive'.minPicked must be at most 64."));
assertTrue(errors.contains("Loot table 'excessive'.maxPicked 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, "loot/t.json", "{\"loot\":[{\"type\":\"minecraft:stone\"}]}");
write(pack, "biomes/x.json", "{\"loot\":{\"mode\":\"CLEAR\",\"tables\":[\"t\"]}}"); 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" 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."), + " and contributes no tables of its own, so these entries are dead. Use REPLACE to substitute them."),
issues.warnings()); warnings(pack));
} }
@Test @Test
@@ -140,12 +141,23 @@ public class PackValidatorLootTest {
File pack = temporaryFolder.newFolder("clear-dangling"); File pack = temporaryFolder.newFolder("clear-dangling");
write(pack, "biomes/x.json", "{\"loot\":{\"mode\":\"CLEAR\",\"tables\":[\"missing\"]}}"); 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'.")); "Biome 'x'.loot.tables[0] references missing loot table 'missing'."));
} }
private static List<String> errors(File pack) {
return messages(pack, Severity.ERROR);
}
private static List<String> warnings(File pack) {
return messages(pack, Severity.WARNING);
}
private static List<String> 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 { private void write(File root, String relative, String content) throws Exception {
File file = new File(root, relative); File file = new File(root, relative);
Files.createDirectories(file.toPath().getParent()); Files.createDirectories(file.toPath().getParent());
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<SaplingGrowth.Growth> 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<SaplingGrowth.Growth> growth = new TreeGrowing().grow(world, OAK_SAPLING, mock(SaplingGrowth.Surroundings.class));
assertTrue(growth.isEmpty());
}
}
@@ -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)));
}
}
@@ -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.IrisObjectPlacementScaleInterpolator;
import art.arcane.iris.engine.object.prefab.IrisObjectScale; import art.arcane.iris.engine.object.prefab.IrisObjectScale;
import art.arcane.iris.core.loader.IrisData; 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.iris.spi.PlatformBlockState;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@@ -20,13 +21,13 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport; import java.util.concurrent.locks.LockSupport;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class IrisObjectScaleCacheTest { public class IrisObjectScaleCacheTest {
private static final IrisObjectScale.ScaleRequest REQUEST = new IrisObjectScale.ScaleRequest( private static final IrisObjectScale.ScaleRequest REQUEST = new IrisObjectScale.ScaleRequest(
@@ -37,55 +38,56 @@ public class IrisObjectScaleCacheTest {
IrisObjectPlacementScaleInterpolator.NONE IrisObjectPlacementScaleInterpolator.NONE
); );
private Engine engine;
@Before @Before
public void setUp() { 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 private int cacheEntryCount() {
public void tearDown() { return IrisObjectScale.cacheOf(engine).size();
IrisObjectScale.invalidate(null); }
private long cacheEstimatedBytes() {
return IrisObjectScale.cacheOf(engine).estimatedBytes();
} }
@Test @Test
public void mutatedOriginCreatesStableReplacementAndCanBeReleased() { public void mutatedOriginCreatesStableReplacement() {
IrisObject origin = new IrisObject(2, 2, 2); IrisObject origin = new IrisObject(2, 2, 2);
IrisObjectScale scale = new IrisObjectScale().setSize(2D); 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.ScaleCache keyCache = new IrisObjectScale.ScaleCache(10L);
IrisObjectScale.CacheKey originalKey = keyCache.key(origin, REQUEST, 0); IrisObjectScale.CacheKey originalKey = keyCache.key(origin, REQUEST, 0);
int originalHash = originalKey.hashCode(); int originalHash = originalKey.hashCode();
origin.setW(3); origin.setW(3);
IrisObject second = scale.get(new RNG(1L), origin); IrisObject second = scale.get(new RNG(1L), origin, engine);
assertEquals(originalHash, originalKey.hashCode()); assertEquals(originalHash, originalKey.hashCode());
assertNotEquals(originalKey, keyCache.key(origin, REQUEST, 0)); assertNotEquals(originalKey, keyCache.key(origin, REQUEST, 0));
assertNotSame(first, second); assertNotSame(first, second);
assertNotEquals(first.getW(), second.getW()); assertNotEquals(first.getW(), second.getW());
assertEquals(2, IrisObjectScale.cacheEntryCount()); assertEquals(2, cacheEntryCount());
IrisObjectScale.invalidate(null);
assertEquals(0, IrisObjectScale.cacheEntryCount());
assertEquals(0L, IrisObjectScale.cacheEstimatedBytes());
assertFalse(IrisObjectScale.isOriginCached(origin));
} }
@Test @Test
public void voxelMutationReplacesCachedVariants() { public void voxelMutationReplacesCachedVariants() {
IrisObject origin = new IrisObject(2, 2, 2); IrisObject origin = new IrisObject(2, 2, 2);
IrisObjectScale scale = new IrisObjectScale().setSize(2D); 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)); 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()); assertEquals(0, empty.getBlocks().size());
assertTrue(populated.getBlocks().size() > 0); assertTrue(populated.getBlocks().size() > 0);
assertNotSame(empty, populated); assertNotSame(empty, populated);
assertEquals(2, IrisObjectScale.cacheEntryCount()); assertEquals(2, cacheEntryCount());
} }
@Test @Test
@@ -97,18 +99,18 @@ public class IrisObjectScaleCacheTest {
.setMaximumScale(2D); .setMaximumScale(2D);
SequenceRng rng = new SequenceRng(); SequenceRng rng = new SequenceRng();
IrisObject first = scale.get(rng, origin); IrisObject first = scale.get(rng, origin, engine);
IrisObject second = scale.get(rng, origin); IrisObject second = scale.get(rng, origin, engine);
IrisObject third = scale.get(rng, origin); IrisObject third = scale.get(rng, origin, engine);
IrisObject fourth = scale.get(rng, origin); IrisObject fourth = scale.get(rng, origin, engine);
IrisObject repeated = scale.get(rng, origin); IrisObject repeated = scale.get(rng, origin, engine);
assertSame(first, repeated); assertSame(first, repeated);
assertNotEquals(first.getW(), second.getW()); assertNotEquals(first.getW(), second.getW());
assertNotEquals(second.getW(), third.getW()); assertNotEquals(second.getW(), third.getW());
assertNotEquals(third.getW(), fourth.getW()); assertNotEquals(third.getW(), fourth.getW());
assertEquals(4, IrisObjectScale.cacheEntryCount()); assertEquals(4, cacheEntryCount());
assertTrue(IrisObjectScale.cacheEstimatedBytes() > 0L); assertTrue(cacheEstimatedBytes() > 0L);
} }
@Test @Test
@@ -116,12 +118,12 @@ public class IrisObjectScaleCacheTest {
OverweightScaleObject origin = new OverweightScaleObject(); OverweightScaleObject origin = new OverweightScaleObject();
IrisObjectScale scale = new IrisObjectScale().setSize(2D); 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_000, result.getW());
assertEquals(1, origin.scaleCalls.get()); assertEquals(1, origin.scaleCalls.get());
assertEquals(0, IrisObjectScale.cacheEntryCount()); assertEquals(0, cacheEntryCount());
assertEquals(0L, IrisObjectScale.cacheEstimatedBytes()); assertEquals(0L, cacheEstimatedBytes());
} }
@Test @Test
@@ -133,12 +135,12 @@ public class IrisObjectScaleCacheTest {
AtomicReference<Thread> secondThread = new AtomicReference<>(); AtomicReference<Thread> secondThread = new AtomicReference<>();
try { try {
Future<IrisObject> first = executor.submit(() -> scale.get(new RNG(1L), origin)); Future<IrisObject> first = executor.submit(() -> scale.get(new RNG(1L), origin, engine));
assertTrue(origin.firstScaleEntered.await(5L, TimeUnit.SECONDS)); assertTrue(origin.firstScaleEntered.await(5L, TimeUnit.SECONDS));
Future<IrisObject> second = executor.submit(() -> { Future<IrisObject> second = executor.submit(() -> {
secondThread.set(Thread.currentThread()); secondThread.set(Thread.currentThread());
secondInvoked.countDown(); secondInvoked.countDown();
return scale.get(new RNG(1L), origin); return scale.get(new RNG(1L), origin, engine);
}); });
assertTrue(secondInvoked.await(5L, TimeUnit.SECONDS)); assertTrue(secondInvoked.await(5L, TimeUnit.SECONDS));
@@ -171,15 +173,15 @@ public class IrisObjectScaleCacheTest {
put(cache, firstKey, new IrisObject(1, 1, 1), 4L); put(cache, firstKey, new IrisObject(1, 1, 1), 4L);
put(cache, secondKey, 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); put(cache, thirdKey, new IrisObject(1, 1, 1), 4L);
assertEquals(2, cache.size()); assertEquals(2, cache.size());
assertEquals(8L, cache.estimatedBytes()); assertEquals(8L, cache.estimatedBytes());
assertTrue(cache.estimatedBytes() <= cache.maximumEstimatedBytes()); assertTrue(cache.estimatedBytes() <= cache.maximumEstimatedBytes());
assertTrue(cache.lookup(firstKey).variant() != null); assertTrue(cache.lookup(firstKey) != null);
assertNull(cache.lookup(secondKey).variant()); assertNull(cache.lookup(secondKey));
assertTrue(cache.lookup(thirdKey).variant() != null); assertTrue(cache.lookup(thirdKey) != null);
} }
@Test @Test
@@ -188,55 +190,14 @@ public class IrisObjectScaleCacheTest {
IrisObject origin = new IrisObject(1, 1, 1); IrisObject origin = new IrisObject(1, 1, 1);
IrisObjectScale.CacheKey key = key(origin); IrisObjectScale.CacheKey key = key(origin);
IrisObject variant = new IrisObject(1, 1, 1); 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); assertSame(variant, result);
assertEquals(0, cache.size()); assertEquals(0, cache.size());
assertEquals(0L, cache.estimatedBytes()); 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 @Test
public void collectedOriginReleasesScaledValueWithOwnerReference() { public void collectedOriginReleasesScaledValueWithOwnerReference() {
IrisObjectScale.ScaleCache cache = new IrisObjectScale.ScaleCache(20L); IrisObjectScale.ScaleCache cache = new IrisObjectScale.ScaleCache(20L);
@@ -261,8 +222,7 @@ public class IrisObjectScaleCacheTest {
private static void put(IrisObjectScale.ScaleCache cache, IrisObjectScale.CacheKey key, private static void put(IrisObjectScale.ScaleCache cache, IrisObjectScale.CacheKey key,
IrisObject variant, long estimatedBytes) { IrisObject variant, long estimatedBytes) {
IrisObjectScale.CacheLookup lookup = cache.lookup(key); cache.putIfAbsent(key, variant, estimatedBytes);
cache.putIfCurrent(key, variant, estimatedBytes, lookup.generation());
} }
private static final class BlockingScaleObject extends IrisObject { private static final class BlockingScaleObject extends IrisObject {
@@ -0,0 +1,169 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.spawn;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.modules.ModuleResourceFixture;
import art.arcane.iris.engine.UsableBlockPlatform;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineGeneration;
import art.arcane.iris.engine.framework.SeedManager;
import art.arcane.iris.engine.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 ModuleResourceFixture fixture;
private PackWorld world;
@BeforeClass
public static void bindPlatform() {
UsableBlockPlatform.bind();
}
@AfterClass
public static void unbindPlatform() {
UsableBlockPlatform.unbind();
}
@Before
public void buildWorld() {
engine = mock(Engine.class);
IrisData data = mock(IrisData.class);
when(engine.getData()).thenReturn(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));
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);
fixture.resource(SpawnResources.MARKERS, "camp", marker);
fixture.resource(SpawnResources.SPAWNERS, "zombies", 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));
fixture.resource(SpawnResources.SPAWNERS, "camp/zombies", spawner);
IrisMarker marker = new IrisMarker();
marker.setExhaustionChance(2);
fixture.resource(SpawnResources.MARKERS, "camp", marker);
IrisEntity zombie = new IrisEntity();
zombie.setType("minecraft:zombie");
fixture.resource(SpawnResources.ENTITIES, "zombie", zombie);
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();
fixture.resource(SpawnResources.SPAWNERS, "empty", empty);
Optional<EntitySpawns.Plan> 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);
fixture.resource(SpawnResources.ENTITIES, "cow", 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());
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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);
}
}
@@ -89,8 +89,7 @@ import static org.junit.Assert.fail;
* deleted) and {@code Particles} (Bukkit registry lookups in a static initializer). * deleted) and {@code Particles} (Bukkit registry lookups in a static initializer).
* <p> * <p>
* <b>Deliberately not asserted:</b> method and constructor descriptors. These classes legitimately * <b>Deliberately not asserted:</b> method and constructor descriptors. These classes legitimately
* expose a Bukkit-typed edge that only the Bukkit adapter calls - {@code IrisEntity.spawn(Engine, * expose a Bukkit-typed edge that only the Bukkit adapter calls - {@code IrisObjectRotation.rotate(BlockData,
* Location)}, {@code IrisLoot.get(...) -> ItemStack}, {@code IrisObjectRotation.rotate(BlockData,
* ...)}, {@code TileData.toBukkit(Block)} and ~60 more. Method descriptors are resolved at * ...)}, {@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 * 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. * 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. * #registeredRootListMatchesIrisData()} fails if the source drifts away from it.
*/ */
private static final List<String> GSON_REGISTERED_ROOTS = List.of( private static final List<String> 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.region.IrisRegion",
"art.arcane.iris.engine.object.world.biome.IrisBiome", "art.arcane.iris.engine.object.world.biome.IrisBiome",
"art.arcane.iris.engine.object.mod.IrisMod", "art.arcane.iris.engine.object.mod.IrisMod",
"art.arcane.iris.engine.object.world.dimension.IrisDimension", "art.arcane.iris.engine.object.world.dimension.IrisDimension",
"art.arcane.iris.engine.object.terrain.IrisGenerator", "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.material.IrisBlockData",
"art.arcane.iris.engine.object.noise.expression.IrisExpression", "art.arcane.iris.engine.object.noise.expression.IrisExpression",
"art.arcane.iris.engine.object.prefab.IrisObject", "art.arcane.iris.engine.object.prefab.IrisObject",
@@ -133,7 +128,11 @@ public class PackTypeBukkitPurityGateTest {
private static final List<String> MODULE_RESOURCE_ROOTS = List.of( private static final List<String> MODULE_RESOURCE_ROOTS = List.of(
"art.arcane.iris.engine.object.structure.IrisStructure", "art.arcane.iris.engine.object.structure.IrisStructure",
"art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool", "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 * 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"); "art.arcane.iris.engine.object.loot.IrisVanillaLootTable");
/** /**
* Bukkit-registry constant holders that a core pack type references, so their class initializer * Bukkit-registry constant holders that a core pack type may reference, so their class initializer
* runs on the modded loaders too. {@code Particles} is statically imported by {@code IrisEntity}. * 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 * ({@code Materials} and {@code Attributes} have the same shape but are only reachable from the
* Bukkit adapter, so they stay out of the gate.) * Bukkit adapter, so they stay out of the gate.)
*/ */
@@ -1,11 +1,10 @@
package art.arcane.iris.util.project.matter; package art.arcane.iris.util.project.matter;
import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.loader.IrisRegistrant; import art.arcane.iris.core.modules.ModuleResourceFixture;
import art.arcane.iris.core.loader.ResourceLoader; import art.arcane.iris.engine.spawn.SpawnResources;
import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; import art.arcane.iris.engine.object.entity.spawn.IrisSpawner;
import art.arcane.iris.util.project.matter.slices.SpawnerMatter; import art.arcane.iris.util.project.matter.slices.SpawnerMatter;
import art.arcane.volmlib.util.collection.KMap;
import org.junit.Test; import org.junit.Test;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
@@ -18,7 +17,6 @@ import java.util.concurrent.Future;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class RegistryMatterContextTest { public class RegistryMatterContextTest {
@Test @Test
@@ -49,14 +47,9 @@ public class RegistryMatterContextTest {
} }
} }
@SuppressWarnings("unchecked")
private IrisData dataReturning(IrisSpawner resolved) { private IrisData dataReturning(IrisSpawner resolved) {
ResourceLoader<IrisSpawner> loader = mock(ResourceLoader.class);
when(loader.load("test-spawner")).thenReturn(resolved);
KMap<Class<? extends IrisRegistrant>, ResourceLoader<? extends IrisRegistrant>> loaders = new KMap<>();
loaders.put(IrisSpawner.class, loader);
IrisData data = mock(IrisData.class); IrisData data = mock(IrisData.class);
when(data.getLoaders()).thenReturn(loaders); ModuleResourceFixture.serve(data).resource(SpawnResources.SPAWNERS, "test-spawner", resolved);
return data; return data;
} }
} }
@@ -42,4 +42,9 @@ public interface PlatformItem {
* on a mod loader. Never null. Only code inside the owning adapter may cast it. * on a mod loader. Never null. Only code inside the owning adapter may cast it.
*/ */
Object nativeHandle(); Object nativeHandle();
/**
* The damage a stack of this item takes before it breaks, 0 for an item that cannot be damaged.
*/
int maxDurability();
} }