Entity spawning asks the EntitySpawns services

WorldEntitySpawner and MarkerSpawnScanner no longer read spawners, entities or markers: modules plan the spawns and
describe the entities as EntitySpec, BukkitEntitySpawner creates them and the host checks light, surface and free space.
Block-break marker cleanup asks the module what a marker means.
This commit is contained in:
piexel committed 2026-10-09 22:16:35 +02:00
1 parent 8bf4fb0115
commit 406d3e47d3
12 files changed
+933 -184

No files matched your search

@@ -41,6 +41,7 @@ import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.terrain.IrisBiomePaletteLayer;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.entity.IrisEntity;
import art.arcane.iris.engine.platform.BukkitEntitySpawner;
import art.arcane.iris.engine.object.terrain.IrisGenerator;
import art.arcane.iris.engine.object.noise.IrisInterpolator;
import art.arcane.iris.engine.object.loot.IrisLootTable;
@@ -661,7 +662,7 @@ public class CommandStudio implements DirectorExecutor {
// Entity creation must run on the thread owning the destination chunk.
Location at = new Location(world(), location.getX(), location.getY(), location.getZ());
if (!J.runAt(at, () -> entity.spawn(spawnEngine, at))) {
if (!J.runAt(at, () -> BukkitEntitySpawner.spawnByKey(spawnEngine, entity.getLoadKey(), at))) {
Iris.warn("Could not schedule the entity spawn at " + at.getBlockX() + ", " + at.getBlockY() + ", " + at.getBlockZ() + ".");
}
}
@@ -24,6 +24,7 @@ import art.arcane.iris.engine.actuator.DecorantModule;
import art.arcane.iris.engine.actuator.TerrainModule;
import art.arcane.iris.engine.loot.LootModule;
import art.arcane.iris.engine.mantle.components.ObjectModule;
import art.arcane.iris.engine.spawn.SpawnModule;
import art.arcane.iris.engine.mantle.components.StructureModule;
import art.arcane.iris.engine.modifier.CarveModule;
import art.arcane.iris.engine.modifier.CustomModule;
@@ -71,7 +72,7 @@ public final class IrisModuleHost {
private static List<IrisModule> generationModules() {
return List.of(new BiomeModule(), new TerrainModule(), new CarveModule(), new ObjectModule(), new StructureModule(),
new PostModule(), new FloatingModule(), new DepositModule(), new MatterModule(), new DecorantModule(),
new PerfectionModule(), new CustomModule(), new LootModule());
new PerfectionModule(), new CustomModule(), new LootModule(), new SpawnModule());
}
/** Whether {@code type} is one of Iris's own classes that built-in settings may hold. */
@@ -21,8 +21,10 @@ package art.arcane.iris.core.modules;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.framework.Engine;
import com.volmit.host.FeatureCatalog;
import com.volmit.entity.EntitySpec;
import com.volmit.item.ItemDrop;
import com.volmit.service.BlockDrops;
import com.volmit.service.EntitySpawns;
import com.volmit.service.LocateResult;
import com.volmit.service.Loot;
import com.volmit.service.ObjectsAt;
@@ -126,6 +128,49 @@ public final class ModuleServices {
return new SaplingGrowth.TreeObjects(objects, procedural);
}
/** What the first module with something to spawn at {@code site} plans; empty when none does. */
public static Optional<PlannedSpawn> planSpawn(Engine engine, EntitySpawns.Site site) {
PackWorld world = engine.getGeneration().world();
for (EntitySpawns provider : catalog(engine.getData()).services(EntitySpawns.class)) {
Optional<EntitySpawns.Plan> plan = provider.plan(world, site);
if (plan.isPresent()) {
return Optional.of(new PlannedSpawn(provider, world, plan.get()));
}
}
return Optional.empty();
}
/** The entity {@code key} as the first module that knows it would spawn it. */
public static Optional<EntitySpec> entity(Engine engine, String key) {
PackWorld world = engine.getGeneration().world();
for (EntitySpawns provider : catalog(engine.getData()).services(EntitySpawns.class)) {
Optional<EntitySpec> entity = provider.entity(world, key);
if (entity.isPresent()) {
return entity;
}
}
return Optional.empty();
}
/** What the first module that knows the marker {@code tag} says it does. */
public static Optional<EntitySpawns.MarkerRule> markerRule(Engine engine, String tag) {
PackWorld world = engine.getGeneration().world();
for (EntitySpawns provider : catalog(engine.getData()).services(EntitySpawns.class)) {
Optional<EntitySpawns.MarkerRule> rule = provider.marker(world, tag);
if (rule.isPresent()) {
return rule;
}
}
return Optional.empty();
}
/** A plan and the module that made it, which hears how many of its entities appeared. */
public record PlannedSpawn(EntitySpawns provider, PackWorld world, EntitySpawns.Plan plan) {
public void spawned(int count) {
provider.spawned(world, plan, count);
}
}
/** Every structure key the pack's modules know, placed or not. */
public static Set<String> structureKeys(IrisData data) {
Set<String> keys = new LinkedHashSet<>();
@@ -19,19 +19,22 @@
package art.arcane.iris.engine;
import art.arcane.iris.engine.data.cache.Cache;
import art.arcane.iris.engine.object.marker.IrisMarker;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.entity.spawn.IrisSpawner;
import art.arcane.iris.core.modules.ModuleServices;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.util.common.plugin.Chunks;
import art.arcane.iris.util.common.scheduling.J;
import art.arcane.volmlib.util.collection.KMap;
import art.arcane.volmlib.util.collection.KSet;
import com.volmit.service.EntitySpawns;
import art.arcane.volmlib.util.matter.MatterMarker;
import org.bukkit.Chunk;
import org.bukkit.World;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;
@@ -49,8 +52,12 @@ final class MarkerSpawnScanner {
this.manager = manager;
}
Map<IrisPosition, KSet<IrisSpawner>> getSpawnersFromMarkers(Chunk c) {
Map<IrisPosition, KSet<IrisSpawner>> p = new KMap<>();
/** A spawner a marker names, and the marker. */
record MarkerSpawner(String marker, String spawner) {
}
Map<IrisPosition, List<MarkerSpawner>> getSpawnersFromMarkers(Chunk c) {
Map<IrisPosition, List<MarkerSpawner>> p = new KMap<>();
Set<IrisPosition> b = new KSet<>();
if (J.isFolia()) {
@@ -61,35 +68,20 @@ final class MarkerSpawnScanner {
}
manager.getMantle().iterateChunk(c.getX(), c.getZ(), MatterMarker.class, (x, y, z, t) -> {
if (t.getTag().equals("cave_floor") || t.getTag().equals("cave_ceiling")) {
return;
}
IrisMarker mark = manager.getData().getMarkerLoader().load(t.getTag());
if (mark == null) {
Optional<EntitySpawns.MarkerRule> rule = markerRule(t);
if (rule.isEmpty()) {
return;
}
IrisPosition pos = new IrisPosition((c.getX() << 4) + x, y, (c.getZ() << 4) + z);
if (isMarkerObstructed(c, pos, mark.isEmptyAbove())) {
if (isMarkerObstructed(c, pos, rule.get().emptyAbove())) {
b.add(pos);
return;
}
for (String i : mark.getSpawners()) {
IrisSpawner m = manager.getData().getSpawnerLoader().load(i);
if (m == null) {
IrisLogging.error("Cannot load spawner: " + i + " for marker on " + manager.getName());
continue;
}
m.setReferenceMarker(mark);
// This is so fucking incorrect its a joke
//noinspection ConstantConditions
if (m != null) {
p.computeIfAbsent(pos, (k) -> new KSet<>()).add(m);
}
for (String spawner : rule.get().spawners()) {
addOnce(p.computeIfAbsent(pos, (k) -> new ArrayList<>()), new MarkerSpawner(t.getTag(), spawner));
}
});
@@ -100,7 +92,15 @@ final class MarkerSpawnScanner {
return p;
}
void forEachMarkerSpawner(Chunk c, BiConsumer<IrisPosition, KSet<IrisSpawner>> consumer) {
/** What the modules say the marker means; empty for the cave markers Iris keeps for itself and for markers no module knows. */
private Optional<EntitySpawns.MarkerRule> markerRule(MatterMarker marker) {
if (marker.getTag().equals("cave_floor") || marker.getTag().equals("cave_ceiling")) {
return Optional.empty();
}
return ModuleServices.markerRule(manager.getEngine(), marker.getTag());
}
void forEachMarkerSpawner(Chunk c, BiConsumer<IrisPosition, List<MarkerSpawner>> consumer) {
if (c == null || consumer == null) {
return;
}
@@ -160,30 +160,26 @@ final class MarkerSpawnScanner {
}, () -> markerScanQueue.remove(key)));
}
private static void addOnce(List<MarkerSpawner> spawners, MarkerSpawner spawner) {
if (!spawners.contains(spawner)) {
spawners.add(spawner);
}
}
private Map<IrisPosition, MarkerSpawnData> collectMarkerSpawnData(int chunkX, int chunkZ) {
Map<IrisPosition, MarkerSpawnData> markerData = new KMap<>();
manager.getMantle().iterateChunk(chunkX, chunkZ, MatterMarker.class, (x, y, z, t) -> {
if (t.getTag().equals("cave_floor") || t.getTag().equals("cave_ceiling")) {
return;
}
IrisMarker mark = manager.getData().getMarkerLoader().load(t.getTag());
if (mark == null) {
Optional<EntitySpawns.MarkerRule> rule = markerRule(t);
if (rule.isEmpty()) {
return;
}
IrisPosition position = new IrisPosition((chunkX << 4) + x, y, (chunkZ << 4) + z);
MarkerSpawnData data = markerData.computeIfAbsent(position, k -> new MarkerSpawnData());
data.requiresEmptyAbove = data.requiresEmptyAbove || mark.isEmptyAbove();
data.requiresEmptyAbove = data.requiresEmptyAbove || rule.get().emptyAbove();
for (String i : mark.getSpawners()) {
IrisSpawner spawner = manager.getData().getSpawnerLoader().load(i);
if (spawner == null) {
IrisLogging.error("Cannot load spawner: " + i + " for marker on " + manager.getName());
continue;
}
spawner.setReferenceMarker(mark);
data.spawners.add(spawner);
for (String spawner : rule.get().spawners()) {
addOnce(data.spawners, new MarkerSpawner(t.getTag(), spawner));
}
});
@@ -218,7 +214,7 @@ final class MarkerSpawnScanner {
}
private static final class MarkerSpawnData {
private final KSet<IrisSpawner> spawners = new KSet<>();
private final List<MarkerSpawner> spawners = new ArrayList<>();
private boolean requiresEmptyAbove;
}
}
@@ -19,7 +19,6 @@
package art.arcane.iris.engine;
import art.arcane.iris.core.service.tree.BlockDropRouter;
import art.arcane.iris.engine.object.marker.IrisMarker;
import art.arcane.iris.core.modules.ModuleServices;
import art.arcane.iris.core.modules.PlatformBlockStates;
import art.arcane.iris.platform.bukkit.BukkitBlockState;
@@ -36,8 +35,10 @@ import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.inventory.ItemStack;
import com.volmit.block.BlockState;
import com.volmit.service.BlockDrops;
import com.volmit.service.EntitySpawns;
import com.volmit.world.BlockPosition;
import java.util.Optional;
import java.util.function.Consumer;
/**
@@ -79,8 +80,8 @@ final class WorldBlockDropRouter {
return;
}
IrisMarker mark = manager.getData().getMarkerLoader().load(marker.getTag());
if (mark == null || mark.isRemoveOnChange()) {
Optional<EntitySpawns.MarkerRule> rule = ModuleServices.markerRule(manager.getEngine(), marker.getTag());
if (rule.isEmpty() || rule.get().removeOnChange()) {
manager.getMantle().remove(blockX, mantleY, blockZ, MatterMarker.class);
}
}));
@@ -20,7 +20,6 @@ package art.arcane.iris.engine;
import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.engine.data.cache.Cache;
import art.arcane.iris.engine.object.entity.spawn.IrisSpawner;
import art.arcane.iris.engine.platform.EngineBukkitOps;
import art.arcane.iris.platform.bukkit.BukkitWorldBinding;
import art.arcane.iris.spi.IrisLogging;
@@ -303,13 +302,8 @@ final class WorldChunkMaintenance {
}), delay);
Chunk markerChunk = world.getChunkAt(chunkX, chunkZ);
manager.markerScanner.forEachMarkerSpawner(markerChunk, (block, spawners) -> {
IrisSpawner s = new KList<>(spawners).getRandom();
if (s == null) {
return;
}
manager.entitySpawner.spawn(block, s, true);
});
manager.markerScanner.forEachMarkerSpawner(markerChunk, (block, spawners) ->
manager.entitySpawner.spawnAtMarker(block, spawners.get(RNG.r.nextInt(spawners.size())), true));
});
}
@@ -19,40 +19,41 @@
package art.arcane.iris.engine;
import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.core.modules.ModuleServices;
import art.arcane.iris.engine.platform.BukkitEntitySpawner;
import art.arcane.iris.engine.platform.BukkitSurfaces;
import art.arcane.iris.platform.bukkit.BukkitPlatform;
import art.arcane.iris.util.common.format.C;
import art.arcane.volmlib.util.math.Vector3d;
import art.arcane.volmlib.util.matter.MatterMarker;
import com.volmit.entity.EntitySpec;
import com.volmit.service.EntitySpawns;
import com.volmit.world.BlockPosition;
import art.arcane.iris.core.gui.PregeneratorJob;
import art.arcane.iris.core.tools.IrisToolbelt;
import art.arcane.iris.engine.object.value.IRare;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.entity.IrisEntitySpawn;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.entity.spawn.IrisSpawner;
import art.arcane.iris.engine.platform.EngineBukkitOps;
import art.arcane.iris.platform.bukkit.BukkitWorldBinding;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.util.common.plugin.Chunks;
import art.arcane.iris.util.common.scheduling.J;
import art.arcane.volmlib.util.bukkit.WorldIdentity;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.format.Form;
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
import art.arcane.volmlib.util.math.Position2;
import art.arcane.volmlib.util.math.RNG;
import lombok.Data;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import java.util.List;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Ambient and marker entity spawning for a Bukkit Iris world. Every count and spawn hops onto the
@@ -281,16 +282,12 @@ final class WorldEntitySpawner {
if (IrisSettings.get().getWorld().isMarkerEntitySpawningSystem()) {
manager.markerScanner.forEachMarkerSpawner(c, (block, spawners) -> {
IrisSpawner s = new KList<>(spawners).getRandom();
if (s == null) {
return;
}
spawn(block, s, false);
MarkerSpawnScanner.MarkerSpawner s = spawners.get(RNG.r.nextInt(spawners.size()));
spawnAtMarker(block, s, false);
J.runRegion(c.getWorld(), c.getX(), c.getZ(), manager.managedTask(
"bukkit_world_manager_marker_spawn_followup",
() -> manager.chunkMaintenance.raiseInitialSpawnMarkerFlag(c.getWorld(), c.getX(), c.getZ(),
() -> spawn(block, s, true))));
() -> spawnAtMarker(block, s, true))));
});
}
@@ -298,87 +295,106 @@ final class WorldEntitySpawner {
return;
}
//@builder
Predicate<IrisSpawner> filter = i -> i.canSpawn(manager.getEngine(), c.getX(), c.getZ());
ChunkCounter counter = new ChunkCounter(c.getEntities());
IrisBiome biome = EngineBukkitOps.getSurfaceBiome(manager.getEngine(), c);
IrisEntitySpawn v = spawnRandomly(Stream.concat(manager.getData().getSpawnerLoader()
.loadAll(manager.getDimension().getEntitySpawners())
.shuffleCopy(RNG.r)
.stream()
.filter(filter)
.filter((i) -> i.isValid(biome)),
Stream.concat(manager.getData()
.getSpawnerLoader()
.loadAll(manager.getEngine().getRegion(PowerOfTwoCoordinates.chunkToBlock(c.getX()), PowerOfTwoCoordinates.chunkToBlock(c.getZ())).getEntitySpawners())
.shuffleCopy(RNG.r)
.stream()
.filter(filter),
manager.getData().getSpawnerLoader()
.loadAll(manager.getEngine().getSurfaceBiome(PowerOfTwoCoordinates.chunkToBlock(c.getX()), PowerOfTwoCoordinates.chunkToBlock(c.getZ())).getEntitySpawners())
.shuffleCopy(RNG.r)
.stream()
.filter(filter)))
.filter(counter)
.flatMap((i) -> stream(i, initial))
.collect(Collectors.toList()))
.getRandom();
//@done
if (v == null || v.getReferenceSpawner() == null)
return;
spawn(c, v);
int livingEntities = (int) Arrays.stream(c.getEntities()).filter(LivingEntity.class::isInstance).count();
ModuleServices.planSpawn(manager.getEngine(), new EntitySpawns.Chunk(c.getX(), c.getZ(), livingEntities, initial))
.ifPresent(planned -> spawn(c.getWorld(), planned));
}
private void spawn(Chunk c, IrisEntitySpawn i) {
IrisSpawner ref = i.getReferenceSpawner();
int s = i.spawn(manager.getEngine(), c, RNG.r);
actuallySpawned.addAndGet(s);
if (s > 0) {
ref.spawn(manager.getEngine(), c.getX(), c.getZ());
/** Spawns at a marker: the spawner of the marker the caller picked, with its initial spawns or its ordinary ones. */
void spawnAtMarker(IrisPosition block, MarkerSpawnScanner.MarkerSpawner spawner, boolean initial) {
if (manager.getEngine().isClosed() || !BukkitWorldBinding.tryBind(manager.getEngine().getWorld())) {
return;
}
BlockPosition position = new BlockPosition(block.getX(), block.getY() - manager.getEngine().getWorld().minHeight(), block.getZ());
EntitySpawns.Marker site = new EntitySpawns.Marker(position, spawner.marker(), spawner.spawner(), initial);
ModuleServices.planSpawn(manager.getEngine(), site).ifPresent(planned -> {
if (planned.plan().exhaustsMarker()) {
removeExhaustedMarker(block);
}
spawn(BukkitWorldBinding.world(manager.getEngine().getWorld()), planned);
});
}
private void removeExhaustedMarker(IrisPosition marker) {
int relativeY = marker.getY() - manager.getEngine().getWorld().minHeight();
Runnable remove = () -> manager.getEngine().getMantle().getMantle().remove(marker.getX(), relativeY, marker.getZ(), MatterMarker.class);
if (J.isFolia()) {
J.a(remove);
return;
}
remove.run();
}
private void spawn(World world, ModuleServices.PlannedSpawn planned) {
int spawned = 0;
for (EntitySpawns.Attempt attempt : planned.plan().attempts()) {
if (spawnIfAllowed(world, attempt)) {
spawned++;
}
}
actuallySpawned.addAndGet(spawned);
planned.spawned(spawned);
}
/** Spawns the attempt's entity unless the light, the surface below or the space around it forbid it. */
private boolean spawnIfAllowed(World world, EntitySpawns.Attempt attempt) {
EntitySpec entity = attempt.entity();
try {
Location l = new Location(world, attempt.at().x(), attempt.at().y() + world.getMinHeight(), attempt.at().z());
if (attempt.restrictsLight() && !lightAllows(l, attempt)) {
return false;
}
if (attempt.checkSurface() && !surfaceAllows(l, attempt)) {
return false;
}
Entity e = BukkitEntitySpawner.spawn(manager.getEngine(), entity, l.add(0.5, 0.5, 0.5));
if (e != null) {
IrisLogging.debug("Spawned " + C.DARK_AQUA + "Entity<" + entity.type() + "> " + C.GREEN + e.getType() + C.LIGHT_PURPLE + " @ " + C.GRAY + e.getLocation().getX() + ", " + e.getLocation().getY() + ", " + e.getLocation().getZ());
}
return e != null;
} catch (Throwable e) {
IrisLogging.reportError(e);
IrisLogging.error(" Failed to retrieve real entity @ " + attempt.at() + " (entity: " + entity.type() + ")");
return false;
}
}
private void spawn(IrisPosition pos, IrisEntitySpawn i) {
IrisSpawner ref = i.getReferenceSpawner();
if (!ref.canSpawn(manager.getEngine(), PowerOfTwoCoordinates.blockToChunkFloor(pos.getX()), PowerOfTwoCoordinates.blockToChunkFloor(pos.getZ())))
return;
int s = i.spawn(manager.getEngine(), pos, RNG.r);
actuallySpawned.addAndGet(s);
if (s > 0) {
ref.spawn(manager.getEngine(), PowerOfTwoCoordinates.blockToChunkFloor(pos.getX()), PowerOfTwoCoordinates.blockToChunkFloor(pos.getZ()));
}
private static boolean lightAllows(Location l, EntitySpawns.Attempt attempt) {
int light = l.getBlock().getLightLevel();
return light >= attempt.minLight() && light <= attempt.maxLight();
}
void spawn(IrisPosition block, IrisSpawner spawner, boolean initial) {
if (manager.getEngine().isClosed()) {
return;
private static boolean surfaceAllows(Location l, EntitySpawns.Attempt attempt) {
if (!BukkitSurfaces.matches(attempt.surface(), l.clone().subtract(0, 1, 0).getBlock())) {
return false;
}
if (spawner == null) {
return;
}
KList<IrisEntitySpawn> s = initial ? spawner.getInitialSpawns() : spawner.getSpawns();
if (s.isEmpty()) {
return;
}
IrisEntitySpawn ss = spawnRandomly(s).getRandom();
ss.setReferenceSpawner(spawner);
ss.setReferenceMarker(spawner.getReferenceMarker());
spawn(block, ss);
Vector3d boundingBox = BukkitPlatform.entityBoundingBox(BukkitEntitySpawner.bukkitType(attempt.entity()));
return boundingBox == null || isAreaClearForSpawn(l, boundingBox);
}
private Stream<IrisEntitySpawn> stream(IrisSpawner s, boolean initial) {
for (IrisEntitySpawn i : initial ? s.getInitialSpawns() : s.getSpawns()) {
i.setReferenceSpawner(s);
i.setReferenceMarker(s.getReferenceMarker());
}
private static boolean isAreaClearForSpawn(Location center, Vector3d boundingBox) {
World world = center.getWorld();
int startX = center.getBlockX() - (int) (boundingBox.x / 2);
int endX = center.getBlockX() + (int) (boundingBox.x / 2);
int startY = center.getBlockY();
int endY = center.getBlockY() + (int) boundingBox.y;
int startZ = center.getBlockZ() - (int) (boundingBox.z / 2);
int endZ = center.getBlockZ() + (int) (boundingBox.z / 2);
return (initial ? s.getInitialSpawns() : s.getSpawns()).stream();
for (int x = startX; x <= endX; x++) {
for (int y = startY; y <= endY; y++) {
for (int z = startZ; z <= endZ; z++) {
if (world.getBlockAt(x, y, z).getType() != Material.AIR) {
return false;
}
}
}
}
return true;
}
boolean isEntitySpawningEnabledForCurrentWorld() {
@@ -388,31 +404,4 @@ final class WorldEntitySpawner {
return IrisSettings.get().getStudio().isEntitySpawning();
}
private KList<IrisEntitySpawn> spawnRandomly(List<IrisEntitySpawn> types) {
return IRare.expandWeighted(types);
}
@Data
private static class ChunkCounter implements Predicate<IrisSpawner> {
private final Entity[] entities;
private transient int index = 0;
private transient int count = 0;
@Override
public boolean test(IrisSpawner spawner) {
int max = spawner.getMaxEntitiesPerChunk();
if (max <= count)
return false;
while (index < entities.length) {
if (entities[index++] instanceof LivingEntity) {
if (++count >= max)
return false;
}
}
return true;
}
}
}
@@ -0,0 +1,447 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.platform;
import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.core.link.Identifier;
import art.arcane.iris.core.modules.ModuleServices;
import art.arcane.iris.core.service.EntityRiseSVC;
import art.arcane.iris.core.service.ExternalDataSVC;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.platform.bukkit.BukkitAttributes;
import art.arcane.iris.platform.bukkit.BukkitItemStacks;
import art.arcane.iris.platform.bukkit.BukkitPlatform;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.IrisServices;
import art.arcane.iris.util.common.data.registry.RegistryUtil;
import art.arcane.iris.util.common.format.C;
import art.arcane.iris.util.common.plugin.Chunks;
import art.arcane.iris.util.common.scheduling.ConsoleCommands;
import art.arcane.iris.util.common.scheduling.J;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.M;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.scheduling.PrecisionStopwatch;
import com.volmit.entity.EntitySpec;
import com.volmit.item.ItemAttribute;
import com.volmit.service.Loot;
import com.volmit.world.BlockPosition;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.NamespacedKey;
import org.bukkit.Particle;
import org.bukkit.Sound;
import org.bukkit.attribute.Attributable;
import org.bukkit.entity.Ageable;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Mob;
import org.bukkit.entity.Panda;
import org.bukkit.entity.Panda.Gene;
import org.bukkit.entity.Villager;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.loot.LootContext;
import org.bukkit.loot.LootTable;
import org.bukkit.loot.Lootable;
import org.bukkit.util.Vector;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static art.arcane.iris.util.common.data.registry.Particles.ITEM;
/**
* Creates the entities a module planned ({@link EntitySpec}) on a Bukkit server: the entity itself, then everything the
* spec sets on it. Every random choice was made by the module; this class only acts on the platform.
*/
public final class BukkitEntitySpawner {
private static final long RISE_START_DEPTH_BLOCKS = 5;
private static final int RISE_MAX_TICKS = 100;
private static final int RISE_NO_DAMAGE_TICKS = 100000;
private static final double RISE_STEP_BLOCKS = 0.1;
private static final double RISE_SOUND_CHANCE = 0.2;
private static final int SPAWN_WAIT_SLEEP_MS = 25;
private static final int SPAWN_WAIT_LIMIT_MS = 500;
private static final String LOOT_TABLE_NAMESPACE = "iris";
private BukkitEntitySpawner() {
}
/** Spawns the pack's entity {@code key} at {@code at}, as a command asks for; null when the pack has no such entity or the spawn fails. */
public static Entity spawnByKey(Engine gen, String key, Location at) {
return ModuleServices.entity(gen, key).map(spec -> spawn(gen, spec, at)).orElse(null);
}
public static Entity spawn(Engine gen, EntitySpec spec, Location at) {
if (!Chunks.isSafe(at)) {
return null;
}
if (spec.riseOutOfGround()) {
at = startBelowGroundWhenWatched(at);
}
Entity ee = doSpawn(spec, at);
if (ee == null && !Chunks.isSafe(at)) {
return null;
}
if (spec.isSpecial() && !spec.applySettingsToSpecial()) {
return ee;
}
if (ee == null) {
return null;
}
Entity e = ee;
applyFlags(e, spec);
addPassengers(gen, e, spec, at);
if (e instanceof Attributable attributable) {
for (ItemAttribute attribute : spec.attributes()) {
BukkitAttributes.apply(attribute, attributable);
}
}
if (e instanceof Lootable lootable && !spec.lootTables().isEmpty()) {
bindLoot(spec, gen, lootable, at);
}
if (e instanceof LivingEntity living) {
applyLivingState(gen, living, spec, at);
}
if (e instanceof Ageable ageable && spec.flags().baby()) {
ageable.setBaby();
}
if (e instanceof Panda panda) {
panda.setMainGene(resolveGene(spec.pandaMainGene()));
panda.setHiddenGene(resolveGene(spec.pandaHiddenGene()));
}
if (e instanceof Villager villager) {
villager.setRemoveWhenFarAway(false);
villager.setPersistent(true);
}
if (e instanceof Mob mob) {
mob.setAware(spec.flags().aware());
}
if (spec.spawnEffect() != null) {
showSpawnEffect(e, spec.spawnEffect());
}
runCommands(spec, at);
Location riseFrom = at;
J.runEntity(e, () -> {
if (spec.riseOutOfGround() && e instanceof LivingEntity living && Chunks.hasPlayersNearby(riseFrom)) {
riseOutOfGround(e, living, riseFrom);
}
});
return e;
}
/** Players watching an entity that rises out of the ground see it start five blocks below the spot. */
private static Location startBelowGroundWhenWatched(Location at) {
AtomicReference<Location> start = new AtomicReference<>(at);
try {
J.sfut(() -> {
if (Chunks.hasPlayersNearby(start.get())) {
Location b = start.get().clone();
start.set(new Location(b.getWorld(), b.getX(), b.getY() - RISE_START_DEPTH_BLOCKS, b.getZ()));
}
}).get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
IrisLogging.reportError("Iris entity spawn preparation was interrupted.", e);
} catch (ExecutionException e) {
IrisLogging.reportError("Iris entity spawn preparation failed.", e);
}
return start.get();
}
private static void applyFlags(Entity e, EntitySpec spec) {
EntitySpec.Flags flags = spec.flags();
e.setCustomName(spec.customName() != null ? C.translateAlternateColorCodes('&', spec.customName()) : null);
e.setCustomNameVisible(flags.customNameVisible());
e.setGlowing(flags.glowing());
e.setGravity(flags.gravity());
e.setInvulnerable(flags.invulnerable());
e.setSilent(flags.silent());
e.setPersistent(flags.keepEntity() || IrisSettings.get().getWorld().isForcePersistEntities());
}
private static void addPassengers(Engine gen, Entity e, EntitySpec spec, Location at) {
for (EntitySpec passengerSpec : spec.passengers()) {
Entity passenger = spawn(gen, passengerSpec, at);
if (passenger == null) {
continue;
}
if (Bukkit.isPrimaryThread()) {
e.addPassenger(passenger);
} else {
J.runEntity(e, () -> e.addPassenger(passenger));
}
}
}
private static void applyLivingState(Engine gen, LivingEntity l, EntitySpec spec, Location at) {
l.setAI(spec.flags().ai());
l.setCanPickupItems(spec.flags().pickupItems());
if (spec.leashHolder() != null) {
l.setLeashHolder(spawn(gen, spec.leashHolder(), at));
}
l.setRemoveWhenFarAway(spec.flags().removable());
EntitySpec.Equipment equipment = spec.equipment();
if (equipment.helmet() != null) {
l.getEquipment().setHelmet(BukkitItemStacks.create(equipment.helmet()));
}
if (equipment.chestplate() != null) {
l.getEquipment().setChestplate(BukkitItemStacks.create(equipment.chestplate()));
}
if (equipment.leggings() != null) {
l.getEquipment().setLeggings(BukkitItemStacks.create(equipment.leggings()));
}
if (equipment.boots() != null) {
l.getEquipment().setBoots(BukkitItemStacks.create(equipment.boots()));
}
if (equipment.mainHand() != null) {
l.getEquipment().setItemInMainHand(BukkitItemStacks.create(equipment.mainHand()));
}
if (equipment.offHand() != null) {
l.getEquipment().setItemInOffHand(BukkitItemStacks.create(equipment.offHand()));
}
}
private static void runCommands(EntitySpec spec, Location at) {
for (EntitySpec.Command command : spec.commands()) {
ConsoleCommands.run(command.commands(), command.delay(), command.repeat(), command.repeatDelay(),
at.getBlockX(), at.getBlockY(), at.getBlockZ());
}
}
private static void riseOutOfGround(Entity e, LivingEntity living, Location from) {
Location start = from.clone();
boolean originalInvulnerable = e.isInvulnerable();
boolean originalAi = living.hasAI();
boolean originalCollidable = living.isCollidable();
int originalNoDamageTicks = living.getNoDamageTicks();
EntityRiseSVC.stamp(e, originalInvulnerable, originalAi, originalCollidable);
e.setInvulnerable(true);
living.setAI(false);
living.setCollidable(false);
living.setNoDamageTicks(RISE_NO_DAMAGE_TICKS);
Runnable restore = () -> restoreRiseState(e, living, originalInvulnerable, originalAi,
originalCollidable, originalNoDamageTicks);
AtomicInteger t = new AtomicInteger(0);
Runnable[] loop = new Runnable[1];
loop[0] = () -> {
if (t.get() > RISE_MAX_TICKS || e.isDead()) {
restore.run();
return;
}
t.incrementAndGet();
if (e.getLocation().getBlock().getType().isSolid() || living.getEyeLocation().getBlock().getType().isSolid()) {
e.teleport(start.add(new Vector(0, RISE_STEP_BLOCKS, 0)));
ItemStack itemCrackData = new ItemStack(living.getEyeLocation().clone().subtract(0, 2, 0).getBlock().getBlockData().getMaterial());
e.getWorld().spawnParticle(ITEM, living.getEyeLocation(), 6, 0.2, 0.4, 0.2, 0.06f, itemCrackData);
if (M.r(RISE_SOUND_CHANCE)) {
e.getWorld().playSound(e.getLocation(), Sound.BLOCK_CHORUS_FLOWER_GROW, 0.8f, 0.1f);
}
if (!J.runEntity(e, loop[0], 1, restore)) {
restore.run();
}
} else {
restore.run();
}
};
if (!J.runEntity(e, loop[0], 0, restore)) {
restore.run();
}
}
private static void restoreRiseState(Entity entity, LivingEntity living, boolean invulnerable,
boolean ai, boolean collidable, int noDamageTicks) {
living.setNoDamageTicks(noDamageTicks);
living.setCollidable(collidable);
living.setAI(ai);
entity.setInvulnerable(invulnerable);
EntityRiseSVC.clearStamp(entity);
}
private static Entity doSpawn(EntitySpec spec, Location at) {
if (!Chunks.isSafe(at)) {
return null;
}
if (EntityType.UNKNOWN.equals(bukkitType(spec)) && !spec.isSpecial()) {
return null;
}
if (!Bukkit.isPrimaryThread()) {
// Someone called spawn (worldedit maybe?) on a non server thread
// Due to the structure of iris, we will call it sync and busy wait until it's done.
AtomicReference<Entity> ae = new AtomicReference<>();
try {
if (!J.runAt(at, () -> ae.set(doSpawn(spec, at)))) {
return null;
}
} catch (Throwable e) {
return null;
}
PrecisionStopwatch p = PrecisionStopwatch.start();
while (ae.get() == null) {
J.sleep(SPAWN_WAIT_SLEEP_MS);
if (p.getMilliseconds() > SPAWN_WAIT_LIMIT_MS) {
return null;
}
}
return ae.get();
}
if (spec.isSpecial()) {
return IrisServices.get(ExternalDataSVC.class).spawnMob(at, Identifier.fromString(spec.specialType()));
}
return BukkitPlatform.spawnEntity(at, bukkitType(spec), bukkitReason(spec));
}
/** The platform's entity type of the spec, unknown when it names none. */
public static EntityType bukkitType(EntitySpec spec) {
if (spec.type().isBlank()) {
return EntityType.UNKNOWN;
}
NamespacedKey key = NamespacedKey.fromString(spec.type().trim().toLowerCase(Locale.ROOT));
if (key == null) {
return EntityType.UNKNOWN;
}
EntityType entityType = RegistryUtil.lookup(EntityType.class).get(key);
return entityType == null ? EntityType.UNKNOWN : entityType;
}
private static CreatureSpawnEvent.SpawnReason bukkitReason(EntitySpec spec) {
if (spec.reason() == null || spec.reason().isBlank()) {
return CreatureSpawnEvent.SpawnReason.NATURAL;
}
try {
return CreatureSpawnEvent.SpawnReason.valueOf(spec.reason().trim().toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException e) {
return CreatureSpawnEvent.SpawnReason.NATURAL;
}
}
private static Gene resolveGene(String gene) {
if (gene == null || gene.isBlank()) {
return Gene.NORMAL;
}
try {
return Gene.valueOf(gene.trim().toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException e) {
return Gene.NORMAL;
}
}
private static void showSpawnEffect(Entity p, EntitySpec.SpawnEffect fx) {
J.runEntity(p, () -> {
Sound soundType = fx.sound() == null ? null : resolveKeyed(Sound.class, fx.sound());
Particle particleType = fx.particle() == null ? null : resolveKeyed(Particle.class, fx.particle());
if (soundType != null) {
Location part = p.getLocation().clone().add(RNG.r.i(-fx.soundDistance(), fx.soundDistance()), RNG.r.i(-fx.soundDistance(), fx.soundDistance()), RNG.r.i(-fx.soundDistance(), fx.soundDistance()));
p.getWorld().playSound(part, soundType, (float) fx.volume(), (float) RNG.r.d(fx.minPitch(), fx.maxPitch()));
}
if (particleType != null) {
Location part = p.getLocation().clone().add(0, 0.25, 0).add(new Vector(1, 1, 1).multiply(RNG.r.d())).subtract(new Vector(1, 1, 1).multiply(RNG.r.d()));
part.add(RNG.r.d(), 0, RNG.r.d());
double motionX = fx.randomAltX() ? RNG.r.d(-fx.altX(), fx.altX()) : fx.altX();
double motionY = fx.randomAltY() ? RNG.r.d(-fx.altY(), fx.altY()) : fx.altY();
double motionZ = fx.randomAltZ() ? RNG.r.d(-fx.altZ(), fx.altZ()) : fx.altZ();
if (fx.extra() != 0) {
p.getWorld().spawnParticle(particleType, part.getX(), part.getY() + RNG.r.i(fx.particleOffset()), part.getZ(),
fx.particleCount(), motionX, motionY, motionZ, fx.extra());
} else {
p.getWorld().spawnParticle(particleType, part.getX(), part.getY() + RNG.r.i(fx.particleOffset()), part.getZ(),
fx.particleCount(), motionX, motionY, motionZ);
}
}
});
}
private static <T> T resolveKeyed(Class<T> type, String key) {
NamespacedKey namespacedKey = NamespacedKey.fromString(key);
return namespacedKey == null ? null : RegistryUtil.lookup(type).get(namespacedKey);
}
private static void bindLoot(EntitySpec spec, Engine gen, Lootable lootable, Location finalAt) {
lootable.setLootTable(new LootTable() {
@Override
public NamespacedKey getKey() {
return new NamespacedKey(LOOT_TABLE_NAMESPACE, "loot-" + spec.hashCode());
}
@Override
public Collection<ItemStack> populateLoot(Random random, LootContext context) {
BlockPosition position = new BlockPosition(finalAt.getBlockX(), finalAt.getBlockY() - gen.getMinHeight(), finalAt.getBlockZ());
Loot.Site site = new Loot.Site(position, null, false, gen.isStudio());
KList<ItemStack> items = new KList<>();
for (String table : spec.lootTables()) {
items.addAll(BukkitItemStacks.createAll(ModuleServices.lootItems(gen, site, table)));
}
return items;
}
@Override
public void fillInventory(Inventory inventory, Random random, LootContext context) {
for (ItemStack i : populateLoot(random, context)) {
inventory.addItem(i);
}
EngineBukkitOps.scramble(gen, inventory, new RNG(spec.lootShuffleSeed()));
}
});
}
}
@@ -0,0 +1,60 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.platform;
import com.volmit.service.EntitySpawns;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.data.Waterlogged;
/** Whether a block is the kind of ground or fluid an entity spawns on. */
public final class BukkitSurfaces {
private BukkitSurfaces() {
}
/** Whether {@code block} suits an entity that wants {@code surface} below it. */
public static boolean matches(EntitySpawns.Surface surface, Block block) {
Material type = block.getType();
if (type.isSolid()) {
return surface == EntitySpawns.Surface.LAND || surface == EntitySpawns.Surface.OVERWORLD
|| (surface == EntitySpawns.Surface.ANIMAL && isAnimalGround(type));
}
if (type == Material.LAVA) {
return surface == EntitySpawns.Surface.LAVA;
}
if (isWater(type, block)) {
return surface == EntitySpawns.Surface.WATER || surface == EntitySpawns.Surface.OVERWORLD;
}
return false;
}
private static boolean isAnimalGround(Material type) {
return type == Material.GRASS_BLOCK || type == Material.DIRT
|| type == Material.DIRT_PATH || type == Material.COARSE_DIRT
|| type == Material.ROOTED_DIRT || type == Material.PODZOL
|| type == Material.MYCELIUM || type == Material.SNOW_BLOCK;
}
private static boolean isWater(Material type, Block block) {
return type == Material.WATER || type == Material.SEAGRASS
|| type == Material.TALL_SEAGRASS || type == Material.KELP_PLANT
|| type == Material.KELP
|| (block.getBlockData() instanceof Waterlogged waterlogged && waterlogged.isWaterlogged());
}
}
@@ -0,0 +1,51 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.util.common.scheduling;
import art.arcane.iris.spi.IrisPlatforms;
import java.util.List;
/** Runs console commands for the pack: once or for ever, after a delay, with {@code {x}}, {@code {y}} and {@code {z}} filled in. */
public final class ConsoleCommands {
private ConsoleCommands() {
}
/**
* @param commands the commands, with an optional leading slash
* @param delay server ticks before the commands run
* @param repeat whether to run them again every {@code repeatDelay} ticks until the server stops
* @param repeatDelay server ticks between repeats
*/
public static void run(List<String> commands, long delay, boolean repeat, long repeatDelay, int x, int y, int z) {
for (String command : commands) {
String filled = (command.startsWith("/") ? command.replaceFirst("/", "") : command)
.replaceAll("\\Q{x}\\E", String.valueOf(x))
.replaceAll("\\Q{y}\\E", String.valueOf(y))
.replaceAll("\\Q{z}\\E", String.valueOf(z));
int safeDelay = (int) Math.max(0, Math.min(Integer.MAX_VALUE, delay));
if (repeat) {
int safeRepeatDelay = (int) Math.max(1, Math.min(Integer.MAX_VALUE, repeatDelay));
J.s(() -> J.sr(() -> IrisPlatforms.get().dispatchConsoleCommand(filled), safeRepeatDelay), safeDelay);
} else {
J.s(() -> IrisPlatforms.get().dispatchConsoleCommand(filled), safeDelay);
}
}
}
}
@@ -1,15 +0,0 @@
package art.arcane.iris.engine.object.entity;
import art.arcane.iris.engine.object.entity.IrisEntitySpawn;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import org.junit.Test;
import static org.junit.Assert.assertNull;
public class IrisEntitySpawnTest {
@Test
public void caveSpawnWithoutSafeMarkerIsSkipped() {
assertNull(IrisEntitySpawn.selectCaveSpawnLocation(new KList<>(), null, new RNG(1L)));
}
}
@@ -0,0 +1,179 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.spawn;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.loader.ResourceLoader;
import art.arcane.iris.core.modules.ModuleResourceFixture;
import art.arcane.iris.engine.UsableBlockPlatform;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineGeneration;
import art.arcane.iris.engine.framework.SeedManager;
import art.arcane.iris.engine.mantle.EngineMantle;
import art.arcane.iris.engine.object.entity.IrisEntity;
import art.arcane.iris.engine.object.entity.IrisEntitySpawn;
import art.arcane.iris.engine.object.entity.spawn.IrisSpawner;
import art.arcane.iris.engine.object.marker.IrisMarker;
import art.arcane.iris.engine.object.world.IrisWorld;
import art.arcane.iris.spi.PlatformWorld;
import art.arcane.volmlib.util.collection.KList;
import com.volmit.entity.EntitySpec;
import com.volmit.item.ItemRegistry;
import com.volmit.service.EntitySpawns;
import com.volmit.world.BlockPosition;
import com.volmit.world.PackWorld;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** What the spawn module plans for markers, and what its markers mean. */
public class EntitySpawningTest {
private static final BlockPosition MARKER_BLOCK = new BlockPosition(40, 70, -12);
private Engine engine;
private ResourceLoader<IrisSpawner> spawners;
private ResourceLoader<IrisMarker> markers;
private ResourceLoader<IrisEntity> entities;
private PackWorld world;
@BeforeClass
public static void bindPlatform() {
UsableBlockPlatform.bind();
}
@AfterClass
public static void unbindPlatform() {
UsableBlockPlatform.unbind();
}
@Before
@SuppressWarnings("unchecked")
public void buildWorld() {
engine = mock(Engine.class);
IrisData data = mock(IrisData.class);
spawners = (ResourceLoader<IrisSpawner>) mock(ResourceLoader.class);
markers = (ResourceLoader<IrisMarker>) mock(ResourceLoader.class);
entities = (ResourceLoader<IrisEntity>) mock(ResourceLoader.class);
when(engine.getData()).thenReturn(data);
when(data.getSpawnerLoader()).thenReturn(spawners);
when(data.getMarkerLoader()).thenReturn(markers);
when(data.getEntityLoader()).thenReturn(entities);
ModuleResourceFixture.serve(data);
when(data.getPackResources().items()).thenReturn(mock(ItemRegistry.class));
IrisWorld engineWorld = mock(IrisWorld.class);
when(engineWorld.platformWorld()).thenReturn(mock(PlatformWorld.class));
when(engine.getWorld()).thenReturn(engineWorld);
SeedManager seeds = mock(SeedManager.class);
when(seeds.getEntity()).thenReturn(11L);
when(engine.getSeedManager()).thenReturn(seeds);
world = new EngineGeneration(engine).world();
}
@Test
public void aCaveWithoutFloorMarkersHasNowhereToSpawn() {
EngineMantle mantle = mock(EngineMantle.class);
when(engine.getMantle()).thenReturn(mantle);
when(mantle.findMarkers(2, 3, art.arcane.volmlib.util.matter.slices.MarkerMatter.CAVE_FLOOR)).thenReturn(new KList<>());
assertNull(EntitySpawning.caveSpawnPosition(engine, 2, 3));
}
@Test
public void aMarkerMeansItsSpawnersAndWhetherItGoesAwayWhenItsBlockChanges() {
IrisMarker marker = new IrisMarker();
marker.setSpawners(new KList<>("zombies", "missing")).setEmptyAbove(true).setRemoveOnChange(false);
when(markers.load("camp")).thenReturn(marker);
when(spawners.load("zombies")).thenReturn(new IrisSpawner());
EntitySpawns.MarkerRule rule = new EntitySpawning().marker(world, "camp").orElseThrow();
assertEquals(List.of("zombies"), rule.spawners());
assertTrue(rule.emptyAbove());
assertFalse(rule.removeOnChange());
}
@Test
public void markersNoModuleKnowsAndTheCaveMarkersMeanNothing() {
assertTrue(new EntitySpawning().marker(world, "unknown").isEmpty());
assertTrue(new EntitySpawning().marker(world, "cave_floor").isEmpty());
}
@Test
public void aMarkerSpawnPlansEntitiesOneBlockAboveTheMarkerWithoutSurfaceChecks() {
IrisSpawner spawner = new IrisSpawner();
spawner.setLoadKey("camp/zombies");
spawner.getSpawns().add(new IrisEntitySpawn().setEntity("zombie").setMinSpawns(2).setMaxSpawns(2));
when(spawners.load("camp/zombies")).thenReturn(spawner);
IrisMarker marker = new IrisMarker();
marker.setExhaustionChance(2);
when(markers.load("camp")).thenReturn(marker);
IrisEntity zombie = new IrisEntity();
zombie.setType("minecraft:zombie");
when(entities.load("zombie")).thenReturn(zombie);
when(engine.getMinHeight()).thenReturn(-64);
EntitySpawns.Plan plan = new EntitySpawning()
.plan(world, new EntitySpawns.Marker(MARKER_BLOCK, "camp", "camp/zombies", false))
.orElseThrow();
assertEquals("camp/zombies", plan.spawner());
assertTrue("an exhaustion chance above 1 always uses the marker up", plan.exhaustsMarker());
assertEquals(2, plan.attempts().size());
for (EntitySpawns.Attempt attempt : plan.attempts()) {
assertEquals(new BlockPosition(40, 71, -12), attempt.at());
assertFalse(attempt.checkSurface());
assertEquals("minecraft:zombie", attempt.entity().type());
}
}
@Test
public void aSpawnerThatCannotFireOrHasNoEntitiesPlansNothing() {
IrisSpawner empty = new IrisSpawner();
when(spawners.load("empty")).thenReturn(empty);
Optional<EntitySpawns.Plan> plan = new EntitySpawning().plan(world, new EntitySpawns.Marker(MARKER_BLOCK, "camp", "empty", false));
assertTrue(plan.isEmpty());
}
@Test
public void anEntityOfThePackResolvesToTheSpecTheHostSpawns() {
IrisEntity entity = new IrisEntity();
entity.setType("minecraft:cow").setCustomName("&6Bessie").setBaby(true);
when(entities.load("cow")).thenReturn(entity);
EntitySpec spec = new EntitySpawning().entity(world, "cow").orElseThrow();
assertEquals("minecraft:cow", spec.type());
assertEquals("&6Bessie", spec.customName());
assertTrue(spec.flags().baby());
assertTrue(new EntitySpawning().entity(world, "nothing").isEmpty());
}
}