iris:loot and iris:spawn onto the module surface and into iris-builtins.jar: no engine, IrisData, IrisPlatforms or Bukkit types; the validator checks the decoded tables and references

This commit is contained in:
piexel committed 2026-10-10 18:21:31 +02:00
1 parent 347c69b0a2
commit 48ff0908e2
19 files changed
+445 -510

No files matched your search

+11 -4
View File
@@ -137,10 +137,12 @@ naming the class and what it uses. A VolmLib class that Iris's Bukkit jar strips
`core/volmlib-left-out-of-bukkit-jar.txt`, which its shadowJar reads too) is on that classpath but missing on a `core/volmlib-left-out-of-bukkit-jar.txt`, which its shadowJar reads too) is on that classpath but missing on a
server, so the check treats it as missing and fails the task naming it. `check` runs the task. server, so the check treats it as missing and fails the task naming it. `check` runs the task.
The jar holds `iris:post`, `iris:perfection` and `iris:matter`. They are written against IrisApi and The jar holds `iris:post`, `iris:perfection`, `iris:matter`, `iris:loot` and `iris:spawn`. They are written against IrisApi and
`art.arcane.iris.builtin` alone: the chunk's `BlockState` hunk, the block registry's traits and `canPlaceOn`, the terrain `art.arcane.iris.builtin` alone: the chunk's `BlockState` hunk, the block registry's traits and `canPlaceOn`, the terrain
sampler (heights around the chunk, slope, fluid height, where the upper dimension begins) and the mantle's planned blocks. sampler (heights around the chunk, slope, fluid height, where the upper dimension begins) and the mantle's planned blocks;
Iris no longer compiles them in (`IrisModuleHost.generationModules()`), so a pack gets them by putting the loot and spawn services, which have no chunk to ask, ask `LiveWorld` (below). Without the jar a pack's world has no
loot, block drops, entity spawns or ambient effects, and its biomes' `loot`, `blockDrops`, `entitySpawners` and `effects` are
not read. Iris no longer compiles them in (`IrisModuleHost.generationModules()`), so a pack gets them by putting
`iris-builtins.jar` into its `modules` folder; the built-ins that order after their stages (`iris:floating`, `iris-builtins.jar` into its `modules` folder; the built-ins that order after their stages (`iris:floating`,
`iris:decorant`, `iris:custom`) only order, so a pack without the jar still loads. Iris warns once per pack folder `iris:decorant`, `iris:custom`) only order, so a pack without the jar still loads. Iris warns once per pack folder
when a pack loads none of the jar's modules (`IrisModuleHost.JAR_MODULE_IDS`, which a test keeps equal to when a pack loads none of the jar's modules (`IrisModuleHost.JAR_MODULE_IDS`, which a test keeps equal to
@@ -149,5 +151,10 @@ when a pack loads none of the jar's modules (`IrisModuleHost.JAR_MODULE_IDS`, wh
`art.arcane.iris.builtin` also holds what the compiled-in built-ins and the jar must share, because each sees its own copy of `art.arcane.iris.builtin` also holds what the compiled-in built-ins and the jar must share, because each sees its own copy of
every other class: `IrisSeed` (Iris's per-feature world seeds, a facade Iris's worlds implement, so existing worlds generate the every other class: `IrisSeed` (Iris's per-feature world seeds, a facade Iris's worlds implement, so existing worlds generate the
same) and `terrain.LayerBlocks` (the world's picks from the biomes' palette layers: terrain, caves and post pick from the same same) and `terrain.LayerBlocks` (the world's picks from the biomes' palette layers: terrain, caves and post pick from the same
layers, and a layer's noise is built once per world by whichever asks first). `iris:post` reads its switches layers, and a layer's noise is built once per world by whichever asks first), `LiveWorld` (what the loot and spawn services ask a
running world, outside any chunk stage: the layout and settings at a block, the platform's weather and loot tables, the
objects' loot and the spawner cooldowns Iris saves with the world; values only, implemented by Iris's worlds like `IrisSeed`),
`loot.LootResolver` (the random streams loot is drawn from, shared with the hosts that fill containers) and the loot and
marker lists of an object placement (`loot.ObjectLoot`, `loot.ObjectVanillaLoot`, `spawn.PlacementMarker`, which the modules
register as held types, because Iris's `IrisObjectPlacement` holds them). `iris:post` reads its switches
(`postProcessingWalls`, `postProcessingSlabs`) and the biome's `wall` and `slab` as module settings through its context. (`postProcessingWalls`, `postProcessingSlabs`) and the biome's `wall` and `slab` as module settings through its context.
+4
View File
@@ -18,3 +18,7 @@ module art.arcane.iris.engine.modifier.PostModule
include art/arcane/iris/engine/modifier/SurfaceSmoothing*.class include art/arcane/iris/engine/modifier/SurfaceSmoothing*.class
module art.arcane.iris.engine.modifier.PerfectionModule module art.arcane.iris.engine.modifier.PerfectionModule
module art.arcane.iris.engine.modifier.MatterModule module art.arcane.iris.engine.modifier.MatterModule
module art.arcane.iris.engine.loot.LootModule
include art/arcane/iris/engine/loot/**
module art.arcane.iris.engine.spawn.SpawnModule
include art/arcane/iris/engine/spawn/**
@@ -18,16 +18,12 @@
package art.arcane.iris.engine.loot; package art.arcane.iris.engine.loot;
import art.arcane.iris.builtin.LiveWorld;
import art.arcane.iris.builtin.LiveWorld.Level;
import art.arcane.iris.builtin.loot.BlockDrop; import art.arcane.iris.builtin.loot.BlockDrop;
import art.arcane.iris.builtin.loot.BlockDropSettings; import art.arcane.iris.builtin.loot.BlockDropSettings;
import art.arcane.iris.builtin.loot.LootEntry; import art.arcane.iris.builtin.loot.LootEntry;
import art.arcane.iris.core.loader.IrisRegistrant;
import art.arcane.iris.core.modules.IrisPackWorld;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.iris.builtin.loot.LootResolver;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import com.volmit.item.ItemDrop; import com.volmit.item.ItemDrop;
import com.volmit.service.BlockDrops; import com.volmit.service.BlockDrops;
@@ -45,19 +41,17 @@ import java.util.concurrent.ConcurrentMap;
public final class BlockDropping implements BlockDrops { public final class BlockDropping implements BlockDrops {
@Override @Override
public Result drops(PackWorld world, Broken broken) { public Result drops(PackWorld world, Broken broken) {
Engine engine = IrisPackWorld.of(world).engine(); LiveWorld live = LiveWorld.of(world);
int x = broken.position().x(); int x = broken.position().x();
int y = broken.position().y(); int y = broken.position().y();
int z = broken.position().z(); int z = broken.position().z();
String brokenKey = IrisPlatforms.get().registries().block(broken.block().key()).key(); String brokenKey = world.resources().blocks().resolve(broken.block()).key();
ResolvedDrops resolved = world.state(ResolvedDrops.class, ignored -> new ResolvedDrops()); ResolvedDrops resolved = world.state(ResolvedDrops.class, ignored -> new ResolvedDrops());
IrisBiome biome = engine.getBiome(x, y, z); List<ResolvedBlockDrop> providers = dropsFor(live, Level.BIOME, x, y, z, brokenKey, resolved, world);
List<ResolvedBlockDrop> providers = dropsFor(biome, brokenKey, resolved, world);
if (providers.stream().noneMatch(provider -> provider.drop().skipParents())) { if (providers.stream().noneMatch(provider -> provider.drop().skipParents())) {
IrisRegion region = engine.getRegion(x, z); providers.addAll(dropsFor(live, Level.REGION, x, y, z, brokenKey, resolved, world));
providers.addAll(dropsFor(region, brokenKey, resolved, world)); providers.addAll(dropsFor(live, Level.DIMENSION, x, y, z, brokenKey, resolved, world));
providers.addAll(dropsFor(engine.getDimension(), brokenKey, resolved, world));
} }
LootItems items = new LootItems(world.resources().items(), false); LootItems items = new LootItems(world.resources().items(), false);
@@ -79,9 +73,10 @@ public final class BlockDropping implements BlockDrops {
} }
} }
private static List<ResolvedBlockDrop> dropsFor(IrisRegistrant owner, String brokenKey, ResolvedDrops resolved, PackWorld world) { private static List<ResolvedBlockDrop> dropsFor(LiveWorld live, Level level, int x, int y, int z, String brokenKey,
ResolvedDrops resolved, PackWorld world) {
List<ResolvedBlockDrop> matching = new ArrayList<>(); List<ResolvedBlockDrop> matching = new ArrayList<>();
for (BlockDrop drop : owner.getModuleSettings().find(BlockDropSettings.class).map(BlockDropSettings::drops).orElse(List.of())) { for (BlockDrop drop : live.settings(BlockDropSettings.class, level, x, y, z).map(BlockDropSettings::drops).orElse(List.of())) {
ResolvedBlockDrop candidate = resolved.of(drop, world); ResolvedBlockDrop candidate = resolved.of(drop, world);
if (candidate.dropsFor(brokenKey)) { if (candidate.dropsFor(brokenKey)) {
matching.add(candidate); matching.add(candidate);
@@ -18,14 +18,11 @@
package art.arcane.iris.engine.loot; package art.arcane.iris.engine.loot;
import art.arcane.iris.builtin.loot.LootTable; import art.arcane.iris.builtin.IrisSeed;
import art.arcane.iris.core.modules.IrisPackWorld; import art.arcane.iris.builtin.LiveWorld;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.builtin.LiveWorld.ObjectLoots;
import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.iris.builtin.loot.LootResolver;
import art.arcane.iris.engine.framework.PlacedObject; import art.arcane.iris.builtin.loot.LootTable;
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import com.volmit.item.ItemDrop; import com.volmit.item.ItemDrop;
import com.volmit.service.Loot; import com.volmit.service.Loot;
@@ -33,7 +30,7 @@ import com.volmit.world.PackWorld;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Optional;
/** /**
* How {@code iris:loot} fills containers: the tables of the object placed around a container, then those of the * How {@code iris:loot} fills containers: the tables of the object placed around a container, then those of the
@@ -43,76 +40,48 @@ import java.util.Set;
public final class LootGiving implements Loot { public final class LootGiving implements Loot {
@Override @Override
public List<Source> tables(PackWorld world, Site site) { public List<Source> tables(PackWorld world, Site site) {
Engine engine = engine(world); LiveWorld live = LiveWorld.of(world);
int x = site.position().x(); int x = site.position().x();
int z = site.position().z(); int z = site.position().z();
int relativeY = site.position().y(); int relativeY = site.position().y();
int worldY = relativeY + engine.getMinHeight(); int worldY = relativeY + live.bottomY();
RNG rng = LootResolver.containerRng(lootSeed(engine), x, worldY, z); RNG rng = LootResolver.containerRng(lootSeed(world), x, worldY, z);
List<Source> sources = new ArrayList<>(); List<Source> sources = new ArrayList<>();
boolean objectLootDefined = site.nativeLootDefined(); boolean objectLootDefined = site.nativeLootDefined();
IrisObjectPlacement placement = site.container() == null ? null : placementAt(engine, x, relativeY, z); Optional<ObjectLoots> objectLoots = site.container() == null ? Optional.empty() : live.objectLoots(x, relativeY, z);
if (placement != null) { if (objectLoots.isPresent()) {
objectLootDefined = objectLootDefined || placement.getLoot().isNotEmpty() || placement.getVanillaLoot().isNotEmpty(); objectLootDefined = objectLootDefined || objectLoots.get().defined();
Source picked = placementLoot(world, engine).pick(placement.getVanillaLoot(), placement.getLoot(), platformState(site), rng, x, worldY, z); Source picked = placementLoot(world, live).pick(objectLoots.get().platformTables(), objectLoots.get().packTables(),
site.container(), rng, x, worldY, z);
if (picked != null) { if (picked != null) {
sources.add(picked); sources.add(picked);
if (placement.isOverrideGlobalLoot()) { if (objectLoots.get().overridesGlobalLoot()) {
return sources; return sources;
} }
} }
} }
LootTables.resolveEnvironmentSources(sources, engine, rng, x, relativeY, z, objectLootDefined, Table::new); LootTables.resolveEnvironmentSources(sources, world, rng, x, relativeY, z, objectLootDefined, Table::new);
return sources; return sources;
} }
@Override @Override
public List<ItemDrop> items(PackWorld world, Site site, String key) { public List<ItemDrop> items(PackWorld world, Site site, String key) {
Engine engine = engine(world); LootTable table = LootResources.table(world.resources(), key);
LootTable table = LootResources.table(engine.getData(), key);
if (table == null) { if (table == null) {
return List.of(); return List.of();
} }
int worldY = site.position().y() + engine.getMinHeight(); int worldY = site.position().y() + LiveWorld.of(world).bottomY();
return new LootItems(world.resources().items(), site.debug()) return new LootItems(world.resources().items(), site.debug())
.draw(key, table, lootSeed(engine), site.position().x(), worldY, site.position().z()); .draw(key, table, lootSeed(world), site.position().x(), worldY, site.position().z());
} }
private static PlacementLoot placementLoot(PackWorld world, Engine engine) { private static PlacementLoot placementLoot(PackWorld world, LiveWorld live) {
PlatformLootTables platformTables = world.state(PlatformLootTables.class, ignored -> new PlatformLootTables()); return new PlacementLoot(world.resources(), live::platformLootTables, lootSeed(world), world.log());
return new PlacementLoot(engine.getData(), platformTables::keys, lootSeed(engine), world.log());
} }
private static IrisObjectPlacement placementAt(Engine engine, int x, int relativeY, int z) { private static long lootSeed(PackWorld world) {
PlacedObject placed = engine.getObjectPlacement(x, relativeY, z); return IrisSeed.LOOT.of(world);
return placed == null ? null : placed.getPlacement();
}
private static PlatformBlockState platformState(Site site) {
return IrisPlatforms.get().registries().block(site.container().key());
}
private static long lootSeed(Engine engine) {
return engine.getSeedManager().getLoot();
}
private static Engine engine(PackWorld world) {
return IrisPackWorld.of(world).engine();
}
/** The loot table keys of the platform, which do not change while a world runs. */
private static final class PlatformLootTables {
private volatile Set<String> keys;
private Set<String> keys() {
Set<String> known = keys;
if (known == null) {
known = PlacementLoot.platformTableKeys();
keys = known;
}
return known;
}
} }
} }
@@ -20,6 +20,8 @@ package art.arcane.iris.engine.loot;
import art.arcane.iris.builtin.loot.BlockDropSettings; import art.arcane.iris.builtin.loot.BlockDropSettings;
import art.arcane.iris.builtin.loot.LootSettings; import art.arcane.iris.builtin.loot.LootSettings;
import art.arcane.iris.builtin.loot.ObjectLoot;
import art.arcane.iris.builtin.loot.ObjectVanillaLoot;
import com.volmit.FeatureRegistry; import com.volmit.FeatureRegistry;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.ModuleInfo; import com.volmit.ModuleInfo;
@@ -49,6 +51,8 @@ public final class LootModule implements IrisModule {
public void register(FeatureRegistry registry) { public void register(FeatureRegistry registry) {
registry.registerSettings(LootSettings.class); registry.registerSettings(LootSettings.class);
registry.registerSettings(BlockDropSettings.class); registry.registerSettings(BlockDropSettings.class);
registry.registerHeldType(ObjectLoot.class);
registry.registerHeldType(ObjectVanillaLoot.class);
LootResources.kinds().forEach(registry::registerResourceKind); LootResources.kinds().forEach(registry::registerResourceKind);
registry.registerValidator(new LootValidator()); registry.registerValidator(new LootValidator());
registry.registerService(Loot.class, new LootGiving()); registry.registerService(Loot.class, new LootGiving());
@@ -19,8 +19,7 @@
package art.arcane.iris.engine.loot; package art.arcane.iris.engine.loot;
import art.arcane.iris.builtin.loot.LootTable; import art.arcane.iris.builtin.loot.LootTable;
import art.arcane.iris.core.loader.IrisData; import com.volmit.resource.PackResources;
import art.arcane.iris.core.modules.IrisPackResources;
import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKind; import com.volmit.resource.ResourceKind;
@@ -46,11 +45,10 @@ public final class LootResources {
return List.of(TABLES); return List.of(TABLES);
} }
public static LootTable table(IrisData data, String key) { public static LootTable table(PackResources resources, String key) {
if (key == null || key.isBlank()) { if (key == null || key.isBlank()) {
return null; return null;
} }
IrisPackResources resources = data.getPackResources();
try { try {
return resources.find(TABLES.key(resources.idOf(key))).orElse(null); return resources.find(TABLES.key(resources.idOf(key))).orElse(null);
} catch (IllegalStateException failedToLoad) { } catch (IllegalStateException failedToLoad) {
@@ -59,7 +57,7 @@ public final class LootResources {
} }
/** The key of every loot table of the pack, in key order. */ /** The key of every loot table of the pack, in key order. */
public static List<String> tableKeys(IrisData data) { public static List<String> tableKeys(PackResources resources) {
return data.getPackResources().ids(TABLES.type()).stream().map(ResourceId::path).toList(); return resources.ids(TABLES.type()).stream().map(ResourceId::path).toList();
} }
} }
@@ -18,14 +18,13 @@
package art.arcane.iris.engine.loot; package art.arcane.iris.engine.loot;
import art.arcane.iris.builtin.LiveWorld;
import art.arcane.iris.builtin.LiveWorld.Level;
import art.arcane.iris.builtin.loot.LootMode; import art.arcane.iris.builtin.loot.LootMode;
import art.arcane.iris.builtin.loot.LootSettings;
import art.arcane.iris.core.loader.IrisRegistrant;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.iris.builtin.loot.LootResolver;
import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.builtin.loot.LootSettings;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import com.volmit.world.PackWorld;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@@ -64,9 +63,9 @@ public final class LootTables {
return LootResolver.spatialOneIn(lootSeed, identity, entryIndex, x, y, z, rarity); return LootResolver.spatialOneIn(lootSeed, identity, entryIndex, x, y, z, rarity);
} }
/** The loot settings a dimension, region or biome declares; the defaults, which add nothing, when it declares none. */ /** The loot settings the level declares at the block; the defaults, which add nothing, when it declares none. */
public static LootSettings settingsOf(IrisRegistrant owner) { private static LootSettings settingsAt(LiveWorld live, Level level, int x, int relativeY, int z) {
return owner.getModuleSettings().find(LootSettings.class).orElseGet(LootSettings::new); return live.settings(LootSettings.class, level, x, relativeY, z).orElseGet(LootSettings::new);
} }
/** /**
@@ -76,7 +75,7 @@ public final class LootTables {
*/ */
public static <T> void resolveEnvironmentSources( public static <T> void resolveEnvironmentSources(
List<T> sources, List<T> sources,
Engine engine, PackWorld world,
RNG rng, RNG rng,
int x, int x,
int relativeY, int relativeY,
@@ -84,31 +83,25 @@ public final class LootTables {
boolean objectLootDefined, boolean objectLootDefined,
Function<String, T> mapper Function<String, T> mapper
) { ) {
IrisRegion region = engine.getComplex().getRegionStream().get(x, z); LiveWorld live = LiveWorld.of(world);
IrisBiome surfaceBiome = engine.getComplex().getTrueBiomeStream().get(x, z); boolean belowSurface = relativeY < live.terrainHeight(x, z);
double terrainHeight = engine.getComplex().getHeightStream().get(x, z); boolean distinctContextualBiome = belowSurface && !live.caveBiome(x, relativeY, z).equals(live.surfaceBiome(x, z));
IrisBiome contextualBiome = relativeY < terrainHeight
? engine.getCaveBiome(x, relativeY, z)
: surfaceBiome;
if (contextualBiome == null) {
contextualBiome = surfaceBiome;
}
LootSettings dimensionLoot = settingsOf(engine.getDimension()); LootSettings dimensionLoot = settingsAt(live, Level.DIMENSION, x, relativeY, z);
LootSettings regionLoot = settingsOf(region); LootSettings regionLoot = settingsAt(live, Level.REGION, x, relativeY, z);
LootSettings surfaceLoot = settingsOf(surfaceBiome); LootSettings surfaceLoot = settingsAt(live, Level.SURFACE_BIOME, x, relativeY, z);
boolean distinctContextualBiome = !sameBiome(surfaceBiome, contextualBiome);
double multiplier = dimensionLoot.multiplier() * regionLoot.multiplier() * surfaceLoot.multiplier(); double multiplier = dimensionLoot.multiplier() * regionLoot.multiplier() * surfaceLoot.multiplier();
if (distinctContextualBiome) { LootSettings contextualLoot = distinctContextualBiome ? settingsAt(live, Level.CAVE_BIOME, x, relativeY, z) : null;
multiplier *= settingsOf(contextualBiome).multiplier(); if (contextualLoot != null) {
multiplier *= contextualLoot.multiplier();
} }
boolean fallback = !objectLootDefined; boolean fallback = !objectLootDefined;
injectReference(sources, dimensionLoot, engine, mapper, fallback); injectReference(sources, dimensionLoot, world, mapper, fallback);
injectReference(sources, regionLoot, engine, mapper, fallback); injectReference(sources, regionLoot, world, mapper, fallback);
injectReference(sources, surfaceLoot, engine, mapper, fallback); injectReference(sources, surfaceLoot, world, mapper, fallback);
if (distinctContextualBiome) { if (contextualLoot != null) {
injectReference(sources, settingsOf(contextualBiome), engine, mapper, fallback); injectReference(sources, contextualLoot, world, mapper, fallback);
} }
LootResolver.scaleSources(sources, multiplier, rng); LootResolver.scaleSources(sources, multiplier, rng);
} }
@@ -133,25 +126,15 @@ public final class LootTables {
sources.addAll(additions); sources.addAll(additions);
} }
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());
}
private static <T> void injectReference( private static <T> void injectReference(
List<T> sources, List<T> sources,
LootSettings loot, LootSettings loot,
Engine engine, PackWorld world,
Function<String, T> mapper, Function<String, T> mapper,
boolean fallback boolean fallback
) { ) {
List<T> additions = loot.tables().stream() List<T> additions = loot.tables().stream()
.filter(key -> LootResources.table(engine.getData(), key) != null) .filter(key -> LootResources.table(world.resources(), key) != null)
.map(mapper) .map(mapper)
.filter(Objects::nonNull) .filter(Objects::nonNull)
.toList(); .toList();
@@ -18,269 +18,210 @@
package art.arcane.iris.engine.loot; package art.arcane.iris.engine.loot;
import art.arcane.iris.core.modules.IrisValidationContext; import art.arcane.iris.builtin.loot.LootEnchantment;
import art.arcane.iris.core.pack.PackIntegerChecks;
import art.arcane.iris.core.pack.PackValidationIo;
import art.arcane.iris.builtin.loot.LootEntry; import art.arcane.iris.builtin.loot.LootEntry;
import art.arcane.iris.builtin.loot.LootMode;
import art.arcane.iris.builtin.loot.LootSettings; import art.arcane.iris.builtin.loot.LootSettings;
import art.arcane.iris.builtin.loot.LootTable; import art.arcane.iris.builtin.loot.LootTable;
import art.arcane.volmlib.util.json.JSONArray; import com.volmit.FeatureAttachment.Target;
import art.arcane.volmlib.util.json.JSONObject; import com.volmit.config.FeatureSettings.Entry;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.validation.Problem; import com.volmit.validation.Problem;
import com.volmit.validation.Subject; import com.volmit.validation.Subject;
import com.volmit.validation.ValidationContext; import com.volmit.validation.ValidationContext;
import com.volmit.validation.Validator; import com.volmit.validation.Validator;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.function.BiFunction;
/** /**
* Module {@code iris:loot}'s check of a pack: every loot table has sane picks, tries and entries, and every loot * Module {@code iris:loot}'s check of a pack: every loot table has sane picks, tries and entries, and every loot
* reference of a dimension, region or biome names a table the pack has. The files are read as written, like the pack * reference of a dimension, region or biome names a table the pack has. It checks the tables and settings as they
* validator's other file checks, so a malformed table is reported rather than failing the load. * decoded; a file that is not valid JSON, or holds a value of the wrong type, is reported by the load that reads it.
*/ */
public final class LootValidator implements Validator { public final class LootValidator implements Validator {
private static final List<String> LOOT_HOST_FOLDERS = List.of("dimensions", "regions", "biomes");
private static final String JSON_EXTENSION = ".json"; private static final String JSON_EXTENSION = ".json";
private static final String LEVEL_FOLDER_SEPARATOR = "/";
@Override @Override
public void validate(ValidationContext pack) { public void validate(ValidationContext pack) {
check(IrisValidationContext.of(pack).data().getDataFolder()).forEach(pack::report); checkTables(pack.resources()).forEach(pack::report);
checkReferences(pack).forEach(pack::report);
} }
/** What is wrong with the loot tables and loot references of the pack in {@code packFolder}. */ private static List<Problem> checkTables(PackResources resources) {
public static List<Problem> check(File packFolder) {
List<Problem> problems = new ArrayList<>(); List<Problem> problems = new ArrayList<>();
if (packFolder == null || !packFolder.isDirectory()) { for (ResourceId id : resources.ids(LootTable.class)) {
return problems; String lootKey = id.path();
}
File lootFolder = new File(packFolder, LootResources.TABLES.folder());
Set<String> lootKeys = keysOf(lootFolder);
checkTables(lootFolder, problems);
for (String folderName : LOOT_HOST_FOLDERS) {
checkReferences(new File(packFolder, folderName), folderName, lootKeys, problems);
}
return problems;
}
private static void checkTables(File lootFolder, List<Problem> problems) {
if (!lootFolder.isDirectory()) {
return;
}
List<File> lootFiles = PackValidationIo.listJsonRecursive(lootFolder);
lootFiles.sort(Comparator.comparing(File::getPath));
for (File lootFile : lootFiles) {
String lootKey = PackValidationIo.deriveKey(lootFolder, lootFile);
List<String> errors = new ArrayList<>(); List<String> errors = new ArrayList<>();
JSONObject table = readTable(lootFile, lootKey, errors); LootTable table = readTable(resources, id, lootKey, errors);
if (table != null) { if (table != null) {
validateLootTable(lootKey, table, errors); validateLootTable(lootKey, table, errors);
} }
report(problems, Problem::error, Subject.file(LootResources.TABLES.folder() + "/" + lootKey + JSON_EXTENSION), errors); report(problems, Problem::error, Subject.file(LootResources.TABLES.folder() + "/" + lootKey + JSON_EXTENSION), errors);
} }
return problems;
} }
private static void checkReferences(File resourceFolder, String folderName, Set<String> lootKeys, List<Problem> problems) { private static List<Problem> checkReferences(ValidationContext pack) {
if (!resourceFolder.isDirectory()) { Set<ResourceId> lootIds = Set.copyOf(pack.resources().ids(LootTable.class));
return; List<Problem> problems = new ArrayList<>();
} List<Entry<LootSettings>> declared = new ArrayList<>(pack.settings().declared(LootSettings.class));
List<File> resourceFiles = PackValidationIo.listJsonRecursive(resourceFolder); declared.sort(Comparator.comparing(Entry<LootSettings>::level).thenComparing(Entry::source));
resourceFiles.sort(Comparator.comparing(File::getPath)); for (Entry<LootSettings> entry : declared) {
for (File resourceFile : resourceFiles) { String resourceKey = keyOf(entry);
JSONObject resource = PackValidationIo.readJson(resourceFile);
if (resource == null || !resource.has("loot")) {
continue;
}
String resourceKey = PackValidationIo.deriveKey(resourceFolder, resourceFile);
List<String> errors = new ArrayList<>(); List<String> errors = new ArrayList<>();
List<String> warnings = new ArrayList<>(); List<String> warnings = new ArrayList<>();
validateLootReference(hostType(folderName), resourceKey, resource.opt("loot"), lootKeys, errors, warnings); validateLootReference(pack.resources(), hostType(entry.level()), resourceKey, entry.value(), lootIds, errors, warnings);
Subject subject = Subject.file(folderName + "/" + resourceKey + JSON_EXTENSION); Subject subject = Subject.file(folderOf(entry.level()) + "/" + resourceKey + JSON_EXTENSION);
report(problems, Problem::error, subject, errors); report(problems, Problem::error, subject, errors);
report(problems, Problem::warning, subject, warnings); report(problems, Problem::warning, subject, warnings);
} }
return problems;
} }
private static void report(List<Problem> problems, java.util.function.BiFunction<Subject, String, Problem> severity, private static void report(List<Problem> problems, BiFunction<Subject, String, Problem> severity,
Subject subject, List<String> messages) { Subject subject, List<String> messages) {
for (String message : messages) { for (String message : messages) {
problems.add(severity.apply(subject, message)); problems.add(severity.apply(subject, message));
} }
} }
private static Set<String> keysOf(File folder) { private static LootTable readTable(PackResources resources, ResourceId id, String key, List<String> errors) {
Set<String> keys = new HashSet<>();
if (!folder.isDirectory()) {
return keys;
}
for (File file : PackValidationIo.listJsonRecursive(folder)) {
String key = PackValidationIo.deriveKey(folder, file);
if (key != null && !key.isBlank()) {
keys.add(key);
}
}
return keys;
}
private static JSONObject readTable(File file, String key, List<String> errors) {
try { try {
return new JSONObject(Files.readString(file.toPath(), StandardCharsets.UTF_8)); return resources.find(LootResources.TABLES.key(id)).orElse(null);
} catch (IOException | RuntimeException e) { } catch (IllegalStateException failedToLoad) {
String reason = e.getMessage(); errors.add("Loot table '" + key + "' cannot be read; the log says what is wrong with the file.");
if (reason == null || reason.isBlank()) {
reason = e.getClass().getSimpleName();
}
errors.add("Loot table '" + key + "' has invalid JSON: " + reason);
return null; return null;
} }
} }
private static String hostType(String folderName) { /** The key of the dimension, region or biome that declared {@code entry}: its source id is {@code <pack>:<level>/<key>}. */
return switch (folderName) { private static String keyOf(Entry<LootSettings> entry) {
case "dimensions" -> "Dimension"; String path = entry.source().path();
case "regions" -> "Region"; return path.substring(path.indexOf(LEVEL_FOLDER_SEPARATOR) + 1);
case "biomes" -> "Biome"; }
default -> "Resource";
private static String hostType(Target level) {
return switch (level) {
case DIMENSION -> "Dimension";
case REGION -> "Region";
case BIOME -> "Biome";
case OBJECT_PLACEMENT -> "Resource";
}; };
} }
private static void validateLootTable(String lootKey, JSONObject table, List<String> blockingErrors) { private static String folderOf(Target level) {
String path = "Loot table '" + lootKey + "'"; return switch (level) {
Integer rarity = PackIntegerChecks.integerField(table, "rarity", 1, path, blockingErrors); case DIMENSION -> "dimensions";
Integer minimumPicked = PackIntegerChecks.integerField(table, "minPicked", 1, path, blockingErrors); case REGION -> "regions";
Integer maximumPicked = PackIntegerChecks.integerField(table, "maxPicked", 5, path, blockingErrors); case BIOME -> "biomes";
Integer maximumTries = PackIntegerChecks.integerField(table, "maxTries", 10, path, blockingErrors); case OBJECT_PLACEMENT -> "placements";
PackIntegerChecks.requireMinimum(path + ".rarity", rarity, 1, blockingErrors); };
PackIntegerChecks.requireMinimum(path + ".minPicked", minimumPicked, 0, blockingErrors); }
PackIntegerChecks.requireMinimum(path + ".maxPicked", maximumPicked, 1, blockingErrors);
PackIntegerChecks.requireMinimum(path + ".maxTries", maximumTries, 1, blockingErrors);
PackIntegerChecks.requireMaximum(path + ".minPicked", minimumPicked, LootTable.MAX_PICKED, blockingErrors);
PackIntegerChecks.requireMaximum(path + ".maxPicked", maximumPicked, LootTable.MAX_PICKED, blockingErrors);
PackIntegerChecks.requireMaximum(path + ".maxTries", maximumTries, LootTable.MAX_TRIES, blockingErrors);
PackIntegerChecks.requireOrdered(path + ".minPicked", minimumPicked, path + ".maxPicked", maximumPicked, blockingErrors);
JSONArray entries = table.optJSONArray("loot"); private static void validateLootTable(String lootKey, LootTable table, List<String> blockingErrors) {
if (entries == null || entries.length() == 0) { String path = "Loot table '" + lootKey + "'";
requireMinimum(path + ".rarity", table.rarity(), 1, blockingErrors);
requireMinimum(path + ".minPicked", table.minPicked(), 0, blockingErrors);
requireMinimum(path + ".maxPicked", table.maxPicked(), 1, blockingErrors);
requireMinimum(path + ".maxTries", table.maxTries(), 1, blockingErrors);
requireMaximum(path + ".minPicked", table.minPicked(), LootTable.MAX_PICKED, blockingErrors);
requireMaximum(path + ".maxPicked", table.maxPicked(), LootTable.MAX_PICKED, blockingErrors);
requireMaximum(path + ".maxTries", table.maxTries(), LootTable.MAX_TRIES, blockingErrors);
requireOrdered(path + ".minPicked", table.minPicked(), path + ".maxPicked", table.maxPicked(), blockingErrors);
List<LootEntry> entries = table.loot();
if (entries.isEmpty()) {
blockingErrors.add(path + ".loot must be a non-empty array."); blockingErrors.add(path + ".loot must be a non-empty array.");
return; return;
} }
for (int entryIndex = 0; entryIndex < entries.length(); entryIndex++) { for (int entryIndex = 0; entryIndex < entries.size(); entryIndex++) {
JSONObject entry = entries.optJSONObject(entryIndex); validateLootEntry(path + ".loot[" + entryIndex + "]", entries.get(entryIndex), blockingErrors);
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 = PackIntegerChecks.integerField(entry, "rarity", 1, entryPath, blockingErrors);
Integer minimumAmount = PackIntegerChecks.integerField(entry, "minAmount", 1, entryPath, blockingErrors);
Integer maximumAmount = PackIntegerChecks.integerField(entry, "maxAmount", 1, entryPath, blockingErrors);
PackIntegerChecks.requireMinimum(entryPath + ".rarity", entryRarity, 1, blockingErrors);
PackIntegerChecks.requireMinimum(entryPath + ".minAmount", minimumAmount, 1, blockingErrors);
PackIntegerChecks.requireMinimum(entryPath + ".maxAmount", maximumAmount, 1, blockingErrors);
PackIntegerChecks.requireMaximum(entryPath + ".minAmount", minimumAmount, LootEntry.MAX_AMOUNT, blockingErrors);
PackIntegerChecks.requireMaximum(entryPath + ".maxAmount", maximumAmount, LootEntry.MAX_AMOUNT, blockingErrors);
PackIntegerChecks.requireOrdered(entryPath + ".minAmount", minimumAmount,
entryPath + ".maxAmount", maximumAmount, blockingErrors);
validateLootEnchantments(entryPath, entry.opt("enchantments"), blockingErrors);
} }
} }
private static void validateLootEnchantments(String entryPath, Object rawEnchantments, private static void validateLootEntry(String entryPath, LootEntry entry, List<String> blockingErrors) {
List<String> blockingErrors) { if (entry == null) {
if (rawEnchantments == null || rawEnchantments == JSONObject.NULL) { blockingErrors.add(entryPath + " must be an object.");
return; return;
} }
if (!(rawEnchantments instanceof JSONArray enchantments)) { if (entry.type().trim().isEmpty()) {
blockingErrors.add(entryPath + ".enchantments must be an array."); blockingErrors.add(entryPath + ".type must not be blank.");
return;
} }
for (int enchantmentIndex = 0; enchantmentIndex < enchantments.length(); enchantmentIndex++) { requireMinimum(entryPath + ".rarity", entry.rarity(), 1, blockingErrors);
JSONObject enchantment = enchantments.optJSONObject(enchantmentIndex); requireMinimum(entryPath + ".minAmount", entry.minAmount(), 1, blockingErrors);
String enchantmentPath = entryPath + ".enchantments[" + enchantmentIndex + "]"; requireMinimum(entryPath + ".maxAmount", entry.maxAmount(), 1, blockingErrors);
if (enchantment == null) { requireMaximum(entryPath + ".minAmount", entry.minAmount(), LootEntry.MAX_AMOUNT, blockingErrors);
blockingErrors.add(enchantmentPath + " must be an object."); requireMaximum(entryPath + ".maxAmount", entry.maxAmount(), LootEntry.MAX_AMOUNT, blockingErrors);
continue; requireOrdered(entryPath + ".minAmount", entry.minAmount(), entryPath + ".maxAmount", entry.maxAmount(), blockingErrors);
}
if (enchantment.optString("enchantment", "").isBlank()) { List<LootEnchantment> enchantments = entry.enchantments();
blockingErrors.add(enchantmentPath + ".enchantment must not be blank."); for (int enchantmentIndex = 0; enchantmentIndex < enchantments.size(); enchantmentIndex++) {
} validateEnchantment(entryPath + ".enchantments[" + enchantmentIndex + "]", enchantments.get(enchantmentIndex), blockingErrors);
Integer minimumLevel = PackIntegerChecks.integerField(enchantment, "minLevel", 1, enchantmentPath, blockingErrors);
Integer maximumLevel = PackIntegerChecks.integerField(enchantment, "maxLevel", 1, enchantmentPath, blockingErrors);
PackIntegerChecks.requireMinimum(enchantmentPath + ".minLevel", minimumLevel, 1, blockingErrors);
PackIntegerChecks.requireMinimum(enchantmentPath + ".maxLevel", maximumLevel, 1, blockingErrors);
PackIntegerChecks.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, private static void validateEnchantment(String enchantmentPath, LootEnchantment enchantment, List<String> blockingErrors) {
Set<String> lootKeys, List<String> blockingErrors, List<String> warnings) { if (enchantment == null) {
blockingErrors.add(enchantmentPath + " must be an object.");
return;
}
String name = enchantment.enchantment();
if (name == null || name.isBlank()) {
blockingErrors.add(enchantmentPath + ".enchantment must not be blank.");
}
requireMinimum(enchantmentPath + ".minLevel", enchantment.minLevel(), 1, blockingErrors);
requireMinimum(enchantmentPath + ".maxLevel", enchantment.maxLevel(), 1, blockingErrors);
requireOrdered(enchantmentPath + ".minLevel", enchantment.minLevel(),
enchantmentPath + ".maxLevel", enchantment.maxLevel(), blockingErrors);
double chance = enchantment.chance();
if (!Double.isFinite(chance) || chance < 0D || chance > 1D) {
blockingErrors.add(enchantmentPath + ".chance must be a finite number from 0 to 1.");
}
}
private static void validateLootReference(PackResources resources, String resourceType, String resourceKey, LootSettings reference,
Set<ResourceId> lootIds, List<String> blockingErrors, List<String> warnings) {
String path = resourceType + " '" + resourceKey + "'.loot"; String path = resourceType + " '" + resourceKey + "'.loot";
if (!(rawLoot instanceof JSONObject reference)) { double multiplier = reference.multiplier();
blockingErrors.add(path + " must be an object."); if (!Double.isFinite(multiplier) || multiplier < 0D || multiplier > LootSettings.MAX_MULTIPLIER) {
return; blockingErrors.add(path + ".multiplier must be a finite number from 0 to " + (int) LootSettings.MAX_MULTIPLIER + ".");
} }
boolean clearMode = false; List<String> tables = reference.tables();
if (reference.has("mode")) { if (reference.mode() == LootMode.CLEAR && !tables.isEmpty()) {
Object rawMode = reference.opt("mode"); warnings.add(path + " uses mode CLEAR and lists " + tables.size()
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() > LootSettings.MAX_MULTIPLIER) {
blockingErrors.add(path + ".multiplier must be a finite number from 0 to "
+ (int) LootSettings.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."); + " 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++) { for (int tableIndex = 0; tableIndex < tables.size(); tableIndex++) {
Object rawTableKey = tables.opt(tableIndex); String tableKey = tables.get(tableIndex);
if (!(rawTableKey instanceof String tableKey) || tableKey.isBlank()) { if (tableKey == null || tableKey.isBlank()) {
blockingErrors.add(path + ".tables[" + tableIndex + "] must name a loot table."); blockingErrors.add(path + ".tables[" + tableIndex + "] must name a loot table.");
} else if (!lootKeys.contains(tableKey)) { } else if (!lootIds.contains(resources.idOf(tableKey))) {
blockingErrors.add(path + ".tables[" + tableIndex blockingErrors.add(path + ".tables[" + tableIndex + "] references missing loot table '" + tableKey + "'.");
+ "] references missing loot table '" + tableKey + "'.");
} }
} }
} }
private static void requireMinimum(String fieldPath, int value, int minimum, List<String> blockingErrors) {
if (value < minimum) {
blockingErrors.add(fieldPath + " must be at least " + minimum + ".");
}
}
private static void requireMaximum(String fieldPath, int value, int maximum, List<String> blockingErrors) {
if (value > maximum) {
blockingErrors.add(fieldPath + " must be at most " + maximum + ".");
}
}
private static void requireOrdered(String minimumPath, int minimum, String maximumPath, int maximum, List<String> blockingErrors) {
if (minimum > maximum) {
blockingErrors.add(minimumPath + " must not exceed " + maximumPath + ".");
}
}
} }
@@ -18,13 +18,13 @@
package art.arcane.iris.engine.loot; package art.arcane.iris.engine.loot;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.iris.builtin.loot.LootResolver;
import art.arcane.iris.engine.object.loot.IObjectLoot; import art.arcane.iris.builtin.loot.ObjectLootEntry;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import com.volmit.ModuleLog; import com.volmit.ModuleLog;
import com.volmit.block.BlockSpec;
import com.volmit.block.BlockState;
import com.volmit.resource.PackResources;
import com.volmit.service.Loot; import com.volmit.service.Loot;
import java.util.ArrayList; import java.util.ArrayList;
@@ -43,32 +43,27 @@ final class PlacementLoot {
private static final char NAMESPACE_SEPARATOR = ':'; private static final char NAMESPACE_SEPARATOR = ':';
private static final char PROPERTIES_START = '['; private static final char PROPERTIES_START = '[';
private final IrisData data; private final PackResources resources;
private final Supplier<Set<String>> platformTables; private final Supplier<Set<String>> platformTables;
private final long lootSeed; private final long lootSeed;
private final ModuleLog log; private final ModuleLog log;
/** @param platformTables the keys of the loot tables the platform has, asked for only when a placement names one */ /** @param platformTables the keys of the loot tables the platform has, asked for only when a placement names one */
PlacementLoot(IrisData data, Supplier<Set<String>> platformTables, long lootSeed, ModuleLog log) { PlacementLoot(PackResources resources, Supplier<Set<String>> platformTables, long lootSeed, ModuleLog log) {
this.data = data; this.resources = resources;
this.platformTables = platformTables; this.platformTables = platformTables;
this.lootSeed = lootSeed; this.lootSeed = lootSeed;
this.log = log; this.log = log;
} }
/** The platform's loot table keys, which a placement may name, in the form a placement names them. */
static Set<String> platformTableKeys() {
return Set.copyOf(IrisPlatforms.get().registries().lootTableKeys());
}
/** /**
* The table a placement, whose platform tables are {@code platformLoot} and whose pack tables are {@code packLoot}, * The table a placement, whose platform tables are {@code platformLoot} and whose pack tables are {@code packLoot},
* gives {@code container}, a storage chest, at the spot {@code x}, {@code worldY}, {@code z}; null when it gives * gives {@code container}, a storage chest, at the spot {@code x}, {@code worldY}, {@code z}; null when it gives
* it none. * it none.
*/ */
Loot.Source pick(List<? extends IObjectLoot> platformLoot, List<? extends IObjectLoot> packLoot, PlatformBlockState container, Loot.Source pick(List<? extends ObjectLootEntry> platformLoot, List<? extends ObjectLootEntry> packLoot, BlockState container,
RNG rng, int x, int worldY, int z) { RNG rng, int x, int worldY, int z) {
Candidates candidates = new Candidates(container); Candidates candidates = new Candidates(resources.blocks().resolve(container));
add(candidates, platformLoot, name -> platformSource(name, x, worldY, z)); add(candidates, platformLoot, name -> platformSource(name, x, worldY, z));
add(candidates, packLoot, this::packSource); add(candidates, packLoot, this::packSource);
List<Candidate> pool = candidates.pool(); List<Candidate> pool = candidates.pool();
@@ -76,22 +71,22 @@ final class PlacementLoot {
return picked == null ? null : picked.source(); return picked == null ? null : picked.source();
} }
private void add(Candidates candidates, List<? extends IObjectLoot> entries, Function<String, Loot.Source> sourceOf) { private void add(Candidates candidates, List<? extends ObjectLootEntry> entries, Function<String, Loot.Source> sourceOf) {
for (IObjectLoot entry : entries) { for (ObjectLootEntry entry : entries) {
if (entry == null || entry.getWeight() <= 0) { if (entry == null || entry.weight() <= 0) {
continue; continue;
} }
Loot.Source source = sourceOf.apply(entry.getName()); Loot.Source source = sourceOf.apply(entry.name());
if (source == null) { if (source == null) {
log.warn("Couldn't find loot table " + entry.getName()); log.warn("Couldn't find loot table " + entry.name());
continue; continue;
} }
candidates.add(entry, data, new Candidate(source, entry.getWeight())); candidates.add(entry, resources, new Candidate(source, entry.weight()));
} }
} }
private Loot.Source packSource(String key) { private Loot.Source packSource(String key) {
return LootResources.table(data, key) == null ? null : new Loot.Table(key); return LootResources.table(resources, key) == null ? null : new Loot.Table(key);
} }
private Loot.Source platformSource(String name, int x, int worldY, int z) { private Loot.Source platformSource(String name, int x, int worldY, int z) {
@@ -121,21 +116,22 @@ final class PlacementLoot {
private final List<Candidate> basic = new ArrayList<>(); private final List<Candidate> basic = new ArrayList<>();
private final List<Candidate> global = new ArrayList<>(); private final List<Candidate> global = new ArrayList<>();
private Candidates(PlatformBlockState container) { private Candidates(BlockState container) {
this.containerKey = container.key(); this.containerKey = container.key();
this.containerMaterial = materialOf(containerKey); this.containerMaterial = materialOf(containerKey);
} }
void add(IObjectLoot entry, IrisData data, Candidate candidate) { void add(ObjectLootEntry entry, PackResources resources, Candidate candidate) {
List<PlatformBlockState> filter = entry.getFilter(data); List<BlockSpec> filter = entry.filter();
if (filter.isEmpty()) { if (filter.isEmpty()) {
global.add(candidate); global.add(candidate);
return; return;
} }
for (PlatformBlockState filterState : filter) { for (BlockSpec filterSpec : filter) {
if (entry.isExact() && filterState.key().equals(containerKey)) { String filterKey = resources.blocks().resolve(filterSpec).key();
if (entry.exact() && filterKey.equals(containerKey)) {
exact.add(candidate); exact.add(candidate);
} else if (!entry.isExact() && materialOf(filterState.key()).equals(containerMaterial)) { } else if (!entry.exact() && materialOf(filterKey).equals(containerMaterial)) {
basic.add(candidate); basic.add(candidate);
} }
} }
@@ -19,8 +19,6 @@
package art.arcane.iris.engine.loot; package art.arcane.iris.engine.loot;
import art.arcane.iris.builtin.loot.BlockDrop; import art.arcane.iris.builtin.loot.BlockDrop;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.PlatformBlockState;
import com.volmit.block.BlockRegistry; import com.volmit.block.BlockRegistry;
import com.volmit.block.BlockSpec; import com.volmit.block.BlockSpec;
@@ -45,10 +43,7 @@ final class ResolvedBlockDrop {
static ResolvedBlockDrop of(BlockDrop drop, BlockRegistry blocks) { static ResolvedBlockDrop of(BlockDrop drop, BlockRegistry blocks) {
Set<String> keys = new LinkedHashSet<>(); Set<String> keys = new LinkedHashSet<>();
for (BlockSpec spec : drop.blocks()) { for (BlockSpec spec : drop.blocks()) {
PlatformBlockState state = IrisPlatforms.get().registries().block(blocks.resolve(spec).key()); keys.add(comparable(blocks.resolve(spec).key(), drop.exactBlocks()));
if (state != null) {
keys.add(comparable(state.key(), drop.exactBlocks()));
}
} }
return new ResolvedBlockDrop(drop, keys); return new ResolvedBlockDrop(drop, keys);
} }
@@ -93,23 +93,5 @@ public interface IRare {
return v instanceof IRare ? Math.max(1, ((IRare) v).getRarity()) : 1; return v instanceof IRare ? Math.max(1, ((IRare) v).getRarity()) : 1;
} }
/**
* Expands a candidate list into a rarity-weighted list: each entry appears totalRarity/rarity
* times, so picking uniformly from the result applies rarity exactly once. Both the Bukkit and
* modded entity spawners select through this expansion; rarity must never be applied a second
* time per spawn position.
*/
static <T> KList<T> expandWeighted(List<T> possibilities) {
KList<T> rarityTypes = new KList<>();
int totalRarity = 0;
for (T i : possibilities) {
totalRarity += get(i);
}
for (T i : possibilities) {
rarityTypes.addMultiple(i, totalRarity / get(i));
}
return rarityTypes;
}
int getRarity(); int getRarity();
} }
@@ -18,14 +18,13 @@
package art.arcane.iris.engine.spawn; package art.arcane.iris.engine.spawn;
import art.arcane.iris.builtin.LiveWorld;
import art.arcane.iris.builtin.LiveWorld.Level;
import art.arcane.iris.builtin.LiveWorld.Sky;
import art.arcane.iris.builtin.spawn.AmbientEffect; import art.arcane.iris.builtin.spawn.AmbientEffect;
import art.arcane.iris.builtin.spawn.EffectCommands; import art.arcane.iris.builtin.spawn.EffectCommands;
import art.arcane.iris.builtin.spawn.EffectSettings; import art.arcane.iris.builtin.spawn.EffectSettings;
import art.arcane.iris.builtin.spawn.SpawnCommand; import art.arcane.iris.builtin.spawn.SpawnCommand;
import art.arcane.iris.core.loader.IrisRegistrant;
import art.arcane.iris.core.modules.IrisPackWorld;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.spi.PlatformWorld;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import com.volmit.entity.EntitySpec; import com.volmit.entity.EntitySpec;
import com.volmit.service.AmbientEffects; import com.volmit.service.AmbientEffects;
@@ -34,6 +33,7 @@ import com.volmit.world.PackWorld;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional;
/** /**
* How {@code iris:spawn} plays the ambient effects of regions and biomes: the region's effects, then the biome's, each * How {@code iris:spawn} plays the ambient effects of regions and biomes: the region's effects, then the biome's, each
@@ -42,32 +42,32 @@ import java.util.List;
public final class AmbientEffecting implements AmbientEffects { public final class AmbientEffecting implements AmbientEffects {
@Override @Override
public List<Effect> due(PackWorld world, BlockPosition at) { public List<Effect> due(PackWorld world, BlockPosition at) {
Engine engine = IrisPackWorld.of(world).engine(); LiveWorld live = LiveWorld.of(world);
EffectTimers timers = world.state(EffectTimers.class, ignored -> new EffectTimers()); EffectTimers timers = world.state(EffectTimers.class, ignored -> new EffectTimers());
PlatformWorld platformWorld = engine.getWorld().platformWorld(); Optional<Sky> sky = live.sky();
List<Effect> due = new ArrayList<>(); List<Effect> due = new ArrayList<>();
addDue(due, effectsOf(engine.getRegion(at.x(), at.z())), timers, platformWorld); addDue(due, effectsOf(live, Level.REGION, at), timers, sky);
addDue(due, effectsOf(engine.getBiome(at.x(), at.y(), at.z())), timers, platformWorld); addDue(due, effectsOf(live, Level.BIOME, at), timers, sky);
return due; return due;
} }
private static List<AmbientEffect> effectsOf(IrisRegistrant owner) { private static List<AmbientEffect> effectsOf(LiveWorld live, Level level, BlockPosition at) {
return owner.getModuleSettings().find(EffectSettings.class).map(EffectSettings::effects).orElse(List.of()); return live.settings(EffectSettings.class, level, at.x(), at.y(), at.z()).map(EffectSettings::effects).orElse(List.of());
} }
private static void addDue(List<Effect> due, List<AmbientEffect> effects, EffectTimers timers, PlatformWorld world) { private static void addDue(List<Effect> due, List<AmbientEffect> effects, EffectTimers timers, Optional<Sky> sky) {
for (AmbientEffect effect : effects) { for (AmbientEffect effect : effects) {
if (timers.shouldPlayNow(effect)) { if (timers.shouldPlayNow(effect)) {
due.add(play(effect, world)); due.add(play(effect, sky));
} }
} }
} }
private static Effect play(AmbientEffect effect, PlatformWorld world) { private static Effect play(AmbientEffect effect, Optional<Sky> sky) {
Sound sound = effect.sound() == null ? null : soundOf(effect); Sound sound = effect.sound() == null ? null : soundOf(effect);
Particles particles = effect.particleEffect() == null ? null : particlesOf(effect); Particles particles = effect.particleEffect() == null ? null : particlesOf(effect);
return new Effect(sound, particles, commandsOf(effect.commandRegistry(), world), potionOf(effect)); return new Effect(sound, particles, commandsOf(effect.commandRegistry(), sky), potionOf(effect));
} }
private static Sound soundOf(AmbientEffect effect) { private static Sound soundOf(AmbientEffect effect) {
@@ -92,7 +92,7 @@ public final class AmbientEffecting implements AmbientEffects {
altX, altY, altZ, effect.extra()); altX, altY, altZ, effect.extra());
} }
private static List<Command> commandsOf(EffectCommands registry, PlatformWorld world) { private static List<Command> commandsOf(EffectCommands registry, Optional<Sky> sky) {
List<Command> commands = new ArrayList<>(); List<Command> commands = new ArrayList<>();
if (registry == null) { if (registry == null) {
return commands; return commands;
@@ -102,7 +102,7 @@ public final class AmbientEffecting implements AmbientEffects {
double offsetY = commandOffset(registry.commandOffsetY(), registry.commandRandomAltY()); double offsetY = commandOffset(registry.commandOffsetY(), registry.commandRandomAltY());
double offsetZ = commandOffset(registry.commandOffsetZ(), registry.commandRandomAltZ()); double offsetZ = commandOffset(registry.commandOffsetZ(), registry.commandRandomAltZ());
for (SpawnCommand command : registry.rawCommands()) { for (SpawnCommand command : registry.rawCommands()) {
if (SpawnConditions.allow(command.timeBlock(), command.weather(), world)) { if (sky.isPresent() && SpawnConditions.allow(command.timeBlock(), command.weather(), sky.get())) {
commands.add(new Command(new EntitySpec.Command(command.commands(), command.delay(), command.repeat(), commands.add(new Command(new EntitySpec.Command(command.commands(), command.delay(), command.repeat(),
command.repeatDelay()), offsetX, offsetY, offsetZ)); command.repeatDelay()), offsetX, offsetY, offsetZ));
} }
@@ -18,6 +18,7 @@
package art.arcane.iris.engine.spawn; package art.arcane.iris.engine.spawn;
import art.arcane.iris.builtin.LiveWorld.Sky;
import art.arcane.iris.builtin.loot.ItemAttributeModifier; import art.arcane.iris.builtin.loot.ItemAttributeModifier;
import art.arcane.iris.builtin.loot.LootEntry; import art.arcane.iris.builtin.loot.LootEntry;
import art.arcane.iris.builtin.spawn.AmbientEffect; import art.arcane.iris.builtin.spawn.AmbientEffect;
@@ -25,7 +26,6 @@ import art.arcane.iris.builtin.spawn.EntityDefinition;
import art.arcane.iris.builtin.spawn.SpawnCommand; import art.arcane.iris.builtin.spawn.SpawnCommand;
import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.iris.builtin.loot.LootResolver;
import art.arcane.iris.engine.loot.LootItems; import art.arcane.iris.engine.loot.LootItems;
import art.arcane.iris.spi.PlatformWorld;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import com.volmit.entity.EntitySpec; import com.volmit.entity.EntitySpec;
import com.volmit.item.ItemAttribute; import com.volmit.item.ItemAttribute;
@@ -33,6 +33,7 @@ import com.volmit.item.ItemDrop;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional;
/** /**
* Turns an entity of the pack into the {@link EntitySpec} the host spawns, making every random choice in the order Iris * Turns an entity of the pack into the {@link EntitySpec} the host spawns, making every random choice in the order Iris
@@ -43,13 +44,13 @@ final class EntityResolution {
private static final long LEASH_HOLDER_STREAM = 234548L; private static final long LEASH_HOLDER_STREAM = 234548L;
private final LootItems items; private final LootItems items;
private final PlatformWorld world; private final Optional<Sky> sky;
private final EffectTimers timers; private final EffectTimers timers;
/** @param world the world the entity appears in, whose time and weather decide which of its commands run */ /** @param sky the sky of the world the entity appears in, whose time and weather decide which of its commands run; none while the world has no platform world */
EntityResolution(LootItems items, PlatformWorld world, EffectTimers timers) { EntityResolution(LootItems items, Optional<Sky> sky, EffectTimers timers) {
this.items = items; this.items = items;
this.world = world; this.sky = sky;
this.timers = timers; this.timers = timers;
} }
@@ -121,7 +122,7 @@ final class EntityResolution {
private List<EntitySpec.Command> commandsOf(EntityDefinition entity) { private List<EntitySpec.Command> commandsOf(EntityDefinition entity) {
List<EntitySpec.Command> commands = new ArrayList<>(); List<EntitySpec.Command> commands = new ArrayList<>();
for (SpawnCommand command : entity.rawCommands()) { for (SpawnCommand command : entity.rawCommands()) {
if (SpawnConditions.allow(command.timeBlock(), command.weather(), world)) { if (sky.isPresent() && SpawnConditions.allow(command.timeBlock(), command.weather(), sky.get())) {
commands.add(new EntitySpec.Command(command.commands(), command.delay(), command.repeat(), command.repeatDelay())); commands.add(new EntitySpec.Command(command.commands(), command.delay(), command.repeat(), command.repeatDelay()));
} }
} }
@@ -18,29 +18,25 @@
package art.arcane.iris.engine.spawn; package art.arcane.iris.engine.spawn;
import art.arcane.iris.builtin.IrisSeed;
import art.arcane.iris.builtin.LiveWorld;
import art.arcane.iris.builtin.LiveWorld.Level;
import art.arcane.iris.builtin.loot.LootResolver;
import art.arcane.iris.builtin.spawn.EntityDefinition; import art.arcane.iris.builtin.spawn.EntityDefinition;
import art.arcane.iris.builtin.spawn.EntitySpawn; import art.arcane.iris.builtin.spawn.EntitySpawn;
import art.arcane.iris.builtin.spawn.SpawnMarker; import art.arcane.iris.builtin.spawn.SpawnMarker;
import art.arcane.iris.builtin.spawn.SpawnSurface; import art.arcane.iris.builtin.spawn.SpawnSurface;
import art.arcane.iris.builtin.spawn.Spawner; import art.arcane.iris.builtin.spawn.Spawner;
import art.arcane.iris.builtin.spawn.SpawnerSettings; import art.arcane.iris.builtin.spawn.SpawnerSettings;
import art.arcane.iris.core.loader.IrisRegistrant;
import art.arcane.iris.core.modules.IrisPackWorld;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.builtin.loot.LootResolver;
import art.arcane.iris.engine.loot.LootItems; import art.arcane.iris.engine.loot.LootItems;
import art.arcane.iris.engine.object.value.IRare;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.spawn.SpawnResources.KeyedSpawner; import art.arcane.iris.engine.spawn.SpawnResources.KeyedSpawner;
import art.arcane.iris.util.common.scheduling.J;
import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.matter.slices.MarkerMatter; import art.arcane.volmlib.util.scheduling.ChronoLatch;
import com.volmit.config.Range; import com.volmit.config.Range;
import com.volmit.entity.EntitySpec; import com.volmit.entity.EntitySpec;
import com.volmit.resource.PackResources;
import com.volmit.service.EntitySpawns; import com.volmit.service.EntitySpawns;
import com.volmit.world.BlockPosition; import com.volmit.world.BlockPosition;
import com.volmit.world.PackWorld; import com.volmit.world.PackWorld;
@@ -63,13 +59,15 @@ public final class EntitySpawning implements EntitySpawns {
private static final String CAVE_FLOOR_MARKER = "cave_floor"; private static final String CAVE_FLOOR_MARKER = "cave_floor";
private static final String CAVE_CEILING_MARKER = "cave_ceiling"; private static final String CAVE_CEILING_MARKER = "cave_ceiling";
private static final int AIR_ABOVE_MARKER = 1; private static final int AIR_ABOVE_MARKER = 1;
private static final long COOLDOWN_CLEANUP_INTERVAL_MILLISECONDS = 60_000L;
private static final int LAYOUT_QUESTION_HEIGHT = 0;
@Override @Override
public Optional<Plan> plan(PackWorld world, Site site) { public Optional<Plan> plan(PackWorld world, Site site) {
Engine engine = engine(world); forgetExpiredCooldowns(world);
return switch (site) { return switch (site) {
case Chunk chunk -> planChunk(world, engine, chunk); case Chunk chunk -> planChunk(world, chunk);
case Marker marker -> planMarker(world, engine, marker); case Marker marker -> planMarker(world, marker);
}; };
} }
@@ -78,19 +76,19 @@ public final class EntitySpawning implements EntitySpawns {
if (count <= 0) { if (count <= 0) {
return; return;
} }
Spawner spawner = SpawnResources.spawner(engine(world).getData(), plan.spawner()); Spawner spawner = SpawnResources.spawner(world.resources(), plan.spawner());
if (spawner != null) { if (spawner != null) {
SpawnerGate.spawned(plan.spawner(), spawner, engine(world), plan.chunkX(), plan.chunkZ()); SpawnerGate.spawned(plan.spawner(), spawner, LiveWorld.of(world), plan.chunkX(), plan.chunkZ());
} }
} }
@Override @Override
public Optional<EntitySpec> entity(PackWorld world, String key) { public Optional<EntitySpec> entity(PackWorld world, String key) {
EntityDefinition entity = SpawnResources.entity(engine(world).getData(), key); EntityDefinition entity = SpawnResources.entity(world.resources(), key);
if (entity == null) { if (entity == null) {
return Optional.empty(); return Optional.empty();
} }
return Optional.of(resolution(world, engine(world)).resolve(entity, entityRandom(world).rng())); return Optional.of(resolution(world).resolve(entity, entityRandom(world).rng()));
} }
@Override @Override
@@ -98,15 +96,14 @@ public final class EntitySpawning implements EntitySpawns {
if (tag.equals(CAVE_FLOOR_MARKER) || tag.equals(CAVE_CEILING_MARKER)) { if (tag.equals(CAVE_FLOOR_MARKER) || tag.equals(CAVE_CEILING_MARKER)) {
return Optional.empty(); return Optional.empty();
} }
Engine engine = engine(world); SpawnMarker marker = SpawnResources.marker(world.resources(), tag);
SpawnMarker marker = SpawnResources.marker(engine.getData(), tag);
if (marker == null) { if (marker == null) {
return Optional.empty(); return Optional.empty();
} }
List<String> spawners = new ArrayList<>(); List<String> spawners = new ArrayList<>();
for (String key : marker.spawners()) { for (String key : marker.spawners()) {
if (SpawnResources.spawner(engine.getData(), key) == null) { if (SpawnResources.spawner(world.resources(), key) == null) {
world.log().error("Cannot load spawner: " + key + " for marker " + tag, null); world.log().error("Cannot load spawner: " + key + " for marker " + tag, null);
continue; continue;
} }
@@ -115,69 +112,78 @@ public final class EntitySpawning implements EntitySpawns {
return Optional.of(new MarkerRule(spawners, marker.emptyAbove(), marker.removeOnChange())); return Optional.of(new MarkerRule(spawners, marker.emptyAbove(), marker.removeOnChange()));
} }
private Optional<Plan> planChunk(PackWorld world, Engine engine, Chunk chunk) { /** Drops the cooldowns that ran out, now and then: the world's data keeps them across restarts. */
Predicate<KeyedSpawner> canSpawn = keyed -> SpawnerGate.canSpawn(keyed.key(), keyed.spawner(), engine, chunk.chunkX(), chunk.chunkZ()); private static void forgetExpiredCooldowns(PackWorld world) {
CooldownCleanup cleanup = world.state(CooldownCleanup.class, ignored -> new CooldownCleanup());
if (!cleanup.due()) {
return;
}
PackResources resources = world.resources();
LiveWorld.of(world).spawnCooldowns().forgetExpired(key -> {
Spawner spawner = SpawnResources.spawner(resources, key);
return spawner == null ? -1L : spawner.maximumRate().interval();
});
}
private Optional<Plan> planChunk(PackWorld world, Chunk chunk) {
LiveWorld live = LiveWorld.of(world);
Predicate<KeyedSpawner> canSpawn = keyed -> SpawnerGate.canSpawn(keyed.key(), keyed.spawner(), live, chunk.chunkX(), chunk.chunkZ());
int blockX = PowerOfTwoCoordinates.chunkToBlock(chunk.chunkX()); int blockX = PowerOfTwoCoordinates.chunkToBlock(chunk.chunkX());
int blockZ = PowerOfTwoCoordinates.chunkToBlock(chunk.chunkZ()); int blockZ = PowerOfTwoCoordinates.chunkToBlock(chunk.chunkZ());
IrisBiome centreBiome = engine.getSurfaceBiome(blockX + BLOCKS_TO_CHUNK_CENTRE, blockZ + BLOCKS_TO_CHUNK_CENTRE); LiveWorld.BiomeKind centreKind = live.surfaceKind(blockX + BLOCKS_TO_CHUNK_CENTRE, blockZ + BLOCKS_TO_CHUNK_CENTRE);
IrisRegion region = engine.getRegion(blockX, blockZ);
IrisBiome biome = engine.getSurfaceBiome(blockX, blockZ);
List<KeyedSpawner> candidates = Stream.concat( List<KeyedSpawner> candidates = Stream.concat(
shuffled(engine, engine.getDimension()).stream() shuffled(world, live, Level.DIMENSION, blockX, blockZ).stream()
.filter(canSpawn).filter(keyed -> SpawnerGate.suits(keyed.spawner(), centreBiome)), .filter(canSpawn).filter(keyed -> SpawnerGate.suits(keyed.spawner(), centreKind)),
Stream.concat( Stream.concat(
shuffled(engine, region).stream().filter(canSpawn), shuffled(world, live, Level.REGION, blockX, blockZ).stream().filter(canSpawn),
shuffled(engine, biome).stream().filter(canSpawn))) shuffled(world, live, Level.SURFACE_BIOME, blockX, blockZ).stream().filter(canSpawn)))
.filter(keyed -> chunk.livingEntities() < keyed.spawner().maxEntitiesPerChunk()) .filter(keyed -> chunk.livingEntities() < keyed.spawner().maxEntitiesPerChunk())
.toList(); .toList();
List<Candidate> spawns = candidates.stream().flatMap(keyed -> spawnsOf(keyed, chunk.initial())).collect(Collectors.toList()); List<Candidate> spawns = candidates.stream().flatMap(keyed -> spawnsOf(keyed, chunk.initial())).collect(Collectors.toList());
Candidate chosen = IRare.expandWeighted(spawns).getRandom(); Candidate chosen = RarityWeighting.expand(spawns, Candidate::rarity).getRandom();
if (chosen == null) { if (chosen == null) {
return Optional.empty(); return Optional.empty();
} }
return planChunkSpawn(world, engine, chunk, chosen); return planChunkSpawn(world, live, chunk, chosen);
} }
private Optional<Plan> planChunkSpawn(PackWorld world, Engine engine, Chunk chunk, Candidate chosen) { private Optional<Plan> planChunkSpawn(PackWorld world, LiveWorld live, Chunk chunk, Candidate chosen) {
EntitySpawn spawn = chosen.spawn(); EntitySpawn spawn = chosen.spawn();
int count = LootResolver.inclusive(RNG.r, spawn.minSpawns(), spawn.maxSpawns()); int count = LootResolver.inclusive(RNG.r, spawn.minSpawns(), spawn.maxSpawns());
List<Attempt> attempts = new ArrayList<>(); List<Attempt> attempts = new ArrayList<>();
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
int x = (chunk.chunkX() * CHUNK_SIZE) + RNG.r.i(CHUNK_SIZE); int x = (chunk.chunkX() * CHUNK_SIZE) + RNG.r.i(CHUNK_SIZE);
int z = (chunk.chunkZ() * CHUNK_SIZE) + RNG.r.i(CHUNK_SIZE); int z = (chunk.chunkZ() * CHUNK_SIZE) + RNG.r.i(CHUNK_SIZE);
BlockPosition at = spawnPosition(engine, chosen.spawner(), chunk.chunkX(), chunk.chunkZ(), x, z); BlockPosition at = spawnPosition(live, chosen.spawner(), chunk.chunkX(), chunk.chunkZ(), x, z);
if (at != null) { if (at != null) {
addAttempt(attempts, world, engine, chosen, at, true); addAttempt(attempts, world, chosen, at, true);
} }
} }
return attempts.isEmpty() ? Optional.empty() : Optional.of(new Plan(chosen.key(), chunk.chunkX(), chunk.chunkZ(), false, attempts)); return attempts.isEmpty() ? Optional.empty() : Optional.of(new Plan(chosen.key(), chunk.chunkX(), chunk.chunkZ(), false, attempts));
} }
/** Where a spawner of its group puts an entity at the column; null when it has no place for one. */ /** Where a spawner of its group puts an entity at the column; null when it has no place for one. */
private static BlockPosition spawnPosition(Engine engine, Spawner spawner, int chunkX, int chunkZ, int x, int z) { private static BlockPosition spawnPosition(LiveWorld live, Spawner spawner, int chunkX, int chunkZ, int x, int z) {
int height = engine.getHeight(x, z, true); int height = live.highestBlock(x, z, true);
int heightWithFluid = engine.getHeight(x, z, false); int heightWithFluid = live.highestBlock(x, z, false);
return switch (spawner.group()) { return switch (spawner.group()) {
case NORMAL -> new BlockPosition(x, heightWithFluid + 1, z); case NORMAL -> new BlockPosition(x, heightWithFluid + 1, z);
case CAVE -> caveSpawnPosition(engine, chunkX, chunkZ); case CAVE -> caveSpawnPosition(live, chunkX, chunkZ);
case UNDERWATER, BEACH -> new BlockPosition(x, RNG.r.i(height + 1, heightWithFluid), z); case UNDERWATER, BEACH -> new BlockPosition(x, RNG.r.i(height + 1, heightWithFluid), z);
}; };
} }
static BlockPosition caveSpawnPosition(Engine engine, int chunkX, int chunkZ) { static BlockPosition caveSpawnPosition(LiveWorld live, int chunkX, int chunkZ) {
if (J.isFolia()) { KList<BlockPosition> floors = new KList<>(live.caveFloors(chunkX, chunkZ));
return null; BlockPosition floor = floors.getRandom(RNG.r);
} return floor == null ? null : new BlockPosition(floor.x(), floor.y() + AIR_ABOVE_MARKER, floor.z());
KList<IrisPosition> floors = engine.getMantle().findMarkers(chunkX, chunkZ, MarkerMatter.CAVE_FLOOR);
IrisPosition floor = floors.getRandom(RNG.r);
return floor == null ? null : new BlockPosition(floor.getX(), floor.getY() - engine.getMinHeight() + AIR_ABOVE_MARKER, floor.getZ());
} }
private Optional<Plan> planMarker(PackWorld world, Engine engine, Marker marker) { private Optional<Plan> planMarker(PackWorld world, Marker marker) {
Spawner spawner = SpawnResources.spawner(engine.getData(), marker.spawner()); Spawner spawner = SpawnResources.spawner(world.resources(), marker.spawner());
SpawnMarker spawnMarker = SpawnResources.marker(engine.getData(), marker.marker()); SpawnMarker spawnMarker = SpawnResources.marker(world.resources(), marker.marker());
if (spawner == null) { if (spawner == null) {
return Optional.empty(); return Optional.empty();
} }
@@ -186,12 +192,13 @@ public final class EntitySpawning implements EntitySpawns {
if (candidates.isEmpty()) { if (candidates.isEmpty()) {
return Optional.empty(); return Optional.empty();
} }
EntitySpawn spawn = IRare.expandWeighted(candidates.stream().map(RareSpawn::new).toList()).getRandom().spawn(); EntitySpawn spawn = RarityWeighting.expand(candidates, EntitySpawn::rarity).getRandom();
BlockPosition position = marker.position(); BlockPosition position = marker.position();
int chunkX = PowerOfTwoCoordinates.blockToChunkFloor(position.x()); int chunkX = PowerOfTwoCoordinates.blockToChunkFloor(position.x());
int chunkZ = PowerOfTwoCoordinates.blockToChunkFloor(position.z()); int chunkZ = PowerOfTwoCoordinates.blockToChunkFloor(position.z());
if (!SpawnerGate.canSpawn(marker.spawner(), spawner, engine, chunkX, chunkZ)) { LiveWorld live = LiveWorld.of(world);
if (!SpawnerGate.canSpawn(marker.spawner(), spawner, live, chunkX, chunkZ)) {
return Optional.empty(); return Optional.empty();
} }
@@ -203,7 +210,7 @@ public final class EntitySpawning implements EntitySpawns {
List<Attempt> attempts = new ArrayList<>(); List<Attempt> attempts = new ArrayList<>();
BlockPosition above = new BlockPosition(position.x(), position.y() + AIR_ABOVE_MARKER, position.z()); BlockPosition above = new BlockPosition(position.x(), position.y() + AIR_ABOVE_MARKER, position.z());
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
addAttempt(attempts, world, engine, new Candidate(marker.spawner(), spawner, spawn), above, false); addAttempt(attempts, world, new Candidate(marker.spawner(), spawner, spawn), above, false);
} }
return attempts.isEmpty() ? Optional.empty() : Optional.of(new Plan(marker.spawner(), chunkX, chunkZ, exhaustsMarker, attempts)); return attempts.isEmpty() ? Optional.empty() : Optional.of(new Plan(marker.spawner(), chunkX, chunkZ, exhaustsMarker, attempts));
} }
@@ -212,22 +219,23 @@ public final class EntitySpawning implements EntitySpawns {
return marker.exhaustionChance() > RNG.r.nextDouble(); return marker.exhaustionChance() > RNG.r.nextDouble();
} }
private void addAttempt(List<Attempt> attempts, PackWorld world, Engine engine, Candidate candidate, BlockPosition at, boolean checkSurface) { private void addAttempt(List<Attempt> attempts, PackWorld world, Candidate candidate, BlockPosition at, boolean checkSurface) {
EntityDefinition entity = SpawnResources.entity(engine.getData(), candidate.spawn().entity()); EntityDefinition entity = SpawnResources.entity(world.resources(), candidate.spawn().entity());
if (entity == null) { if (entity == null) {
world.log().debug(" You are trying to spawn an entity that does not exist!"); world.log().debug(" You are trying to spawn an entity that does not exist!");
return; return;
} }
Range light = candidate.spawner().allowedLightLevels(); Range light = candidate.spawner().allowedLightLevels();
EntitySpec spec = resolution(world, engine).resolve(entity, entityRandom(world).rng()); EntitySpec spec = resolution(world).resolve(entity, entityRandom(world).rng());
attempts.add(new Attempt(at, spec, surfaceOf(entity.surface()), attempts.add(new Attempt(at, spec, surfaceOf(entity.surface()),
(int) Math.ceil(light.min()), (int) Math.floor(light.max()), checkSurface)); (int) Math.ceil(light.min()), (int) Math.floor(light.max()), checkSurface));
} }
private static EntityResolution resolution(PackWorld world, Engine engine) { private static EntityResolution resolution(PackWorld world) {
LootItems items = new LootItems(world.resources().items(), engine.isStudio()); LiveWorld live = LiveWorld.of(world);
return new EntityResolution(items, engine.getWorld().platformWorld(), world.state(EffectTimers.class, ignored -> new EffectTimers())); LootItems items = new LootItems(world.resources().items(), live.studio());
return new EntityResolution(items, live.sky(), world.state(EffectTimers.class, ignored -> new EffectTimers()));
} }
private static EntityRandom entityRandom(PackWorld world) { private static EntityRandom entityRandom(PackWorld world) {
@@ -238,10 +246,11 @@ public final class EntitySpawning implements EntitySpawns {
return Surface.valueOf(surface.name()); return Surface.valueOf(surface.name());
} }
/** The spawners an area lists, in a random order. */ /** The spawners the dimension, region or surface biome at the column lists, in a random order. */
private static List<KeyedSpawner> shuffled(Engine engine, IrisRegistrant owner) { private static List<KeyedSpawner> shuffled(PackWorld world, LiveWorld live, Level level, int x, int z) {
List<String> keys = owner.getModuleSettings().find(SpawnerSettings.class).map(SpawnerSettings::spawners).orElse(List.of()); List<String> keys = live.settings(SpawnerSettings.class, level, x, LAYOUT_QUESTION_HEIGHT, z)
return new KList<>(SpawnResources.spawners(engine.getData(), keys)).shuffleCopy(RNG.r); .map(SpawnerSettings::spawners).orElse(List.of());
return new KList<>(SpawnResources.spawners(world.resources(), keys)).shuffleCopy(RNG.r);
} }
private static Stream<Candidate> spawnsOf(KeyedSpawner keyed, boolean initial) { private static Stream<Candidate> spawnsOf(KeyedSpawner keyed, boolean initial) {
@@ -250,35 +259,31 @@ public final class EntitySpawning implements EntitySpawns {
} }
/** A spawn of a spawner, which picks as often as the spawn's rarity says. */ /** A spawn of a spawner, which picks as often as the spawn's rarity says. */
private record Candidate(String key, Spawner spawner, EntitySpawn spawn) implements IRare { private record Candidate(String key, Spawner spawner, EntitySpawn spawn) {
@Override int rarity() {
public int getRarity() {
return spawn.rarity(); return spawn.rarity();
} }
} }
/** A spawn that picks as often as its rarity says. */
private record RareSpawn(EntitySpawn spawn) implements IRare {
@Override
public int getRarity() {
return spawn.rarity();
}
}
private static Engine engine(PackWorld world) {
return IrisPackWorld.of(world).engine();
}
/** The random stream entities are made from, seeded from the world like Iris always seeded it; one per world. */ /** The random stream entities are made from, seeded from the world like Iris always seeded it; one per world. */
private static final class EntityRandom { private static final class EntityRandom {
private final RNG rng; private final RNG rng;
private EntityRandom(PackWorld world) { private EntityRandom(PackWorld world) {
this.rng = new RNG(IrisPackWorld.of(world).engine().getSeedManager().getEntity()); this.rng = new RNG(IrisSeed.ENTITY.of(world));
} }
private RNG rng() { private RNG rng() {
return rng; return rng;
} }
} }
/** When the world's spawner cooldowns were last tidied. */
private static final class CooldownCleanup {
private final ChronoLatch latch = new ChronoLatch(COOLDOWN_CLEANUP_INTERVAL_MILLISECONDS);
private boolean due() {
return latch.flip();
}
}
} }
@@ -0,0 +1,53 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.spawn;
import art.arcane.volmlib.util.collection.KList;
import java.util.List;
import java.util.function.ToIntFunction;
/**
* Applies rarity to a pick: each possibility appears in the expansion as often as its rarity says, so picking one at
* random from the expansion picks the rarer ones less often. Spawner choices go through this once; rarity must never be
* applied a second time per spawn position.
*/
final class RarityWeighting {
private static final int MINIMUM_RARITY = 1;
private RarityWeighting() {
}
/** Each of {@code possibilities} repeated total/rarity times, where a rarity below 1 counts as 1. */
static <T> KList<T> expand(List<T> possibilities, ToIntFunction<T> rarity) {
KList<T> expanded = new KList<>();
int totalRarity = 0;
for (T possibility : possibilities) {
totalRarity += rarityOf(possibility, rarity);
}
for (T possibility : possibilities) {
expanded.addMultiple(possibility, totalRarity / rarityOf(possibility, rarity));
}
return expanded;
}
private static <T> int rarityOf(T possibility, ToIntFunction<T> rarity) {
return Math.max(MINIMUM_RARITY, rarity.applyAsInt(possibility));
}
}
@@ -18,11 +18,11 @@
package art.arcane.iris.engine.spawn; package art.arcane.iris.engine.spawn;
import art.arcane.iris.builtin.LiveWorld.Sky;
import art.arcane.iris.builtin.spawn.SpawnTimeBlock; import art.arcane.iris.builtin.spawn.SpawnTimeBlock;
import art.arcane.iris.builtin.spawn.SpawnWeather; import art.arcane.iris.builtin.spawn.SpawnWeather;
import art.arcane.iris.spi.PlatformWorld;
/** The time of day and the weather a command or spawner of the pack asks for, checked against a world. */ /** The time of day and the weather a command or spawner of the pack asks for, checked against a world's sky. */
final class SpawnConditions { final class SpawnConditions {
private static final double TICKS_PER_HOUR = 1000D; private static final double TICKS_PER_HOUR = 1000D;
private static final double HOURS_AT_TIME_ZERO = 6; private static final double HOURS_AT_TIME_ZERO = 6;
@@ -31,12 +31,12 @@ final class SpawnConditions {
private SpawnConditions() { private SpawnConditions() {
} }
static boolean allow(SpawnTimeBlock time, SpawnWeather weather, PlatformWorld world) { static boolean allow(SpawnTimeBlock time, SpawnWeather weather, Sky sky) {
return time.contains(hourOf(world)) && weather.matches(world.isStorming(), world.isThundering()); return time.contains(hourOf(sky)) && weather.matches(sky.storming(), sky.thundering());
} }
/** The world's time of day as a clock hour: tick 0 is 6 in the morning. */ /** The world's time of day as a clock hour: tick 0 is 6 in the morning. */
static double hourOf(PlatformWorld world) { static double hourOf(Sky sky) {
return ((world.getTime() / TICKS_PER_HOUR) + HOURS_AT_TIME_ZERO) % HOURS_PER_DAY; return ((sky.time() / TICKS_PER_HOUR) + HOURS_AT_TIME_ZERO) % HOURS_PER_DAY;
} }
} }
@@ -19,6 +19,7 @@
package art.arcane.iris.engine.spawn; package art.arcane.iris.engine.spawn;
import art.arcane.iris.builtin.spawn.EffectSettings; import art.arcane.iris.builtin.spawn.EffectSettings;
import art.arcane.iris.builtin.spawn.PlacementMarker;
import art.arcane.iris.builtin.spawn.SpawnerSettings; import art.arcane.iris.builtin.spawn.SpawnerSettings;
import com.volmit.FeatureRegistry; import com.volmit.FeatureRegistry;
import com.volmit.IrisModule; import com.volmit.IrisModule;
@@ -50,6 +51,7 @@ public final class SpawnModule implements IrisModule {
public void register(FeatureRegistry registry) { public void register(FeatureRegistry registry) {
registry.registerSettings(SpawnerSettings.class); registry.registerSettings(SpawnerSettings.class);
registry.registerSettings(EffectSettings.class); registry.registerSettings(EffectSettings.class);
registry.registerHeldType(PlacementMarker.class);
SpawnResources.kinds().forEach(registry::registerResourceKind); SpawnResources.kinds().forEach(registry::registerResourceKind);
registry.registerService(EntitySpawns.class, new EntitySpawning()); registry.registerService(EntitySpawns.class, new EntitySpawning());
registry.registerService(AmbientEffects.class, new AmbientEffecting()); registry.registerService(AmbientEffects.class, new AmbientEffecting());
@@ -21,8 +21,7 @@ package art.arcane.iris.engine.spawn;
import art.arcane.iris.builtin.spawn.EntityDefinition; import art.arcane.iris.builtin.spawn.EntityDefinition;
import art.arcane.iris.builtin.spawn.SpawnMarker; import art.arcane.iris.builtin.spawn.SpawnMarker;
import art.arcane.iris.builtin.spawn.Spawner; import art.arcane.iris.builtin.spawn.Spawner;
import art.arcane.iris.core.loader.IrisData; import com.volmit.resource.PackResources;
import art.arcane.iris.core.modules.IrisPackResources;
import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKind; import com.volmit.resource.ResourceKind;
@@ -57,23 +56,23 @@ public final class SpawnResources {
return List.of(SPAWNERS, ENTITIES, MARKERS); return List.of(SPAWNERS, ENTITIES, MARKERS);
} }
public static Spawner spawner(IrisData data, String key) { public static Spawner spawner(PackResources resources, String key) {
return find(data, SPAWNERS, key); return find(resources, SPAWNERS, key);
} }
public static EntityDefinition entity(IrisData data, String key) { public static EntityDefinition entity(PackResources resources, String key) {
return find(data, ENTITIES, key); return find(resources, ENTITIES, key);
} }
public static SpawnMarker marker(IrisData data, String key) { public static SpawnMarker marker(PackResources resources, String key) {
return find(data, MARKERS, key); return find(resources, MARKERS, key);
} }
/** The spawners of the pack named by {@code keys}, in order, without the ones the pack lacks. */ /** The spawners of the pack named by {@code keys}, in order, without the ones the pack lacks. */
public static List<KeyedSpawner> spawners(IrisData data, List<String> keys) { public static List<KeyedSpawner> spawners(PackResources resources, List<String> keys) {
List<KeyedSpawner> spawners = new ArrayList<>(); List<KeyedSpawner> spawners = new ArrayList<>();
for (String key : keys) { for (String key : keys) {
Spawner spawner = spawner(data, key); Spawner spawner = spawner(resources, key);
if (spawner != null) { if (spawner != null) {
spawners.add(new KeyedSpawner(key, spawner)); spawners.add(new KeyedSpawner(key, spawner));
} }
@@ -82,25 +81,24 @@ public final class SpawnResources {
} }
/** The key of every entity of the pack, in key order. */ /** The key of every entity of the pack, in key order. */
public static List<String> entityKeys(IrisData data) { public static List<String> entityKeys(PackResources resources) {
return keys(data, ENTITIES); return keys(resources, ENTITIES);
} }
/** The key of every spawner of the pack, in key order. */ /** The key of every spawner of the pack, in key order. */
public static List<String> spawnerKeys(IrisData data) { public static List<String> spawnerKeys(PackResources resources) {
return keys(data, SPAWNERS); return keys(resources, SPAWNERS);
} }
/** The key of every marker of the pack, in key order. */ /** The key of every marker of the pack, in key order. */
public static List<String> markerKeys(IrisData data) { public static List<String> markerKeys(PackResources resources) {
return keys(data, MARKERS); return keys(resources, MARKERS);
} }
private static <T> T find(IrisData data, ResourceKind<T> kind, String key) { private static <T> T find(PackResources resources, ResourceKind<T> kind, String key) {
if (key == null || key.isBlank()) { if (key == null || key.isBlank()) {
return null; return null;
} }
IrisPackResources resources = data.getPackResources();
try { try {
return resources.find(kind.key(resources.idOf(key))).orElse(null); return resources.find(kind.key(resources.idOf(key))).orElse(null);
} catch (IllegalStateException failedToLoad) { } catch (IllegalStateException failedToLoad) {
@@ -109,7 +107,7 @@ public final class SpawnResources {
} }
/** A key's id has the key as its path, so the path names the resource again wherever a key is expected. */ /** A key's id has the key as its path, so the path names the resource again wherever a key is expected. */
private static List<String> keys(IrisData data, ResourceKind<?> kind) { private static List<String> keys(PackResources resources, ResourceKind<?> kind) {
return data.getPackResources().ids(kind.type()).stream().map(ResourceId::path).toList(); return resources.ids(kind.type()).stream().map(ResourceId::path).toList();
} }
} }
@@ -18,34 +18,36 @@
package art.arcane.iris.engine.spawn; package art.arcane.iris.engine.spawn;
import art.arcane.iris.builtin.LiveWorld;
import art.arcane.iris.builtin.LiveWorld.BiomeKind;
import art.arcane.iris.builtin.LiveWorld.Sky;
import art.arcane.iris.builtin.spawn.SpawnRate; import art.arcane.iris.builtin.spawn.SpawnRate;
import art.arcane.iris.builtin.spawn.SpawnCooldowns;
import art.arcane.iris.builtin.spawn.Spawner; import art.arcane.iris.builtin.spawn.Spawner;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.object.world.biome.IrisBiome; import java.util.Optional;
import art.arcane.iris.spi.PlatformWorld;
/** /**
* Whether a spawner may fire: in a biome of the kind its group wants, in the time and weather it asks for, and not * Whether a spawner may fire: in a biome of the kind its group wants, in the time and weather it asks for, and not
* more often than its rates allow. The rates count in the engine's persisted data, by the key the pack names the * more often than its rates allow. The rates count in the world's data, by the key the pack names the spawner by.
* spawner by.
*/ */
final class SpawnerGate { final class SpawnerGate {
private SpawnerGate() { private SpawnerGate() {
} }
/** Whether a spawner of this group fires in {@code biome}. */ /** Whether a spawner of this group fires in a biome of {@code kind}. */
static boolean suits(Spawner spawner, IrisBiome biome) { static boolean suits(Spawner spawner, BiomeKind kind) {
return switch (spawner.group()) { return switch (spawner.group()) {
case NORMAL -> switch (biome.getInferredType()) { case NORMAL -> switch (kind) {
case SHORE, SEA, CAVE -> false; case SHORE, SEA, CAVE -> false;
case LAND -> true; case LAND -> true;
}; };
case CAVE -> true; case CAVE -> true;
case UNDERWATER -> switch (biome.getInferredType()) { case UNDERWATER -> switch (kind) {
case SHORE, LAND, CAVE -> false; case SHORE, LAND, CAVE -> false;
case SEA -> true; case SEA -> true;
}; };
case BEACH -> switch (biome.getInferredType()) { case BEACH -> switch (kind) {
case SHORE -> true; case SHORE -> true;
case LAND, CAVE, SEA -> false; case LAND, CAVE, SEA -> false;
}; };
@@ -53,45 +55,45 @@ final class SpawnerGate {
} }
/** Whether the world is in the time and weather the spawner asks for. */ /** Whether the world is in the time and weather the spawner asks for. */
static boolean suits(Spawner spawner, PlatformWorld world) { static boolean suits(Spawner spawner, Sky sky) {
return SpawnConditions.allow(spawner.timeBlock(), spawner.weather(), world); return SpawnConditions.allow(spawner.timeBlock(), spawner.weather(), sky);
} }
/** Whether the spawner may fire in the chunk now. */ /** Whether the spawner may fire in the chunk now. */
static boolean canSpawn(String key, Spawner spawner, Engine engine, int chunkX, int chunkZ) { static boolean canSpawn(String key, Spawner spawner, LiveWorld live, int chunkX, int chunkZ) {
if (!canSpawn(key, spawner, engine)) { if (!canSpawn(key, spawner, live)) {
return false; return false;
} }
SpawnRate rate = spawner.maximumRatePerChunk(); SpawnRate rate = spawner.maximumRatePerChunk();
return rate.isInfinite() || engine.getEngineData().getChunk(chunkX, chunkZ).getCooldown(key).canSpawn(rate.interval()); return rate.isInfinite() || live.spawnCooldowns().canSpawnInChunk(chunkX, chunkZ, key, rate.interval());
} }
/** Counts a spawn of the spawner in the chunk against its rates. */ /** Counts a spawn of the spawner in the chunk against its rates. */
static void spawned(String key, Spawner spawner, Engine engine, int chunkX, int chunkZ) { static void spawned(String key, Spawner spawner, LiveWorld live, int chunkX, int chunkZ) {
spawned(key, spawner, engine); spawned(key, spawner, live);
if (spawner.maximumRatePerChunk().isInfinite()) { if (spawner.maximumRatePerChunk().isInfinite()) {
return; return;
} }
engine.getEngineData().getChunk(chunkX, chunkZ).getCooldown(key).spawn(); live.spawnCooldowns().spawnedInChunk(chunkX, chunkZ, key);
} }
private static boolean canSpawn(String key, Spawner spawner, Engine engine) { private static boolean canSpawn(String key, Spawner spawner, LiveWorld live) {
PlatformWorld world = engine.getWorld().platformWorld(); Optional<Sky> sky = live.sky();
if (world == null || !suits(spawner, world)) { if (sky.isEmpty() || !suits(spawner, sky.get())) {
return false; return false;
} }
SpawnRate rate = spawner.maximumRate(); SpawnRate rate = spawner.maximumRate();
return rate.isInfinite() || engine.getEngineData().getCooldown(key).canSpawn(rate.interval()); return rate.isInfinite() || live.spawnCooldowns().canSpawn(key, rate.interval());
} }
private static void spawned(String key, Spawner spawner, Engine engine) { private static void spawned(String key, Spawner spawner, LiveWorld live) {
if (spawner.maximumRate().isInfinite()) { if (spawner.maximumRate().isInfinite()) {
return; return;
} }
engine.getEngineData().getCooldown(key).spawn(); live.spawnCooldowns().spawned(key);
} }
} }