Modded loot, drops, spawns, mobs and effects ask the modules through host-typed content services

This commit is contained in:
piexel committed 2026-10-10 13:00:03 +02:00
1 parent f404dec7d7
commit fbbc9ce4ac
24 files changed
+1178 -944

No files matched your search

@@ -18,21 +18,13 @@
package art.arcane.iris.modded;
import art.arcane.iris.engine.spawn.SpawnResources;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.content.ContentLoot;
import art.arcane.iris.core.content.ContentServices;
import art.arcane.iris.core.content.ContentSpawns;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.LootResolver;
import art.arcane.iris.engine.framework.TreeBlockMaterial;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.material.IrisBlockData;
import art.arcane.iris.engine.object.loot.IrisBlockDrops;
import art.arcane.iris.engine.object.loot.IrisLoot;
import art.arcane.iris.engine.object.marker.IrisMarker;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.modded.service.ModdedTreeFellerService;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.matter.MatterMarker;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
@@ -204,26 +196,13 @@ public final class ModdedBlockBreakHandler {
BlockState brokenState,
Engine engine
) {
KList<IrisBlockDrops> providers = providers(engine, position, brokenState);
if (providers.isEmpty()) {
ContentLoot.BlockDrops dropped = ContentServices.blockDrops(engine, position.getX(), position.getY(), position.getZ(),
ModdedBlockState.serialize(brokenState));
if (dropped.drops().isEmpty() && !dropped.replacesVanillaDrops()) {
return Result.empty();
}
KList<ItemStack> drops = new KList<>();
boolean replaceVanillaDrops = false;
for (IrisBlockDrops provider : providers) {
replaceVanillaDrops |= provider.isReplaceVanillaDrops();
for (IrisLoot loot : provider.getDrops()) {
if (!LootResolver.oneIn(RNG.r, loot.getRarity())) {
continue;
}
ItemStack stack = ModdedItemTranslator.stack(loot, RNG.r, level);
if (stack != null && !stack.isEmpty()) {
drops.add(stack);
}
}
}
return new Result(drops, replaceVanillaDrops, null);
return new Result(ModdedItemTranslator.stacks(dropped.drops(), level), dropped.replacesVanillaDrops(), null);
}
private static void removeMarker(Engine engine, BlockPos position) {
@@ -236,8 +215,7 @@ public final class ModdedBlockBreakHandler {
if ("cave_floor".equals(tag) || "cave_ceiling".equals(tag)) {
return;
}
IrisMarker configured = SpawnResources.marker(engine.getData(), tag);
if (configured == null || configured.isRemoveOnChange()) {
if (ContentServices.markerRule(engine, tag).map(ContentSpawns.MarkerRule::removeOnChange).orElse(true)) {
engine.getMantle().getMantle().remove(position.getX(), mantleY, position.getZ(), MatterMarker.class);
}
}
@@ -248,59 +226,6 @@ public final class ModdedBlockBreakHandler {
engine.getMantle().getMantle().remove(position.getX(), mantleY, position.getZ(), TreeBlockMaterial.class);
}
private static KList<IrisBlockDrops> providers(Engine engine, BlockPos position, BlockState brokenState) {
KList<IrisBlockDrops> providers = new KList<>();
IrisData data = engine.getData();
int relativeY = position.getY() - engine.getMinHeight();
IrisBiome biome = engine.getBiome(position.getX(), relativeY, position.getZ());
if (biome != null) {
addMatching(providers, biome.getBlockDrops(), brokenState, data);
}
if (skipsParents(providers)) {
return providers;
}
IrisRegion region = engine.getRegion(position.getX(), position.getZ());
if (region != null) {
addMatching(providers, region.getBlockDrops(), brokenState, data);
}
addMatching(providers, engine.getDimension().getBlockDrops(), brokenState, data);
return providers;
}
private static void addMatching(KList<IrisBlockDrops> matches, KList<IrisBlockDrops> candidates, BlockState brokenState, IrisData data) {
for (IrisBlockDrops candidate : candidates) {
if (matches(candidate, brokenState, data)) {
matches.add(candidate);
}
}
}
private static boolean skipsParents(KList<IrisBlockDrops> providers) {
for (IrisBlockDrops provider : providers) {
if (provider.isSkipParents()) {
return true;
}
}
return false;
}
private static boolean matches(IrisBlockDrops provider, BlockState brokenState, IrisData data) {
for (IrisBlockData configuredBlock : provider.getBlocks()) {
PlatformBlockState resolved = configuredBlock.getBlockData(data);
if (resolved == null || !(resolved.nativeHandle() instanceof BlockState configuredState)) {
continue;
}
if (matchesState(configuredState, brokenState, provider.isExactBlocks())) {
return true;
}
}
return false;
}
static boolean matchesState(BlockState configuredState, BlockState brokenState, boolean exact) {
return exact ? configuredState.equals(brokenState) : configuredState.getBlock() == brokenState.getBlock();
}
public static Engine engineFor(ServerLevel level) {
ChunkGenerator generator = level.getChunkSource().getGenerator();
if (!(generator instanceof IrisModdedChunkGenerator irisGenerator)) {
@@ -18,10 +18,8 @@
package art.arcane.iris.modded;
import art.arcane.iris.engine.loot.LootResources;
import art.arcane.iris.core.content.ContentServices;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.object.loot.InventorySlotType;
import art.arcane.iris.engine.object.loot.IrisLootTable;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
@@ -34,22 +32,23 @@ import net.minecraft.world.entity.vehicle.ContainerEntity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.chunk.ChunkGenerator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public final class ModdedDeathLoot {
private static final String TAG_PREFIX = "iris_loot|";
private static final Set<String> WARNED_TABLES = ConcurrentHashMap.newKeySet();
private static final Set<String> WARNED_ENTITY_TYPES = ConcurrentHashMap.newKeySet();
private ModdedDeathLoot() {
}
public static void bind(Engine engine, Entity entity, KList<String> tableKeys, int spawnX, int spawnY, int spawnZ, RNG rng) {
/** Makes the loot of the pack's tables {@code tableKeys} the loot {@code entity} drops, or holds if it is a container; {@code shuffleSeed} seeds how a container's loot is shuffled. */
public static void bind(Engine engine, Entity entity, List<String> tableKeys, int spawnX, int spawnY, int spawnZ, long shuffleSeed) {
if (engine == null || entity == null || tableKeys == null || tableKeys.isEmpty()) {
return;
}
LootBinding binding = new LootBinding(rng.getSeed(), spawnX, spawnY, spawnZ, new KList<>(tableKeys));
LootBinding binding = new LootBinding(shuffleSeed, spawnX, spawnY, spawnZ, new KList<>(tableKeys));
if (entity instanceof Mob) {
entity.addTag(encode(binding));
return;
@@ -105,15 +104,8 @@ public final class ModdedDeathLoot {
private static KList<ItemStack> resolve(Engine engine, ServerLevel level, LootBinding binding) {
KList<ItemStack> drops = new KList<>();
for (String key : binding.tableKeys()) {
IrisLootTable table = LootResources.table(engine.getData(), key);
if (table == null) {
if (WARNED_TABLES.add(key)) {
IrisLogging.warn("Iris death loot: unknown loot table '" + key + "'");
}
continue;
}
drops.addAll(ModdedItemTranslator.loot(table, engine.getSeedManager().getLoot(), InventorySlotType.STORAGE, level,
binding.spawnX(), binding.spawnY(), binding.spawnZ()));
drops.addAll(ModdedItemTranslator.stacks(
ContentServices.tableItems(engine, binding.spawnX(), binding.spawnY(), binding.spawnZ(), key), level));
}
return drops;
}
@@ -19,14 +19,11 @@
package art.arcane.iris.modded;
import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.core.content.ContentEffect;
import art.arcane.iris.core.content.ContentServices;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineAssignedComponent;
import art.arcane.iris.engine.framework.EngineEffects;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.marker.IrisCommand;
import art.arcane.iris.engine.object.marker.IrisCommandRegistry;
import art.arcane.iris.engine.object.entity.IrisEffect;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.volmlib.util.math.RNG;
import net.minecraft.core.Holder;
@@ -194,17 +191,16 @@ public final class ModdedEngineEffects extends EngineAssignedComponent implement
}
samplePlayer(state);
if (!IrisSettings.get().getWorld().isEffectSystem()) {
if (!IrisSettings.get().getWorld().isEffectSystem() || !state.sampled()) {
return;
}
IrisRegion region = state.region();
if (region != null) {
applyEffects(level, player, region.getEffects());
}
IrisBiome biome = state.biome();
if (biome != null) {
applyEffects(level, player, biome.getEffects());
for (ContentEffect effect : ContentServices.ambientEffects(getEngine(), state.sampledX(), state.sampledY(), state.sampledZ())) {
try {
applyEffect(level, player, effect);
} catch (Throwable error) {
IrisLogging.reportError(error);
}
}
}
@@ -222,36 +218,24 @@ public final class ModdedEngineEffects extends EngineAssignedComponent implement
state.sampled(true);
state.lastPosition(player.getX(), player.getY(), player.getZ());
state.lastSample(now);
int blockX = floor(player.getX());
int blockY = floor(player.getY()) - getEngine().getWorld().minHeight();
int blockZ = floor(player.getZ());
state.biome(getEngine().getBiome(blockX, blockY, blockZ));
state.region(getEngine().getRegion(blockX, blockZ));
state.sampledAt(floor(player.getX()), floor(player.getY()), floor(player.getZ()));
}
private void applyEffects(ServerLevel level, ServerPlayer player, Iterable<IrisEffect> effects) {
for (IrisEffect effect : effects) {
try {
applyEffect(level, player, effect);
} catch (Throwable error) {
IrisLogging.reportError(error);
}
private void applyEffect(ServerLevel level, ServerPlayer player, ContentEffect effect) {
if (effect.sound() != null) {
applySound(player, effect.sound());
}
if (effect.particles() != null) {
applyParticles(level, player, effect.particles());
}
applyCommands(level, player, effect.commands());
if (effect.potion() != null) {
applyPotion(player, effect.potion());
}
}
private void applyEffect(ServerLevel level, ServerPlayer player, IrisEffect effect) {
if (!effect.shouldApplyNow()) {
return;
}
applySound(player, effect);
applyParticles(level, player, effect);
applyCommands(level, player, effect.getCommandRegistry());
applyPotion(player, effect);
}
private void applySound(ServerPlayer player, IrisEffect effect) {
String key = normalizeRegistryKey(effect.getSoundKey());
private void applySound(ServerPlayer player, ContentEffect.Sound effect) {
String key = normalizeRegistryKey(effect.key());
if (key == null) {
return;
}
@@ -264,18 +248,13 @@ public final class ModdedEngineEffects extends EngineAssignedComponent implement
return;
}
int distance = effect.getSoundDistance();
double x = player.getX() + RNG.r.i(-distance, distance);
double y = player.getY() + RNG.r.i(-distance, distance);
double z = player.getZ() + RNG.r.i(-distance, distance);
float volume = (float) effect.getVolume();
float pitch = (float) RNG.r.d(effect.getMinPitch(), effect.getMaxPitch());
player.connection.send(new ClientboundSoundPacket(
sound.get(), SoundSource.MASTER, x, y, z, volume, pitch, ThreadLocalRandom.current().nextLong()));
sound.get(), SoundSource.MASTER, player.getX() + effect.offsetX(), player.getY() + effect.offsetY(),
player.getZ() + effect.offsetZ(), effect.volume(), effect.pitch(), ThreadLocalRandom.current().nextLong()));
}
private void applyParticles(ServerLevel level, ServerPlayer player, IrisEffect effect) {
String key = normalizeRegistryKey(effect.getParticleEffectKey());
private void applyParticles(ServerLevel level, ServerPlayer player, ContentEffect.Particles effect) {
String key = normalizeRegistryKey(effect.key());
if (key == null) {
return;
}
@@ -295,59 +274,34 @@ public final class ModdedEngineEffects extends EngineAssignedComponent implement
}
Vec3 direction = player.getLookAngle();
double forward = RNG.r.i(effect.getParticleDistance()) + effect.getParticleAway();
double sideways = RNG.r.d(-effect.getParticleDistanceWidth(), effect.getParticleDistanceWidth());
double surfaceX = player.getX() + direction.x * forward + direction.z * sideways;
double surfaceZ = player.getZ() + direction.z * forward - direction.x * sideways;
double surfaceX = player.getX() + direction.x * effect.forward() + direction.z * effect.sideways();
double surfaceZ = player.getZ() + direction.z * effect.forward() - direction.x * effect.sideways();
int surfaceY = getEngine().getHeight(floor(surfaceX), floor(surfaceZ));
double x = surfaceX + RNG.r.d();
double y = surfaceY + 1.0D + level.getMinY() + RNG.r.i(effect.getParticleOffset());
double z = surfaceZ + RNG.r.d();
double altX = randomized(effect.getParticleAltX(), effect.isRandomAltX());
double altY = randomized(effect.getParticleAltY(), effect.isRandomAltY());
double altZ = randomized(effect.getParticleAltZ(), effect.isRandomAltZ());
double x = surfaceX + effect.jitterX();
double y = surfaceY + 1.0D + level.getMinY() + effect.lift();
double z = surfaceZ + effect.jitterZ();
level.sendParticles(player, simpleParticle, false, false,
x, y, z, effect.getParticleCount(), altX, altY, altZ, effect.getExtra());
x, y, z, effect.count(), effect.altX(), effect.altY(), effect.altZ(), effect.extra());
}
private void applyCommands(ServerLevel level, ServerPlayer player, IrisCommandRegistry registry) {
if (registry == null || registry.getRawCommands() == null || registry.getRawCommands().isEmpty()) {
return;
}
ModdedPlatformWorld world = new ModdedPlatformWorld(level);
double x = commandCoordinate(player.getX(), registry.getCommandOffsetX(), registry.isCommandRandomAltX());
double y = commandCoordinate(player.getY(), registry.getCommandOffsetY(), registry.isCommandRandomAltY());
double z = commandCoordinate(player.getZ(), registry.getCommandOffsetZ(), registry.isCommandRandomAltZ());
for (IrisCommand command : registry.getRawCommands()) {
command.run(world, floor(x), floor(y), floor(z));
if (registry.isCommandAllRandomLocations()) {
x = commandCoordinate(player.getX(), registry.getCommandOffsetX(), registry.isCommandRandomAltX());
y = commandCoordinate(player.getY(), registry.getCommandOffsetY(), registry.isCommandRandomAltY());
z = commandCoordinate(player.getZ(), registry.getCommandOffsetZ(), registry.isCommandRandomAltZ());
}
private void applyCommands(ServerLevel level, ServerPlayer player, List<ContentEffect.Command> commands) {
for (ContentEffect.Command command : commands) {
ModdedEntityCommandRunner.run(List.of(command.command()), level, floor(player.getX() + command.offsetX()),
floor(player.getY() + command.offsetY()), floor(player.getZ() + command.offsetZ()));
}
}
private void applyPotion(ServerPlayer player, IrisEffect effect) {
int strength = effect.getPotionStrength();
if (strength < 0) {
return;
}
Holder<MobEffect> type = resolvePotion(effect.getPotionEffect());
private void applyPotion(ServerPlayer player, ContentEffect.Potion effect) {
Holder<MobEffect> type = resolvePotion(effect.key());
MobEffectInstance current = player.getEffect(type);
if (current != null && !shouldReplacePotionEffect(current.getAmplifier(), strength)) {
if (current != null && !shouldReplacePotionEffect(current.getAmplifier(), effect.strength())) {
return;
}
if (current != null) {
player.removeEffect(type);
}
int minimum = Math.min(effect.getPotionTicksMin(), effect.getPotionTicksMax());
int maximum = Math.max(effect.getPotionTicksMin(), effect.getPotionTicksMax());
int duration = RNG.r.i(minimum, maximum);
player.addEffect(new MobEffectInstance(type, duration, strength, true, false, false));
player.addEffect(new MobEffectInstance(type, effect.ticks(), effect.strength(), true, false, false));
}
private Holder<MobEffect> resolvePotion(String rawKey) {
@@ -405,14 +359,6 @@ public final class ModdedEngineEffects extends EngineAssignedComponent implement
return (int) Math.floor(value);
}
private static double randomized(double value, boolean random) {
return random ? RNG.r.d(-value, value) : value;
}
private static double commandCoordinate(double base, double offset, boolean random) {
return base + randomized(offset, random);
}
private static void warnUnknown(Set<String> warned, String type, String key) {
if (warned.add(key)) {
IrisLogging.warn("Unknown " + type + " type: \"" + key + "\".");
@@ -421,8 +367,9 @@ public final class ModdedEngineEffects extends EngineAssignedComponent implement
private static final class PlayerState {
private ServerPlayer player;
private IrisBiome biome;
private IrisRegion region;
private int sampledX;
private int sampledY;
private int sampledZ;
private double lastX;
private double lastY;
private double lastZ;
@@ -446,20 +393,22 @@ public final class ModdedEngineEffects extends EngineAssignedComponent implement
this.player = player;
}
private IrisBiome biome() {
return biome;
private int sampledX() {
return sampledX;
}
private void biome(IrisBiome biome) {
this.biome = biome;
private int sampledY() {
return sampledY;
}
private IrisRegion region() {
return region;
private int sampledZ() {
return sampledZ;
}
private void region(IrisRegion region) {
this.region = region;
private void sampledAt(int x, int y, int z) {
sampledX = x;
sampledY = y;
sampledZ = z;
}
private double lastX() {
@@ -1,16 +1,18 @@
package art.arcane.iris.modded;
import art.arcane.iris.engine.object.marker.IrisCommand;
import art.arcane.iris.core.content.ContentEntity;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.volmlib.util.collection.KList;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import java.util.List;
final class ModdedEntityCommandRunner {
private ModdedEntityCommandRunner() {
}
static void run(KList<IrisCommand> commands, ServerLevel level, int blockX, int blockY, int blockZ) {
/** Schedules the commands, which a module already checked against the time and weather, at the block. */
static void run(List<ContentEntity.Command> commands, ServerLevel level, int blockX, int blockY, int blockZ) {
if (commands.isEmpty()) {
return;
}
@@ -21,24 +23,20 @@ final class ModdedEntityCommandRunner {
return;
}
ModdedPlatformWorld world = new ModdedPlatformWorld(level);
for (IrisCommand command : commands) {
if (command == null || !command.isValid(world)) {
continue;
}
for (ContentEntity.Command command : commands) {
schedule(command, server, scheduler, blockX, blockY, blockZ);
}
}
private static void schedule(IrisCommand command, MinecraftServer server, ModdedScheduler scheduler, int blockX, int blockY, int blockZ) {
int delay = clampDelay(command.getDelay(), 0);
int repeatDelay = clampDelay(command.getRepeatDelay(), 1);
for (String raw : command.getCommands()) {
private static void schedule(ContentEntity.Command command, MinecraftServer server, ModdedScheduler scheduler, int blockX, int blockY, int blockZ) {
int delay = clampDelay(command.delay(), 0);
int repeatDelay = clampDelay(command.repeatDelay(), 1);
for (String raw : command.commands()) {
String prepared = prepareCommand(raw, blockX, blockY, blockZ);
if (prepared == null) {
continue;
}
if (command.isRepeat()) {
if (command.repeat()) {
scheduler.laterGlobal(() -> new RepeatingCommand(server, scheduler, prepared, repeatDelay).run(), delay);
} else {
scheduler.laterGlobal(() -> ModdedServerCommands.dispatch(server, prepared), delay);
@@ -20,14 +20,10 @@ package art.arcane.iris.modded;
import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.LootResolver;
import art.arcane.iris.engine.object.entity.IrisAttributeModifier;
import art.arcane.iris.engine.object.entity.IrisEntity;
import art.arcane.iris.engine.object.entity.IrisEffect;
import art.arcane.iris.engine.object.loot.IrisLoot;
import art.arcane.iris.core.content.ContentEntity;
import art.arcane.iris.core.content.ContentItem;
import art.arcane.iris.modded.api.ModdedCustomContentRegistry;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
@@ -82,8 +78,9 @@ public final class ModdedEntitySpawner {
private ModdedEntitySpawner() {
}
public static Entity spawn(Engine engine, IrisEntity irisEntity, ServerLevel level, int blockX, int blockY, int blockZ, RNG rng) {
if (engine == null || irisEntity == null || level == null) {
/** Spawns {@code entity}, whose every random choice a module made, at the block; null when it cannot appear. */
public static Entity spawn(Engine engine, ContentEntity entity, ServerLevel level, int blockX, int blockY, int blockZ) {
if (engine == null || entity == null || level == null) {
return null;
}
if (!chunksSafe(level, blockX >> 4, blockZ >> 4)) {
@@ -93,73 +90,71 @@ public final class ModdedEntitySpawner {
double x = blockX + 0.5;
double y = blockY + 0.5;
double z = blockZ + 0.5;
boolean riseEffectActive = irisEntity.isSpawnEffectRiseOutOfGround() && hasPlayersNearby(level, x, y, z);
boolean riseEffectActive = entity.riseOutOfGround() && hasPlayersNearby(level, x, y, z);
int spawnBlockY = riseEffectActive ? blockY - 5 : blockY;
double spawnY = spawnBlockY + 0.5;
Entity created = create(irisEntity, level, x, spawnY, z);
Entity created = create(entity, level, x, spawnY, z);
if (created == null) {
return null;
}
if (irisEntity.isSpecialType() && !irisEntity.isApplySettingsToCustomMobAnyways()) {
if (entity.isSpecial() && !entity.applySettingsToSpecial()) {
return created;
}
applyConfig(engine, irisEntity, created, level, blockX, spawnBlockY, blockZ, rng, riseEffectActive);
applyConfig(engine, entity, created, level, blockX, spawnBlockY, blockZ, riseEffectActive);
return created;
}
private static Entity create(IrisEntity irisEntity, ServerLevel level, double x, double y, double z) {
if (irisEntity.isSpecialType()) {
return ModdedCustomContentRegistry.spawnMob(level, x, y, z, irisEntity.getSpecialType());
private static Entity create(ContentEntity entity, ServerLevel level, double x, double y, double z) {
if (entity.isSpecial()) {
return ModdedCustomContentRegistry.spawnMob(level, x, y, z, entity.specialType());
}
EntityType<?> type = resolveType(irisEntity.getType());
EntityType<?> type = resolveType(entity.type());
if (type == null) {
return null;
}
Entity entity = type.spawn(level, BlockPos.containing(x, y, z), reasonFor(irisEntity.getReason()));
if (entity != null) {
entity.snapTo(x, y, z, 0F, 0F);
Entity created = type.spawn(level, BlockPos.containing(x, y, z), reasonFor(entity.reason()));
if (created != null) {
created.snapTo(x, y, z, 0F, 0F);
}
return entity;
return created;
}
private static void applyConfig(Engine engine, IrisEntity irisEntity, Entity entity, ServerLevel level, int blockX, int blockY, int blockZ, RNG rng, boolean riseEffectActive) {
String customName = irisEntity.getCustomName();
if (customName != null) {
entity.setCustomName(Component.literal(colorize(customName)));
}
entity.setCustomNameVisible(irisEntity.isCustomNameVisible());
entity.setGlowingTag(irisEntity.isGlowing());
entity.setNoGravity(!irisEntity.isGravity());
entity.setInvulnerable(irisEntity.isInvulnerable());
entity.setSilent(irisEntity.isSilent());
private static void applyConfig(Engine engine, ContentEntity spec, Entity entity, ServerLevel level, int blockX, int blockY, int blockZ, boolean riseEffectActive) {
ContentEntity.Flags flags = spec.flags();
entity.setCustomName(Component.literal(colorize(spec.customName())));
entity.setCustomNameVisible(flags.customNameVisible());
entity.setGlowingTag(flags.glowing());
entity.setNoGravity(!flags.gravity());
entity.setInvulnerable(flags.invulnerable());
entity.setSilent(flags.silent());
boolean persistent = irisEntity.isKeepEntity() || forcePersist();
boolean persistent = flags.keepEntity() || forcePersist();
applyPersistence(entity, persistent);
applyPassengers(engine, irisEntity, entity, level, blockX, blockY, blockZ, rng);
applyPassengers(engine, spec, entity, level, blockX, blockY, blockZ);
if (entity instanceof LivingEntity living) {
applyAttributes(irisEntity, living, level, rng);
applyAttributes(spec, living, level);
}
if (!irisEntity.getLoot().getTables().isEmpty()) {
ModdedDeathLoot.bind(engine, entity, irisEntity.getLoot().getTables(), blockX, blockY, blockZ, rng);
if (!spec.lootTables().isEmpty()) {
ModdedDeathLoot.bind(engine, entity, spec.lootTables(), blockX, blockY, blockZ, spec.lootShuffleSeed());
}
if (entity instanceof Mob mob) {
mob.setNoAi(shouldDisableAi(irisEntity.isAi()));
ModdedEntityAwareness.configure(mob, irisEntity.isAware());
mob.setCanPickUpLoot(irisEntity.isPickupItems());
if (!irisEntity.isRemovable()) {
mob.setNoAi(shouldDisableAi(flags.ai()));
ModdedEntityAwareness.configure(mob, flags.aware());
mob.setCanPickUpLoot(flags.pickupItems());
if (!flags.removable()) {
mob.setPersistenceRequired();
}
if (irisEntity.getLeashHolder() != null) {
Entity holder = spawn(engine, irisEntity.getLeashHolder(), level, blockX, blockY, blockZ, rng.nextParallelRNG(LEASH_RNG_SEED));
if (spec.leashHolder() != null) {
Entity holder = spawn(engine, spec.leashHolder(), level, blockX, blockY, blockZ);
if (holder != null) {
mob.setLeashedTo(holder, true);
}
@@ -167,56 +162,51 @@ public final class ModdedEntitySpawner {
}
if (entity instanceof LivingEntity equippable) {
applyEquipment(irisEntity, equippable, level, rng);
applyEquipment(spec, equippable, level);
}
if (irisEntity.isBaby()) {
if (flags.baby()) {
applyBaby(entity);
}
if (entity instanceof Panda panda) {
panda.setMainGene(gene(irisEntity.getPandaMainGene()));
panda.setHiddenGene(gene(irisEntity.getPandaHiddenGene()));
panda.setMainGene(gene(spec.pandaMainGene()));
panda.setHiddenGene(gene(spec.pandaHiddenGene()));
}
if (entity instanceof Villager villager) {
ModdedEntityPersistence.configure(villager, true);
}
applySpawnEffect(irisEntity.getSpawnEffect(), entity, level);
ModdedEntityCommandRunner.run(irisEntity.getRawCommands(), level, blockX, blockY, blockZ);
applySpawnEffect(spec.spawnEffect(), entity, level);
ModdedEntityCommandRunner.run(spec.commands(), level, blockX, blockY, blockZ);
if (riseEffectActive && entity instanceof LivingEntity living) {
startRiseEffect(engine, level, entity, living);
}
}
private static void applyPassengers(Engine engine, IrisEntity irisEntity, Entity entity, ServerLevel level, int blockX, int blockY, int blockZ, RNG rng) {
int index = 0;
for (IrisEntity passengerEntity : irisEntity.getPassengers()) {
Entity passenger = spawn(engine, passengerEntity, level, blockX, blockY, blockZ, rng.nextParallelRNG(PASSENGER_RNG_BASE + index++));
private static void applyPassengers(Engine engine, ContentEntity spec, Entity entity, ServerLevel level, int blockX, int blockY, int blockZ) {
for (ContentEntity passengerSpec : spec.passengers()) {
Entity passenger = spawn(engine, passengerSpec, level, blockX, blockY, blockZ);
if (passenger != null) {
passenger.startRiding(entity);
}
}
}
private static void applyAttributes(IrisEntity irisEntity, LivingEntity living, ServerLevel level, RNG rng) {
KList<IrisAttributeModifier> modifiers = irisEntity.getAttributes();
if (modifiers.isEmpty()) {
private static void applyAttributes(ContentEntity spec, LivingEntity living, ServerLevel level) {
if (spec.attributes().isEmpty()) {
return;
}
Registry<Attribute> registry = level.registryAccess().lookupOrThrow(Registries.ATTRIBUTE);
int index = 0;
for (IrisAttributeModifier modifier : modifiers) {
for (ContentItem.Attribute modifier : spec.attributes()) {
index++;
if (rng.nextDouble() >= modifier.getChance()) {
continue;
}
Holder<Attribute> holder = ModdedItemTranslator.resolveAttribute(registry, modifier.getAttribute());
Holder<Attribute> holder = ModdedItemTranslator.resolveAttribute(registry, modifier.attribute());
if (holder == null) {
if (WARNED_ATTRIBUTES.add(modifier.getAttribute())) {
IrisLogging.warn("Iris entity: unknown attribute '" + modifier.getAttribute() + "'");
if (WARNED_ATTRIBUTES.add(modifier.attribute())) {
IrisLogging.warn("Iris entity: unknown attribute '" + modifier.attribute() + "'");
}
continue;
}
@@ -224,28 +214,29 @@ public final class ModdedEntitySpawner {
if (instance == null) {
continue;
}
Identifier id = Identifier.tryParse("iris:" + normalizeName(modifier.getName()) + "_" + index);
Identifier id = Identifier.tryParse("iris:" + normalizeName(modifier.name()) + "_" + index);
if (id == null) {
continue;
}
instance.addOrReplacePermanentModifier(new AttributeModifier(id, modifier.getAmount(rng), ModdedItemTranslator.operationFor(modifier.getOperation())));
instance.addOrReplacePermanentModifier(new AttributeModifier(id, modifier.amount(), ModdedItemTranslator.operationFor(modifier.operation())));
}
}
private static void applyEquipment(IrisEntity irisEntity, LivingEntity living, ServerLevel level, RNG rng) {
setSlot(living, EquipmentSlot.HEAD, irisEntity.getHelmet(), level, rng);
setSlot(living, EquipmentSlot.CHEST, irisEntity.getChestplate(), level, rng);
setSlot(living, EquipmentSlot.LEGS, irisEntity.getLeggings(), level, rng);
setSlot(living, EquipmentSlot.FEET, irisEntity.getBoots(), level, rng);
setSlot(living, EquipmentSlot.MAINHAND, irisEntity.getMainHand(), level, rng);
setSlot(living, EquipmentSlot.OFFHAND, irisEntity.getOffHand(), level, rng);
private static void applyEquipment(ContentEntity spec, LivingEntity living, ServerLevel level) {
ContentEntity.Equipment equipment = spec.equipment();
setSlot(living, EquipmentSlot.HEAD, equipment.helmet(), level);
setSlot(living, EquipmentSlot.CHEST, equipment.chestplate(), level);
setSlot(living, EquipmentSlot.LEGS, equipment.leggings(), level);
setSlot(living, EquipmentSlot.FEET, equipment.boots(), level);
setSlot(living, EquipmentSlot.MAINHAND, equipment.mainHand(), level);
setSlot(living, EquipmentSlot.OFFHAND, equipment.offHand(), level);
}
private static void setSlot(LivingEntity living, EquipmentSlot slot, IrisLoot loot, ServerLevel level, RNG rng) {
if (loot == null || !LootResolver.oneIn(rng, loot.getRarity())) {
private static void setSlot(LivingEntity living, EquipmentSlot slot, ContentItem item, ServerLevel level) {
if (item == null) {
return;
}
ItemStack stack = ModdedItemTranslator.stack(loot, rng, level);
ItemStack stack = ModdedItemTranslator.stack(item, level);
if (stack != null && !stack.isEmpty()) {
living.setItemSlot(slot, stack);
}
@@ -257,11 +248,11 @@ public final class ModdedEntitySpawner {
}
}
static boolean isAreaClearForSpawn(ServerLevel level, IrisEntity irisEntity, int blockX, int blockY, int blockZ) {
if (irisEntity.isSpecialType()) {
static boolean isAreaClearForSpawn(ServerLevel level, ContentEntity entity, int blockX, int blockY, int blockZ) {
if (entity.isSpecial()) {
return true;
}
EntityType<?> type = resolveType(irisEntity.getType());
EntityType<?> type = resolveType(entity.type());
if (type == null) {
return true;
}
@@ -320,21 +311,21 @@ public final class ModdedEntitySpawner {
return false;
}
private static void applySpawnEffect(IrisEffect effect, Entity entity, ServerLevel level) {
if (effect == null || !effect.shouldApplyNow()) {
private static void applySpawnEffect(ContentEntity.SpawnEffect effect, Entity entity, ServerLevel level) {
if (effect == null) {
return;
}
SoundEvent sound = resolveSound(effect.getSoundKey());
SoundEvent sound = resolveSound(effect.sound());
if (sound != null) {
double soundX = entity.getX() + RNG.r.i(-effect.getSoundDistance(), effect.getSoundDistance());
double soundY = entity.getY() + RNG.r.i(-effect.getSoundDistance(), effect.getSoundDistance());
double soundZ = entity.getZ() + RNG.r.i(-effect.getSoundDistance(), effect.getSoundDistance());
double soundX = entity.getX() + RNG.r.i(-effect.soundDistance(), effect.soundDistance());
double soundY = entity.getY() + RNG.r.i(-effect.soundDistance(), effect.soundDistance());
double soundZ = entity.getZ() + RNG.r.i(-effect.soundDistance(), effect.soundDistance());
level.playSound(null, soundX, soundY, soundZ, sound, SoundSource.MASTER,
(float) effect.getVolume(), (float) RNG.r.d(effect.getMinPitch(), effect.getMaxPitch()));
(float) effect.volume(), (float) RNG.r.d(effect.minPitch(), effect.maxPitch()));
}
ParticleOptions particle = resolveParticle(effect.getParticleEffectKey());
ParticleOptions particle = resolveParticle(effect.particle());
if (particle == null) {
return;
}
@@ -342,13 +333,13 @@ public final class ModdedEntitySpawner {
double addition = RNG.r.d();
double subtraction = RNG.r.d();
double particleX = entity.getX() + addition - subtraction + RNG.r.d();
double particleY = entity.getY() + 0.25 + addition - subtraction + RNG.r.i(effect.getParticleOffset());
double particleY = entity.getY() + 0.25 + addition - subtraction + RNG.r.i(effect.particleOffset());
double particleZ = entity.getZ() + addition - subtraction + RNG.r.d();
double altX = effect.isRandomAltX() ? RNG.r.d(-effect.getParticleAltX(), effect.getParticleAltX()) : effect.getParticleAltX();
double altY = effect.isRandomAltY() ? RNG.r.d(-effect.getParticleAltY(), effect.getParticleAltY()) : effect.getParticleAltY();
double altZ = effect.isRandomAltZ() ? RNG.r.d(-effect.getParticleAltZ(), effect.getParticleAltZ()) : effect.getParticleAltZ();
level.sendParticles(particle, particleX, particleY, particleZ, effect.getParticleCount(),
altX, altY, altZ, effect.getExtra());
double altX = effect.randomAltX() ? RNG.r.d(-effect.altX(), effect.altX()) : effect.altX();
double altY = effect.randomAltY() ? RNG.r.d(-effect.altY(), effect.altY()) : effect.altY();
double altZ = effect.randomAltZ() ? RNG.r.d(-effect.altZ(), effect.altZ()) : effect.altZ();
level.sendParticles(particle, particleX, particleY, particleZ, effect.particleCount(),
altX, altY, altZ, effect.extra());
}
private static SoundEvent resolveSound(String key) {
@@ -18,19 +18,11 @@
package art.arcane.iris.modded;
import art.arcane.iris.engine.framework.LootResolver;
import art.arcane.iris.engine.loot.LootTables;
import art.arcane.iris.engine.object.loot.InventorySlotType;
import art.arcane.iris.engine.object.entity.IrisAttributeModifier;
import art.arcane.iris.engine.object.loot.IrisEnchantment;
import art.arcane.iris.engine.object.loot.IrisLoot;
import art.arcane.iris.engine.object.loot.IrisLootTable;
import art.arcane.iris.core.content.ContentItem;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.collection.KMap;
import art.arcane.volmlib.util.format.Form;
import art.arcane.volmlib.util.json.JSONObject;
import art.arcane.volmlib.util.math.RNG;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
@@ -63,6 +55,7 @@ import net.minecraft.world.item.enchantment.ItemEnchantments;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -74,42 +67,27 @@ public final class ModdedItemTranslator {
private ModdedItemTranslator() {
}
public static KList<ItemStack> loot(IrisLootTable table, long lootSeed, InventorySlotType slot, ServerLevel level, int x, int y, int z) {
KList<ItemStack> out = new KList<>();
KList<IrisLoot> entries = table.getLoot();
if (entries.isEmpty() || table.getMaxTries() <= 0) {
return out;
}
RNG rng = LootTables.rng(lootSeed, table, x, y, z);
int m = 0;
int c = 0;
int mx = Math.max(0, LootResolver.inclusive(rng, table.getMinPicked(), table.getMaxPicked()));
while (m < mx && c++ < table.getMaxTries()) {
int entryIndex = rng.nextInt(entries.size());
IrisLoot entry = entries.get(entryIndex);
if (entry == null || entry.getSlotTypes() != slot) {
continue;
}
ItemStack item = item(entry, table, rng, lootSeed, entryIndex, level, x, y, z);
if (item != null && !item.isEmpty()) {
out.add(item);
m++;
/** The stacks of {@code items}, without the ones the platform cannot make. */
public static KList<ItemStack> stacks(List<ContentItem> items, ServerLevel level) {
KList<ItemStack> stacks = new KList<>();
for (ContentItem item : items) {
ItemStack stack = stack(item, level);
if (stack != null && !stack.isEmpty()) {
stacks.add(stack);
}
}
return out;
return stacks;
}
public static ItemStack stack(IrisLoot loot, RNG rng, ServerLevel level) {
/** The stack of {@code item}, or null when the platform has no such item. */
public static ItemStack stack(ContentItem item, ServerLevel level) {
try {
ItemStack stack = baseStack(loot, rng);
ItemStack stack = baseStack(item);
if (stack == null || stack.isEmpty()) {
return null;
}
applyComponents(loot, stack, rng, level);
applyCustomNbt(stack, loot.getCustomNbt());
applyComponents(item, stack, level);
applyCustomNbt(stack, item.customNbt());
return stack;
} catch (Throwable e) {
IrisLogging.reportError(e);
@@ -117,28 +95,8 @@ public final class ModdedItemTranslator {
}
}
public static ItemStack item(IrisLoot loot, IrisLootTable table, RNG rng, long lootSeed, int entryIndex, ServerLevel level, int x, int y, int z) {
long combinedRarity = LootResolver.combinedRarity(loot.getRarity(), table.getRarity());
if (!LootTables.spatialOneIn(lootSeed, table, entryIndex, x, y, z, combinedRarity)) {
return null;
}
try {
ItemStack stack = baseStack(loot, rng);
if (stack == null || stack.isEmpty()) {
return null;
}
applyComponents(loot, stack, rng, level);
applyCustomNbt(stack, loot.getCustomNbt());
return stack;
} catch (Throwable e) {
IrisLogging.reportError(e);
return null;
}
}
private static ItemStack baseStack(IrisLoot loot, RNG rng) {
String raw = loot.getTypeKey();
private static ItemStack baseStack(ContentItem item) {
String raw = item.item();
if (raw == null || raw.isBlank()) {
return null;
}
@@ -150,55 +108,53 @@ public final class ModdedItemTranslator {
return null;
}
Item item = BuiltInRegistries.ITEM.getValue(id);
return new ItemStack(item, Math.max(1, LootResolver.inclusive(rng, loot.getMinAmount(), loot.getMaxAmount())));
return new ItemStack(BuiltInRegistries.ITEM.getValue(id), item.amount());
}
private static void applyComponents(IrisLoot loot, ItemStack stack, RNG rng, ServerLevel level) {
applyEnchantments(loot, stack, rng, level);
applyAttributes(loot, stack, rng, level);
private static void applyComponents(ContentItem item, ItemStack stack, ServerLevel level) {
applyEnchantments(item, stack, level);
applyAttributes(item, stack, level);
if (loot.isUnbreakable()) {
if (item.unbreakable()) {
stack.set(DataComponents.UNBREAKABLE, Unit.INSTANCE);
}
if (loot.getItemFlags().isNotEmpty()) {
applyItemFlags(loot, stack);
if (!item.flags().isEmpty()) {
applyItemFlags(item, stack);
}
if (loot.getCustomModel() != null) {
stack.set(DataComponents.CUSTOM_MODEL_DATA, new CustomModelData(List.of(loot.getCustomModel().floatValue()), List.of(), List.of(), List.of()));
if (item.customModel() != null) {
stack.set(DataComponents.CUSTOM_MODEL_DATA, new CustomModelData(List.of(item.customModel().floatValue()), List.of(), List.of(), List.of()));
}
if (stack.getMaxDamage() > 0) {
if (stack.getMaxDamage() > 0 && item.damage() != null) {
int max = stack.getMaxDamage();
int damage = (int) Math.round(Math.max(0, Math.min(max, (1D - rng.d(loot.getMinDurability(), loot.getMaxDurability())) * max)));
int damage = (int) Math.round(Math.max(0, Math.min(max, item.damage() * max)));
stack.set(DataComponents.DAMAGE, damage);
}
if (loot.getLeatherColor() != null) {
if (item.leatherColor() != null) {
try {
int rgb = Integer.decode(loot.getLeatherColor()) & 0xFFFFFF;
int rgb = Integer.decode(item.leatherColor()) & 0xFFFFFF;
stack.set(DataComponents.DYED_COLOR, new DyedItemColor(rgb));
} catch (NumberFormatException e) {
warnOnce("leatherColor:" + loot.getLeatherColor(), "Iris loot: invalid leatherColor '" + loot.getLeatherColor() + "'");
warnOnce("leatherColor:" + item.leatherColor(), "Iris loot: invalid leatherColor '" + item.leatherColor() + "'");
}
}
String dye = loot.getDyeColorKey();
if (dye != null) {
applyDyeColor(stack, dye);
if (item.dyeColor() != null) {
applyDyeColor(stack, item.dyeColor());
}
if (loot.getDisplayName() != null) {
stack.set(DataComponents.CUSTOM_NAME, Component.literal(colorize(loot.getDisplayName())));
if (item.displayName() != null) {
stack.set(DataComponents.CUSTOM_NAME, Component.literal(colorize(item.displayName())));
}
applyLore(loot, stack);
applyLore(item, stack);
}
private static void applyEnchantments(IrisLoot loot, ItemStack stack, RNG rng, ServerLevel level) {
if (loot.getEnchantments().isEmpty()) {
private static void applyEnchantments(ContentItem item, ItemStack stack, ServerLevel level) {
if (item.enchantments().isEmpty()) {
return;
}
@@ -207,8 +163,8 @@ public final class ModdedItemTranslator {
ItemEnchantments.Mutable mutable = new ItemEnchantments.Mutable(stack.getOrDefault(component, ItemEnchantments.EMPTY));
boolean changed = false;
for (IrisEnchantment enchantment : loot.getEnchantments()) {
String name = enchantment.getEnchantment();
for (ContentItem.Enchantment enchantment : item.enchantments()) {
String name = enchantment.key();
if (name == null || name.isBlank()) {
continue;
}
@@ -221,10 +177,8 @@ public final class ModdedItemTranslator {
warnOnce("enchantment:" + key, "Iris loot: unknown enchantment '" + name + "'");
continue;
}
if (rng.nextDouble() < enchantment.getChance()) {
mutable.set(holder.get(), enchantment.getLevel(rng));
changed = true;
}
mutable.set(holder.get(), enchantment.level());
changed = true;
}
if (changed) {
@@ -232,8 +186,8 @@ public final class ModdedItemTranslator {
}
}
private static void applyAttributes(IrisLoot loot, ItemStack stack, RNG rng, ServerLevel level) {
if (loot.getAttributes().isEmpty()) {
private static void applyAttributes(ContentItem item, ItemStack stack, ServerLevel level) {
if (item.attributes().isEmpty()) {
return;
}
@@ -241,21 +195,17 @@ public final class ModdedItemTranslator {
ItemAttributeModifiers.Builder builder = ItemAttributeModifiers.builder();
boolean changed = false;
for (IrisAttributeModifier attribute : loot.getAttributes()) {
if (rng.nextDouble() >= attribute.getChance()) {
continue;
}
double amount = attribute.getAmount(rng);
Holder<Attribute> holder = resolveAttribute(registry, attribute.getAttribute());
for (ContentItem.Attribute attribute : item.attributes()) {
Holder<Attribute> holder = resolveAttribute(registry, attribute.attribute());
if (holder == null) {
warnOnce("attribute:" + attribute.getAttribute(), "Iris loot: unknown attribute '" + attribute.getAttribute() + "'");
warnOnce("attribute:" + attribute.attribute(), "Iris loot: unknown attribute '" + attribute.attribute() + "'");
continue;
}
Identifier modifierId = attributeModifierId(attribute.getName());
Identifier modifierId = attributeModifierId(attribute.name());
if (modifierId == null) {
continue;
}
AttributeModifier modifier = new AttributeModifier(modifierId, amount, operationFor(attribute.getOperation()));
AttributeModifier modifier = new AttributeModifier(modifierId, attribute.amount(), operationFor(attribute.operation()));
builder.add(holder, modifier, EquipmentSlotGroup.ANY);
changed = true;
}
@@ -311,11 +261,11 @@ public final class ModdedItemTranslator {
return Identifier.tryParse("iris:" + normalized);
}
private static void applyItemFlags(IrisLoot loot, ItemStack stack) {
private static void applyItemFlags(ContentItem item, ItemStack stack) {
TooltipDisplay display = stack.getOrDefault(DataComponents.TOOLTIP_DISPLAY, TooltipDisplay.DEFAULT);
boolean changed = false;
for (String flag : loot.getItemFlags()) {
for (String flag : item.flags()) {
if (flag == null || flag.isBlank()) {
continue;
}
@@ -356,13 +306,13 @@ public final class ModdedItemTranslator {
stack.set(DataComponents.BASE_COLOR, color);
}
private static void applyLore(IrisLoot loot, ItemStack stack) {
if (loot.getLore().isEmpty()) {
private static void applyLore(ContentItem item, ItemStack stack) {
if (item.lore().isEmpty()) {
return;
}
List<Component> lines = new ArrayList<>();
for (String line : loot.getLore()) {
for (String line : item.lore()) {
String colored = colorize(line);
if (colored.length() > 24) {
for (String wrapped : Form.wrapWords(colored, 24).split("\\Q\n\\E")) {
@@ -375,7 +325,7 @@ public final class ModdedItemTranslator {
stack.set(DataComponents.LORE, new ItemLore(lines));
}
private static void applyCustomNbt(ItemStack stack, KMap<String, Object> customNbt) {
private static void applyCustomNbt(ItemStack stack, Map<String, Object> customNbt) {
if (customNbt == null || customNbt.isEmpty()) {
return;
}
@@ -18,19 +18,11 @@
package art.arcane.iris.modded;
import art.arcane.iris.engine.loot.LootResources;
import art.arcane.iris.engine.object.loot.IrisObjectLoot;
import art.arcane.iris.engine.object.loot.IrisObjectVanillaLoot;
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
import art.arcane.iris.core.content.ContentLoot;
import art.arcane.iris.core.content.ContentServices;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.LootResolver;
import art.arcane.iris.engine.loot.LootTables;
import art.arcane.iris.engine.framework.PlacedObject;
import art.arcane.iris.engine.object.loot.IObjectLoot;
import art.arcane.iris.engine.object.loot.InventorySlotType;
import art.arcane.iris.engine.object.loot.IrisLootTable;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.math.RNG;
@@ -53,7 +45,6 @@ import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets;
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
import net.minecraft.world.phys.Vec3;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
@@ -65,10 +56,10 @@ public final class ModdedLootApplier {
if (!isCanonicalContainer(pos, state)) {
return;
}
RNG rng = LootResolver.containerRng(engine.getSeedManager().getLoot(), pos.getX(), pos.getY(), pos.getZ());
boolean nativeLootDefined = hasNativeLootTable(level, pos, state);
List<LootSource> sources = resolveSources(engine, level, rng, pos, state, mc, nativeLootDefined);
if (sources.isEmpty()) {
String containerKey = ModdedBlockResolution.isStorageChest(state) ? ModdedBlockState.serialize(state) : null;
List<ContentLoot.Part> parts = ContentServices.containerLoot(engine, pos.getX(), pos.getY(), pos.getZ(), containerKey, nativeLootDefined);
if (parts.isEmpty()) {
return;
}
@@ -80,97 +71,38 @@ public final class ModdedLootApplier {
KList<ItemStack> items = new KList<>();
LootParams nativeParams = null;
for (LootSource source : sources) {
if (source instanceof IrisLootSource irisSource) {
IrisLootTable table = irisSource.table();
if (table == null) {
continue;
}
items.addAll(ModdedItemTranslator.loot(table, engine.getSeedManager().getLoot(), InventorySlotType.STORAGE, level, pos.getX(), pos.getY(), pos.getZ()));
for (ContentLoot.Part part : parts) {
if (part instanceof ContentLoot.Items drawn) {
items.addAll(ModdedItemTranslator.stacks(drawn.items(), level));
continue;
}
if (source instanceof NativeLootSource nativeSource) {
if (part instanceof ContentLoot.PlatformTable platform) {
LootTable table = nativeTable(level, platform.key());
if (table == null) {
IrisLogging.warn("Unknown vanilla loot table " + platform.key());
continue;
}
if (nativeParams == null) {
nativeParams = new LootParams.Builder(level)
.withParameter(LootContextParams.ORIGIN, Vec3.atCenterOf(pos))
.create(LootContextParamSets.CHEST);
}
items.addAll(nativeSource.table().getRandomItems(nativeParams, rng.nextLong()));
items.addAll(table.getRandomItems(nativeParams, platform.seed()));
}
}
fillContainer(container, items, rng);
fillContainer(container, items, LootResolver.containerRng(engine.getSeedManager().getLoot(), pos.getX(), pos.getY(), pos.getZ()));
}
private static List<LootSource> resolveSources(Engine engine, ServerLevel level, RNG rng, BlockPos pos, BlockState state, MantleChunk<Matter> mc, boolean nativeLootDefined) {
int rx = pos.getX();
int rz = pos.getZ();
int ry = pos.getY() - engine.getWorld().minHeight();
List<LootSource> sources = new ArrayList<>();
boolean objectLootDefined = nativeLootDefined;
PlacedObject po = engine.getObjectPlacement(rx, ry, rz, mc);
if (po != null && po.getPlacement() != null && ModdedBlockResolution.isStorageChest(state)) {
objectLootDefined = objectLootDefined
|| po.getPlacement().getLoot().isNotEmpty()
|| po.getPlacement().getVanillaLoot().isNotEmpty();
Candidate picked = pickPlacementTable(engine, level, po.getPlacement(), state, rng);
if (picked != null) {
sources.add(picked.source());
if (po.getPlacement().isOverrideGlobalLoot()) {
return sources;
}
}
private static LootTable nativeTable(ServerLevel level, String name) {
ResourceKey<LootTable> key = resolveNativeKey(name, candidate -> hasNativeTable(level, candidate));
if (key == null) {
return null;
}
LootTables.resolveEnvironmentSources(
sources,
engine,
rng,
rx,
ry,
rz,
objectLootDefined,
IrisLootSource::new
);
return sources;
}
private static Candidate pickPlacementTable(Engine engine, ServerLevel level, IrisObjectPlacement placement, BlockState state, RNG rng) {
List<Candidate> exact = new ArrayList<>();
List<Candidate> basic = new ArrayList<>();
List<Candidate> global = new ArrayList<>();
for (IrisObjectLoot loot : placement.getLoot()) {
if (loot == null || loot.getWeight() <= 0) {
continue;
}
IrisLootTable table = LootResources.table(engine.getData(), loot.getName());
if (table == null) {
IrisLogging.warn("Couldn't find loot table " + loot.getName());
continue;
}
bucket(engine, loot, new Candidate(new IrisLootSource(table), loot.getWeight()), state, exact, basic, global);
}
for (IrisObjectVanillaLoot loot : placement.getVanillaLoot()) {
if (loot == null || loot.getWeight() <= 0) {
continue;
}
ResourceKey<LootTable> key = resolveNativeKey(loot.getName(), candidate -> hasNativeTable(level, candidate));
if (key == null) {
IrisLogging.warn("Couldn't find vanilla loot table " + loot.getName());
continue;
}
LootTable table = level.getServer().reloadableRegistries().lookup()
.lookupOrThrow(Registries.LOOT_TABLE)
.getOrThrow(key)
.value();
bucket(engine, loot, new Candidate(new NativeLootSource(table), loot.getWeight()), state, exact, basic, global);
}
List<Candidate> pool = !exact.isEmpty() ? exact : !basic.isEmpty() ? basic : global;
return LootResolver.pickWeighted(pool, Candidate::weight, rng);
return level.getServer().reloadableRegistries().lookup()
.lookupOrThrow(Registries.LOOT_TABLE)
.getOrThrow(key)
.value();
}
static ResourceKey<LootTable> resolveNativeKey(String name, Predicate<ResourceKey<LootTable>> registryContains) {
@@ -197,21 +129,6 @@ public final class ModdedLootApplier {
.isPresent();
}
private static void bucket(Engine engine, IObjectLoot loot, Candidate candidate, BlockState state, List<Candidate> exact, List<Candidate> basic, List<Candidate> global) {
if (loot.getFilter().isEmpty()) {
global.add(candidate);
return;
}
for (PlatformBlockState filterState : loot.getFilter(engine.getData())) {
BlockState filter = (BlockState) filterState.nativeHandle();
if (loot.isExact() ? filter == state : filter.getBlock() == state.getBlock()) {
(loot.isExact() ? exact : basic).add(candidate);
return;
}
}
}
static boolean isCanonicalContainer(BlockPos pos, BlockState state) {
if (!(state.getBlock() instanceof ChestBlock) || state.getValue(ChestBlock.TYPE) == ChestType.SINGLE) {
return true;
@@ -324,16 +241,4 @@ public final class ModdedLootApplier {
container.setItem(i, items[i]);
}
}
private interface LootSource {
}
private record IrisLootSource(IrisLootTable table) implements LootSource {
}
private record NativeLootSource(LootTable table) implements LootSource {
}
private record Candidate(LootSource source, int weight) {
}
}
@@ -18,25 +18,15 @@
package art.arcane.iris.modded;
import art.arcane.iris.engine.spawn.SpawnResources;
import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.core.content.ContentServices;
import art.arcane.iris.core.content.ContentSpawns;
import art.arcane.iris.core.gui.PregeneratorJob;
import art.arcane.iris.engine.IrisComplex;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineLifecycleTasks;
import art.arcane.iris.engine.framework.EngineWorldManager;
import art.arcane.iris.engine.framework.LootResolver;
import art.arcane.iris.engine.object.value.IRare;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.entity.IrisEntity;
import art.arcane.iris.engine.object.entity.IrisEntitySpawn;
import art.arcane.iris.engine.object.marker.IrisMarker;
import art.arcane.iris.engine.object.value.IrisPosition;
import art.arcane.iris.engine.object.value.IrisRange;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.entity.spawn.IrisSpawnGroup;
import art.arcane.iris.engine.object.entity.spawn.IrisSpawner;
import art.arcane.iris.engine.object.entity.spawn.IrisSurface;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.mantle.flag.MantleFlag;
@@ -45,7 +35,6 @@ import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.MatterMarker;
import art.arcane.volmlib.util.matter.slices.MarkerMatter;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
@@ -60,6 +49,8 @@ import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.phys.AABB;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
@@ -397,8 +388,8 @@ public final class ModdedWorldManager implements EngineWorldManager {
if (tag.equals("cave_floor") || tag.equals("cave_ceiling")) {
return;
}
IrisMarker resolved = SpawnResources.marker(engine.getData(), tag);
if (resolved == null) {
Optional<ContentSpawns.MarkerRule> rule = ContentServices.markerRule(engine, tag);
if (rule.isEmpty()) {
return;
}
@@ -406,20 +397,17 @@ public final class ModdedWorldManager implements EngineWorldManager {
int worldZ = (chunkZ << 4) + (z & 15);
int worldY = yf + minHeight;
if (resolved.isEmptyAbove() && aboveObstructed(level, worldX, worldY, worldZ)) {
if (rule.get().emptyAbove() && aboveObstructed(level, worldX, worldY, worldZ)) {
obstructed.add(new IrisPosition(worldX, yf, worldZ));
return;
}
KList<IrisSpawner> spawners = resolveMarkerSpawners(resolved);
List<String> spawners = rule.get().spawners();
if (spawners.isEmpty()) {
return;
}
IrisSpawner chosen = spawners.getRandom();
if (chosen == null) {
return;
}
spawnFromSpawner(level, new IrisPosition(worldX, worldY, worldZ), chosen, initial);
String chosen = spawners.get(RNG.r.nextInt(spawners.size()));
spawnAtMarker(level, new IrisPosition(worldX, worldY, worldZ), tag, chosen, initial);
});
Mantle<Matter> mantle = engine.getMantle().getMantle();
for (IrisPosition position : obstructed) {
@@ -427,43 +415,14 @@ public final class ModdedWorldManager implements EngineWorldManager {
}
}
private KList<IrisSpawner> resolveMarkerSpawners(IrisMarker marker) {
KList<IrisSpawner> spawners = new KList<>();
for (String key : marker.getSpawners()) {
IrisSpawner spawner = SpawnResources.spawner(engine.getData(), key);
if (spawner == null) {
IrisLogging.error("Cannot load spawner: " + key + " for marker on " + engine.getName());
continue;
}
spawner.setReferenceMarker(marker);
spawners.add(spawner);
}
return spawners;
}
private void spawnFromSpawner(ServerLevel level, IrisPosition position, IrisSpawner spawner, boolean initial) {
KList<IrisEntitySpawn> spawns = initial ? spawner.getInitialSpawns() : spawner.getSpawns();
if (spawns.isEmpty()) {
return;
}
for (IrisEntitySpawn entry : spawns) {
entry.setReferenceSpawner(spawner);
entry.setReferenceMarker(spawner.getReferenceMarker());
}
IrisEntitySpawn chosen = rarityPick(spawns);
if (chosen == null) {
return;
}
int chunkX = position.getX() >> 4;
int chunkZ = position.getZ() >> 4;
if (!canSpawn(spawner, chunkX, chunkZ)) {
return;
}
int spawned = spawnEntryAt(level, chosen, spawner, position);
if (spawned > 0) {
spawner.spawn(engine, chunkX, chunkZ);
}
private void spawnAtMarker(ServerLevel level, IrisPosition position, String marker, String spawner, boolean initial) {
ContentServices.planMarkerSpawn(engine, position.getX(), position.getY(), position.getZ(), marker, spawner, initial)
.ifPresent(plan -> {
if (plan.exhaustsMarker()) {
engine.getMantle().getMantle().remove(position.getX(), position.getY() - engine.getWorld().minHeight(), position.getZ(), MatterMarker.class);
}
spawn(level, plan);
});
}
private void spawnAmbient(ServerLevel level, int chunkX, int chunkZ, boolean initial) {
@@ -472,184 +431,55 @@ public final class ModdedWorldManager implements EngineWorldManager {
return;
}
int blockX = chunkX << 4;
int blockZ = chunkZ << 4;
IrisBiome biome = engine.getSurfaceBiome(blockX, blockZ);
IrisRegion region = engine.getRegion(blockX, blockZ);
int chunkMobs = countChunkLivingEntities(level, chunkX, chunkZ);
KList<IrisEntitySpawn> pool = new KList<>();
collectSpawns(pool, SpawnResources.spawners(engine.getData(), engine.getDimension().getEntitySpawners()), biome, chunkX, chunkZ, chunkMobs, initial);
collectSpawns(pool, SpawnResources.spawners(engine.getData(), region.getEntitySpawners()), null, chunkX, chunkZ, chunkMobs, initial);
collectSpawns(pool, SpawnResources.spawners(engine.getData(), biome.getEntitySpawners()), null, chunkX, chunkZ, chunkMobs, initial);
if (pool.isEmpty()) {
return;
}
IrisEntitySpawn chosen = rarityPick(pool);
if (chosen == null || chosen.getReferenceSpawner() == null) {
return;
}
IrisSpawner spawner = chosen.getReferenceSpawner();
if (!canSpawn(spawner, chunkX, chunkZ)) {
return;
}
int spawned = spawnEntry(level, chosen, spawner, chunkX, chunkZ);
if (spawned > 0) {
spawner.spawn(engine, chunkX, chunkZ);
}
ContentServices.planChunkSpawn(engine, chunkX, chunkZ, countChunkLivingEntities(level, chunkX, chunkZ), initial)
.ifPresent(plan -> spawn(level, plan));
}
private void collectSpawns(KList<IrisEntitySpawn> pool, KList<IrisSpawner> spawners, IrisBiome biomeFilter, int chunkX, int chunkZ, int chunkMobs, boolean initial) {
for (IrisSpawner spawner : spawners) {
if (spawner == null) {
continue;
}
if (spawner.getMaxEntitiesPerChunk() <= chunkMobs) {
continue;
}
if (biomeFilter != null && !spawner.isValid(biomeFilter)) {
continue;
}
if (!canSpawn(spawner, chunkX, chunkZ)) {
continue;
}
KList<IrisEntitySpawn> spawns = initial ? spawner.getInitialSpawns() : spawner.getSpawns();
for (IrisEntitySpawn entry : spawns) {
entry.setReferenceSpawner(spawner);
entry.setReferenceMarker(spawner.getReferenceMarker());
pool.add(entry);
}
}
}
private int spawnEntry(ServerLevel level, IrisEntitySpawn entry, IrisSpawner spawner, int chunkX, int chunkZ) {
IrisEntity irisEntity = entry.getRealEntity(engine);
if (irisEntity == null) {
return 0;
}
int min = entry.getMinSpawns();
int max = entry.getMaxSpawns();
int count = LootResolver.inclusive(RNG.r, min, max);
if (count <= 0) {
return 0;
}
RNG entityRng = entry.getRng().aquire(() -> new RNG(engine.getSeedManager().getEntity()));
IrisSpawnGroup group = spawner.getGroup();
KList<IrisPosition> caveFloors = group == IrisSpawnGroup.CAVE
? engine.getMantle().findMarkers(chunkX, chunkZ, MarkerMatter.CAVE_FLOOR)
: new KList<>();
/** Spawns the entities of the plan that the light, the surface below and the space around them allow, and tells the plan how many appeared. */
private void spawn(ServerLevel level, ContentSpawns.Plan plan) {
int spawned = 0;
for (int i = 0; i < count; i++) {
int worldX;
int worldY;
int worldZ;
if (group == IrisSpawnGroup.CAVE) {
if (caveFloors.isEmpty()) {
continue;
}
IrisPosition caveFloor = caveFloors.getRandom(RNG.r);
worldX = caveFloor.getX();
worldY = caveFloor.getY() + 1;
worldZ = caveFloor.getZ();
} else {
worldX = (chunkX << 4) + RNG.r.i(16);
worldZ = (chunkZ << 4) + RNG.r.i(16);
int surfaceY = level.getMinY() + engine.getHeight(worldX, worldZ, false);
int solidY = level.getMinY() + engine.getHeight(worldX, worldZ, true);
worldY = group == IrisSpawnGroup.NORMAL
? surfaceY + 1
: RNG.r.i(solidY + 1, surfaceY);
}
if (worldY <= level.getMinY() || worldY >= level.getMaxY()) {
continue;
}
// Rarity is applied exactly once, as pool weighting in rarityPick - never re-rolled per position (Bukkit parity).
if (!lightAllowed(spawner, level, worldX, worldY, worldZ)) {
continue;
}
if (!surfaceMatches(irisEntity.getSurface(), level, worldX, worldY, worldZ)) {
continue;
}
if (!ModdedEntitySpawner.isAreaClearForSpawn(level, irisEntity, worldX, worldY, worldZ)) {
continue;
}
if (ModdedEntitySpawner.spawn(engine, irisEntity, level, worldX, worldY, worldZ, entityRng) != null) {
for (ContentSpawns.Attempt attempt : plan.attempts()) {
if (spawnIfAllowed(level, attempt)) {
spawned++;
}
}
return spawned;
plan.spawned(spawned);
}
private int spawnEntryAt(ServerLevel level, IrisEntitySpawn entry, IrisSpawner spawner, IrisPosition position) {
IrisEntity irisEntity = entry.getRealEntity(engine);
if (irisEntity == null) {
return 0;
private boolean spawnIfAllowed(ServerLevel level, ContentSpawns.Attempt attempt) {
if (attempt.worldY() <= level.getMinY() || attempt.worldY() >= level.getMaxY()) {
return false;
}
int min = entry.getMinSpawns();
int max = entry.getMaxSpawns();
int count = LootResolver.inclusive(RNG.r, min, max);
if (count <= 0) {
return 0;
if (attempt.restrictsLight() && !lightAllowed(attempt, level)) {
return false;
}
exhaustMarker(spawner, position);
RNG entityRng = entry.getRng().aquire(() -> new RNG(engine.getSeedManager().getEntity()));
int worldX = position.getX();
int worldY = position.getY() + 1;
int worldZ = position.getZ();
int spawned = 0;
for (int i = 0; i < count; i++) {
// Rarity is applied exactly once, as pool weighting in rarityPick - never re-rolled per position (Bukkit parity).
if (!lightAllowed(spawner, level, worldX, worldY, worldZ)) {
continue;
}
if (ModdedEntitySpawner.spawn(engine, irisEntity, level, worldX, worldY, worldZ, entityRng) != null) {
spawned++;
}
if (attempt.checkSurface() && !surfaceAllows(attempt, level)) {
return false;
}
return spawned;
return ModdedEntitySpawner.spawn(engine, attempt.entity(), level, attempt.x(), attempt.worldY(), attempt.z()) != null;
}
private void exhaustMarker(IrisSpawner spawner, IrisPosition position) {
IrisMarker marker = spawner.getReferenceMarker();
if (marker == null || !marker.shouldExhaust()) {
return;
}
engine.getMantle().getMantle().remove(position.getX(), position.getY() - engine.getWorld().minHeight(), position.getZ(), MatterMarker.class);
private static boolean lightAllowed(ContentSpawns.Attempt attempt, ServerLevel level) {
int light = level.getMaxLocalRawBrightness(new BlockPos(attempt.x(), attempt.worldY(), attempt.z()));
return light >= attempt.minLight() && light <= attempt.maxLight();
}
private boolean canSpawn(IrisSpawner spawner, int chunkX, int chunkZ) {
return spawner.canSpawn(engine, chunkX, chunkZ);
private static boolean surfaceAllows(ContentSpawns.Attempt attempt, ServerLevel level) {
BlockState below = level.getBlockState(new BlockPos(attempt.x(), attempt.worldY() - 1, attempt.z()));
return matchesSurface(attempt.surface(), below)
&& ModdedEntitySpawner.isAreaClearForSpawn(level, attempt.entity(), attempt.x(), attempt.worldY(), attempt.z());
}
private boolean lightAllowed(IrisSpawner spawner, ServerLevel level, int worldX, int worldY, int worldZ) {
IrisRange range = spawner.getAllowedLightLevels();
if (range.getMin() > 0 || range.getMax() < 15) {
return range.contains(level.getMaxLocalRawBrightness(new BlockPos(worldX, worldY, worldZ)));
}
return true;
}
private boolean surfaceMatches(IrisSurface surface, ServerLevel level, int worldX, int worldY, int worldZ) {
BlockState below = level.getBlockState(new BlockPos(worldX, worldY - 1, worldZ));
return matchesSurface(surface, below);
}
private static boolean matchesSurface(IrisSurface surface, BlockState below) {
private static boolean matchesSurface(ContentSpawns.Surface surface, BlockState below) {
if (ModdedBlockResolution.isSolid(below)) {
return surface == IrisSurface.LAND || surface == IrisSurface.OVERWORLD
|| (surface == IrisSurface.ANIMAL && isAnimalGround(below));
return surface == ContentSpawns.Surface.LAND || surface == ContentSpawns.Surface.OVERWORLD
|| (surface == ContentSpawns.Surface.ANIMAL && isAnimalGround(below));
}
if (below.is(Blocks.LAVA)) {
return surface == IrisSurface.LAVA;
return surface == ContentSpawns.Surface.LAVA;
}
if (ModdedBlockResolution.isWater(below) || ModdedBlockResolution.isWaterLogged(below) || isAquaticFoliage(below)) {
return surface == IrisSurface.WATER || surface == IrisSurface.OVERWORLD;
return surface == ContentSpawns.Surface.WATER || surface == ContentSpawns.Surface.OVERWORLD;
}
return false;
}
@@ -770,11 +600,6 @@ public final class ModdedWorldManager implements EngineWorldManager {
return !studio || studioSetting;
}
private IrisEntitySpawn rarityPick(KList<IrisEntitySpawn> entries) {
KList<IrisEntitySpawn> weighted = IRare.expandWeighted(entries);
return weighted.isEmpty() ? entries.getRandom() : weighted.getRandom();
}
private static long pack(int x, int z) {
return (((long) x) & 0xFFFFFFFFL) | ((((long) z) & 0xFFFFFFFFL) << 32);
}
@@ -18,9 +18,6 @@
package art.arcane.iris.modded.command;
import art.arcane.iris.core.loader.IrisRegistrant;
import art.arcane.iris.engine.spawn.SpawnResources;
import art.arcane.iris.engine.loot.LootResources;
import art.arcane.iris.modded.ModdedIrisLog;
import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.core.gui.GuiHost;
@@ -37,13 +34,10 @@ import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.biome.IrisBiomeGeneratorLink;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.entity.IrisEntitySpawn;
import art.arcane.iris.engine.object.terrain.IrisGenerator;
import art.arcane.iris.core.pack.ModuleResourceClosure;
import art.arcane.iris.core.pack.PackExportClosure;
import art.arcane.iris.engine.object.entity.IrisEntity;
import art.arcane.iris.engine.object.marker.IrisMarker;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.entity.spawn.IrisSpawner;
import art.arcane.iris.engine.object.structure.IrisStructurePlacement;
import art.arcane.iris.modded.ModdedDimensionManager;
import art.arcane.iris.modded.ModdedEngineBootstrap;
@@ -56,7 +50,6 @@ import art.arcane.volmlib.util.format.Form;
import art.arcane.volmlib.util.io.IO;
import art.arcane.volmlib.util.json.JSONObject;
import art.arcane.volmlib.util.math.M;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.math.Spiraler;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.arguments.LongArgumentType;
@@ -887,12 +880,9 @@ public final class ModdedStudioCommands {
LinkedHashSet<String> regionKeys = new LinkedHashSet<>();
LinkedHashSet<String> biomeKeys = new LinkedHashSet<>();
LinkedHashSet<String> entityKeys = new LinkedHashSet<>();
LinkedHashSet<String> spawnerKeys = new LinkedHashSet<>();
LinkedHashSet<String> generatorKeys = new LinkedHashSet<>();
LinkedHashSet<String> lootKeys = new LinkedHashSet<>();
ModuleResourceClosure moduleResources = new ModuleResourceClosure(dm);
LinkedHashSet<String> objectKeys = new LinkedHashSet<>();
LinkedHashSet<String> markerKeys = new LinkedHashSet<>();
LinkedHashSet<String> structureKeys = new LinkedHashSet<>();
dimension.getAllRegions(() -> dm).forEach((IrisRegion region) -> {
@@ -905,8 +895,7 @@ public final class ModdedStudioCommands {
biomeKeys.add(biome.getLoadKey());
}
});
lootKeys.addAll(dimension.getLoot().getTables());
spawnerKeys.addAll(dimension.getEntitySpawners());
moduleResources.followSettingsOf(dimension);
collectStructureKeys(structureKeys, dimension.getStructures());
for (String regionKey : regionKeys) {
@@ -919,11 +908,10 @@ public final class ModdedStudioCommands {
biomeKeys.add(biome.getLoadKey());
}
});
lootKeys.addAll(region.getLoot().getTables());
spawnerKeys.addAll(region.getEntitySpawners());
moduleResources.followSettingsOf(region);
moduleResources.follow(region.getObjects());
collectStructureKeys(structureKeys, region.getStructures());
objectKeys.addAll(PackExportClosure.collectObjectKeys(region.getObjects()));
markerKeys.addAll(PackExportClosure.collectMarkerKeys(region.getObjects()));
}
for (String biomeKey : biomeKeys) {
IrisBiome biome = dm.getBiomeLoader().load(biomeKey);
@@ -931,33 +919,10 @@ public final class ModdedStudioCommands {
continue;
}
biome.getGenerators().forEach((IrisBiomeGeneratorLink link) -> generatorKeys.add(link.getGenerator()));
lootKeys.addAll(biome.getLoot().getTables());
spawnerKeys.addAll(biome.getEntitySpawners());
moduleResources.followSettingsOf(biome);
moduleResources.follow(biome.getObjects());
collectStructureKeys(structureKeys, biome.getStructures());
objectKeys.addAll(PackExportClosure.collectObjectKeys(biome.getObjects()));
markerKeys.addAll(PackExportClosure.collectMarkerKeys(biome.getObjects()));
}
for (String markerKey : markerKeys) {
IrisMarker marker = SpawnResources.marker(dm, markerKey);
if (marker == null) {
continue;
}
spawnerKeys.addAll(marker.getSpawners());
}
for (String spawnerKey : spawnerKeys) {
IrisSpawner spawner = SpawnResources.spawner(dm, spawnerKey);
if (spawner == null) {
continue;
}
spawner.getSpawns().forEach((IrisEntitySpawn spawn) -> entityKeys.add(spawn.getEntity()));
spawner.getInitialSpawns().forEach((IrisEntitySpawn spawn) -> entityKeys.add(spawn.getEntity()));
}
for (String entityKey : entityKeys) {
IrisEntity entity = SpawnResources.entity(dm, entityKey);
if (entity == null) {
continue;
}
lootKeys.addAll(entity.getLoot().getTables());
}
StringBuilder hashes = new StringBuilder();
@@ -990,18 +955,7 @@ public final class ModdedStudioCommands {
for (String key : biomeKeys) {
hashes.append(copyJson(folder, "biomes", key, dm.getBiomeLoader().findFile(key)));
}
for (String key : entityKeys) {
hashes.append(copyJson(folder, "entities", key, loadFile(SpawnResources.entity(dm, key))));
}
for (String key : lootKeys) {
hashes.append(copyJson(folder, "loot", key, loadFile(LootResources.table(dm, key))));
}
for (String key : spawnerKeys) {
hashes.append(copyJson(folder, "spawners", key, loadFile(SpawnResources.spawner(dm, key))));
}
for (String key : markerKeys) {
hashes.append(copyJson(folder, "markers", key, loadFile(SpawnResources.marker(dm, key))));
}
hashes.append(moduleResources.writeTo(folder, true));
JSONObject meta = new JSONObject();
meta.put("hash", IO.hash(hashes.toString()));
@@ -1091,9 +1045,4 @@ public final class ModdedStudioCommands {
thread.start();
return 1;
}
/** The file a resource was read from, or null when the pack has no such resource. */
private static File loadFile(IrisRegistrant resource) {
return resource == null ? null : resource.getLoadFile();
}
}
@@ -1,41 +0,0 @@
/*
* 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.modded;
import net.minecraft.core.Direction;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.StairBlock;
import net.minecraft.world.level.block.state.BlockState;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ModdedBlockBreakHandlerTest {
@Test
public void exactMatchingIncludesPropertiesWhileTypeMatchingDoesNot() {
BlockState north = Blocks.OAK_STAIRS.defaultBlockState().setValue(StairBlock.FACING, Direction.NORTH);
BlockState east = Blocks.OAK_STAIRS.defaultBlockState().setValue(StairBlock.FACING, Direction.EAST);
assertTrue(ModdedBlockBreakHandler.matchesState(north, north, true));
assertFalse(ModdedBlockBreakHandler.matchesState(north, east, true));
assertTrue(ModdedBlockBreakHandler.matchesState(north, east, false));
assertFalse(ModdedBlockBreakHandler.matchesState(north, Blocks.COBBLESTONE.defaultBlockState(), false));
}
}
@@ -1,6 +1,5 @@
package art.arcane.iris.modded;
import art.arcane.iris.engine.object.entity.IrisEffect;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.EntitySpawnReason;
@@ -149,16 +148,6 @@ public class ModdedEntitySpawnerParityTest {
assertEquals(EntitySpawnReason.NATURAL, ModdedEntitySpawner.reasonFor("not_a_spawn_reason"));
}
@Test
public void entityEffectExposesNeutralRegistryKeys() {
IrisEffect effect = new IrisEffect()
.setSound("minecraft:block.amethyst_block.chime")
.setParticleEffect("minecraft:flame");
assertEquals("minecraft:block.amethyst_block.chime", effect.getSoundKey());
assertEquals("minecraft:flame", effect.getParticleEffectKey());
}
private static long pack(int x, int z) {
return (((long) x) & 0xFFFFFFFFL) | ((((long) z) & 0xFFFFFFFFL) << 32);
}
@@ -2,7 +2,7 @@ package art.arcane.iris.modded;
import art.arcane.iris.engine.framework.LootResolver;
import art.arcane.iris.engine.loot.LootTables;
import art.arcane.iris.engine.object.loot.IrisLootMode;
import art.arcane.iris.builtin.loot.LootMode;
import art.arcane.volmlib.util.math.RNG;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
@@ -31,7 +31,7 @@ public class ModdedLootApplierTest {
public void addAppendsSourcesInOrder() {
List<String> sources = new ArrayList<>(List.of("placement-native"));
LootTables.injectSources(sources, List.of("dimension-iris", "region-iris"), IrisLootMode.ADD, false);
LootTables.injectSources(sources, List.of("dimension-iris", "region-iris"), LootMode.ADD, false);
assertEquals(List.of("placement-native", "dimension-iris", "region-iris"), sources);
}
@@ -40,7 +40,7 @@ public class ModdedLootApplierTest {
public void clearRemovesEverythingAndContributesNothing() {
List<String> sources = new ArrayList<>(List.of("placement-native", "dimension-iris"));
LootTables.injectSources(sources, List.of("biome-iris"), IrisLootMode.CLEAR, false);
LootTables.injectSources(sources, List.of("biome-iris"), LootMode.CLEAR, false);
assertEquals(List.of(), sources);
}
@@ -49,7 +49,7 @@ public class ModdedLootApplierTest {
public void replaceRemovesNativeAndIrisSourcesBeforeAdding() {
List<String> sources = new ArrayList<>(List.of("placement-native", "dimension-iris"));
LootTables.injectSources(sources, List.of("biome-iris"), IrisLootMode.REPLACE, false);
LootTables.injectSources(sources, List.of("biome-iris"), LootMode.REPLACE, false);
assertEquals(List.of("biome-iris"), sources);
}
@@ -64,7 +64,7 @@ public class ModdedLootApplierTest {
public void fallbackDoesNotOverrideExistingNativeOrIrisSources() {
List<String> sources = new ArrayList<>(List.of("placement-native", "dimension-iris"));
LootTables.injectSources(sources, List.of("fallback-iris"), IrisLootMode.FALLBACK, false);
LootTables.injectSources(sources, List.of("fallback-iris"), LootMode.FALLBACK, false);
assertEquals(List.of("placement-native", "dimension-iris"), sources);
}
@@ -73,7 +73,7 @@ public class ModdedLootApplierTest {
public void fallbackAddsSourcesWhenPlacementIsEmpty() {
List<String> sources = new ArrayList<>();
LootTables.injectSources(sources, List.of("fallback-iris"), IrisLootMode.FALLBACK, true);
LootTables.injectSources(sources, List.of("fallback-iris"), LootMode.FALLBACK, true);
assertEquals(List.of("fallback-iris"), sources);
}
@@ -1,75 +0,0 @@
package art.arcane.iris.modded;
import art.arcane.iris.engine.object.value.IRare;
import art.arcane.iris.engine.object.entity.IrisEntitySpawn;
import art.arcane.volmlib.util.collection.KList;
import org.junit.Test;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ModdedSpawnerRarityParityTest {
private static IrisEntitySpawn spawn(int rarity) {
IrisEntitySpawn spawn = new IrisEntitySpawn();
spawn.setRarity(rarity);
return spawn;
}
@Test
public void rarityIsAppliedOnceAsPoolWeightOnly() {
IrisEntitySpawn common = spawn(1);
IrisEntitySpawn rare = spawn(4);
KList<IrisEntitySpawn> expanded = IRare.expandWeighted(List.of(common, rare));
// totalRarity 5 -> common appears 5/1 = 5 times, rare 5/4 = 1 time.
assertEquals(6, expanded.size());
assertEquals(5, expanded.stream().filter(entry -> entry == common).count());
assertEquals(1, expanded.stream().filter(entry -> entry == rare).count());
}
@Test
public void rarityZeroAndNegativeAreClampedToOne() {
assertEquals(1, IRare.get(spawn(0)));
assertEquals(1, IRare.get(spawn(-5)));
assertEquals(3, IRare.get(spawn(3)));
}
@Test
public void perPositionSpawnLoopsDoNotRerollEntryRarity() throws Exception {
String source = Files.readString(Path.of(System.getProperty("iris.moddedCommonSources"),
"art/arcane/iris/modded/ModdedWorldManager.java"));
for (String method : List.of("private int spawnEntry(", "private int spawnEntryAt(")) {
String body = methodBody(source, method);
assertFalse(method + " must not re-roll rarity per position; rarityPick already weighted the pool",
body.contains("getRarity()"));
assertTrue(method + " must keep the min/max spawn-count roll",
body.contains("LootResolver.inclusive("));
}
}
private static String methodBody(String source, String declaration) {
int start = source.indexOf(declaration);
assertTrue("ModdedWorldManager must declare " + declaration, start >= 0);
int open = source.indexOf('{', start);
int depth = 0;
for (int index = open; index < source.length(); index++) {
char character = source.charAt(index);
if (character == '{') {
depth++;
} else if (character == '}') {
depth--;
if (depth == 0) {
return source.substring(open + 1, index);
}
}
}
throw new AssertionError(declaration + " is not brace balanced");
}
}