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

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

No files matched your search

@@ -1,8 +1,6 @@
package art.arcane.iris.core.events;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.object.loot.InventorySlotType;
import art.arcane.iris.engine.object.loot.IrisLootTable;
import art.arcane.iris.platform.bukkit.BukkitPlatform;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.volmlib.util.collection.KList;
@@ -17,6 +15,7 @@ import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.event.world.LootGenerateEvent;
import com.volmit.service.Loot;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
@@ -52,21 +51,18 @@ public class IrisLootEvent extends Event {
private final Engine engine;
private final Block block;
private final InventorySlotType slot;
private final KList<IrisLootTable> tables;
private final KList<Loot.Source> tables;
/**
* Constructor for IrisLootEvent with mode selection.
*
* @param engine The engine instance.
* @param block The block associated with the event.
* @param slot The inventory slot type.
* @param tables The list of IrisLootTables. (mutable*)
* @param tables The loot tables the container draws from, as the pack's modules named them. (mutable*)
*/
public IrisLootEvent(Engine engine, Block block, InventorySlotType slot, KList<IrisLootTable> tables) {
public IrisLootEvent(Engine engine, Block block, KList<Loot.Source> tables) {
this.engine = engine;
this.block = block;
this.slot = slot;
this.tables = tables;
}
@@ -37,24 +37,18 @@ import art.arcane.iris.core.modules.PackModuleSet;
import art.arcane.iris.core.pack.PackDirectoryResolver;
import art.arcane.iris.engine.data.cache.AtomicCache;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.structure.StructureGraphCatalog;
import art.arcane.iris.core.structure.authoring.StructureRecoveryResult;
import art.arcane.iris.core.structure.authoring.StructureTransactionWriter;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.material.IrisBlockData;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.entity.IrisEntity;
import art.arcane.iris.engine.object.noise.expression.IrisExpression;
import art.arcane.iris.engine.object.prefab.IrisObjectScale;
import art.arcane.iris.engine.object.terrain.IrisGenerator;
import art.arcane.iris.engine.object.image.IrisImage;
import art.arcane.iris.engine.object.image.IrisImageMap;
import art.arcane.iris.engine.object.loot.IrisLootTable;
import art.arcane.iris.engine.object.marker.IrisMarker;
import art.arcane.iris.engine.object.mod.IrisMod;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.entity.spawn.IrisSpawner;
import art.arcane.iris.engine.object.annotations.Snippet;
import art.arcane.iris.engine.object.prefab.matter.IrisMatterObject;
import art.arcane.volmlib.util.collection.KList;
@@ -105,9 +99,8 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
private static final Set<IrisData> ENGINE_HOLDERS =
Collections.synchronizedSet(Collections.newSetFromMap(new IdentityHashMap<>()));
/** Every resource type Iris loads itself for generation, studio and validation; module resource kinds come on top. */
private static final List<Class<? extends IrisRegistrant>> RUNTIME_RESOURCE_TYPES = List.of(IrisLootTable.class,
IrisSpawner.class, IrisEntity.class, IrisRegion.class, IrisBiome.class, IrisMod.class, IrisDimension.class,
IrisGenerator.class, IrisMarker.class, IrisBlockData.class, IrisExpression.class, IrisObject.class, IrisImage.class,
private static final List<Class<? extends IrisRegistrant>> RUNTIME_RESOURCE_TYPES = List.of(IrisRegion.class, IrisBiome.class, IrisMod.class, IrisDimension.class,
IrisGenerator.class, IrisBlockData.class, IrisExpression.class, IrisObject.class, IrisImage.class,
IrisImageMap.class, IrisMatterObject.class);
/** Pack folders Iris reads that hold no resources of its loaders: snippets and module jars. */
private static final List<String> OTHER_OWN_FOLDERS = List.of("snippet", "modules");
@@ -120,13 +113,9 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
@ToString.Exclude
private volatile IrisPackResources packResources;
private ResourceLoader<IrisBiome> biomeLoader;
private ResourceLoader<IrisLootTable> lootLoader;
private ResourceLoader<IrisRegion> regionLoader;
private ResourceLoader<IrisDimension> dimensionLoader;
private ResourceLoader<IrisGenerator> generatorLoader;
private ResourceLoader<IrisEntity> entityLoader;
private ResourceLoader<IrisMarker> markerLoader;
private ResourceLoader<IrisSpawner> spawnerLoader;
private ResourceLoader<IrisMod> modLoader;
private ResourceLoader<IrisBlockData> blockLoader;
private ResourceLoader<IrisExpression> expressionLoader;
@@ -256,30 +245,14 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
return loadAny(IrisMod.class, key, nearest);
}
public static IrisEntity loadAnyEntity(String key, @Nullable IrisData nearest) {
return loadAny(IrisEntity.class, key, nearest);
}
public static IrisLootTable loadAnyLootTable(String key, @Nullable IrisData nearest) {
return loadAny(IrisLootTable.class, key, nearest);
}
public static IrisBlockData loadAnyBlock(String key, @Nullable IrisData nearest) {
return loadAny(IrisBlockData.class, key, nearest);
}
public static IrisSpawner loadAnySpaner(String key, @Nullable IrisData nearest) {
return loadAny(IrisSpawner.class, key, nearest);
}
public static IrisRegion loadAnyRegion(String key, @Nullable IrisData nearest) {
return loadAny(IrisRegion.class, key, nearest);
}
public static IrisMarker loadAnyMarker(String key, @Nullable IrisData nearest) {
return loadAny(IrisMarker.class, key, nearest);
}
public static IrisImage loadAnyImage(String key, @Nullable IrisData nearest) {
return loadAny(IrisImage.class, key, nearest);
}
@@ -496,8 +469,6 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
}
public synchronized void hotloaded() {
StructureGraphCatalog.invalidate(this);
IrisObjectScale.invalidate(this);
closed = false;
dataFolder.mkdirs();
recoverStructureTransactions();
@@ -525,15 +496,11 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
.registerTypeAdapter(MantleFlag.class, new MantleFlagAdapter())
.setPrettyPrinting();
KMap<Class<? extends IrisRegistrant>, ResourceLoader<? extends IrisRegistrant>> replacement = new KMap<>();
this.lootLoader = registerLoader(IrisLootTable.class, replacement);
this.spawnerLoader = registerLoader(IrisSpawner.class, replacement);
this.entityLoader = registerLoader(IrisEntity.class, replacement);
this.regionLoader = registerLoader(IrisRegion.class, replacement);
this.biomeLoader = registerLoader(IrisBiome.class, replacement);
this.modLoader = registerLoader(IrisMod.class, replacement);
this.dimensionLoader = registerLoader(IrisDimension.class, replacement);
this.generatorLoader = registerLoader(IrisGenerator.class, replacement);
this.markerLoader = registerLoader(IrisMarker.class, replacement);
this.blockLoader = registerLoader(IrisBlockData.class, replacement);
this.expressionLoader = registerLoader(IrisExpression.class, replacement);
this.objectLoader = registerLoader(IrisObject.class, replacement);
@@ -578,8 +545,6 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
/** Forgets everything read so far: the loaders' caches and the module resources, which a new snapshot reads again. */
public void dump() {
StructureGraphCatalog.invalidate(this);
IrisObjectScale.invalidate(this);
for (ResourceLoader<?> i : loaders.values()) {
i.clearCache();
}
@@ -588,7 +553,6 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
/** Reads objects and module resources (structures, jigsaw pools and pieces among them) again after a tool rewrote their files. */
public synchronized void invalidateStructureResources() {
StructureGraphCatalog.invalidate(this);
invalidateLoader(objectLoader);
reloadModuleResources();
}
@@ -0,0 +1,56 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.modules;
import art.arcane.iris.core.link.Identifier;
import art.arcane.iris.core.service.ExternalDataSVC;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.IrisServices;
import art.arcane.iris.spi.PlatformItem;
import com.volmit.item.ItemRegistry;
import java.util.OptionalInt;
/**
* IrisApi's view of the bound platform's items: the platform's registry for plain keys, and the item providers of
* Iris's external data service for keys with a namespace of their own ({@code itemsadder:ruby}), which is how packs name
* custom items.
*/
public final class IrisItemRegistry implements ItemRegistry {
private static final String MINECRAFT_PREFIX = "minecraft:";
private static final char NAMESPACE_SEPARATOR = ':';
@Override
public OptionalInt maxDurability(String key) {
if (isCustomItem(key)) {
return customItemDurability(key);
}
PlatformItem item = IrisPlatforms.get().registries().item(key);
return item == null ? OptionalInt.empty() : OptionalInt.of(item.maxDurability());
}
/** Whether {@code key} names an item of an external provider, which resolves it, rather than of the platform. */
public static boolean isCustomItem(String key) {
return !key.startsWith(MINECRAFT_PREFIX) && key.indexOf(NAMESPACE_SEPARATOR) >= 0;
}
private static OptionalInt customItemDurability(String key) {
return IrisServices.get(ExternalDataSVC.class).maxDurability(Identifier.fromString(key));
}
}
@@ -22,7 +22,9 @@ import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.actuator.BiomeModule;
import art.arcane.iris.engine.actuator.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;
@@ -70,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 PerfectionModule(), new CustomModule(), new LootModule(), new SpawnModule());
}
/** Whether {@code type} is one of Iris's own classes that built-in settings may hold. */
@@ -26,6 +26,7 @@ import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import com.volmit.block.BlockRegistry;
import com.volmit.host.ResourceKindRegistration;
import com.volmit.item.ItemRegistry;
import com.volmit.noise.NoiseFactory;
import com.volmit.object.GeneratedObject;
import com.volmit.resource.PackResources;
@@ -69,6 +70,7 @@ public final class IrisPackResources implements PackResources {
private final PackResourceIds ids;
private final UUID snapshotId = UUID.randomUUID();
private final BlockRegistry blocks;
private final ItemRegistry items = new IrisItemRegistry();
private final NoiseFactory noise;
private final Map<Class<?>, Kind<?>> irisKinds;
private final Supplier<List<ResourceKind<?>>> moduleKindList;
@@ -122,6 +124,11 @@ public final class IrisPackResources implements PackResources {
return blocks;
}
@Override
public ItemRegistry items() {
return items;
}
@Override
public NoiseFactory noise() {
return noise;
@@ -21,11 +21,19 @@ 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;
import com.volmit.service.SaplingGrowth;
import com.volmit.service.StructureLocator;
import com.volmit.world.PackWorld;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
@@ -49,6 +57,120 @@ public final class ModuleServices {
return keys;
}
/** The biomes and regions of the engine's layout that every module says place the object {@code objectKey}. */
public static ObjectsAt.PlacedBy objectPlacers(Engine engine, String objectKey) {
PackWorld world = engine.getGeneration().world();
Set<String> biomes = new LinkedHashSet<>();
Set<String> regions = new LinkedHashSet<>();
for (ObjectsAt provider : catalog(engine.getData()).services(ObjectsAt.class)) {
ObjectsAt.PlacedBy placedBy = provider.placedBy(world, objectKey);
biomes.addAll(placedBy.biomes());
regions.addAll(placedBy.regions());
}
return new ObjectsAt.PlacedBy(biomes, regions);
}
/** The loot tables the modules say the container at {@code site} draws from, in module order. */
public static List<Loot.Source> lootTables(Engine engine, Loot.Site site) {
PackWorld world = engine.getGeneration().world();
List<Loot.Source> tables = new ArrayList<>();
for (Loot provider : catalog(engine.getData()).services(Loot.class)) {
tables.addAll(provider.tables(world, site));
}
return tables;
}
/** The items loot table {@code key} gives at {@code site}, from the module that knows the table. */
public static List<ItemDrop> lootItems(Engine engine, Loot.Site site, String key) {
PackWorld world = engine.getGeneration().world();
List<ItemDrop> items = new ArrayList<>();
for (Loot provider : catalog(engine.getData()).services(Loot.class)) {
items.addAll(provider.items(world, site, key));
}
return items;
}
/** What the modules drop for the broken block, put together. */
public static BlockDrops.Result blockDrops(Engine engine, BlockDrops.Broken broken) {
PackWorld world = engine.getGeneration().world();
List<ItemDrop> drops = new ArrayList<>();
boolean replacesVanillaDrops = false;
for (BlockDrops provider : catalog(engine.getData()).services(BlockDrops.class)) {
BlockDrops.Result result = provider.drops(world, broken);
drops.addAll(result.drops());
replacesVanillaDrops |= result.replacesVanillaDrops();
}
return new BlockDrops.Result(drops, replacesVanillaDrops);
}
/** The tree grown by the first module that grows one for {@code sapling}; empty leaves the growth to the platform. */
public static Optional<SaplingGrowth.Growth> growSapling(Engine engine, SaplingGrowth.Sapling sapling, SaplingGrowth.Surroundings surroundings) {
PackWorld world = engine.getGeneration().world();
for (SaplingGrowth provider : catalog(engine.getData()).services(SaplingGrowth.class)) {
Optional<SaplingGrowth.Growth> growth = provider.grow(world, sapling, surroundings);
if (growth.isPresent()) {
return growth;
}
}
return Optional.empty();
}
/** The objects every module places as trees. */
public static SaplingGrowth.TreeObjects treeObjects(Engine engine) {
PackWorld world = engine.getGeneration().world();
Set<String> objects = new LinkedHashSet<>();
Set<String> procedural = new LinkedHashSet<>();
for (SaplingGrowth provider : catalog(engine.getData()).services(SaplingGrowth.class)) {
SaplingGrowth.TreeObjects trees = provider.treeObjects(world);
objects.addAll(trees.objects());
procedural.addAll(trees.procedural());
}
return new SaplingGrowth.TreeObjects(objects, procedural);
}
/** What the first module with something to spawn at {@code site} plans; empty when none does. */
public static Optional<PlannedSpawn> planSpawn(Engine engine, EntitySpawns.Site site) {
PackWorld world = engine.getGeneration().world();
for (EntitySpawns provider : catalog(engine.getData()).services(EntitySpawns.class)) {
Optional<EntitySpawns.Plan> plan = provider.plan(world, site);
if (plan.isPresent()) {
return Optional.of(new PlannedSpawn(provider, world, plan.get()));
}
}
return Optional.empty();
}
/** The entity {@code key} as the first module that knows it would spawn it. */
public static Optional<EntitySpec> entity(Engine engine, String key) {
PackWorld world = engine.getGeneration().world();
for (EntitySpawns provider : catalog(engine.getData()).services(EntitySpawns.class)) {
Optional<EntitySpec> entity = provider.entity(world, key);
if (entity.isPresent()) {
return entity;
}
}
return Optional.empty();
}
/** What the first module that knows the marker {@code tag} says it does. */
public static Optional<EntitySpawns.MarkerRule> markerRule(Engine engine, String tag) {
PackWorld world = engine.getGeneration().world();
for (EntitySpawns provider : catalog(engine.getData()).services(EntitySpawns.class)) {
Optional<EntitySpawns.MarkerRule> rule = provider.marker(world, tag);
if (rule.isPresent()) {
return rule;
}
}
return Optional.empty();
}
/** A plan and the module that made it, which hears how many of its entities appeared. */
public record PlannedSpawn(EntitySpawns provider, PackWorld world, EntitySpawns.Plan plan) {
public void spawned(int count) {
provider.spawned(world, plan, count);
}
}
/** Every structure key the pack's modules know, placed or not. */
public static Set<String> structureKeys(IrisData data) {
Set<String> keys = new LinkedHashSet<>();
@@ -0,0 +1,68 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.pack;
import art.arcane.volmlib.util.json.JSONObject;
import java.util.List;
/** Checks of integer fields in the JSON of pack files, which add what is wrong to a list of messages. */
public final class PackIntegerChecks {
private PackIntegerChecks() {
}
/** The integer in {@code field}, {@code defaultValue} when it is absent, or null (with a message) when it is not an integer. */
public static Integer integerField(JSONObject object, String field, int defaultValue,
String path, List<String> blockingErrors) {
if (!object.has(field)) {
return defaultValue;
}
Object rawValue = object.opt(field);
if (!(rawValue instanceof Number number)
|| !Double.isFinite(number.doubleValue())
|| number.doubleValue() != Math.rint(number.doubleValue())
|| number.longValue() < Integer.MIN_VALUE
|| number.longValue() > Integer.MAX_VALUE) {
blockingErrors.add(path + "." + field + " must be an integer.");
return null;
}
return number.intValue();
}
public static void requireMinimum(String fieldPath, Integer value, int minimum,
List<String> blockingErrors) {
if (value != null && value < minimum) {
blockingErrors.add(fieldPath + " must be at least " + minimum + ".");
}
}
public static void requireMaximum(String fieldPath, Integer value, int maximum,
List<String> blockingErrors) {
if (value != null && value > maximum) {
blockingErrors.add(fieldPath + " must be at most " + maximum + ".");
}
}
public static void requireOrdered(String minimumPath, Integer minimum, String maximumPath,
Integer maximum, List<String> blockingErrors) {
if (minimum != null && maximum != null && minimum > maximum) {
blockingErrors.add(minimumPath + " must not exceed " + maximumPath + ".");
}
}
}
@@ -62,9 +62,9 @@ final class PackJsonFieldChecks {
if (!object.has(field) || object.opt(field) == JSONObject.NULL) {
return;
}
Integer value = PackLootValidator.lootInteger(object, field, minimum, path, blockingErrors);
PackLootValidator.requireMinimum(path + "." + field, value, minimum, blockingErrors);
PackLootValidator.requireMaximum(path + "." + field, value, maximum, blockingErrors);
Integer value = PackIntegerChecks.integerField(object, field, minimum, path, blockingErrors);
PackIntegerChecks.requireMinimum(path + "." + field, value, minimum, blockingErrors);
PackIntegerChecks.requireMaximum(path + "." + field, value, maximum, blockingErrors);
}
static void validateOptionalDoubleRange(String path, JSONObject object, String field,
@@ -1,255 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.pack;
import art.arcane.iris.engine.object.loot.IrisLoot;
import art.arcane.iris.engine.object.loot.IrisLootReference;
import art.arcane.iris.engine.object.loot.IrisLootTable;
import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
final class PackLootValidator {
private PackLootValidator() {
}
record LootGraphIssues(List<String> errors, List<String> warnings) {
LootGraphIssues {
errors = List.copyOf(errors);
warnings = List.copyOf(warnings);
}
}
static LootGraphIssues validateLootGraph(File packFolder) {
List<String> blockingErrors = new ArrayList<>();
List<String> warnings = new ArrayList<>();
if (packFolder == null || !packFolder.isDirectory()) {
return new LootGraphIssues(blockingErrors, warnings);
}
File lootFolder = new File(packFolder, PackValidator.LOOT_FOLDER);
Set<String> lootKeys = ContentKeyValidator.deriveRegistrantKeysExact(lootFolder);
if (lootFolder.isDirectory()) {
List<File> lootFiles = PackValidationIo.listJsonRecursive(lootFolder);
lootFiles.sort(Comparator.comparing(File::getPath));
for (File lootFile : lootFiles) {
String lootKey = PackValidationIo.deriveKey(lootFolder, lootFile);
JSONObject table = PackStructurePlacementValidator.readGraphJson(
lootFile, "Loot table", lootKey, blockingErrors);
if (table != null) {
validateLootTable(lootKey, table, blockingErrors);
}
}
}
for (String folderName : PackValidator.STRUCTURE_HOST_FOLDERS) {
File resourceFolder = new File(packFolder, folderName);
if (!resourceFolder.isDirectory()) {
continue;
}
List<File> resourceFiles = PackValidationIo.listJsonRecursive(resourceFolder);
resourceFiles.sort(Comparator.comparing(File::getPath));
for (File resourceFile : resourceFiles) {
JSONObject resource = PackValidationIo.readJson(resourceFile);
if (resource == null || !resource.has("loot")) {
continue;
}
String resourceType = PackStructurePlacementValidator.structureHostType(folderName);
String resourceKey = PackValidationIo.deriveKey(resourceFolder, resourceFile);
validateLootReference(resourceType, resourceKey, resource.opt("loot"), lootKeys, blockingErrors, warnings);
}
}
return new LootGraphIssues(blockingErrors, warnings);
}
private static void validateLootTable(String lootKey, JSONObject table, List<String> blockingErrors) {
String path = "Loot table '" + lootKey + "'";
Integer rarity = lootInteger(table, "rarity", 1, path, blockingErrors);
Integer minimumPicked = lootInteger(table, "minPicked", 1, path, blockingErrors);
Integer maximumPicked = lootInteger(table, "maxPicked", 5, path, blockingErrors);
Integer maximumTries = lootInteger(table, "maxTries", 10, path, blockingErrors);
requireMinimum(path + ".rarity", rarity, 1, blockingErrors);
requireMinimum(path + ".minPicked", minimumPicked, 0, blockingErrors);
requireMinimum(path + ".maxPicked", maximumPicked, 1, blockingErrors);
requireMinimum(path + ".maxTries", maximumTries, 1, blockingErrors);
requireMaximum(path + ".minPicked", minimumPicked, IrisLootTable.MAX_PICKED, blockingErrors);
requireMaximum(path + ".maxPicked", maximumPicked, IrisLootTable.MAX_PICKED, blockingErrors);
requireMaximum(path + ".maxTries", maximumTries, IrisLootTable.MAX_TRIES, blockingErrors);
requireOrdered(path + ".minPicked", minimumPicked, path + ".maxPicked", maximumPicked, blockingErrors);
JSONArray entries = table.optJSONArray("loot");
if (entries == null || entries.length() == 0) {
blockingErrors.add(path + ".loot must be a non-empty array.");
return;
}
for (int entryIndex = 0; entryIndex < entries.length(); entryIndex++) {
JSONObject entry = entries.optJSONObject(entryIndex);
String entryPath = path + ".loot[" + entryIndex + "]";
if (entry == null) {
blockingErrors.add(entryPath + " must be an object.");
continue;
}
String type = entry.optString("type", "").trim();
if (type.isEmpty()) {
blockingErrors.add(entryPath + ".type must not be blank.");
}
Integer entryRarity = lootInteger(entry, "rarity", 1, entryPath, blockingErrors);
Integer minimumAmount = lootInteger(entry, "minAmount", 1, entryPath, blockingErrors);
Integer maximumAmount = lootInteger(entry, "maxAmount", 1, entryPath, blockingErrors);
requireMinimum(entryPath + ".rarity", entryRarity, 1, blockingErrors);
requireMinimum(entryPath + ".minAmount", minimumAmount, 1, blockingErrors);
requireMinimum(entryPath + ".maxAmount", maximumAmount, 1, blockingErrors);
requireMaximum(entryPath + ".minAmount", minimumAmount, IrisLoot.MAX_AMOUNT, blockingErrors);
requireMaximum(entryPath + ".maxAmount", maximumAmount, IrisLoot.MAX_AMOUNT, blockingErrors);
requireOrdered(entryPath + ".minAmount", minimumAmount,
entryPath + ".maxAmount", maximumAmount, blockingErrors);
validateLootEnchantments(entryPath, entry.opt("enchantments"), blockingErrors);
}
}
private static void validateLootEnchantments(String entryPath, Object rawEnchantments,
List<String> blockingErrors) {
if (rawEnchantments == null || rawEnchantments == JSONObject.NULL) {
return;
}
if (!(rawEnchantments instanceof JSONArray enchantments)) {
blockingErrors.add(entryPath + ".enchantments must be an array.");
return;
}
for (int enchantmentIndex = 0; enchantmentIndex < enchantments.length(); enchantmentIndex++) {
JSONObject enchantment = enchantments.optJSONObject(enchantmentIndex);
String enchantmentPath = entryPath + ".enchantments[" + enchantmentIndex + "]";
if (enchantment == null) {
blockingErrors.add(enchantmentPath + " must be an object.");
continue;
}
if (enchantment.optString("enchantment", "").isBlank()) {
blockingErrors.add(enchantmentPath + ".enchantment must not be blank.");
}
Integer minimumLevel = lootInteger(enchantment, "minLevel", 1, enchantmentPath, blockingErrors);
Integer maximumLevel = lootInteger(enchantment, "maxLevel", 1, enchantmentPath, blockingErrors);
requireMinimum(enchantmentPath + ".minLevel", minimumLevel, 1, blockingErrors);
requireMinimum(enchantmentPath + ".maxLevel", maximumLevel, 1, blockingErrors);
requireOrdered(enchantmentPath + ".minLevel", minimumLevel,
enchantmentPath + ".maxLevel", maximumLevel, blockingErrors);
if (enchantment.has("chance")) {
Object rawChance = enchantment.opt("chance");
if (!(rawChance instanceof Number number)
|| !Double.isFinite(number.doubleValue())
|| number.doubleValue() < 0D
|| number.doubleValue() > 1D) {
blockingErrors.add(enchantmentPath + ".chance must be a finite number from 0 to 1.");
}
}
}
}
private static void validateLootReference(String resourceType, String resourceKey, Object rawLoot,
Set<String> lootKeys, List<String> blockingErrors, List<String> warnings) {
String path = resourceType + " '" + resourceKey + "'.loot";
if (!(rawLoot instanceof JSONObject reference)) {
blockingErrors.add(path + " must be an object.");
return;
}
boolean clearMode = false;
if (reference.has("mode")) {
Object rawMode = reference.opt("mode");
if (!(rawMode instanceof String mode)
|| !Set.of("ADD", "CLEAR", "REPLACE", "FALLBACK").contains(mode)) {
blockingErrors.add(path + ".mode must be ADD, CLEAR, REPLACE, or FALLBACK.");
} else {
clearMode = "CLEAR".equals(mode);
}
}
if (reference.has("multiplier")) {
Object rawMultiplier = reference.opt("multiplier");
if (!(rawMultiplier instanceof Number multiplier)
|| !Double.isFinite(multiplier.doubleValue())
|| multiplier.doubleValue() < 0D
|| multiplier.doubleValue() > IrisLootReference.MAX_MULTIPLIER) {
blockingErrors.add(path + ".multiplier must be a finite number from 0 to "
+ (int) IrisLootReference.MAX_MULTIPLIER + ".");
}
}
if (!reference.has("tables")) {
return;
}
JSONArray tables = reference.optJSONArray("tables");
if (tables == null) {
blockingErrors.add(path + ".tables must be an array.");
return;
}
if (clearMode && tables.length() > 0) {
warnings.add(path + " uses mode CLEAR and lists " + tables.length()
+ " table(s); CLEAR clears parent tables and contributes no tables of its own, so these entries are dead. Use REPLACE to substitute them.");
}
for (int tableIndex = 0; tableIndex < tables.length(); tableIndex++) {
Object rawTableKey = tables.opt(tableIndex);
if (!(rawTableKey instanceof String tableKey) || tableKey.isBlank()) {
blockingErrors.add(path + ".tables[" + tableIndex + "] must name a loot table.");
} else if (!lootKeys.contains(tableKey)) {
blockingErrors.add(path + ".tables[" + tableIndex
+ "] references missing loot table '" + tableKey + "'.");
}
}
}
static Integer lootInteger(JSONObject object, String field, int defaultValue,
String path, List<String> blockingErrors) {
if (!object.has(field)) {
return defaultValue;
}
Object rawValue = object.opt(field);
if (!(rawValue instanceof Number number)
|| !Double.isFinite(number.doubleValue())
|| number.doubleValue() != Math.rint(number.doubleValue())
|| number.longValue() < Integer.MIN_VALUE
|| number.longValue() > Integer.MAX_VALUE) {
blockingErrors.add(path + "." + field + " must be an integer.");
return null;
}
return number.intValue();
}
static void requireMinimum(String fieldPath, Integer value, int minimum,
List<String> blockingErrors) {
if (value != null && value < minimum) {
blockingErrors.add(fieldPath + " must be at least " + minimum + ".");
}
}
static void requireMaximum(String fieldPath, Integer value, int maximum,
List<String> blockingErrors) {
if (value != null && value > maximum) {
blockingErrors.add(fieldPath + " must be at most " + maximum + ".");
}
}
static void requireOrdered(String minimumPath, Integer minimum, String maximumPath,
Integer maximum, List<String> blockingErrors) {
if (minimum != null && maximum != null && minimum > maximum) {
blockingErrors.add(minimumPath + " must not exceed " + maximumPath + ".");
}
}
}
@@ -395,8 +395,8 @@ final class PackStructurePlacementValidator {
if (!structureKey.isEmpty() && !sourceKeys.add(structureKey.toLowerCase(Locale.ROOT))) {
blockingErrors.add(sourcePath + ".structure duplicates native source '" + structureKey + "'.");
}
Integer weight = PackLootValidator.lootInteger(source, "weight", 1, sourcePath, blockingErrors);
PackLootValidator.requireMinimum(sourcePath + ".weight", weight, 1, blockingErrors);
Integer weight = PackIntegerChecks.integerField(source, "weight", 1, sourcePath, blockingErrors);
PackIntegerChecks.requireMinimum(sourcePath + ".weight", weight, 1, blockingErrors);
if (weight != null && weight > 0) {
totalWeight += weight;
}
@@ -36,7 +36,6 @@ public final class PackValidator {
static final String DATAPACKS_FOLDER = "datapacks";
static final String CACHE_FOLDER = "cache";
static final String OBJECTS_FOLDER = "objects";
static final String LOOT_FOLDER = "loot";
static final String DIMENSIONS_FOLDER = "dimensions";
static final String STRUCTURES_FOLDER = "structures";
static final String JIGSAW_POOLS_FOLDER = "jigsaw-pools";
@@ -90,9 +89,6 @@ public final class PackValidator {
addDistinct(blockingErrors, imageMaps.errors());
addDistinct(warnings, imageMaps.warnings());
blockingErrors.addAll(PackCaveProfileValidator.validateLegacyFields(packFolder));
PackLootValidator.LootGraphIssues lootIssues = PackLootValidator.validateLootGraph(packFolder);
addDistinct(blockingErrors, lootIssues.errors());
addDistinct(warnings, lootIssues.warnings());
blockingErrors.addAll(PackObjectSurfaceValidator.validateRemovedWorldgenFields(packFolder));
blockingErrors.addAll(PackObjectSurfaceValidator.validateObjectSurfaceSupport(packFolder));
blockingErrors.addAll(PackObjectSurfaceValidator.validateUnsupportedStructureTransforms(packFolder));
@@ -18,6 +18,8 @@
package art.arcane.iris.core.project;
import art.arcane.iris.engine.spawn.SpawnResources;
import art.arcane.iris.engine.loot.LootResources;
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
import com.google.gson.Gson;
import art.arcane.iris.core.loader.IrisData;
@@ -120,29 +122,29 @@ public class IrisPackageCompiler {
}
dimension.getAllRegions(() -> dm).forEach((region) -> addIfPresent(regions, region));
dimension.getLoot().getTables().forEach((i) -> addIfPresent(loot, dm.getLootLoader().load(i)));
dimension.getLoot().getTables().forEach((i) -> addIfPresent(loot, LootResources.table(dm, i)));
regions.forEach((i) -> biomes.addAll(i.getAllBiomes(() -> dm)));
dimension.getReachableBiomes(() -> dm).forEach((biome) -> addIfPresent(biomes, biome));
regions.forEach((r) -> r.getLoot().getTables().forEach((i) -> addIfPresent(loot, dm.getLootLoader().load(i))));
regions.forEach((r) -> r.getEntitySpawners().forEach((sp) -> addIfPresent(spawners, dm.getSpawnerLoader().load(sp))));
dimension.getEntitySpawners().forEach((sp) -> addIfPresent(spawners, dm.getSpawnerLoader().load(sp)));
regions.forEach((r) -> r.getLoot().getTables().forEach((i) -> addIfPresent(loot, LootResources.table(dm, i))));
regions.forEach((r) -> r.getEntitySpawners().forEach((sp) -> addIfPresent(spawners, SpawnResources.spawner(dm, sp))));
dimension.getEntitySpawners().forEach((sp) -> addIfPresent(spawners, SpawnResources.spawner(dm, sp)));
biomes.forEach((i) -> i.getGenerators().forEach((j) -> addIfPresent(generators, j.getCachedGenerator(() -> dm))));
biomes.forEach((r) -> r.getLoot().getTables().forEach((i) -> addIfPresent(loot, dm.getLootLoader().load(i))));
biomes.forEach((r) -> r.getEntitySpawners().forEach((sp) -> addIfPresent(spawners, dm.getSpawnerLoader().load(sp))));
biomes.forEach((r) -> r.getLoot().getTables().forEach((i) -> addIfPresent(loot, LootResources.table(dm, i))));
biomes.forEach((r) -> r.getEntitySpawners().forEach((sp) -> addIfPresent(spawners, SpawnResources.spawner(dm, sp))));
KList<IrisObjectPlacement> allPlacements = new KList<>();
regions.forEach((r) -> allPlacements.addAll(r.getObjects()));
biomes.forEach((i) -> allPlacements.addAll(i.getObjects()));
KSet<IrisMarker> markers = new KSet<>();
for (String markerKey : PackExportClosure.collectMarkerKeys(allPlacements)) {
IrisMarker marker = dm.getMarkerLoader().load(markerKey);
IrisMarker marker = SpawnResources.marker(dm, markerKey);
if (marker == null) {
continue;
}
markers.add(marker);
marker.getSpawners().forEach((sp) -> addIfPresent(spawners, dm.getSpawnerLoader().load(sp)));
marker.getSpawners().forEach((sp) -> addIfPresent(spawners, SpawnResources.spawner(dm, sp)));
}
collectSpawnerEntityKeys(spawners).forEach((i) -> addIfPresent(entities, dm.getEntityLoader().load(i)));
entities.forEach((e) -> e.getLoot().getTables().forEach((i) -> addIfPresent(loot, dm.getLootLoader().load(i))));
collectSpawnerEntityKeys(spawners).forEach((i) -> addIfPresent(entities, SpawnResources.entity(dm, i)));
entities.forEach((e) -> e.getLoot().getTables().forEach((i) -> addIfPresent(loot, LootResources.table(dm, i))));
Set<String> structureKeys = new LinkedHashSet<>();
collectStructureKeys(structureKeys, dimension.getStructures());
regions.forEach((region) -> collectStructureKeys(structureKeys, region.getStructures()));
@@ -45,6 +45,7 @@ import java.util.List;
import java.util.MissingResourceException;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.stream.Collectors;
public class ExternalDataSVC implements IrisService {
@@ -159,6 +160,12 @@ public class ExternalDataSVC implements IrisService {
}
}
/** The most damage the custom item {@code key} takes before it breaks, 0 if it cannot be damaged; empty when no provider has the item. */
public OptionalInt maxDurability(Identifier key) {
Optional<ItemStack> stack = getItemStack(key, null);
return stack.isEmpty() ? OptionalInt.empty() : OptionalInt.of(stack.get().getType().getMaxDurability());
}
public void processUpdate(Engine engine, Block block, Identifier blockId) {
Optional<ExternalDataProvider> provider = activeProviders.stream().filter(p -> p.isValidProvider(blockId, DataType.BLOCK)).findFirst();
if (provider.isEmpty()) {
@@ -18,38 +18,28 @@
package art.arcane.iris.core.service;
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
import art.arcane.iris.engine.object.procedural.tree.IrisTreeModes;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.IrisServices;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.core.modules.ModuleServices;
import art.arcane.iris.core.modules.PlatformBlockStates;
import art.arcane.iris.core.tools.IrisToolbelt;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineLifecycleTasks;
import art.arcane.iris.engine.framework.TreeBlockMaterial;
import art.arcane.iris.engine.object.placement.IObjectPlacer;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.placement.IrisTreeSize;
import art.arcane.iris.engine.object.prefab.TileData;
import art.arcane.iris.engine.platform.PlatformChunkGenerator;
import art.arcane.iris.platform.bukkit.BukkitBlockState;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.collection.KMap;
import art.arcane.volmlib.util.data.Cuboid;
import art.arcane.iris.util.common.data.IrisCustomData;
import com.volmit.placement.PlacedBlock;
import com.volmit.service.SaplingGrowth;
import art.arcane.volmlib.util.math.BlockPosition;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.iris.util.common.plugin.IrisService;
import art.arcane.iris.util.common.scheduling.J;
import org.bukkit.Bukkit;
import org.bukkit.HeightMap;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.TreeType;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
@@ -60,7 +50,7 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.world.StructureGrowEvent;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Predicate;
@@ -117,134 +107,43 @@ public class TreeSVC implements IrisService {
return;
}
IrisDimension dimension = engine.getDimension();
if (dimension == null) {
if (engine.getDimension() == null) {
IrisLogging.debug(this.getClass().getName() + " passed it off to vanilla because could not get Dimension for this world");
IrisLogging.reportError(new NullPointerException(event.getWorld().getName() + " could not be accessed despite being an Iris world"));
return;
}
if (!dimension.getTreeSettings().isEnabled()) {
IrisLogging.debug(this.getClass().getName() + " cancelled because tree overrides are disabled");
return;
}
BlockData first = event.getLocation().getBlock().getBlockData().clone();
Cuboid saplingPlane = getSaplings(event.getLocation(), blockData -> blockData instanceof Sapling && blockData.getMaterial().equals(first.getMaterial()), event.getWorld());
IrisLogging.debug("Sapling grew @ " + event.getLocation() + " for " + event.getSpecies().name() + " usedBoneMeal is " + event.isFromBonemeal());
IrisLogging.debug("Sapling plane is: " + saplingPlane.getSizeX() + " by " + saplingPlane.getSizeZ());
IrisObjectPlacement placement = getObjectPlacement(worldAccess, event.getLocation(), event.getSpecies(), new IrisTreeSize(1, 1));
int minHeight = event.getWorld().getMinHeight();
SaplingGrowth.Sapling sapling = new SaplingGrowth.Sapling(
relativePosition(event.getLocation(), minHeight),
relativePosition(saplingPlane.getCenter(), minHeight),
event.getSpecies().name());
Optional<SaplingGrowth.Growth> growth = ModuleServices.growSapling(engine, sapling, new WorldSurroundings(event.getWorld(), saplingPlane));
if (placement == null) {
if (growth.isEmpty()) {
IrisLogging.debug(this.getClass().getName() + " had options but did not manage to find objectPlacements for them");
return;
}
saplingPlane.forEach(block -> block.setType(Material.AIR));
IrisObject object = worldAccess.getData().getObjectLoader().load(placement.getPlace().getRandom(RNG.r));
String treeMarker = object.getLoadKey() + "@" + ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE);
String treeMarker = growth.get().object() + "@" + ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE);
List<BlockState> blockStateList = new KList<>();
KMap<Location, BlockData> dataCache = new KMap<>();
// TODO: REAL CLASSES!!!!
IObjectPlacer placer = new IObjectPlacer() {
@Override
public int getHighest(int x, int z, IrisData data) {
return event.getWorld().getHighestBlockYAt(x, z);
}
@Override
public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) {
return event.getWorld().getHighestBlockYAt(x, z, ignoreFluid ? HeightMap.OCEAN_FLOOR : HeightMap.WORLD_SURFACE);
}
@Override
public void set(int x, int y, int z, PlatformBlockState s) {
BlockData d = (BlockData) s.nativeHandle();
Block b = event.getWorld().getBlockAt(x, y, z);
// Listeners get the post-growth tree, per the StructureGrowEvent contract;
// a fresh snapshot here handed every plugin an all-air "tree".
BlockState state = b.getState();
if (d instanceof IrisCustomData data)
state.setBlockData(data.getBase());
else state.setBlockData(d);
blockStateList.add(state);
dataCache.put(new Location(event.getWorld(), x, y, z), d);
}
@Override
public PlatformBlockState get(int x, int y, int z) {
return BukkitBlockState.of(event.getWorld().getBlockAt(x, y, z).getBlockData());
}
@Override
public boolean isPreventingDecay() {
return true;
}
@Override
public boolean isCarved(int x, int y, int z) {
return false;
}
@Override
public boolean isSurfaceSolid(int x, int y, int z) {
return event.getWorld().getBlockAt(x, y, z).getType().isSolid();
}
@Override
public boolean isSolid(int x, int y, int z) {
return event.getWorld().getBlockAt(x, y, z).getBlockData().getMaterial().isSolid();
}
@Override
public boolean isUnderwater(int x, int z) {
return false;
}
@Override
public int getFluidHeight() {
return worldFluidHeight(engine);
}
@Override
public boolean isDebugSmartBore() {
return false;
}
@Override
public void setTile(int xx, int yy, int zz, TileData tile) {
}
@Override
public <T> void setData(int xx, int yy, int zz, T data) {
}
@Override
public <T> T getData(int xx, int yy, int zz, Class<T> t) {
return null;
}
@Override
public Engine getEngine() {
return engine;
}
};
object.place(
saplingPlane.getCenter().getBlockX(),
(saplingPlane.getCenter().getBlockY() + object.getH() / 2),
saplingPlane.getCenter().getBlockZ(),
placer,
placement,
RNG.r,
Objects.requireNonNull(worldAccess).getData()
);
for (PlacedBlock placed : growth.get().blocks()) {
Block b = event.getWorld().getBlockAt(placed.position().x(), placed.position().y() + minHeight, placed.position().z());
BlockData d = (BlockData) IrisPlatforms.get().registries().block(placed.state().key()).nativeHandle();
// Listeners get the post-growth tree, per the StructureGrowEvent contract;
// a fresh snapshot here handed every plugin an all-air "tree".
BlockState state = b.getState();
state.setBlockData(d);
blockStateList.add(state);
dataCache.put(b.getLocation(), d);
}
event.setCancelled(true);
@@ -266,10 +165,7 @@ public class TreeSVC implements IrisService {
if (d == null) continue;
Block block = l.getBlock();
if (d instanceof IrisCustomData data) {
block.setBlockData(data.getBase(), false);
IrisServices.get(ExternalDataSVC.class).processUpdate(engine, block, data.getCustom());
} else block.setBlockData(d, false);
block.setBlockData(d, false);
int mantleY = block.getY() - event.getWorld().getMinHeight();
// Lease-gated: the grow task can land after the engine started closing, and
// an unleased mantle write would race the region flush.
@@ -290,58 +186,36 @@ public class TreeSVC implements IrisService {
}
}
static int worldFluidHeight(Engine engine) {
return engine.getMinHeight() + engine.getDimension().getFluidHeight();
private static com.volmit.world.BlockPosition relativePosition(Location location, int minHeight) {
return new com.volmit.world.BlockPosition(location.getBlockX(), location.getBlockY() - minHeight, location.getBlockZ());
}
/**
* Finds a single object placement (which may contain more than one object) for the requirements species, location &
* size
*
* @param worldAccess The world to access (check for biome, region, dimension, etc)
* @param location The location of the growth event (For biome/region finding)
* @param type The bukkit TreeType to match
* @param size The size of the sapling area
* @return An object placement which contains the matched tree, or null if none were found / it's disabled.
*/
private IrisObjectPlacement getObjectPlacement(PlatformChunkGenerator worldAccess, Location location, TreeType type, IrisTreeSize size) {
/** The world around the saplings as the modules read it; the saplings that grow count as air, as they are about to. */
private static final class WorldSurroundings implements SaplingGrowth.Surroundings {
private static final com.volmit.block.BlockState AIR = com.volmit.block.BlockState.parse("minecraft:air");
KList<IrisObjectPlacement> placements = new KList<>();
boolean isUseAll = worldAccess.getEngine().getDimension().getTreeSettings().getMode().equals(IrisTreeModes.ALL);
private final World world;
private final Cuboid saplingPlane;
// Retrieve objectPlacements of type `species` from biome
IrisBiome biome = worldAccess.getEngine().getBiome(location.getBlockX(), location.getBlockY()-worldAccess.getTarget().getWorld().minHeight(), location.getBlockZ());
placements.addAll(matchObjectPlacements(biome.getObjects(), size, type));
// Add more or find any in the region
if (isUseAll || placements.isEmpty()) {
IrisRegion region = worldAccess.getEngine().getRegion(location.getBlockX(), location.getBlockZ());
placements.addAll(matchObjectPlacements(region.getObjects(), size, type));
private WorldSurroundings(World world, Cuboid saplingPlane) {
this.world = world;
this.saplingPlane = saplingPlane;
}
// Check if no matches were found, return a random one if they are
return placements.isNotEmpty() ? placements.getRandom() : null;
}
@Override
public int highest(int x, int z, boolean ignoreFluid) {
int worldY = ignoreFluid ? world.getHighestBlockYAt(x, z, HeightMap.OCEAN_FLOOR) : world.getHighestBlockYAt(x, z);
return worldY - world.getMinHeight();
}
/**
* Filters out mismatches and returns matches
*
* @param objects The object placements to check
* @param size The size of the sapling area to filter with
* @param type The type of the tree to filter with
* @return A list of objectPlacements that matched. May be empty.
*/
private KList<IrisObjectPlacement> matchObjectPlacements(KList<IrisObjectPlacement> objects, IrisTreeSize size, TreeType type) {
KList<IrisObjectPlacement> p = new KList<>();
for (IrisObjectPlacement i : objects) {
if (i.matches(size, type)) {
p.add(i);
@Override
public com.volmit.block.BlockState blockAt(int x, int y, int z) {
int worldY = y + world.getMinHeight();
if (saplingPlane.contains(x, worldY, z)) {
return AIR;
}
return com.volmit.block.BlockState.parse(PlatformBlockStates.namespaced(BukkitBlockState.of(world.getBlockAt(x, worldY, z).getBlockData()).key()));
}
return p;
}
/**
@@ -1,14 +1,10 @@
package art.arcane.iris.core.service.tree;
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
import art.arcane.iris.core.modules.ModuleServices;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.StructurePlacementMarker;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.procedural.IrisProceduralObjects;
import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import com.volmit.service.SaplingGrowth;
import java.util.HashSet;
import java.util.Set;
public final class TreeDefinitionIndex {
@@ -23,26 +19,8 @@ public final class TreeDefinitionIndex {
}
public static TreeDefinitionIndex build(Engine engine) {
Set<String> explicitObjectKeys = new HashSet<>();
Set<String> proceduralTreeKeys = new HashSet<>();
for (IrisRegion region : engine.getDimension().getAllRegions(engine)) {
if (region == null) {
continue;
}
collectPlacements(region.getObjects(), explicitObjectKeys);
collectProceduralTrees(region.getProceduralObjects(), proceduralTreeKeys);
}
for (IrisBiome biome : engine.getDimension().getReachableBiomes(engine)) {
if (biome == null) {
continue;
}
collectPlacements(biome.getObjects(), explicitObjectKeys);
collectProceduralTrees(biome.getProceduralObjects(), proceduralTreeKeys);
}
return new TreeDefinitionIndex(explicitObjectKeys, proceduralTreeKeys);
SaplingGrowth.TreeObjects trees = ModuleServices.treeObjects(engine);
return new TreeDefinitionIndex(trees.objects(), trees.procedural());
}
public boolean isTreeMarker(String marker) {
@@ -60,38 +38,4 @@ public final class TreeDefinitionIndex {
}
return objectKey.startsWith("trees/") || explicitObjectKeys.contains(objectKey);
}
private static void collectPlacements(Iterable<IrisObjectPlacement> placements, Set<String> objectKeys) {
if (placements == null) {
return;
}
for (IrisObjectPlacement placement : placements) {
if (placement == null
|| placement.getTrees() == null
|| placement.getTrees().isEmpty()
|| placement.getPlace() == null) {
continue;
}
for (String objectKey : placement.getPlace()) {
if (objectKey != null && !objectKey.isBlank()) {
objectKeys.add(objectKey);
}
}
}
}
private static void collectProceduralTrees(IrisProceduralObjects proceduralObjects, Set<String> objectKeys) {
if (proceduralObjects == null || proceduralObjects.getTrees() == null) {
return;
}
for (IrisProceduralTree tree : proceduralObjects.getTrees()) {
if (tree == null || tree.getName() == null || tree.getName().isBlank()) {
continue;
}
int variants = Math.max(1, tree.getVariants());
for (int index = 0; index < variants; index++) {
objectKeys.add(tree.getVariantLoadKey(index));
}
}
}
}
@@ -19,19 +19,22 @@
package art.arcane.iris.engine;
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;
}
}
@@ -18,13 +18,11 @@
package art.arcane.iris.engine;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.service.tree.BlockDropRouter;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.loot.IrisBlockDrops;
import art.arcane.iris.engine.object.marker.IrisMarker;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.platform.EngineBukkitOps;
import art.arcane.iris.core.modules.ModuleServices;
import art.arcane.iris.core.modules.PlatformBlockStates;
import art.arcane.iris.platform.bukkit.BukkitBlockState;
import art.arcane.iris.platform.bukkit.BukkitItemStacks;
import art.arcane.iris.platform.bukkit.BukkitWorldBinding;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.util.common.scheduling.J;
@@ -35,8 +33,12 @@ import org.bukkit.World;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.inventory.ItemStack;
import com.volmit.block.BlockState;
import com.volmit.service.BlockDrops;
import com.volmit.service.EntitySpawns;
import com.volmit.world.BlockPosition;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
/**
@@ -57,19 +59,10 @@ final class WorldBlockDropRouter {
int mantleY = toMantleY(e.getBlock().getY(), manager.getEngine().getWorld().minHeight());
int blockZ = e.getBlock().getZ();
KList<ItemStack> d = new KList<>();
IrisBiome b = EngineBukkitOps.getBiome(manager.getEngine(), e.getBlock().getLocation());
List<IrisBlockDrops> dropProviders = filterDrops(b.getBlockDrops(), e, manager.getData());
BlockDrops.Result result = ModuleServices.blockDrops(manager.getEngine(), brokenBlock(e));
KList<ItemStack> d = BukkitItemStacks.createAll(result.drops());
if (dropProviders.stream().noneMatch(IrisBlockDrops::isSkipParents)) {
IrisRegion r = EngineBukkitOps.getRegion(manager.getEngine(), e.getBlock().getLocation());
dropProviders.addAll(filterDrops(r.getBlockDrops(), e, manager.getData()));
dropProviders.addAll(filterDrops(manager.getEngine().getDimension().getBlockDrops(), e, manager.getData()));
}
dropProviders.forEach(provider -> provider.fillDrops(false, d));
if (dropProviders.stream().anyMatch(IrisBlockDrops::isReplaceVanillaDrops)) {
if (result.replacesVanillaDrops()) {
e.setDropItems(false);
}
@@ -87,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);
}
}));
@@ -128,7 +121,10 @@ final class WorldBlockDropRouter {
return mantleY + minHeight;
}
private List<IrisBlockDrops> filterDrops(KList<IrisBlockDrops> drops, BlockBreakEvent e, IrisData data) {
return new KList<>(drops.stream().filter(d -> d.shouldDropFor(e.getBlock().getBlockData(), data)).toList());
private BlockDrops.Broken brokenBlock(BlockBreakEvent e) {
int relativeY = toMantleY(e.getBlock().getY(), manager.getEngine().getWorld().minHeight());
BlockPosition position = new BlockPosition(e.getBlock().getX(), relativeY, e.getBlock().getZ());
BlockState block = BlockState.parse(PlatformBlockStates.namespaced(BukkitBlockState.of(e.getBlock().getBlockData()).key()));
return new BlockDrops.Broken(position, block);
}
}
@@ -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;
}
}
}
@@ -18,14 +18,15 @@
package art.arcane.iris.engine.framework;
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.core.modules.ModuleServices;
import art.arcane.iris.engine.IrisComplex;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.util.common.parallel.BurstExecutor;
import art.arcane.iris.util.common.parallel.MultiBurst;
import art.arcane.iris.util.project.context.IrisContext;
import com.volmit.service.ObjectsAt;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.collection.KMap;
import art.arcane.volmlib.util.collection.KSet;
@@ -33,6 +34,7 @@ import art.arcane.volmlib.util.math.Position2;
import art.arcane.volmlib.util.scheduling.PrecisionStopwatch;
import java.util.ArrayDeque;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
@@ -389,6 +391,7 @@ public final class HintedLocator<T> implements Locator<T> {
}
IrisComplex complex = engine.getComplex();
ObjectsAt.PlacedBy placers = ModuleServices.objectPlacers(engine, objectKey);
BiomeSource source = new BiomeSource(engine);
KSet<String> landHosts = new KSet<>();
KSet<String> seaHosts = new KSet<>();
@@ -401,28 +404,28 @@ public final class HintedLocator<T> implements Locator<T> {
continue;
}
if (placesObject(region.getSurfaceObjects(), objectKey)) {
if (placers.regions().contains(region.getLoadKey())) {
directRegions.add(region.getLoadKey());
}
boolean hosted = false;
for (String root : region.getLandBiomes()) {
if (source.closurePlacesObject(root, objectKey)) {
if (source.closureContainsAny(root, placers.biomes())) {
landHosts.add(root);
hosted = true;
}
}
for (String root : region.getSeaBiomes()) {
if (source.closurePlacesObject(root, objectKey)) {
if (source.closureContainsAny(root, placers.biomes())) {
seaHosts.add(root);
hosted = true;
}
}
for (String root : region.getShoreBiomes()) {
if (source.closurePlacesObject(root, objectKey)) {
if (source.closureContainsAny(root, placers.biomes())) {
shoreHosts.add(root);
hosted = true;
}
@@ -502,16 +505,6 @@ public final class HintedLocator<T> implements Locator<T> {
};
}
private static boolean placesObject(KList<IrisObjectPlacement> placements, String objectKey) {
for (IrisObjectPlacement placement : placements) {
if (placement != null && placement.getPlace().contains(objectKey)) {
return true;
}
}
return false;
}
private static final class BiomeSource {
private final Engine engine;
private final KMap<String, IrisBiome> cache = new KMap<>();
@@ -576,8 +569,8 @@ public final class HintedLocator<T> implements Locator<T> {
return false;
}
private boolean closurePlacesObject(String rootKey, String objectKey) {
if (rootKey == null || objectKey == null) {
private boolean closureContainsAny(String rootKey, Set<String> targetKeys) {
if (rootKey == null || targetKeys.isEmpty()) {
return false;
}
@@ -598,7 +591,7 @@ public final class HintedLocator<T> implements Locator<T> {
continue;
}
if (placesObject(biome.getSurfaceObjects(), objectKey)) {
if (targetKeys.contains(biome.getLoadKey())) {
return true;
}
@@ -18,18 +18,10 @@
package art.arcane.iris.engine.framework;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.loot.IrisLootMode;
import art.arcane.iris.engine.object.loot.IrisLootReference;
import art.arcane.iris.engine.object.loot.IrisLootTable;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.ToIntFunction;
public final class LootResolver {
@@ -52,17 +44,18 @@ public final class LootResolver {
return mix(seed ^ ((long) z * 0x8CB92BA72F3D8DD7L));
}
public static RNG tableRng(long lootSeed, IrisLootTable table, int x, int y, int z) {
return new RNG(tableSeed(lootSeed, table, x, y, z));
/** The random stream of one loot table at one position; {@code tableIdentity} names the table (its key, else its name). */
public static RNG tableRng(long lootSeed, String tableIdentity, int x, int y, int z) {
return new RNG(tableSeed(lootSeed, tableIdentity, x, y, z));
}
public static long tableSeed(long lootSeed, IrisLootTable table, int x, int y, int z) {
return mix(containerSeed(lootSeed, x, y, z) ^ stableHash(tableIdentity(table)) ^ TABLE_SALT);
public static long tableSeed(long lootSeed, String tableIdentity, int x, int y, int z) {
return mix(containerSeed(lootSeed, x, y, z) ^ stableHash(tableIdentity) ^ TABLE_SALT);
}
public static boolean spatialOneIn(
long lootSeed,
IrisLootTable table,
String tableIdentity,
int entryIndex,
int x,
int y,
@@ -72,7 +65,7 @@ public final class LootResolver {
if (rarity <= 1L) {
return true;
}
long roll = mix(tableSeed(lootSeed, table, x, y, z) ^ ((long) entryIndex * ENTRY_SALT));
long roll = mix(tableSeed(lootSeed, tableIdentity, x, y, z) ^ ((long) entryIndex * ENTRY_SALT));
return new RNG(roll).nextLong(rarity) == 0L;
}
@@ -119,63 +112,6 @@ public final class LootResolver {
return null;
}
public static <T> void resolveEnvironmentSources(
List<T> sources,
Engine engine,
RNG rng,
int x,
int relativeY,
int z,
boolean objectLootDefined,
Function<IrisLootTable, T> mapper
) {
IrisRegion region = engine.getComplex().getRegionStream().get(x, z);
IrisBiome surfaceBiome = engine.getComplex().getTrueBiomeStream().get(x, z);
double terrainHeight = engine.getComplex().getHeightStream().get(x, z);
IrisBiome contextualBiome = relativeY < terrainHeight
? engine.getCaveBiome(x, relativeY, z)
: surfaceBiome;
if (contextualBiome == null) {
contextualBiome = surfaceBiome;
}
boolean distinctContextualBiome = !sameBiome(surfaceBiome, contextualBiome);
double multiplier = engine.getDimension().getLoot().getMultiplier()
* region.getLoot().getMultiplier()
* surfaceBiome.getLoot().getMultiplier();
if (distinctContextualBiome) {
multiplier *= contextualBiome.getLoot().getMultiplier();
}
boolean fallback = !objectLootDefined;
injectReference(sources, engine.getDimension().getLoot(), engine, mapper, fallback);
injectReference(sources, region.getLoot(), engine, mapper, fallback);
injectReference(sources, surfaceBiome.getLoot(), engine, mapper, fallback);
if (distinctContextualBiome) {
injectReference(sources, contextualBiome.getLoot(), engine, mapper, fallback);
}
scaleSources(sources, multiplier, rng);
}
public static <T> void injectSources(
List<T> sources,
List<? extends T> additions,
IrisLootMode mode,
boolean fallback
) {
if (mode == IrisLootMode.FALLBACK && !fallback) {
return;
}
if (mode == IrisLootMode.CLEAR) {
sources.clear();
return;
}
if (mode == IrisLootMode.REPLACE) {
sources.clear();
}
sources.addAll(additions);
}
public static <T> void scaleSources(List<T> sources, double multiplier, RNG rng) {
if (!Double.isFinite(multiplier) || multiplier < 0D) {
throw new IllegalArgumentException("Effective loot source multiplier must be finite and non-negative, got "
@@ -206,49 +142,6 @@ public final class LootResolver {
expandSources(sources, original, order, target, rng);
}
static boolean sameBiome(IrisBiome first, IrisBiome second) {
if (first == second) {
return true;
}
if (first == null || second == null) {
return false;
}
return Objects.equals(first.getLoadKey(), second.getLoadKey());
}
static String tableIdentity(IrisLootTable table) {
if (table == null) {
return "";
}
String loadKey = table.getLoadKey();
if (loadKey != null && !loadKey.isBlank()) {
return loadKey;
}
String name = table.getName();
return name == null ? "" : name;
}
private static <T> void injectReference(
List<T> sources,
IrisLootReference reference,
Engine engine,
Function<IrisLootTable, T> mapper,
boolean fallback
) {
KList<IrisLootTable> tables = reference.getLootTables(engine.getComplex());
KList<T> additions = new KList<>();
for (IrisLootTable table : tables) {
if (table == null) {
continue;
}
T source = mapper.apply(table);
if (source != null) {
additions.add(source);
}
}
injectSources(sources, additions, reference.getMode(), fallback);
}
private static <T> void shrinkSources(List<T> sources, List<T> original, int[] order, int target, RNG rng) {
shuffleOrder(order, rng);
boolean[] selected = new boolean[original.size()];
@@ -5,20 +5,18 @@ import art.arcane.iris.platform.bukkit.BukkitBlockResolution;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.tools.IrisToolbelt;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.LootResolver;
import art.arcane.iris.core.events.IrisLootEvent;
import art.arcane.iris.engine.mantle.EngineMantle;
import art.arcane.iris.engine.platform.EngineBukkitOps;
import art.arcane.iris.engine.platform.PlatformChunkGenerator;
import art.arcane.iris.engine.object.placement.IObjectPlacer;
import art.arcane.iris.engine.object.loot.InventorySlotType;
import art.arcane.iris.engine.object.loot.IrisLootTable;
import art.arcane.iris.engine.object.prefab.TileData;
import art.arcane.iris.platform.bukkit.BukkitBlockState;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.util.common.scheduling.J;
import art.arcane.volmlib.util.collection.KList;
import com.volmit.service.Loot;
import art.arcane.iris.util.common.data.IrisCustomData;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.matter.MatterCavern;
@@ -85,16 +83,15 @@ public class WorldObjectPlacer implements IObjectPlacer {
int x = block.getX();
int y = block.getY();
int z = block.getZ();
RNG rng = LootResolver.containerRng(engine.getSeedManager().getLoot(), x, y, z);
KList<IrisLootTable> tables = EngineBukkitOps.getLootTables(engine, rng, block);
KList<Loot.Source> tables = EngineBukkitOps.getLootTables(engine, block);
try {
Bukkit.getPluginManager().callEvent(new IrisLootEvent(engine, block, InventorySlotType.STORAGE, tables));
Bukkit.getPluginManager().callEvent(new IrisLootEvent(engine, block, tables));
if (tables.isEmpty()) {
return;
}
InventoryHolder holder = (InventoryHolder) block.getState();
EngineBukkitOps.addItems(engine, false, holder.getInventory(), tables, InventorySlotType.STORAGE, world, x, y, z);
EngineBukkitOps.addItems(engine, false, holder.getInventory(), tables, world, x, y, z);
} catch (Throwable e) {
IrisLogging.reportError(e);
}
@@ -0,0 +1,447 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.platform;
import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.core.link.Identifier;
import art.arcane.iris.core.modules.ModuleServices;
import art.arcane.iris.core.service.EntityRiseSVC;
import art.arcane.iris.core.service.ExternalDataSVC;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.platform.bukkit.BukkitAttributes;
import art.arcane.iris.platform.bukkit.BukkitItemStacks;
import art.arcane.iris.platform.bukkit.BukkitPlatform;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.IrisServices;
import art.arcane.iris.util.common.data.registry.RegistryUtil;
import art.arcane.iris.util.common.format.C;
import art.arcane.iris.util.common.plugin.Chunks;
import art.arcane.iris.util.common.scheduling.ConsoleCommands;
import art.arcane.iris.util.common.scheduling.J;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.M;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.scheduling.PrecisionStopwatch;
import com.volmit.entity.EntitySpec;
import com.volmit.item.ItemAttribute;
import com.volmit.service.Loot;
import com.volmit.world.BlockPosition;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.NamespacedKey;
import org.bukkit.Particle;
import org.bukkit.Sound;
import org.bukkit.attribute.Attributable;
import org.bukkit.entity.Ageable;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Mob;
import org.bukkit.entity.Panda;
import org.bukkit.entity.Panda.Gene;
import org.bukkit.entity.Villager;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.loot.LootContext;
import org.bukkit.loot.LootTable;
import org.bukkit.loot.Lootable;
import org.bukkit.util.Vector;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static art.arcane.iris.util.common.data.registry.Particles.ITEM;
/**
* Creates the entities a module planned ({@link EntitySpec}) on a Bukkit server: the entity itself, then everything the
* spec sets on it. Every random choice was made by the module; this class only acts on the platform.
*/
public final class BukkitEntitySpawner {
private static final long RISE_START_DEPTH_BLOCKS = 5;
private static final int RISE_MAX_TICKS = 100;
private static final int RISE_NO_DAMAGE_TICKS = 100000;
private static final double RISE_STEP_BLOCKS = 0.1;
private static final double RISE_SOUND_CHANCE = 0.2;
private static final int SPAWN_WAIT_SLEEP_MS = 25;
private static final int SPAWN_WAIT_LIMIT_MS = 500;
private static final String LOOT_TABLE_NAMESPACE = "iris";
private BukkitEntitySpawner() {
}
/** Spawns the pack's entity {@code key} at {@code at}, as a command asks for; null when the pack has no such entity or the spawn fails. */
public static Entity spawnByKey(Engine gen, String key, Location at) {
return ModuleServices.entity(gen, key).map(spec -> spawn(gen, spec, at)).orElse(null);
}
public static Entity spawn(Engine gen, EntitySpec spec, Location at) {
if (!Chunks.isSafe(at)) {
return null;
}
if (spec.riseOutOfGround()) {
at = startBelowGroundWhenWatched(at);
}
Entity ee = doSpawn(spec, at);
if (ee == null && !Chunks.isSafe(at)) {
return null;
}
if (spec.isSpecial() && !spec.applySettingsToSpecial()) {
return ee;
}
if (ee == null) {
return null;
}
Entity e = ee;
applyFlags(e, spec);
addPassengers(gen, e, spec, at);
if (e instanceof Attributable attributable) {
for (ItemAttribute attribute : spec.attributes()) {
BukkitAttributes.apply(attribute, attributable);
}
}
if (e instanceof Lootable lootable && !spec.lootTables().isEmpty()) {
bindLoot(spec, gen, lootable, at);
}
if (e instanceof LivingEntity living) {
applyLivingState(gen, living, spec, at);
}
if (e instanceof Ageable ageable && spec.flags().baby()) {
ageable.setBaby();
}
if (e instanceof Panda panda) {
panda.setMainGene(resolveGene(spec.pandaMainGene()));
panda.setHiddenGene(resolveGene(spec.pandaHiddenGene()));
}
if (e instanceof Villager villager) {
villager.setRemoveWhenFarAway(false);
villager.setPersistent(true);
}
if (e instanceof Mob mob) {
mob.setAware(spec.flags().aware());
}
if (spec.spawnEffect() != null) {
showSpawnEffect(e, spec.spawnEffect());
}
runCommands(spec, at);
Location riseFrom = at;
J.runEntity(e, () -> {
if (spec.riseOutOfGround() && e instanceof LivingEntity living && Chunks.hasPlayersNearby(riseFrom)) {
riseOutOfGround(e, living, riseFrom);
}
});
return e;
}
/** Players watching an entity that rises out of the ground see it start five blocks below the spot. */
private static Location startBelowGroundWhenWatched(Location at) {
AtomicReference<Location> start = new AtomicReference<>(at);
try {
J.sfut(() -> {
if (Chunks.hasPlayersNearby(start.get())) {
Location b = start.get().clone();
start.set(new Location(b.getWorld(), b.getX(), b.getY() - RISE_START_DEPTH_BLOCKS, b.getZ()));
}
}).get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
IrisLogging.reportError("Iris entity spawn preparation was interrupted.", e);
} catch (ExecutionException e) {
IrisLogging.reportError("Iris entity spawn preparation failed.", e);
}
return start.get();
}
private static void applyFlags(Entity e, EntitySpec spec) {
EntitySpec.Flags flags = spec.flags();
e.setCustomName(spec.customName() != null ? C.translateAlternateColorCodes('&', spec.customName()) : null);
e.setCustomNameVisible(flags.customNameVisible());
e.setGlowing(flags.glowing());
e.setGravity(flags.gravity());
e.setInvulnerable(flags.invulnerable());
e.setSilent(flags.silent());
e.setPersistent(flags.keepEntity() || IrisSettings.get().getWorld().isForcePersistEntities());
}
private static void addPassengers(Engine gen, Entity e, EntitySpec spec, Location at) {
for (EntitySpec passengerSpec : spec.passengers()) {
Entity passenger = spawn(gen, passengerSpec, at);
if (passenger == null) {
continue;
}
if (Bukkit.isPrimaryThread()) {
e.addPassenger(passenger);
} else {
J.runEntity(e, () -> e.addPassenger(passenger));
}
}
}
private static void applyLivingState(Engine gen, LivingEntity l, EntitySpec spec, Location at) {
l.setAI(spec.flags().ai());
l.setCanPickupItems(spec.flags().pickupItems());
if (spec.leashHolder() != null) {
l.setLeashHolder(spawn(gen, spec.leashHolder(), at));
}
l.setRemoveWhenFarAway(spec.flags().removable());
EntitySpec.Equipment equipment = spec.equipment();
if (equipment.helmet() != null) {
l.getEquipment().setHelmet(BukkitItemStacks.create(equipment.helmet()));
}
if (equipment.chestplate() != null) {
l.getEquipment().setChestplate(BukkitItemStacks.create(equipment.chestplate()));
}
if (equipment.leggings() != null) {
l.getEquipment().setLeggings(BukkitItemStacks.create(equipment.leggings()));
}
if (equipment.boots() != null) {
l.getEquipment().setBoots(BukkitItemStacks.create(equipment.boots()));
}
if (equipment.mainHand() != null) {
l.getEquipment().setItemInMainHand(BukkitItemStacks.create(equipment.mainHand()));
}
if (equipment.offHand() != null) {
l.getEquipment().setItemInOffHand(BukkitItemStacks.create(equipment.offHand()));
}
}
private static void runCommands(EntitySpec spec, Location at) {
for (EntitySpec.Command command : spec.commands()) {
ConsoleCommands.run(command.commands(), command.delay(), command.repeat(), command.repeatDelay(),
at.getBlockX(), at.getBlockY(), at.getBlockZ());
}
}
private static void riseOutOfGround(Entity e, LivingEntity living, Location from) {
Location start = from.clone();
boolean originalInvulnerable = e.isInvulnerable();
boolean originalAi = living.hasAI();
boolean originalCollidable = living.isCollidable();
int originalNoDamageTicks = living.getNoDamageTicks();
EntityRiseSVC.stamp(e, originalInvulnerable, originalAi, originalCollidable);
e.setInvulnerable(true);
living.setAI(false);
living.setCollidable(false);
living.setNoDamageTicks(RISE_NO_DAMAGE_TICKS);
Runnable restore = () -> restoreRiseState(e, living, originalInvulnerable, originalAi,
originalCollidable, originalNoDamageTicks);
AtomicInteger t = new AtomicInteger(0);
Runnable[] loop = new Runnable[1];
loop[0] = () -> {
if (t.get() > RISE_MAX_TICKS || e.isDead()) {
restore.run();
return;
}
t.incrementAndGet();
if (e.getLocation().getBlock().getType().isSolid() || living.getEyeLocation().getBlock().getType().isSolid()) {
e.teleport(start.add(new Vector(0, RISE_STEP_BLOCKS, 0)));
ItemStack itemCrackData = new ItemStack(living.getEyeLocation().clone().subtract(0, 2, 0).getBlock().getBlockData().getMaterial());
e.getWorld().spawnParticle(ITEM, living.getEyeLocation(), 6, 0.2, 0.4, 0.2, 0.06f, itemCrackData);
if (M.r(RISE_SOUND_CHANCE)) {
e.getWorld().playSound(e.getLocation(), Sound.BLOCK_CHORUS_FLOWER_GROW, 0.8f, 0.1f);
}
if (!J.runEntity(e, loop[0], 1, restore)) {
restore.run();
}
} else {
restore.run();
}
};
if (!J.runEntity(e, loop[0], 0, restore)) {
restore.run();
}
}
private static void restoreRiseState(Entity entity, LivingEntity living, boolean invulnerable,
boolean ai, boolean collidable, int noDamageTicks) {
living.setNoDamageTicks(noDamageTicks);
living.setCollidable(collidable);
living.setAI(ai);
entity.setInvulnerable(invulnerable);
EntityRiseSVC.clearStamp(entity);
}
private static Entity doSpawn(EntitySpec spec, Location at) {
if (!Chunks.isSafe(at)) {
return null;
}
if (EntityType.UNKNOWN.equals(bukkitType(spec)) && !spec.isSpecial()) {
return null;
}
if (!Bukkit.isPrimaryThread()) {
// Someone called spawn (worldedit maybe?) on a non server thread
// Due to the structure of iris, we will call it sync and busy wait until it's done.
AtomicReference<Entity> ae = new AtomicReference<>();
try {
if (!J.runAt(at, () -> ae.set(doSpawn(spec, at)))) {
return null;
}
} catch (Throwable e) {
return null;
}
PrecisionStopwatch p = PrecisionStopwatch.start();
while (ae.get() == null) {
J.sleep(SPAWN_WAIT_SLEEP_MS);
if (p.getMilliseconds() > SPAWN_WAIT_LIMIT_MS) {
return null;
}
}
return ae.get();
}
if (spec.isSpecial()) {
return IrisServices.get(ExternalDataSVC.class).spawnMob(at, Identifier.fromString(spec.specialType()));
}
return BukkitPlatform.spawnEntity(at, bukkitType(spec), bukkitReason(spec));
}
/** The platform's entity type of the spec, unknown when it names none. */
public static EntityType bukkitType(EntitySpec spec) {
if (spec.type().isBlank()) {
return EntityType.UNKNOWN;
}
NamespacedKey key = NamespacedKey.fromString(spec.type().trim().toLowerCase(Locale.ROOT));
if (key == null) {
return EntityType.UNKNOWN;
}
EntityType entityType = RegistryUtil.lookup(EntityType.class).get(key);
return entityType == null ? EntityType.UNKNOWN : entityType;
}
private static CreatureSpawnEvent.SpawnReason bukkitReason(EntitySpec spec) {
if (spec.reason() == null || spec.reason().isBlank()) {
return CreatureSpawnEvent.SpawnReason.NATURAL;
}
try {
return CreatureSpawnEvent.SpawnReason.valueOf(spec.reason().trim().toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException e) {
return CreatureSpawnEvent.SpawnReason.NATURAL;
}
}
private static Gene resolveGene(String gene) {
if (gene == null || gene.isBlank()) {
return Gene.NORMAL;
}
try {
return Gene.valueOf(gene.trim().toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException e) {
return Gene.NORMAL;
}
}
private static void showSpawnEffect(Entity p, EntitySpec.SpawnEffect fx) {
J.runEntity(p, () -> {
Sound soundType = fx.sound() == null ? null : resolveKeyed(Sound.class, fx.sound());
Particle particleType = fx.particle() == null ? null : resolveKeyed(Particle.class, fx.particle());
if (soundType != null) {
Location part = p.getLocation().clone().add(RNG.r.i(-fx.soundDistance(), fx.soundDistance()), RNG.r.i(-fx.soundDistance(), fx.soundDistance()), RNG.r.i(-fx.soundDistance(), fx.soundDistance()));
p.getWorld().playSound(part, soundType, (float) fx.volume(), (float) RNG.r.d(fx.minPitch(), fx.maxPitch()));
}
if (particleType != null) {
Location part = p.getLocation().clone().add(0, 0.25, 0).add(new Vector(1, 1, 1).multiply(RNG.r.d())).subtract(new Vector(1, 1, 1).multiply(RNG.r.d()));
part.add(RNG.r.d(), 0, RNG.r.d());
double motionX = fx.randomAltX() ? RNG.r.d(-fx.altX(), fx.altX()) : fx.altX();
double motionY = fx.randomAltY() ? RNG.r.d(-fx.altY(), fx.altY()) : fx.altY();
double motionZ = fx.randomAltZ() ? RNG.r.d(-fx.altZ(), fx.altZ()) : fx.altZ();
if (fx.extra() != 0) {
p.getWorld().spawnParticle(particleType, part.getX(), part.getY() + RNG.r.i(fx.particleOffset()), part.getZ(),
fx.particleCount(), motionX, motionY, motionZ, fx.extra());
} else {
p.getWorld().spawnParticle(particleType, part.getX(), part.getY() + RNG.r.i(fx.particleOffset()), part.getZ(),
fx.particleCount(), motionX, motionY, motionZ);
}
}
});
}
private static <T> T resolveKeyed(Class<T> type, String key) {
NamespacedKey namespacedKey = NamespacedKey.fromString(key);
return namespacedKey == null ? null : RegistryUtil.lookup(type).get(namespacedKey);
}
private static void bindLoot(EntitySpec spec, Engine gen, Lootable lootable, Location finalAt) {
lootable.setLootTable(new LootTable() {
@Override
public NamespacedKey getKey() {
return new NamespacedKey(LOOT_TABLE_NAMESPACE, "loot-" + spec.hashCode());
}
@Override
public Collection<ItemStack> populateLoot(Random random, LootContext context) {
BlockPosition position = new BlockPosition(finalAt.getBlockX(), finalAt.getBlockY() - gen.getMinHeight(), finalAt.getBlockZ());
Loot.Site site = new Loot.Site(position, null, false, gen.isStudio());
KList<ItemStack> items = new KList<>();
for (String table : spec.lootTables()) {
items.addAll(BukkitItemStacks.createAll(ModuleServices.lootItems(gen, site, table)));
}
return items;
}
@Override
public void fillInventory(Inventory inventory, Random random, LootContext context) {
for (ItemStack i : populateLoot(random, context)) {
inventory.addItem(i);
}
EngineBukkitOps.scramble(gen, inventory, new RNG(spec.lootShuffleSeed()));
}
});
}
}
@@ -0,0 +1,60 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.platform;
import com.volmit.service.EntitySpawns;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.data.Waterlogged;
/** Whether a block is the kind of ground or fluid an entity spawns on. */
public final class BukkitSurfaces {
private BukkitSurfaces() {
}
/** Whether {@code block} suits an entity that wants {@code surface} below it. */
public static boolean matches(EntitySpawns.Surface surface, Block block) {
Material type = block.getType();
if (type.isSolid()) {
return surface == EntitySpawns.Surface.LAND || surface == EntitySpawns.Surface.OVERWORLD
|| (surface == EntitySpawns.Surface.ANIMAL && isAnimalGround(type));
}
if (type == Material.LAVA) {
return surface == EntitySpawns.Surface.LAVA;
}
if (isWater(type, block)) {
return surface == EntitySpawns.Surface.WATER || surface == EntitySpawns.Surface.OVERWORLD;
}
return false;
}
private static boolean isAnimalGround(Material type) {
return type == Material.GRASS_BLOCK || type == Material.DIRT
|| type == Material.DIRT_PATH || type == Material.COARSE_DIRT
|| type == Material.ROOTED_DIRT || type == Material.PODZOL
|| type == Material.MYCELIUM || type == Material.SNOW_BLOCK;
}
private static boolean isWater(Material type, Block block) {
return type == Material.WATER || type == Material.SEAGRASS
|| type == Material.TALL_SEAGRASS || type == Material.KELP_PLANT
|| type == Material.KELP
|| (block.getBlockData() instanceof Waterlogged waterlogged && waterlogged.isWaterlogged());
}
}
@@ -25,12 +25,12 @@ import art.arcane.iris.core.service.ExternalDataSVC;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.GenerationSessionLease;
import art.arcane.iris.engine.framework.Locator;
import art.arcane.iris.core.modules.ModuleServices;
import art.arcane.iris.core.modules.PlatformBlockStates;
import art.arcane.iris.engine.framework.LootResolver;
import art.arcane.iris.engine.framework.PlacedObject;
import art.arcane.iris.platform.bukkit.BukkitItemStacks;
import art.arcane.iris.engine.framework.WrongEngineBroException;
import art.arcane.iris.engine.object.loot.InventorySlotType;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.loot.IrisLootTable;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.prefab.TileData;
import art.arcane.iris.platform.bukkit.BukkitBlockResolution;
@@ -63,6 +63,10 @@ import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.loot.LootContext;
import org.bukkit.loot.LootTable;
import com.volmit.service.Loot;
import com.volmit.world.BlockPosition;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
@@ -76,6 +80,7 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.loot.Lootable;
import java.lang.reflect.Method;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
@@ -162,14 +167,14 @@ public final class EngineBukkitOps {
if (grid[x][z] == Integer.MIN_VALUE) {
continue;
}
update(engine, x, grid[x][z], z, c, chunk);
update(engine, x, grid[x][z], z, c);
}
}
chunk.iterate(MatterUpdate.class, (x, yf, z, v) -> {
int y = yf + engine.getWorld().minHeight();
if (v != null && v.isUpdate()) {
update(engine, x, y, z, c, chunk);
update(engine, x, y, z, c);
}
});
chunk.deleteSlices(MatterUpdate.class);
@@ -274,7 +279,7 @@ public final class EngineBukkitOps {
}
}
public static void update(Engine engine, int x, int y, int z, Chunk c, MantleChunk<Matter> mc) {
public static void update(Engine engine, int x, int y, int z, Chunk c) {
World world = c.getWorld();
if (y < world.getMinHeight() || y >= world.getMaxHeight()) {
return;
@@ -283,30 +288,8 @@ public final class EngineBukkitOps {
BlockData data = block.getBlockData();
engine.blockUpdatedMetric();
if (BukkitBlockResolution.isStorage(data)) {
InventorySlotType slot = null;
if (BukkitBlockResolution.isStorageChest(data)) {
slot = InventorySlotType.STORAGE;
}
if (slot != null) {
if (!isCanonicalContainer(block)) {
return;
}
int worldX = block.getX();
int worldZ = block.getZ();
RNG rx = LootResolver.containerRng(engine.getSeedManager().getLoot(), worldX, y, worldZ);
KList<IrisLootTable> tables = getLootTables(engine, rx, block, mc, hasNativeLootTable(block));
try {
Bukkit.getPluginManager().callEvent(new IrisLootEvent(engine, block, slot, tables));
if (tables.isEmpty()) return;
InventoryHolder m = (InventoryHolder) block.getState();
addItems(engine, false, m.getInventory(), tables, slot, c.getWorld(), worldX, y, worldZ);
} catch (Throwable e) {
IrisLogging.reportError(e);
}
fillStorageChest(engine, block, y, c);
}
} else {
block.setType(Material.AIR, false);
@@ -314,6 +297,23 @@ public final class EngineBukkitOps {
}
}
private static void fillStorageChest(Engine engine, Block block, int y, Chunk c) {
if (!isCanonicalContainer(block)) {
return;
}
KList<Loot.Source> tables = new KList<>(getLootTables(engine, block, hasNativeLootTable(block)));
try {
Bukkit.getPluginManager().callEvent(new IrisLootEvent(engine, block, tables));
if (tables.isEmpty()) return;
InventoryHolder m = (InventoryHolder) block.getState();
addItems(engine, false, m.getInventory(), tables, c.getWorld(), block.getX(), y, block.getZ());
} catch (Throwable e) {
IrisLogging.reportError(e);
}
}
public static boolean isCanonicalContainer(Block block) {
if (!(block.getBlockData() instanceof Chest chest) || chest.getType() == Chest.Type.SINGLE) {
return true;
@@ -407,66 +407,32 @@ public final class EngineBukkitOps {
inventory.setContents(nitems);
}
public static KList<IrisLootTable> getLootTables(Engine engine, RNG rng, Block b) {
MantleChunk<Matter> mc = engine.getMantle().getMantle().getChunk(b.getChunk()).use();
try {
return getLootTables(engine, rng, b, mc, hasNativeLootTable(b));
} finally {
mc.release();
}
/** The loot tables the modules say the container at {@code b} draws from, in the order their items are added. */
public static KList<Loot.Source> getLootTables(Engine engine, Block b) {
return new KList<>(getLootTables(engine, b, hasNativeLootTable(b)));
}
public static KList<IrisLootTable> getLootTables(Engine engine, RNG rng, Block b, MantleChunk<Matter> mc) {
return getLootTables(engine, rng, b, mc, hasNativeLootTable(b));
private static List<Loot.Source> getLootTables(Engine engine, Block b, boolean nativeLootDefined) {
return ModuleServices.lootTables(engine, lootSite(engine, b, nativeLootDefined));
}
public static KList<IrisLootTable> getLootTables(Engine engine, RNG rng, Block b, MantleChunk<Matter> mc, boolean nativeLootDefined) {
int rx = b.getX();
int rz = b.getZ();
int ry = b.getY() - engine.getWorld().minHeight();
KList<IrisLootTable> tables = new KList<>();
boolean objectLootDefined = nativeLootDefined;
PlacedObject po = engine.getObjectPlacement(rx, ry, rz, mc);
if (po != null && po.getPlacement() != null) {
if (BukkitBlockResolution.isStorageChest(b.getBlockData())) {
objectLootDefined = objectLootDefined
|| po.getPlacement().getLoot().isNotEmpty()
|| po.getPlacement().getVanillaLoot().isNotEmpty();
IrisLootTable table = po.getPlacement().getTable(
BukkitBlockState.of(b.getBlockData()), engine.getData(), rng);
if (table != null) {
tables.add(table);
if (po.getPlacement().isOverrideGlobalLoot()) {
return new KList<>(table);
}
}
}
}
LootResolver.resolveEnvironmentSources(
tables,
engine,
rng,
rx,
ry,
rz,
objectLootDefined,
table -> table
);
return tables;
private static Loot.Site lootSite(Engine engine, Block b, boolean nativeLootDefined) {
BlockPosition position = new BlockPosition(b.getX(), b.getY() - engine.getMinHeight(), b.getZ());
BlockData data = b.getBlockData();
com.volmit.block.BlockState container = BukkitBlockResolution.isStorageChest(data)
? com.volmit.block.BlockState.parse(PlatformBlockStates.namespaced(BukkitBlockState.of(data).key()))
: null;
return new Loot.Site(position, container, nativeLootDefined, false);
}
public static void addItems(Engine engine, boolean debug, Inventory inv, KList<IrisLootTable> tables, InventorySlotType slot, World world, int x, int y, int z) {
KList<ItemStack> items = new KList<>();
/** Adds the loot a container at {@code at} would hold to {@code inv}; {@code debug} makes the items say where they came from. */
public static void addLootOf(Engine engine, boolean debug, Inventory inv, Location at) {
addItems(engine, debug, inv, getLootTables(engine, at.getBlock()), at.getWorld(), at.getBlockX(), at.getBlockY(), at.getBlockZ());
}
for (IrisLootTable i : tables) {
if (i == null)
continue;
items.addAll(i.getLoot(debug, engine.getSeedManager().getLoot(), slot, world, x, y, z));
}
if (IrisLootEvent.callLootEvent(items, inv, world, x, y, z))
public static void addItems(Engine engine, boolean debug, Inventory inv, List<Loot.Source> tables, World world, int x, int y, int z) {
List<ItemStack> items = lootItems(engine, debug, tables, world, x, y, z);
if (IrisLootEvent.callLootEvent(new KList<>(items), inv, world, x, y, z))
return;
if (PaperLib.isPaper() && engine.getWorld().hasPlatformWorld()) {
@@ -504,6 +470,29 @@ public final class EngineBukkitOps {
}
}
/** The items of {@code tables} at the spot, in the tables' order: the modules' for pack tables, the platform's own for platform tables. */
private static List<ItemStack> lootItems(Engine engine, boolean debug, List<Loot.Source> tables, World world, int x, int y, int z) {
Loot.Site site = new Loot.Site(new BlockPosition(x, y - engine.getMinHeight(), z), null, false, debug);
List<ItemStack> items = new KList<>();
for (Loot.Source source : tables) {
switch (source) {
case Loot.Table table -> items.addAll(BukkitItemStacks.createAll(ModuleServices.lootItems(engine, site, table.key())));
case Loot.PlatformTable table -> items.addAll(platformLoot(table, world, x, y, z));
}
}
return items;
}
private static List<ItemStack> platformLoot(Loot.PlatformTable table, World world, int x, int y, int z) {
NamespacedKey key = NamespacedKey.fromString(table.key());
LootTable platformTable = key == null ? null : Bukkit.getLootTable(key);
if (platformTable == null) {
IrisLogging.warn("Unknown vanilla loot table " + table.key());
return List.of();
}
return new KList<>(platformTable.populateLoot(new RNG(table.seed()), new LootContext.Builder(new Location(world, x, y, z)).build()));
}
static boolean dispatchLootMutation(
LootMutationTask task,
boolean folia,
@@ -0,0 +1,113 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.platform.bukkit;
import art.arcane.iris.spi.IrisLogging;
import com.volmit.item.ItemAttribute;
import org.bukkit.NamespacedKey;
import org.bukkit.Registry;
import org.bukkit.attribute.Attributable;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeInstance;
import org.bukkit.attribute.AttributeModifier;
import org.bukkit.inventory.EquipmentSlotGroup;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.Locale;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/** Applies the attribute modifiers a module decided on to Bukkit items and entities. */
public final class BukkitAttributes {
private static final Set<String> WARNED_ATTRIBUTES = ConcurrentHashMap.newKeySet();
private static final String GENERIC_UNDERSCORE = "generic_";
private static final String GENERIC_DOT = "generic.";
private static final int MAX_NAME_LENGTH = 32;
private static final String DEFAULT_NAME = "modifier";
private BukkitAttributes() {
}
public static void apply(ItemAttribute modifier, ItemMeta meta) {
Attribute attribute = resolveAttribute(modifier);
if (attribute != null) {
meta.addAttributeModifier(attribute, create(modifier));
}
}
public static void apply(ItemAttribute modifier, Attributable target) {
Attribute attribute = resolveAttribute(modifier);
if (attribute == null) {
return;
}
AttributeInstance instance = target.getAttribute(attribute);
if (instance != null) {
instance.addModifier(create(modifier));
}
}
private static Attribute resolveAttribute(ItemAttribute modifier) {
String value = modifier.attribute().trim().toLowerCase(Locale.ROOT);
Attribute resolved;
if (value.contains(":")) {
NamespacedKey key = NamespacedKey.fromString(value);
resolved = key == null ? null : Registry.ATTRIBUTE.get(key);
} else {
resolved = Registry.ATTRIBUTE.get(NamespacedKey.minecraft(value));
if (resolved == null && value.startsWith(GENERIC_UNDERSCORE)) {
resolved = Registry.ATTRIBUTE.get(NamespacedKey.minecraft(value.substring(GENERIC_UNDERSCORE.length())));
}
if (resolved == null && value.startsWith(GENERIC_DOT)) {
resolved = Registry.ATTRIBUTE.get(NamespacedKey.minecraft(value.substring(GENERIC_DOT.length())));
}
}
if (resolved == null && WARNED_ATTRIBUTES.add(value)) {
IrisLogging.warn("Unknown attribute '" + modifier.attribute() + "' in attribute-modifier '" + modifier.name() + "'");
}
return resolved;
}
private static AttributeModifier create(ItemAttribute modifier) {
NamespacedKey key = NamespacedKey.minecraft(uniqueKey(modifier.name()));
return new AttributeModifier(key, modifier.amount(), resolveOperation(modifier.operation()), EquipmentSlotGroup.ANY);
}
private static AttributeModifier.Operation resolveOperation(String operation) {
if (operation.isBlank()) {
return AttributeModifier.Operation.ADD_NUMBER;
}
try {
return AttributeModifier.Operation.valueOf(operation.trim().toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException e) {
return AttributeModifier.Operation.ADD_NUMBER;
}
}
private static String uniqueKey(String name) {
String normalized = name.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9/._-]", "_");
if (normalized.isBlank()) {
normalized = DEFAULT_NAME;
}
if (normalized.length() > MAX_NAME_LENGTH) {
normalized = normalized.substring(0, MAX_NAME_LENGTH);
}
return normalized + "_" + UUID.randomUUID().toString().replace("-", "");
}
}
@@ -59,4 +59,9 @@ public final class BukkitItem implements PlatformItem {
public Object nativeHandle() {
return material;
}
@Override
public int maxDurability() {
return material.getMaxDurability();
}
}
@@ -0,0 +1,228 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.platform.bukkit;
import art.arcane.iris.core.link.Identifier;
import art.arcane.iris.core.modules.IrisItemRegistry;
import art.arcane.iris.core.service.ExternalDataSVC;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.IrisServices;
import art.arcane.iris.util.common.format.C;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.collection.KMap;
import art.arcane.volmlib.util.format.Form;
import com.volmit.item.ItemAttribute;
import com.volmit.item.ItemDrop;
import com.volmit.item.ItemEnchantment;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.Registry;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.inventory.meta.components.CustomModelDataComponent;
import org.bukkit.material.Colorable;
import java.awt.Color;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
/** Creates the Bukkit item stacks that module {@link ItemDrop}s describe. */
public final class BukkitItemStacks {
private static final int LORE_WRAP_WIDTH = 24;
private static final String LORE_RULE = C.GRAY + "--------------------";
private static final int CHANCE_DIGITS = 5;
private BukkitItemStacks() {
}
/** The stack {@code drop} describes; an air stack when the item cannot be made. */
public static ItemStack create(ItemDrop drop) {
try {
ItemStack stack = baseStack(drop);
if (stack == null || stack.getType() == Material.AIR) {
return new ItemStack(Material.AIR);
}
stack.setItemMeta(applyProperties(stack, drop));
return BukkitPlatform.applyCustomNbt(stack, drop.customNbt().isEmpty() ? null : new KMap<>(drop.customNbt()));
} catch (Throwable e) {
IrisLogging.reportError(e);
return new ItemStack(Material.AIR);
}
}
/** The non-air stacks of {@code drops}, in order. */
public static KList<ItemStack> createAll(List<ItemDrop> drops) {
KList<ItemStack> stacks = new KList<>();
for (ItemDrop drop : drops) {
ItemStack stack = create(drop);
if (stack.getType() != Material.AIR) {
stacks.add(stack);
}
}
return stacks;
}
private static ItemStack baseStack(ItemDrop drop) {
if (IrisItemRegistry.isCustomItem(drop.item())) {
Optional<ItemStack> custom = IrisServices.get(ExternalDataSVC.class)
.getItemStack(Identifier.fromString(drop.item()), drop.customNbt().isEmpty() ? null : new KMap<>(drop.customNbt()));
if (custom.isEmpty()) {
IrisLogging.warn("Unknown Material: " + drop.item());
return null;
}
ItemStack stack = custom.get();
stack.setAmount(drop.amount());
return stack;
}
return new ItemStack(BukkitBlockResolution.getMaterial(drop.item()), drop.amount());
}
private static ItemMeta applyProperties(ItemStack stack, ItemDrop drop) {
ItemMeta meta = stack.getItemMeta();
if (meta == null) {
return null;
}
drop.enchantments().forEach(enchantment -> enchant(meta, enchantment));
for (ItemAttribute attribute : drop.attributes()) {
BukkitAttributes.apply(attribute, meta);
}
meta.setUnbreakable(drop.unbreakable());
flags(drop).forEach(meta::addItemFlags);
if (drop.customModel() != null) {
CustomModelDataComponent customModelData = meta.getCustomModelDataComponent();
customModelData.setFloats(List.of(drop.customModel().floatValue()));
meta.setCustomModelDataComponent(customModelData);
}
int maxDurability = stack.getType().getMaxDurability();
if (drop.damage() != null && maxDurability > 0 && meta instanceof Damageable damageable) {
damageable.setDamage((int) Math.round(Math.max(0, Math.min(maxDurability, drop.damage() * maxDurability))));
}
if (drop.leatherColor() != null && meta instanceof LeatherArmorMeta leather) {
Color c = Color.decode(drop.leatherColor());
leather.setColor(org.bukkit.Color.fromRGB(c.getRed(), c.getGreen(), c.getBlue()));
}
DyeColor dye = dyeColor(drop);
if (dye != null && meta instanceof Colorable colorable) {
colorable.setColor(dye);
}
if (drop.displayName() != null) {
meta.setDisplayName(C.translateAlternateColorCodes('&', drop.displayName()));
}
meta.setLore(lore(drop));
return meta;
}
private static void enchant(ItemMeta meta, ItemEnchantment enchantment) {
try {
Enchantment resolved = resolveEnchantment(enchantment.key());
if (resolved == null) {
IrisLogging.warn("Unknown Enchantment: " + enchantment.key());
return;
}
if (meta instanceof EnchantmentStorageMeta storage) {
storage.addStoredEnchant(resolved, enchantment.level(), true);
return;
}
meta.addEnchant(resolved, enchantment.level(), true);
} catch (Throwable e) {
IrisLogging.reportError(e);
}
}
/** A bare path ({@code sharpness}) or a full namespaced key ({@code mymod:vorpal}), as the modded resolver accepts. */
private static Enchantment resolveEnchantment(String raw) {
if (raw.isBlank()) {
return null;
}
String value = raw.trim().toLowerCase(Locale.ROOT).replace(' ', '_');
NamespacedKey key = value.indexOf(':') >= 0 ? NamespacedKey.fromString(value) : NamespacedKey.minecraft(value);
return key == null ? null : Registry.ENCHANTMENT.get(key);
}
private static List<ItemFlag> flags(ItemDrop drop) {
KList<ItemFlag> resolved = new KList<>();
for (String flag : drop.flags()) {
if (flag == null) {
continue;
}
try {
resolved.add(ItemFlag.valueOf(flag));
} catch (IllegalArgumentException ignored) {
}
}
return resolved;
}
private static DyeColor dyeColor(ItemDrop drop) {
if (drop.dyeColor() == null) {
return null;
}
try {
return DyeColor.valueOf(drop.dyeColor());
} catch (IllegalArgumentException e) {
return null;
}
}
private static KList<String> lore(ItemDrop drop) {
KList<String> lore = new KList<>();
for (String line : drop.lore()) {
String colored = C.translateAlternateColorCodes('&', line);
if (colored.length() > LORE_WRAP_WIDTH) {
for (String wrapped : Form.wrapWords(colored, LORE_WRAP_WIDTH).split("\\Q\n\\E")) {
lore.add(wrapped.trim());
}
} else {
lore.add(colored);
}
}
if (drop.source() != null) {
addSourceLore(lore, drop.source());
}
return lore;
}
private static void addSourceLore(KList<String> lore, ItemDrop.Source source) {
if (lore.isNotEmpty()) {
lore.add(LORE_RULE);
}
if (source.table() == null) {
lore.add(C.GRAY + "1 in " + source.entryRarity() + " Chance (" + Form.pc(1D / source.entryRarity(), CHANCE_DIGITS) + ")");
return;
}
long combined = (long) source.tableRarity() * source.entryRarity();
lore.add(C.GRAY + "From: " + source.table() + " (" + Form.pc(1D / source.tableRarity(), CHANCE_DIGITS) + ")");
lore.add(C.GRAY + "1 in " + combined + " Chance (" + Form.pc(1D / combined, CHANCE_DIGITS) + ")");
}
}
@@ -1,14 +1,12 @@
package art.arcane.iris.util.common.data.registry;
import art.arcane.iris.engine.object.entity.IrisEntity;
import org.bukkit.Particle;
import static art.arcane.iris.util.common.data.registry.RegistryUtil.find;
/**
* Bukkit particle constants. Statically imported by {@code IrisEntity} (a Gson-registered pack
* type), so this class is reachable from core on the modded loaders. The resolution below is
* therefore guarded against the absent Bukkit class: without the guard the class initializer dies
* Bukkit particle constants, used by the Bukkit entity spawner. Core code can reach this class on the modded
* loaders, so the resolution below is guarded against the absent Bukkit class: without the guard the class initializer dies
* with a NoClassDefFoundError and the class stays permanently erroneous for the rest of the JVM's
* life. On Bukkit a genuinely missing registry key still throws, exactly as before.
*/
@@ -18,7 +18,10 @@
package art.arcane.iris.util.common.director.handlers;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.object.entity.IrisEntity;
import art.arcane.iris.engine.spawn.SpawnResources;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.iris.util.common.director.specialhandlers.RegistrantHandler;
public class EntityHandler extends RegistrantHandler<IrisEntity> {
@@ -27,6 +30,18 @@ public class EntityHandler extends RegistrantHandler<IrisEntity> {
super(IrisEntity.class, false);
}
@Override
protected KList<IrisEntity> loadAll(IrisData data) {
KList<IrisEntity> entities = new KList<>();
for (String key : SpawnResources.entityKeys(data)) {
IrisEntity entity = SpawnResources.entity(data, key);
if (entity != null) {
entities.add(entity);
}
}
return entities;
}
@Override
public String getRandomDefault() {
return "entity";
@@ -29,7 +29,7 @@ public abstract class RegistrantHandler<T extends IrisRegistrant> implements Dir
Set<String> known = new HashSet<>();
IrisData data = data();
if (data != null) {
for (T j : data.getLoader(type).loadAll(data.getLoader(type).getPossibleKeys())) {
for (T j : loadAll(data)) {
known.add(j.getLoadKey());
p.add(j);
}
@@ -38,7 +38,7 @@ public abstract class RegistrantHandler<T extends IrisRegistrant> implements Dir
for (File i : PackDirectoryResolver.listVisiblePackDirectories(
IrisPlatforms.get().packsFolder())) {
data = IrisData.get(i);
for (T j : data.getLoader(type).loadAll(data.getLoader(type).getPossibleKeys())) {
for (T j : loadAll(data)) {
if (known.add(j.getLoadKey()))
p.add(j);
}
@@ -47,6 +47,11 @@ public abstract class RegistrantHandler<T extends IrisRegistrant> implements Dir
return p;
}
/** Every resource of this handler's type that {@code data}'s pack has. */
protected KList<T> loadAll(IrisData data) {
return data.getLoader(type).loadAll(data.getLoader(type).getPossibleKeys());
}
@Override
public String toString(T t) {
return t != null ? t.getLoadKey() : "null";
@@ -0,0 +1,51 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.util.common.scheduling;
import art.arcane.iris.spi.IrisPlatforms;
import java.util.List;
/** Runs console commands for the pack: once or for ever, after a delay, with {@code {x}}, {@code {y}} and {@code {z}} filled in. */
public final class ConsoleCommands {
private ConsoleCommands() {
}
/**
* @param commands the commands, with an optional leading slash
* @param delay server ticks before the commands run
* @param repeat whether to run them again every {@code repeatDelay} ticks until the server stops
* @param repeatDelay server ticks between repeats
*/
public static void run(List<String> commands, long delay, boolean repeat, long repeatDelay, int x, int y, int z) {
for (String command : commands) {
String filled = (command.startsWith("/") ? command.replaceFirst("/", "") : command)
.replaceAll("\\Q{x}\\E", String.valueOf(x))
.replaceAll("\\Q{y}\\E", String.valueOf(y))
.replaceAll("\\Q{z}\\E", String.valueOf(z));
int safeDelay = (int) Math.max(0, Math.min(Integer.MAX_VALUE, delay));
if (repeat) {
int safeRepeatDelay = (int) Math.max(1, Math.min(Integer.MAX_VALUE, repeatDelay));
J.s(() -> J.sr(() -> IrisPlatforms.get().dispatchConsoleCommand(filled), safeRepeatDelay), safeDelay);
} else {
J.s(() -> IrisPlatforms.get().dispatchConsoleCommand(filled), safeDelay);
}
}
}
}
@@ -20,7 +20,6 @@ package art.arcane.iris.util.project.matter.slices;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.loader.IrisRegistrant;
import art.arcane.iris.core.loader.ResourceLoader;
import art.arcane.iris.util.project.matter.IrisMatterContext;
import art.arcane.volmlib.util.data.palette.Palette;
import art.arcane.volmlib.util.matter.slices.RawMatter;
@@ -29,7 +28,7 @@ import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class RegistryMatter<T extends IrisRegistrant> extends RawMatter<T> {
public abstract class RegistryMatter<T extends IrisRegistrant> extends RawMatter<T> {
public RegistryMatter(int width, int height, int depth, Class<T> c, T e) {
super(width, height, depth, c);
}
@@ -46,12 +45,9 @@ public class RegistryMatter<T extends IrisRegistrant> extends RawMatter<T> {
@Override
public T readNode(DataInputStream din) throws IOException {
String key = din.readUTF();
IrisData data = IrisMatterContext.require();
ResourceLoader<? extends IrisRegistrant> loader = data.getLoaders().get(getType());
if (loader == null) {
throw new IOException("No Iris registry loader is available for matter type " + getType().getName() + " while reading key " + key + ".");
}
return (T) loader.load(key);
return load(IrisMatterContext.require(), din.readUTF());
}
/** The resource of the pack {@code data} named by {@code key}, or null when the pack has none. */
protected abstract T load(IrisData data, String key);
}
@@ -18,7 +18,9 @@
package art.arcane.iris.util.project.matter.slices;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.engine.object.entity.spawn.IrisSpawner;
import art.arcane.iris.engine.spawn.SpawnResources;
import art.arcane.volmlib.util.matter.Sliced;
@Sliced
@@ -30,4 +32,9 @@ public class SpawnerMatter extends RegistryMatter<IrisSpawner> {
public SpawnerMatter(int width, int height, int depth) {
super(width, height, depth, IrisSpawner.class, new IrisSpawner());
}
@Override
protected IrisSpawner load(IrisData data, String key) {
return SpawnResources.spawner(data, key);
}
}