mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-27 16:25:36 +00:00
Merge branch 'wave2/d'
This commit is contained in:
commit
877564f545
35 files changed
+1888
-1143
No files matched your search
+9
-11
@@ -1,6 +1,7 @@
|
||||
package art.arcane.iris.engine.framework.structure;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.modules.IrisPackResources;
|
||||
import art.arcane.iris.engine.framework.StructureAssembler;
|
||||
import art.arcane.iris.engine.object.value.IrisPosition;
|
||||
import art.arcane.iris.engine.object.structure.IrisStructure;
|
||||
@@ -14,10 +15,14 @@ import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
/**
|
||||
* Compiled structure graphs, kept per resource snapshot of the pack: every reload of the pack's resources starts a new
|
||||
* snapshot ({@link IrisData#getPackResources()}), so nothing stale is ever read and nothing is invalidated by hand.
|
||||
*/
|
||||
public final class StructureGraphCatalog {
|
||||
private static final Cache<IrisData, ConcurrentMap<String, StructureGraphCompilation>> CACHE =
|
||||
private static final Cache<IrisPackResources, ConcurrentMap<String, StructureGraphCompilation>> CACHE =
|
||||
Caffeine.newBuilder().weakKeys().build();
|
||||
private static final Cache<IrisData, ConcurrentMap<String, Boolean>> RUNTIME_OUTPUT =
|
||||
private static final Cache<IrisPackResources, ConcurrentMap<String, Boolean>> RUNTIME_OUTPUT =
|
||||
Caffeine.newBuilder().weakKeys().build();
|
||||
private static final List<Long> RUNTIME_SAMPLE_SEEDS = List.of(
|
||||
0L, 1L, 2L, 3L, 5L, 8L, 13L, 21L, 34L, 55L, 89L, 144L, 233L, 377L, 610L, 987L);
|
||||
@@ -33,17 +38,10 @@ public final class StructureGraphCatalog {
|
||||
return compileAndReport(activeData, activeStructure);
|
||||
}
|
||||
ConcurrentMap<String, StructureGraphCompilation> catalog = CACHE.get(
|
||||
activeData, ignored -> new ConcurrentHashMap<>());
|
||||
activeData.getPackResources(), ignored -> new ConcurrentHashMap<>());
|
||||
return catalog.computeIfAbsent(structureKey, ignored -> compileAndReport(activeData, activeStructure));
|
||||
}
|
||||
|
||||
public static void invalidate(IrisData data) {
|
||||
if (data != null) {
|
||||
CACHE.invalidate(data);
|
||||
RUNTIME_OUTPUT.invalidate(data);
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean guaranteesRuntimeOutput(IrisData data, IrisStructure structure) {
|
||||
IrisData activeData = Objects.requireNonNull(data);
|
||||
IrisStructure activeStructure = Objects.requireNonNull(structure);
|
||||
@@ -55,7 +53,7 @@ public final class StructureGraphCatalog {
|
||||
return sampleRuntimeAssembly(activeData, activeStructure);
|
||||
}
|
||||
ConcurrentMap<String, Boolean> catalog = RUNTIME_OUTPUT.get(
|
||||
activeData, ignored -> new ConcurrentHashMap<>());
|
||||
activeData.getPackResources(), ignored -> new ConcurrentHashMap<>());
|
||||
return catalog.computeIfAbsent(
|
||||
structureKey, ignored -> sampleRuntimeAssembly(activeData, activeStructure));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.loot;
|
||||
|
||||
import art.arcane.iris.core.modules.IrisPackWorld;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.object.loot.IrisBlockDrops;
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
import art.arcane.iris.engine.object.world.region.IrisRegion;
|
||||
import art.arcane.iris.spi.IrisPlatforms;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import com.volmit.item.ItemDrop;
|
||||
import com.volmit.service.BlockDrops;
|
||||
import com.volmit.world.PackWorld;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* How {@code iris:loot} drops items for broken blocks: the block drops of the biome, the region and the dimension, the
|
||||
* biome's first and the biome able to keep the others from dropping.
|
||||
*/
|
||||
public final class BlockDropping implements BlockDrops {
|
||||
@Override
|
||||
public Result drops(PackWorld world, Broken broken) {
|
||||
Engine engine = IrisPackWorld.of(world).engine();
|
||||
int x = broken.position().x();
|
||||
int y = broken.position().y();
|
||||
int z = broken.position().z();
|
||||
PlatformBlockState block = IrisPlatforms.get().registries().block(broken.block().key());
|
||||
|
||||
IrisBiome biome = engine.getBiome(x, y, z);
|
||||
List<IrisBlockDrops> providers = dropsFor(biome.getBlockDrops(), block, engine);
|
||||
if (providers.stream().noneMatch(IrisBlockDrops::isSkipParents)) {
|
||||
IrisRegion region = engine.getRegion(x, z);
|
||||
providers.addAll(dropsFor(region.getBlockDrops(), block, engine));
|
||||
providers.addAll(dropsFor(engine.getDimension().getBlockDrops(), block, engine));
|
||||
}
|
||||
|
||||
LootItems items = new LootItems(world.resources().items(), false);
|
||||
List<ItemDrop> drops = new ArrayList<>();
|
||||
providers.forEach(provider -> provider.fillDrops(items, drops));
|
||||
return new Result(drops, providers.stream().anyMatch(IrisBlockDrops::isReplaceVanillaDrops));
|
||||
}
|
||||
|
||||
private static List<IrisBlockDrops> dropsFor(KList<IrisBlockDrops> candidates, PlatformBlockState block, Engine engine) {
|
||||
return new KList<>(candidates.stream().filter(drops -> drops.shouldDropFor(block, engine.getData())).toList());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.loot;
|
||||
|
||||
import art.arcane.iris.core.modules.IrisPackWorld;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.framework.LootResolver;
|
||||
import art.arcane.iris.engine.framework.PlacedObject;
|
||||
import art.arcane.iris.engine.object.loot.IrisLootTable;
|
||||
import art.arcane.iris.engine.object.loot.IrisVanillaLootTable;
|
||||
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
|
||||
import art.arcane.iris.spi.IrisPlatforms;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import com.volmit.item.ItemDrop;
|
||||
import com.volmit.service.Loot;
|
||||
import com.volmit.world.PackWorld;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* How {@code iris:loot} fills containers: the tables of the object placed around a container, then those of the
|
||||
* dimension, region and biomes at its column, and the items each table gives. Draws are deterministic per container, so
|
||||
* a container always holds the same loot.
|
||||
*/
|
||||
public final class LootGiving implements Loot {
|
||||
@Override
|
||||
public List<Source> tables(PackWorld world, Site site) {
|
||||
Engine engine = engine(world);
|
||||
int x = site.position().x();
|
||||
int z = site.position().z();
|
||||
int relativeY = site.position().y();
|
||||
RNG rng = LootResolver.containerRng(lootSeed(engine), x, relativeY + engine.getMinHeight(), z);
|
||||
|
||||
List<IrisLootTable> tables = new KList<>();
|
||||
boolean objectLootDefined = site.nativeLootDefined();
|
||||
IrisObjectPlacement placement = site.container() == null ? null : placementAt(engine, x, relativeY, z);
|
||||
if (placement != null) {
|
||||
objectLootDefined = objectLootDefined || placement.getLoot().isNotEmpty() || placement.getVanillaLoot().isNotEmpty();
|
||||
IrisLootTable table = placement.getTable(platformState(site), engine.getData(), rng);
|
||||
if (table != null) {
|
||||
tables.add(table);
|
||||
if (placement.isOverrideGlobalLoot()) {
|
||||
return sourcesOf(engine, site, List.of(table));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LootTables.resolveEnvironmentSources(tables, engine, rng, x, relativeY, z, objectLootDefined, table -> table);
|
||||
return sourcesOf(engine, site, tables);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ItemDrop> items(PackWorld world, Site site, String key) {
|
||||
Engine engine = engine(world);
|
||||
IrisLootTable table = LootResources.table(engine.getData(), key);
|
||||
if (table == null) {
|
||||
return List.of();
|
||||
}
|
||||
int worldY = site.position().y() + engine.getMinHeight();
|
||||
return new LootItems(world.resources().items(), site.debug())
|
||||
.draw(table, lootSeed(engine), site.position().x(), worldY, site.position().z());
|
||||
}
|
||||
|
||||
private static IrisObjectPlacement placementAt(Engine engine, int x, int relativeY, int z) {
|
||||
PlacedObject placed = engine.getObjectPlacement(x, relativeY, z);
|
||||
return placed == null ? null : placed.getPlacement();
|
||||
}
|
||||
|
||||
private static List<Source> sourcesOf(Engine engine, Site site, List<IrisLootTable> tables) {
|
||||
int worldY = site.position().y() + engine.getMinHeight();
|
||||
List<Source> sources = new KList<>();
|
||||
for (IrisLootTable table : tables) {
|
||||
if (table instanceof IrisVanillaLootTable vanilla) {
|
||||
long seed = LootTables.seed(lootSeed(engine), vanilla, site.position().x(), worldY, site.position().z());
|
||||
sources.add(new PlatformTable(vanilla.getLootTableKey(), seed));
|
||||
continue;
|
||||
}
|
||||
if (table != null && table.getLoadKey() != null) {
|
||||
sources.add(new Table(table.getLoadKey()));
|
||||
}
|
||||
}
|
||||
return sources;
|
||||
}
|
||||
|
||||
private static PlatformBlockState platformState(Site site) {
|
||||
return IrisPlatforms.get().registries().block(site.container().key());
|
||||
}
|
||||
|
||||
private static long lootSeed(Engine engine) {
|
||||
return engine.getSeedManager().getLoot();
|
||||
}
|
||||
|
||||
private static Engine engine(PackWorld world) {
|
||||
return IrisPackWorld.of(world).engine();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.loot;
|
||||
|
||||
import art.arcane.iris.engine.framework.LootResolver;
|
||||
import art.arcane.iris.engine.object.entity.IrisAttributeModifier;
|
||||
import art.arcane.iris.engine.object.loot.IrisEnchantment;
|
||||
import art.arcane.iris.engine.object.loot.InventorySlotType;
|
||||
import art.arcane.iris.engine.object.loot.IrisLoot;
|
||||
import art.arcane.iris.engine.object.loot.IrisLootTable;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import com.volmit.item.ItemAttribute;
|
||||
import com.volmit.item.ItemDrop;
|
||||
import com.volmit.item.ItemEnchantment;
|
||||
import com.volmit.item.ItemRegistry;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.OptionalInt;
|
||||
|
||||
/**
|
||||
* Turns loot entries into the items they give: every random choice is made here, in the order Iris always made them
|
||||
* (amount, enchantments, attribute modifiers, damage), so that a container's loot stays what it was. What the platform
|
||||
* must do with the result is the host's.
|
||||
*/
|
||||
public final class LootItems {
|
||||
private static final String AIR = "air";
|
||||
private static final String MINECRAFT_PREFIX = "minecraft:";
|
||||
private static final int MIN_AMOUNT = 1;
|
||||
|
||||
private final ItemRegistry items;
|
||||
private final boolean debug;
|
||||
|
||||
/** @param debug whether the items say where they came from */
|
||||
public LootItems(ItemRegistry items, boolean debug) {
|
||||
this.items = items;
|
||||
this.debug = debug;
|
||||
}
|
||||
|
||||
/**
|
||||
* The items {@code table} gives at the spot {@code x}, {@code y}, {@code z} (world coordinates): picks entries
|
||||
* from the table's own random stream until it has the number of items the table asks for or runs out of tries.
|
||||
*/
|
||||
public List<ItemDrop> draw(IrisLootTable table, long lootSeed, int x, int y, int z) {
|
||||
List<ItemDrop> drops = new ArrayList<>();
|
||||
List<IrisLoot> entries = table.getLoot();
|
||||
if (entries.isEmpty() || table.getMaxTries() <= 0) {
|
||||
return drops;
|
||||
}
|
||||
|
||||
RNG rng = LootTables.rng(lootSeed, table, x, y, z);
|
||||
int wanted = Math.max(0, LootResolver.inclusive(rng, table.getMinPicked(), table.getMaxPicked()));
|
||||
int tries = 0;
|
||||
while (drops.size() < wanted && tries++ < table.getMaxTries()) {
|
||||
int index = rng.nextInt(entries.size());
|
||||
IrisLoot entry = entries.get(index);
|
||||
if (entry == null || entry.getSlotTypes() != InventorySlotType.STORAGE) {
|
||||
continue;
|
||||
}
|
||||
ItemDrop drop = drawEntry(entry, table, rng, lootSeed, index, x, y, z);
|
||||
if (drop != null) {
|
||||
drops.add(drop);
|
||||
}
|
||||
}
|
||||
return drops;
|
||||
}
|
||||
|
||||
/** The item {@code entry} gives when nothing else decides whether it does, such as a block's drop or a mob's equipment; null for no item. */
|
||||
public ItemDrop give(IrisLoot entry, RNG rng) {
|
||||
return resolve(entry, rng, null);
|
||||
}
|
||||
|
||||
private ItemDrop drawEntry(IrisLoot entry, IrisLootTable table, RNG rng, long lootSeed, int index, int x, int y, int z) {
|
||||
long combinedRarity = LootResolver.combinedRarity(entry.getRarity(), table.getRarity());
|
||||
if (!LootTables.spatialOneIn(lootSeed, table, index, x, y, z, combinedRarity)) {
|
||||
return null;
|
||||
}
|
||||
return resolve(entry, rng, table);
|
||||
}
|
||||
|
||||
private ItemDrop resolve(IrisLoot entry, RNG rng, IrisLootTable table) {
|
||||
String type = entry.getTypeKey();
|
||||
OptionalInt maxDurability = items.maxDurability(type);
|
||||
if (maxDurability.isEmpty() || isAir(type)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
int amount = Math.max(MIN_AMOUNT, LootResolver.inclusive(rng, entry.getMinAmount(), entry.getMaxAmount()));
|
||||
List<ItemEnchantment> enchantments = drawEnchantments(entry, rng);
|
||||
List<ItemAttribute> attributes = drawAttributes(entry, rng);
|
||||
Double damage = maxDurability.getAsInt() > 0 ? 1D - rng.d(entry.getMinDurability(), entry.getMaxDurability()) : null;
|
||||
return new ItemDrop(type, amount, entry.getDisplayName(), entry.getLore(), enchantments, attributes,
|
||||
entry.isUnbreakable(), entry.getItemFlags(), entry.getCustomModel(), damage, entry.getLeatherColor(),
|
||||
entry.getDyeColorKey(), entry.getCustomNbt(), debug ? sourceOf(entry, table) : null);
|
||||
}
|
||||
|
||||
private static List<ItemEnchantment> drawEnchantments(IrisLoot entry, RNG rng) {
|
||||
List<ItemEnchantment> enchantments = new ArrayList<>();
|
||||
for (IrisEnchantment enchantment : entry.getEnchantments()) {
|
||||
String key = enchantment.getEnchantment();
|
||||
if (key == null || key.isBlank() || rng.nextDouble() >= enchantment.getChance()) {
|
||||
continue;
|
||||
}
|
||||
enchantments.add(new ItemEnchantment(key, Math.max(1, enchantment.getLevel(rng))));
|
||||
}
|
||||
return enchantments;
|
||||
}
|
||||
|
||||
private static List<ItemAttribute> drawAttributes(IrisLoot entry, RNG rng) {
|
||||
List<ItemAttribute> attributes = new ArrayList<>();
|
||||
for (IrisAttributeModifier modifier : entry.getAttributes()) {
|
||||
if (rng.nextDouble() >= modifier.getChance()) {
|
||||
continue;
|
||||
}
|
||||
String attribute = modifier.getAttribute();
|
||||
if (attribute == null || attribute.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
attributes.add(new ItemAttribute(attribute, modifier.getName(), modifier.getOperation(), modifier.getAmount(rng)));
|
||||
}
|
||||
return attributes;
|
||||
}
|
||||
|
||||
private static ItemDrop.Source sourceOf(IrisLoot entry, IrisLootTable table) {
|
||||
if (table == null) {
|
||||
return new ItemDrop.Source(null, 0, entry.getRarity());
|
||||
}
|
||||
return new ItemDrop.Source(table.getName(), table.getRarity(), entry.getRarity());
|
||||
}
|
||||
|
||||
private static boolean isAir(String type) {
|
||||
String key = type.startsWith(MINECRAFT_PREFIX) ? type.substring(MINECRAFT_PREFIX.length()) : type;
|
||||
return AIR.equalsIgnoreCase(key);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.loot;
|
||||
|
||||
import com.volmit.FeatureRegistry;
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.service.BlockDrops;
|
||||
import com.volmit.service.Loot;
|
||||
import com.volmit.stage.StageGraph;
|
||||
|
||||
/**
|
||||
* Module {@code iris:loot}: the loot tables of the pack ({@link LootResources}) and the items they and the block drops
|
||||
* of the dimension, regions and biomes give. It checks the tables and the references to them ({@link LootValidator}). It has no generation stage; Iris asks it through {@link Loot} when a container is filled and through
|
||||
* {@link BlockDrops} when a player breaks a block.
|
||||
*/
|
||||
public final class LootModule implements IrisModule {
|
||||
private static final String VERSION = "built-in";
|
||||
|
||||
@Override
|
||||
public ModuleInfo info() {
|
||||
return ModuleInfo.of("iris:loot", "Loot", VERSION);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void install(StageGraph graph) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void register(FeatureRegistry registry) {
|
||||
LootResources.kinds().forEach(registry::registerResourceKind);
|
||||
registry.registerValidator(new LootValidator());
|
||||
registry.registerService(Loot.class, new LootGiving());
|
||||
registry.registerService(BlockDrops.class, new BlockDropping());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.loot;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.modules.IrisPackResources;
|
||||
import art.arcane.iris.engine.object.loot.IrisLootTable;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.resource.ResourceKind;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The resource kind of module {@code iris:loot}, which keeps the folder and files Iris packs have always used, and
|
||||
* lookups by pack key for code that still names loot tables by key. Every lookup goes through the pack's
|
||||
* {@link com.volmit.resource.PackResources}, so it sees the pack's current snapshot.
|
||||
* <p>
|
||||
* Lookups answer null where Iris's loader did: for a blank key, a key the pack has no file for, and a file that fails
|
||||
* to load, which was reported when it was read.
|
||||
*/
|
||||
public final class LootResources {
|
||||
/** Loot tables, in {@code loot/}. */
|
||||
public static final ResourceKind<IrisLootTable> TABLES = ResourceKind.of("iris:loot/table", "loot", IrisLootTable.class);
|
||||
|
||||
private LootResources() {
|
||||
}
|
||||
|
||||
/** Every resource kind of the loot module. */
|
||||
public static List<ResourceKind<?>> kinds() {
|
||||
return List.of(TABLES);
|
||||
}
|
||||
|
||||
public static IrisLootTable table(IrisData data, String key) {
|
||||
if (key == null || key.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
IrisPackResources resources = data.getPackResources();
|
||||
try {
|
||||
return resources.find(TABLES.key(resources.idOf(key))).orElse(null);
|
||||
} catch (IllegalStateException failedToLoad) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The tables of the pack named by {@code keys}, in order, without the ones the pack lacks. */
|
||||
public static KList<IrisLootTable> tables(IrisData data, List<String> keys) {
|
||||
KList<IrisLootTable> tables = new KList<>();
|
||||
for (String key : keys) {
|
||||
IrisLootTable table = table(data, key);
|
||||
if (table != null) {
|
||||
tables.add(table);
|
||||
}
|
||||
}
|
||||
return tables;
|
||||
}
|
||||
|
||||
/** The key of every loot table of the pack, in key order. */
|
||||
public static List<String> tableKeys(IrisData data) {
|
||||
return data.getPackResources().ids(TABLES.type()).stream().map(ResourceId::path).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.loot;
|
||||
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.framework.LootResolver;
|
||||
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.biome.IrisBiome;
|
||||
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.List;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* Which loot tables a place in the world draws from, and the random streams that draw from them: the part of loot
|
||||
* that reads the pack's tables, loot references and layout. The streams themselves are
|
||||
* {@link LootResolver}'s; here a table is named by its {@linkplain #identity identity}.
|
||||
*/
|
||||
public final class LootTables {
|
||||
private LootTables() {
|
||||
}
|
||||
|
||||
/** What names a table in the random streams: its key, else its name. */
|
||||
public static String identity(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;
|
||||
}
|
||||
|
||||
public static RNG rng(long lootSeed, IrisLootTable table, int x, int y, int z) {
|
||||
return LootResolver.tableRng(lootSeed, identity(table), x, y, z);
|
||||
}
|
||||
|
||||
public static long seed(long lootSeed, IrisLootTable table, int x, int y, int z) {
|
||||
return LootResolver.tableSeed(lootSeed, identity(table), x, y, z);
|
||||
}
|
||||
|
||||
public static boolean spatialOneIn(long lootSeed, IrisLootTable table, int entryIndex, int x, int y, int z, long rarity) {
|
||||
return LootResolver.spatialOneIn(lootSeed, identity(table), entryIndex, x, y, z, rarity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the tables of the dimension, the region, the surface biome and (below the surface) the cave biome at a
|
||||
* column to {@code sources}, as their loot references say, then scales their number by the areas' multipliers.
|
||||
* {@code mapper} turns a table into the caller's own source; a null result skips it.
|
||||
*/
|
||||
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);
|
||||
}
|
||||
LootResolver.scaleSources(sources, multiplier, rng);
|
||||
}
|
||||
|
||||
/** Adds {@code additions} to {@code sources} the way {@code mode} says; {@code fallback} is whether nothing else defined a table. */
|
||||
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);
|
||||
}
|
||||
|
||||
static boolean sameBiome(IrisBiome first, IrisBiome second) {
|
||||
if (first == second) {
|
||||
return true;
|
||||
}
|
||||
if (first == null || second == null) {
|
||||
return false;
|
||||
}
|
||||
return Objects.equals(first.getLoadKey(), second.getLoadKey());
|
||||
}
|
||||
|
||||
private static <T> void injectReference(
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.loot;
|
||||
|
||||
import art.arcane.iris.core.modules.IrisValidationContext;
|
||||
import art.arcane.iris.core.pack.PackIntegerChecks;
|
||||
import art.arcane.iris.core.pack.PackValidationIo;
|
||||
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 com.volmit.validation.Problem;
|
||||
import com.volmit.validation.Subject;
|
||||
import com.volmit.validation.ValidationContext;
|
||||
import com.volmit.validation.Validator;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Module {@code iris:loot}'s check of a pack: every loot table has sane picks, tries and entries, and every loot
|
||||
* reference of a dimension, region or biome names a table the pack has. The files are read as written, like the pack
|
||||
* validator's other file checks, so a malformed table is reported rather than failing the load.
|
||||
*/
|
||||
public final class LootValidator implements Validator {
|
||||
private static final List<String> LOOT_HOST_FOLDERS = List.of("dimensions", "regions", "biomes");
|
||||
private static final String JSON_EXTENSION = ".json";
|
||||
|
||||
@Override
|
||||
public void validate(ValidationContext pack) {
|
||||
check(IrisValidationContext.of(pack).data().getDataFolder()).forEach(pack::report);
|
||||
}
|
||||
|
||||
/** What is wrong with the loot tables and loot references of the pack in {@code packFolder}. */
|
||||
public static List<Problem> check(File packFolder) {
|
||||
List<Problem> problems = new ArrayList<>();
|
||||
if (packFolder == null || !packFolder.isDirectory()) {
|
||||
return problems;
|
||||
}
|
||||
|
||||
File lootFolder = new File(packFolder, LootResources.TABLES.folder());
|
||||
Set<String> lootKeys = keysOf(lootFolder);
|
||||
checkTables(lootFolder, problems);
|
||||
for (String folderName : LOOT_HOST_FOLDERS) {
|
||||
checkReferences(new File(packFolder, folderName), folderName, lootKeys, problems);
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
private static void checkTables(File lootFolder, List<Problem> problems) {
|
||||
if (!lootFolder.isDirectory()) {
|
||||
return;
|
||||
}
|
||||
List<File> lootFiles = PackValidationIo.listJsonRecursive(lootFolder);
|
||||
lootFiles.sort(Comparator.comparing(File::getPath));
|
||||
for (File lootFile : lootFiles) {
|
||||
String lootKey = PackValidationIo.deriveKey(lootFolder, lootFile);
|
||||
List<String> errors = new ArrayList<>();
|
||||
JSONObject table = readTable(lootFile, lootKey, errors);
|
||||
if (table != null) {
|
||||
validateLootTable(lootKey, table, errors);
|
||||
}
|
||||
report(problems, Problem::error, Subject.file(LootResources.TABLES.folder() + "/" + lootKey + JSON_EXTENSION), errors);
|
||||
}
|
||||
}
|
||||
|
||||
private static void checkReferences(File resourceFolder, String folderName, Set<String> lootKeys, List<Problem> problems) {
|
||||
if (!resourceFolder.isDirectory()) {
|
||||
return;
|
||||
}
|
||||
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 resourceKey = PackValidationIo.deriveKey(resourceFolder, resourceFile);
|
||||
List<String> errors = new ArrayList<>();
|
||||
List<String> warnings = new ArrayList<>();
|
||||
validateLootReference(hostType(folderName), resourceKey, resource.opt("loot"), lootKeys, errors, warnings);
|
||||
Subject subject = Subject.file(folderName + "/" + resourceKey + JSON_EXTENSION);
|
||||
report(problems, Problem::error, subject, errors);
|
||||
report(problems, Problem::warning, subject, warnings);
|
||||
}
|
||||
}
|
||||
|
||||
private static void report(List<Problem> problems, java.util.function.BiFunction<Subject, String, Problem> severity,
|
||||
Subject subject, List<String> messages) {
|
||||
for (String message : messages) {
|
||||
problems.add(severity.apply(subject, message));
|
||||
}
|
||||
}
|
||||
|
||||
private static Set<String> keysOf(File folder) {
|
||||
Set<String> keys = new HashSet<>();
|
||||
if (!folder.isDirectory()) {
|
||||
return keys;
|
||||
}
|
||||
for (File file : PackValidationIo.listJsonRecursive(folder)) {
|
||||
String key = PackValidationIo.deriveKey(folder, file);
|
||||
if (key != null && !key.isBlank()) {
|
||||
keys.add(key);
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
private static JSONObject readTable(File file, String key, List<String> errors) {
|
||||
try {
|
||||
return new JSONObject(Files.readString(file.toPath(), StandardCharsets.UTF_8));
|
||||
} catch (IOException | RuntimeException e) {
|
||||
String reason = e.getMessage();
|
||||
if (reason == null || reason.isBlank()) {
|
||||
reason = e.getClass().getSimpleName();
|
||||
}
|
||||
errors.add("Loot table '" + key + "' has invalid JSON: " + reason);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String hostType(String folderName) {
|
||||
return switch (folderName) {
|
||||
case "dimensions" -> "Dimension";
|
||||
case "regions" -> "Region";
|
||||
case "biomes" -> "Biome";
|
||||
default -> "Resource";
|
||||
};
|
||||
}
|
||||
|
||||
private static void validateLootTable(String lootKey, JSONObject table, List<String> blockingErrors) {
|
||||
String path = "Loot table '" + lootKey + "'";
|
||||
Integer rarity = PackIntegerChecks.integerField(table, "rarity", 1, path, blockingErrors);
|
||||
Integer minimumPicked = PackIntegerChecks.integerField(table, "minPicked", 1, path, blockingErrors);
|
||||
Integer maximumPicked = PackIntegerChecks.integerField(table, "maxPicked", 5, path, blockingErrors);
|
||||
Integer maximumTries = PackIntegerChecks.integerField(table, "maxTries", 10, path, blockingErrors);
|
||||
PackIntegerChecks.requireMinimum(path + ".rarity", rarity, 1, blockingErrors);
|
||||
PackIntegerChecks.requireMinimum(path + ".minPicked", minimumPicked, 0, blockingErrors);
|
||||
PackIntegerChecks.requireMinimum(path + ".maxPicked", maximumPicked, 1, blockingErrors);
|
||||
PackIntegerChecks.requireMinimum(path + ".maxTries", maximumTries, 1, blockingErrors);
|
||||
PackIntegerChecks.requireMaximum(path + ".minPicked", minimumPicked, IrisLootTable.MAX_PICKED, blockingErrors);
|
||||
PackIntegerChecks.requireMaximum(path + ".maxPicked", maximumPicked, IrisLootTable.MAX_PICKED, blockingErrors);
|
||||
PackIntegerChecks.requireMaximum(path + ".maxTries", maximumTries, IrisLootTable.MAX_TRIES, blockingErrors);
|
||||
PackIntegerChecks.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 = PackIntegerChecks.integerField(entry, "rarity", 1, entryPath, blockingErrors);
|
||||
Integer minimumAmount = PackIntegerChecks.integerField(entry, "minAmount", 1, entryPath, blockingErrors);
|
||||
Integer maximumAmount = PackIntegerChecks.integerField(entry, "maxAmount", 1, entryPath, blockingErrors);
|
||||
PackIntegerChecks.requireMinimum(entryPath + ".rarity", entryRarity, 1, blockingErrors);
|
||||
PackIntegerChecks.requireMinimum(entryPath + ".minAmount", minimumAmount, 1, blockingErrors);
|
||||
PackIntegerChecks.requireMinimum(entryPath + ".maxAmount", maximumAmount, 1, blockingErrors);
|
||||
PackIntegerChecks.requireMaximum(entryPath + ".minAmount", minimumAmount, IrisLoot.MAX_AMOUNT, blockingErrors);
|
||||
PackIntegerChecks.requireMaximum(entryPath + ".maxAmount", maximumAmount, IrisLoot.MAX_AMOUNT, blockingErrors);
|
||||
PackIntegerChecks.requireOrdered(entryPath + ".minAmount", minimumAmount,
|
||||
entryPath + ".maxAmount", maximumAmount, blockingErrors);
|
||||
validateLootEnchantments(entryPath, entry.opt("enchantments"), blockingErrors);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateLootEnchantments(String entryPath, Object rawEnchantments,
|
||||
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 = PackIntegerChecks.integerField(enchantment, "minLevel", 1, enchantmentPath, blockingErrors);
|
||||
Integer maximumLevel = PackIntegerChecks.integerField(enchantment, "maxLevel", 1, enchantmentPath, blockingErrors);
|
||||
PackIntegerChecks.requireMinimum(enchantmentPath + ".minLevel", minimumLevel, 1, blockingErrors);
|
||||
PackIntegerChecks.requireMinimum(enchantmentPath + ".maxLevel", maximumLevel, 1, blockingErrors);
|
||||
PackIntegerChecks.requireOrdered(enchantmentPath + ".minLevel", minimumLevel,
|
||||
enchantmentPath + ".maxLevel", maximumLevel, blockingErrors);
|
||||
if (enchantment.has("chance")) {
|
||||
Object rawChance = enchantment.opt("chance");
|
||||
if (!(rawChance instanceof Number number)
|
||||
|| !Double.isFinite(number.doubleValue())
|
||||
|| number.doubleValue() < 0D
|
||||
|| number.doubleValue() > 1D) {
|
||||
blockingErrors.add(enchantmentPath + ".chance must be a finite number from 0 to 1.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateLootReference(String resourceType, String resourceKey, Object rawLoot,
|
||||
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 + "'.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -184,12 +184,12 @@ public class FloatingObjectPlacing {
|
||||
if (raw == null) {
|
||||
continue;
|
||||
}
|
||||
IrisObject obj0 = placement.getScale().get(rng, raw);
|
||||
IrisObject obj0 = placement.getScale().get(rng, raw, engine);
|
||||
if (obj0 == null) {
|
||||
continue;
|
||||
}
|
||||
if (entry != null && entry.hasObjectShrink()) {
|
||||
obj0 = entry.getShrinkScale().get(rng, obj0);
|
||||
obj0 = entry.getShrinkScale().get(rng, obj0, engine);
|
||||
if (obj0 == null) {
|
||||
continue;
|
||||
}
|
||||
@@ -232,12 +232,12 @@ public class FloatingObjectPlacing {
|
||||
if (raw == null) {
|
||||
continue;
|
||||
}
|
||||
IrisObject obj0 = placement.getScale().get(rng, raw);
|
||||
IrisObject obj0 = placement.getScale().get(rng, raw, engine);
|
||||
if (obj0 == null) {
|
||||
continue;
|
||||
}
|
||||
if (entry != null && entry.hasObjectShrink()) {
|
||||
obj0 = entry.getShrinkScale().get(rng, obj0);
|
||||
obj0 = entry.getShrinkScale().get(rng, obj0, engine);
|
||||
if (obj0 == null) {
|
||||
continue;
|
||||
}
|
||||
@@ -317,12 +317,12 @@ public class FloatingObjectPlacing {
|
||||
if (raw == null) {
|
||||
continue;
|
||||
}
|
||||
IrisObject obj0 = placement.getScale().get(rng, raw);
|
||||
IrisObject obj0 = placement.getScale().get(rng, raw, engine);
|
||||
if (obj0 == null) {
|
||||
continue;
|
||||
}
|
||||
if (entry != null && entry.hasObjectShrink()) {
|
||||
obj0 = entry.getShrinkScale().get(rng, obj0);
|
||||
obj0 = entry.getShrinkScale().get(rng, obj0, engine);
|
||||
if (obj0 == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.mantle.components;
|
||||
|
||||
import art.arcane.iris.core.modules.IrisPackWorld;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
import art.arcane.iris.engine.object.world.region.IrisRegion;
|
||||
import com.volmit.service.ObjectsAt;
|
||||
import com.volmit.world.PackWorld;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* How {@code iris:objects} tells Iris where its objects are: the objects the biome and region of a chunk would place,
|
||||
* and the biomes and regions whose surface placements name an object.
|
||||
*/
|
||||
public final class ObjectLocating implements ObjectsAt {
|
||||
@Override
|
||||
public Set<String> objectsAt(PackWorld world, int chunkX, int chunkZ) {
|
||||
return ObjectModule.placing(engine(world)).guess(chunkX, chunkZ);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlacedBy placedBy(PackWorld world, String objectKey) {
|
||||
Engine engine = engine(world);
|
||||
Set<String> biomes = new LinkedHashSet<>();
|
||||
for (IrisBiome biome : engine.getDimension().getReachableBiomes(engine)) {
|
||||
if (biome != null && placesObject(biome.getSurfaceObjects(), objectKey)) {
|
||||
biomes.add(biome.getLoadKey());
|
||||
}
|
||||
}
|
||||
|
||||
Set<String> regions = new LinkedHashSet<>();
|
||||
for (IrisRegion region : engine.getDimension().getAllRegions(engine)) {
|
||||
if (region != null && placesObject(region.getSurfaceObjects(), objectKey)) {
|
||||
regions.add(region.getLoadKey());
|
||||
}
|
||||
}
|
||||
return new PlacedBy(biomes, regions);
|
||||
}
|
||||
|
||||
private static boolean placesObject(List<IrisObjectPlacement> placements, String objectKey) {
|
||||
for (IrisObjectPlacement placement : placements) {
|
||||
if (placement != null && placement.getPlace().contains(objectKey)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static Engine engine(PackWorld world) {
|
||||
return IrisPackWorld.of(world).engine();
|
||||
}
|
||||
}
|
||||
@@ -21,24 +21,22 @@ package art.arcane.iris.engine.mantle.components;
|
||||
import art.arcane.iris.builtin.IrisStages;
|
||||
import art.arcane.iris.core.modules.IrisMantleChunk;
|
||||
import art.arcane.iris.core.modules.IrisPackSettings;
|
||||
import art.arcane.iris.core.modules.IrisPackWorld;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import com.volmit.FeatureRegistry;
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.config.PackSettings;
|
||||
import com.volmit.service.ObjectsAt;
|
||||
import com.volmit.service.SaplingGrowth;
|
||||
import com.volmit.stage.MantleStageContext;
|
||||
import com.volmit.stage.StageGraph;
|
||||
import com.volmit.world.PackWorld;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Module {@code iris:objects}: the objects the dimension's regions and biomes place, written into the mantle
|
||||
* once the caves they may anchor in are planned. A port of what was Iris's object mantle component, its work
|
||||
* done by {@link ObjectPlacing}, one per engine runtime. Its reach is the pack's largest object placement. It tells
|
||||
* Iris which objects a chunk would get ({@link ObjectsAt}), for the object search and studio tools.
|
||||
* Iris which objects a chunk would get and which biomes and regions place an object ({@link ObjectLocating}), for the
|
||||
* object search and studio tools, and grows the trees of saplings ({@link TreeGrowing}).
|
||||
*/
|
||||
public final class ObjectModule implements IrisModule {
|
||||
private static final String VERSION = "built-in";
|
||||
@@ -55,7 +53,8 @@ public final class ObjectModule implements IrisModule {
|
||||
|
||||
@Override
|
||||
public void register(FeatureRegistry registry) {
|
||||
registry.registerService(ObjectsAt.class, ObjectModule::objectsAt);
|
||||
registry.registerService(ObjectsAt.class, new ObjectLocating());
|
||||
registry.registerService(SaplingGrowth.class, new TreeGrowing());
|
||||
}
|
||||
|
||||
private static void place(MantleStageContext context) {
|
||||
@@ -67,11 +66,6 @@ public final class ObjectModule implements IrisModule {
|
||||
return placing(IrisPackSettings.of(settings).engine()).reach();
|
||||
}
|
||||
|
||||
/** The keys of the objects the surface placements of the chunk's biome and region would place, guessed without generating it. */
|
||||
private static Set<String> objectsAt(PackWorld world, int chunkX, int chunkZ) {
|
||||
return placing(IrisPackWorld.of(world).engine()).guess(chunkX, chunkZ);
|
||||
}
|
||||
|
||||
/** The engine runtime's object placing, which the module's {@link ObjectsAt} also asks. */
|
||||
public static ObjectPlacing placing(Engine engine) {
|
||||
return engine.getGeneration().state(ObjectPlacing.class, ObjectPlacing::new);
|
||||
|
||||
@@ -663,7 +663,7 @@ public class ObjectPlacing {
|
||||
|
||||
for (int i = 0; i < density; i++) {
|
||||
attempts++;
|
||||
IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng));
|
||||
IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng), engine);
|
||||
if (v == null) {
|
||||
nullObjects++;
|
||||
if (traceRegen) {
|
||||
@@ -801,7 +801,7 @@ public class ObjectPlacing {
|
||||
|
||||
for (int i = 0; i < density; i++) {
|
||||
attempts++;
|
||||
IrisObject object = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng));
|
||||
IrisObject object = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng), engine);
|
||||
if (object == null) {
|
||||
nullObjects++;
|
||||
if (traceRegen) {
|
||||
@@ -1034,7 +1034,7 @@ public class ObjectPlacing {
|
||||
int density = objectPlacement.getDensity(rng, minX, minZ, engine.getData());
|
||||
|
||||
for (int i = 0; i < density; i++) {
|
||||
IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng));
|
||||
IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng), engine);
|
||||
if (v == null) {
|
||||
continue;
|
||||
}
|
||||
@@ -1419,7 +1419,7 @@ public class ObjectPlacing {
|
||||
private Set<String> guessPlacedKeys(RNG rng, int x, int z, IrisObjectPlacement objectPlacement) {
|
||||
Set<String> f = new KSet<>();
|
||||
for (int i = 0; i < objectPlacement.getDensity(rng, x, z, engine.getData()); i++) {
|
||||
IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(engine.getComplex(), rng));
|
||||
IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(engine.getComplex(), rng), engine);
|
||||
if (v == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.mantle.components;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.modules.IrisPackWorld;
|
||||
import art.arcane.iris.core.modules.PlatformBlockStates;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.object.placement.IObjectPlacer;
|
||||
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
|
||||
import art.arcane.iris.engine.object.placement.IrisTreeSize;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import art.arcane.iris.engine.object.prefab.TileData;
|
||||
import art.arcane.iris.engine.object.procedural.IrisProceduralObjects;
|
||||
import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree;
|
||||
import art.arcane.iris.engine.object.procedural.tree.IrisTreeModes;
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
import art.arcane.iris.engine.object.world.region.IrisRegion;
|
||||
import art.arcane.iris.spi.IrisPlatforms;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.placement.PlacedBlock;
|
||||
import com.volmit.service.SaplingGrowth;
|
||||
import com.volmit.world.BlockPosition;
|
||||
import com.volmit.world.PackWorld;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* How {@code iris:objects} grows trees: when a sapling grows, the tree comes from the tree placements of the biome and
|
||||
* region at the sapling (the region's too when the dimension uses all of them), placed like any object but into a list
|
||||
* of blocks the host then places. The same placements tell which objects are trees.
|
||||
*/
|
||||
public final class TreeGrowing implements SaplingGrowth {
|
||||
private static final IrisTreeSize SAPLING_SIZE = new IrisTreeSize(1, 1);
|
||||
|
||||
@Override
|
||||
public Optional<Growth> grow(PackWorld world, Sapling sapling, Surroundings surroundings) {
|
||||
Engine engine = IrisPackWorld.of(world).engine();
|
||||
if (!engine.getDimension().getTreeSettings().isEnabled()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
IrisObjectPlacement placement = pickPlacement(engine, sapling);
|
||||
if (placement == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
IrisData data = engine.getData();
|
||||
IrisObject object = data.getObjectLoader().load(placement.getPlace().getRandom(RNG.r));
|
||||
GrowthPlacer placer = new GrowthPlacer(engine, surroundings);
|
||||
BlockPosition center = sapling.center();
|
||||
object.place(center.x(), center.y() + object.getH() / 2, center.z(), placer, placement, RNG.r, data);
|
||||
return Optional.of(new Growth(object.getLoadKey(), placer.placed()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public TreeObjects treeObjects(PackWorld world) {
|
||||
Engine engine = IrisPackWorld.of(world).engine();
|
||||
Set<String> objects = new HashSet<>();
|
||||
Set<String> procedural = new HashSet<>();
|
||||
|
||||
for (IrisRegion region : engine.getDimension().getAllRegions(engine)) {
|
||||
if (region != null) {
|
||||
collectPlacements(region.getObjects(), objects);
|
||||
collectProceduralTrees(region.getProceduralObjects(), procedural);
|
||||
}
|
||||
}
|
||||
for (IrisBiome biome : engine.getDimension().getReachableBiomes(engine)) {
|
||||
if (biome != null) {
|
||||
collectPlacements(biome.getObjects(), objects);
|
||||
collectProceduralTrees(biome.getProceduralObjects(), procedural);
|
||||
}
|
||||
}
|
||||
return new TreeObjects(objects, procedural);
|
||||
}
|
||||
|
||||
/** One placement, picked at random, of the tree placements that grow {@code sapling}'s species; null for none. */
|
||||
private static IrisObjectPlacement pickPlacement(Engine engine, Sapling sapling) {
|
||||
KList<IrisObjectPlacement> placements = new KList<>();
|
||||
boolean useAll = engine.getDimension().getTreeSettings().getMode().equals(IrisTreeModes.ALL);
|
||||
|
||||
BlockPosition at = sapling.at();
|
||||
placements.addAll(matching(engine.getBiome(at.x(), at.y(), at.z()).getObjects(), sapling.species()));
|
||||
if (useAll || placements.isEmpty()) {
|
||||
placements.addAll(matching(engine.getRegion(at.x(), at.z()).getObjects(), sapling.species()));
|
||||
}
|
||||
return placements.isNotEmpty() ? placements.getRandom() : null;
|
||||
}
|
||||
|
||||
private static KList<IrisObjectPlacement> matching(KList<IrisObjectPlacement> objects, String species) {
|
||||
KList<IrisObjectPlacement> matches = new KList<>();
|
||||
for (IrisObjectPlacement placement : objects) {
|
||||
if (placement.matches(SAPLING_SIZE, species)) {
|
||||
matches.add(placement);
|
||||
}
|
||||
}
|
||||
return matches;
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Places an object into a list of blocks, reading the world around the sapling through the host. */
|
||||
private static final class GrowthPlacer implements IObjectPlacer {
|
||||
private final Engine engine;
|
||||
private final Surroundings surroundings;
|
||||
private final PlatformBlockStates states = new PlatformBlockStates(key -> IrisPlatforms.get().registries().block(key));
|
||||
private final List<PlacedBlock> placed = new ArrayList<>();
|
||||
|
||||
private GrowthPlacer(Engine engine, Surroundings surroundings) {
|
||||
this.engine = engine;
|
||||
this.surroundings = surroundings;
|
||||
}
|
||||
|
||||
private List<PlacedBlock> placed() {
|
||||
return placed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHighest(int x, int z, IrisData data) {
|
||||
return surroundings.highest(x, z, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) {
|
||||
return surroundings.highest(x, z, ignoreFluid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(int x, int y, int z, PlatformBlockState state) {
|
||||
placed.add(new PlacedBlock(new BlockPosition(x, y, z), states.toApi(state), Optional.empty()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformBlockState get(int x, int y, int z) {
|
||||
BlockState block = surroundings.blockAt(x, y, z);
|
||||
return states.toPlatform(block);
|
||||
}
|
||||
|
||||
@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 isSolid(x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSolid(int x, int y, int z) {
|
||||
return get(x, y, z).isSolid();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUnderwater(int x, int z) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getFluidHeight() {
|
||||
return engine.getDimension().getFluidHeight();
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,25 +23,12 @@ import art.arcane.iris.engine.object.annotations.MaxNumber;
|
||||
import art.arcane.iris.engine.object.annotations.MinNumber;
|
||||
import art.arcane.iris.engine.object.annotations.Required;
|
||||
import art.arcane.iris.engine.object.annotations.Snippet;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.Registry;
|
||||
import org.bukkit.attribute.Attributable;
|
||||
import org.bukkit.attribute.Attribute;
|
||||
import org.bukkit.attribute.AttributeModifier;
|
||||
import org.bukkit.attribute.AttributeModifier.Operation;
|
||||
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;
|
||||
|
||||
@Snippet("attribute-modifier")
|
||||
@Accessors(chain = true)
|
||||
@@ -50,8 +37,6 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
@Desc("Represents an attribute modifier for an item or an entity. This allows you to create modifications to basic game attributes such as MAX_HEALTH or ARMOR_VALUE.")
|
||||
@Data
|
||||
public class IrisAttributeModifier {
|
||||
private static final Set<String> WARNED_ATTRIBUTES = ConcurrentHashMap.newKeySet();
|
||||
|
||||
@Required
|
||||
@Desc("The Attribute type key such as max_health or minecraft:armor. This type is pulled from the game attributes. Zombie & Horse attributes will not work on non-zombie/horse entities.\nUsing an attribute on an item will have affects when held, or worn. There is no way to specify further granularity as the game picks this depending on the item type.")
|
||||
private String attribute = null;
|
||||
@@ -75,80 +60,7 @@ public class IrisAttributeModifier {
|
||||
@Desc("The chance that this attribute is applied (0 to 1). If the chance is 0.5 (50%), then Iris will only apply this attribute 50% of the time.")
|
||||
private double chance = 1;
|
||||
|
||||
public void apply(RNG rng, ItemMeta meta) {
|
||||
if (rng.nextDouble() < getChance()) {
|
||||
Attribute resolved = resolveAttribute();
|
||||
if (resolved == null) {
|
||||
return;
|
||||
}
|
||||
meta.addAttributeModifier(resolved, createModifier(rng));
|
||||
}
|
||||
}
|
||||
|
||||
public void apply(RNG rng, Attributable meta) {
|
||||
if (rng.nextDouble() < getChance()) {
|
||||
Attribute resolved = resolveAttribute();
|
||||
if (resolved == null) {
|
||||
return;
|
||||
}
|
||||
meta.getAttribute(resolved).addModifier(createModifier(rng));
|
||||
}
|
||||
}
|
||||
|
||||
public double getAmount(RNG rng) {
|
||||
return rng.d(getMinAmount(), getMaxAmount());
|
||||
}
|
||||
|
||||
private Attribute resolveAttribute() {
|
||||
if (attribute == null || attribute.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
String value = 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_")) {
|
||||
resolved = Registry.ATTRIBUTE.get(NamespacedKey.minecraft(value.substring("generic_".length())));
|
||||
}
|
||||
if (resolved == null && value.startsWith("generic.")) {
|
||||
resolved = Registry.ATTRIBUTE.get(NamespacedKey.minecraft(value.substring("generic.".length())));
|
||||
}
|
||||
}
|
||||
if (resolved == null && WARNED_ATTRIBUTES.add(value)) {
|
||||
IrisLogging.warn("Unknown attribute '" + attribute + "' in attribute-modifier '" + name + "'");
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
private Operation resolveOperation() {
|
||||
if (operation == null || operation.isBlank()) {
|
||||
return Operation.ADD_NUMBER;
|
||||
}
|
||||
try {
|
||||
return Operation.valueOf(operation.trim().toUpperCase(Locale.ROOT));
|
||||
} catch (IllegalArgumentException e) {
|
||||
return Operation.ADD_NUMBER;
|
||||
}
|
||||
}
|
||||
|
||||
private AttributeModifier createModifier(RNG rng) {
|
||||
NamespacedKey key = NamespacedKey.minecraft(generateModifierKey());
|
||||
return new AttributeModifier(key, getAmount(rng), resolveOperation(), EquipmentSlotGroup.ANY);
|
||||
}
|
||||
|
||||
private String generateModifierKey() {
|
||||
String source = getName() == null ? "modifier" : getName();
|
||||
String normalized = source.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9/._-]", "_");
|
||||
if (normalized.isBlank()) {
|
||||
normalized = "modifier";
|
||||
}
|
||||
if (normalized.length() > 32) {
|
||||
normalized = normalized.substring(0, 32);
|
||||
}
|
||||
String random = UUID.randomUUID().toString().replace("-", "");
|
||||
return normalized + "_" + random;
|
||||
}
|
||||
}
|
||||
@@ -285,39 +285,4 @@ public class IrisEffect {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void apply(Entity p) {
|
||||
if (!shouldApplyNow()) {
|
||||
return;
|
||||
}
|
||||
|
||||
J.runEntity(p, () -> {
|
||||
Sound soundType = getSound();
|
||||
Particle particleType = getParticleEffect();
|
||||
if (soundType != null) {
|
||||
Location part = p.getLocation().clone().add(RNG.r.i(-soundDistance, soundDistance), RNG.r.i(-soundDistance, soundDistance), RNG.r.i(-soundDistance, soundDistance));
|
||||
p.getWorld().playSound(part, soundType, (float) volume, (float) RNG.r.d(minPitch, 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());
|
||||
if (extra != 0) {
|
||||
p.getWorld().spawnParticle(particleType, part.getX(), part.getY() + RNG.r.i(particleOffset),
|
||||
part.getZ(),
|
||||
particleCount,
|
||||
randomAltX ? RNG.r.d(-particleAltX, particleAltX) : particleAltX,
|
||||
randomAltY ? RNG.r.d(-particleAltY, particleAltY) : particleAltY,
|
||||
randomAltZ ? RNG.r.d(-particleAltZ, particleAltZ) : particleAltZ,
|
||||
extra);
|
||||
} else {
|
||||
p.getWorld().spawnParticle(particleType, part.getX(), part.getY() + RNG.r.i(particleOffset), part.getZ(),
|
||||
particleCount,
|
||||
randomAltX ? RNG.r.d(-particleAltX, particleAltX) : particleAltX,
|
||||
randomAltY ? RNG.r.d(-particleAltY, particleAltY) : particleAltY,
|
||||
randomAltZ ? RNG.r.d(-particleAltZ, particleAltZ) : particleAltZ);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -19,70 +19,20 @@
|
||||
package art.arcane.iris.engine.object.entity;
|
||||
|
||||
import art.arcane.iris.engine.object.entity.spawn.IrisSurface;
|
||||
import art.arcane.iris.engine.object.loot.InventorySlotType;
|
||||
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.iris.engine.object.marker.IrisCommand;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.spi.IrisServices;
|
||||
import art.arcane.iris.core.IrisSettings;
|
||||
import art.arcane.iris.core.link.Identifier;
|
||||
import art.arcane.iris.core.loader.IrisRegistrant;
|
||||
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.engine.framework.LootResolver;
|
||||
import art.arcane.iris.engine.platform.EngineBukkitOps;
|
||||
import art.arcane.iris.engine.object.annotations.ArrayType;
|
||||
import art.arcane.iris.engine.object.annotations.Desc;
|
||||
import art.arcane.iris.engine.object.annotations.RegistryListEntityType;
|
||||
import art.arcane.iris.engine.object.annotations.RegistryListSpecialEntity;
|
||||
import art.arcane.iris.engine.object.annotations.Required;
|
||||
import art.arcane.iris.platform.bukkit.BukkitPlatform;
|
||||
import art.arcane.iris.util.common.data.registry.RegistryUtil;
|
||||
import art.arcane.iris.platform.bukkit.BukkitWorld;
|
||||
import art.arcane.iris.spi.PlatformWorld;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.iris.util.common.format.C;
|
||||
import art.arcane.volmlib.util.math.M;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import art.arcane.iris.util.common.plugin.Chunks;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
import art.arcane.volmlib.util.scheduling.PrecisionStopwatch;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.NamespacedKey;
|
||||
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.Villager;
|
||||
import org.bukkit.entity.Panda.Gene;
|
||||
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.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;
|
||||
|
||||
@SuppressWarnings("ALL")
|
||||
@Accessors(chain = true)
|
||||
@@ -194,355 +144,10 @@ public class IrisEntity extends IrisRegistrant {
|
||||
@Desc("Run raw commands when this entity is spawned. Use {x}, {y}, and {z} for location. /summon pig {x} {y} {z}")
|
||||
private KList<IrisCommand> rawCommands = new KList<>();
|
||||
|
||||
public EntityType getBukkitType() {
|
||||
if (type == null || type.isBlank()) {
|
||||
return EntityType.UNKNOWN;
|
||||
}
|
||||
|
||||
NamespacedKey key = NamespacedKey.fromString(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;
|
||||
}
|
||||
|
||||
public CreatureSpawnEvent.SpawnReason getBukkitReason() {
|
||||
if (reason == null || reason.isBlank()) {
|
||||
return CreatureSpawnEvent.SpawnReason.NATURAL;
|
||||
}
|
||||
|
||||
try {
|
||||
return CreatureSpawnEvent.SpawnReason.valueOf(reason.trim().toUpperCase(Locale.ROOT));
|
||||
} catch (IllegalArgumentException e) {
|
||||
return CreatureSpawnEvent.SpawnReason.NATURAL;
|
||||
}
|
||||
}
|
||||
|
||||
public Gene getBukkitPandaMainGene() {
|
||||
return resolveGene(pandaMainGene);
|
||||
}
|
||||
|
||||
public Gene getBukkitPandaHiddenGene() {
|
||||
return resolveGene(pandaHiddenGene);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
public Entity spawn(Engine gen, Location at) {
|
||||
return spawn(gen, at, new RNG(at.hashCode()));
|
||||
}
|
||||
|
||||
public Entity spawn(Engine gen, Location at, RNG rng) {
|
||||
if (!Chunks.isSafe(at)) {
|
||||
return null;
|
||||
}
|
||||
if (isSpawnEffectRiseOutOfGround()) {
|
||||
AtomicReference<Location> f = new AtomicReference<>(at);
|
||||
try {
|
||||
J.sfut(() -> {
|
||||
if (Chunks.hasPlayersNearby(f.get())) {
|
||||
Location b = f.get().clone();
|
||||
Location start = new Location(b.getWorld(), b.getX(), b.getY() - 5, b.getZ());
|
||||
f.set(start);
|
||||
}
|
||||
}).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);
|
||||
}
|
||||
at = f.get();
|
||||
}
|
||||
|
||||
Entity ee = doSpawn(at);
|
||||
|
||||
if (ee == null && !Chunks.isSafe(at)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isSpecialType() && !applySettingsToCustomMobAnyways) {
|
||||
return ee;
|
||||
}
|
||||
|
||||
if (ee == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Entity e = ee;
|
||||
e.setCustomName(getCustomName() != null ? C.translateAlternateColorCodes('&', getCustomName()) : null);
|
||||
e.setCustomNameVisible(isCustomNameVisible());
|
||||
e.setGlowing(isGlowing());
|
||||
e.setGravity(isGravity());
|
||||
e.setInvulnerable(isInvulnerable());
|
||||
e.setSilent(isSilent());
|
||||
e.setPersistent(isKeepEntity() || IrisSettings.get().getWorld().isForcePersistEntities());
|
||||
|
||||
int gg = 0;
|
||||
for (IrisEntity i : passengers) {
|
||||
Entity passenger = i.spawn(gen, at, rng.nextParallelRNG(234858 + gg++));
|
||||
if (passenger == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Bukkit.isPrimaryThread()) {
|
||||
e.addPassenger(passenger);
|
||||
} else {
|
||||
J.runEntity(e, () -> e.addPassenger(passenger));
|
||||
}
|
||||
}
|
||||
|
||||
if (e instanceof Attributable) {
|
||||
Attributable a = (Attributable) e;
|
||||
|
||||
for (IrisAttributeModifier i : getAttributes()) {
|
||||
i.apply(rng, a);
|
||||
}
|
||||
}
|
||||
|
||||
if (e instanceof Lootable) {
|
||||
Lootable l = (Lootable) e;
|
||||
|
||||
if (getLoot().getTables().isNotEmpty()) {
|
||||
BukkitOps.bindLoot(this, gen, l, at, rng);
|
||||
}
|
||||
}
|
||||
|
||||
if (e instanceof LivingEntity) {
|
||||
LivingEntity l = (LivingEntity) e;
|
||||
l.setAI(isAi());
|
||||
l.setCanPickupItems(isPickupItems());
|
||||
|
||||
if (getLeashHolder() != null) {
|
||||
l.setLeashHolder(getLeashHolder().spawn(gen, at, rng.nextParallelRNG(234548)));
|
||||
}
|
||||
|
||||
l.setRemoveWhenFarAway(isRemovable());
|
||||
|
||||
if (getHelmet() != null && LootResolver.oneIn(rng, getHelmet().getRarity())) {
|
||||
l.getEquipment().setHelmet(getHelmet().get(gen.isStudio(), rng));
|
||||
}
|
||||
|
||||
if (getChestplate() != null && LootResolver.oneIn(rng, getChestplate().getRarity())) {
|
||||
l.getEquipment().setChestplate(getChestplate().get(gen.isStudio(), rng));
|
||||
}
|
||||
|
||||
if (getLeggings() != null && LootResolver.oneIn(rng, getLeggings().getRarity())) {
|
||||
l.getEquipment().setLeggings(getLeggings().get(gen.isStudio(), rng));
|
||||
}
|
||||
|
||||
if (getBoots() != null && LootResolver.oneIn(rng, getBoots().getRarity())) {
|
||||
l.getEquipment().setBoots(getBoots().get(gen.isStudio(), rng));
|
||||
}
|
||||
|
||||
if (getMainHand() != null && LootResolver.oneIn(rng, getMainHand().getRarity())) {
|
||||
l.getEquipment().setItemInMainHand(getMainHand().get(gen.isStudio(), rng));
|
||||
}
|
||||
|
||||
if (getOffHand() != null && LootResolver.oneIn(rng, getOffHand().getRarity())) {
|
||||
l.getEquipment().setItemInOffHand(getOffHand().get(gen.isStudio(), rng));
|
||||
}
|
||||
}
|
||||
|
||||
if (e instanceof Ageable && isBaby()) {
|
||||
((Ageable) e).setBaby();
|
||||
}
|
||||
|
||||
if (e instanceof Panda) {
|
||||
((Panda) e).setMainGene(getBukkitPandaMainGene());
|
||||
((Panda) e).setHiddenGene(getBukkitPandaHiddenGene());
|
||||
}
|
||||
|
||||
if (e instanceof Villager) {
|
||||
Villager villager = (Villager) e;
|
||||
villager.setRemoveWhenFarAway(false);
|
||||
BukkitOps.persistVillager(villager);
|
||||
}
|
||||
|
||||
if (e instanceof Mob) {
|
||||
Mob m = (Mob) e;
|
||||
m.setAware(isAware());
|
||||
}
|
||||
|
||||
if (spawnEffect != null) {
|
||||
spawnEffect.apply(e);
|
||||
}
|
||||
|
||||
if (rawCommands.isNotEmpty()) {
|
||||
final Location fat = at;
|
||||
final PlatformWorld commandWorld = new BukkitWorld(fat.getWorld());
|
||||
rawCommands.forEach(r -> r.run(commandWorld, fat.getBlockX(), fat.getBlockY(), fat.getBlockZ()));
|
||||
}
|
||||
|
||||
Location finalAt1 = at;
|
||||
|
||||
J.runEntity(e, () -> {
|
||||
if (isSpawnEffectRiseOutOfGround() && e instanceof LivingEntity && Chunks.hasPlayersNearby(finalAt1)) {
|
||||
LivingEntity living = (LivingEntity) e;
|
||||
Location start = finalAt1.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(100000);
|
||||
Runnable restore = () -> restoreRiseState(e, living, originalInvulnerable, originalAi,
|
||||
originalCollidable, originalNoDamageTicks);
|
||||
AtomicInteger t = new AtomicInteger(0);
|
||||
Runnable[] loop = new Runnable[1];
|
||||
loop[0] = () -> {
|
||||
if (t.get() > 100 || 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, 0.1, 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(0.2)) {
|
||||
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();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
return e;
|
||||
}
|
||||
|
||||
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 int surfaceY(Location l) {
|
||||
int m = l.getBlockY();
|
||||
|
||||
while (m-- > 0) {
|
||||
Location ll = l.clone();
|
||||
ll.setY(m);
|
||||
|
||||
if (ll.getBlock().getType().isSolid()) {
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private Entity doSpawn(Location at) {
|
||||
if (!Chunks.isSafe(at)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (EntityType.UNKNOWN.equals(getBukkitType()) && !isSpecialType()) {
|
||||
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(at)))) {
|
||||
return null;
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
return null;
|
||||
}
|
||||
PrecisionStopwatch p = PrecisionStopwatch.start();
|
||||
|
||||
while (ae.get() == null) {
|
||||
J.sleep(25);
|
||||
|
||||
if (p.getMilliseconds() > 500) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return ae.get();
|
||||
}
|
||||
|
||||
if (isSpecialType()) {
|
||||
return IrisServices.get(ExternalDataSVC.class).spawnMob(at, Identifier.fromString(specialType));
|
||||
}
|
||||
|
||||
|
||||
return BukkitPlatform.spawnEntity(at, getBukkitType(), getBukkitReason());
|
||||
}
|
||||
|
||||
public boolean isSpecialType() {
|
||||
return specialType != null && !specialType.equals("");
|
||||
}
|
||||
|
||||
private static final class BukkitOps {
|
||||
private static void persistVillager(Villager villager) {
|
||||
villager.setPersistent(true);
|
||||
}
|
||||
|
||||
private static void bindLoot(IrisEntity entity, Engine gen, Lootable l, Location finalAt, RNG rng) {
|
||||
l.setLootTable(new LootTable() {
|
||||
@Override
|
||||
public NamespacedKey getKey() {
|
||||
return new NamespacedKey("iris", "loot-" + entity.hashCode());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<ItemStack> populateLoot(Random random, LootContext context) {
|
||||
KList<ItemStack> items = new KList<>();
|
||||
|
||||
for (String fi : entity.getLoot().getTables()) {
|
||||
IrisLootTable i = gen.getData().getLootLoader().load(fi);
|
||||
items.addAll(i.getLoot(gen.isStudio(), gen.getSeedManager().getLoot(), InventorySlotType.STORAGE, finalAt.getWorld(), finalAt.getBlockX(), finalAt.getBlockY(), finalAt.getBlockZ()));
|
||||
}
|
||||
|
||||
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, rng);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFolderName() {
|
||||
return "entities";
|
||||
|
||||
@@ -18,37 +18,22 @@
|
||||
|
||||
package art.arcane.iris.engine.object.entity;
|
||||
|
||||
import art.arcane.iris.engine.spawn.SpawnResources;
|
||||
import art.arcane.iris.engine.object.entity.spawn.IrisSpawner;
|
||||
import art.arcane.iris.engine.object.marker.IrisMarker;
|
||||
import art.arcane.iris.engine.object.value.IRare;
|
||||
import art.arcane.iris.engine.object.value.IrisPosition;
|
||||
import art.arcane.iris.platform.bukkit.BukkitWorldBinding;
|
||||
import art.arcane.iris.platform.bukkit.BukkitPlatform;
|
||||
import art.arcane.iris.engine.data.cache.AtomicCache;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.framework.LootResolver;
|
||||
import art.arcane.iris.engine.object.annotations.Desc;
|
||||
import art.arcane.iris.engine.object.annotations.MinNumber;
|
||||
import art.arcane.iris.engine.object.annotations.RegistryListResource;
|
||||
import art.arcane.iris.engine.object.annotations.Required;
|
||||
import art.arcane.iris.engine.object.annotations.Snippet;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.util.common.format.C;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import art.arcane.volmlib.util.math.Vector3d;
|
||||
import art.arcane.volmlib.util.matter.MatterMarker;
|
||||
import art.arcane.volmlib.util.matter.slices.MarkerMatter;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
import org.bukkit.Chunk;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Entity;
|
||||
|
||||
@Snippet("entity-spawn")
|
||||
@Accessors(chain = true)
|
||||
@@ -75,164 +60,7 @@ public class IrisEntitySpawn implements IRare {
|
||||
private transient IrisSpawner referenceSpawner;
|
||||
private transient IrisMarker referenceMarker;
|
||||
|
||||
public int spawn(Engine gen, Chunk c, RNG rng) {
|
||||
int spawns = LootResolver.inclusive(rng, minSpawns, maxSpawns);
|
||||
int s = 0;
|
||||
|
||||
if (spawns > 0) {
|
||||
for (int id = 0; id < spawns; id++) {
|
||||
int x = (c.getX() * 16) + rng.i(16);
|
||||
int z = (c.getZ() * 16) + rng.i(16);
|
||||
World world = BukkitWorldBinding.tryBind(gen.getWorld()) ? BukkitWorldBinding.world(gen.getWorld()) : null;
|
||||
int h = gen.getHeight(x, z, true) + (world == null ? -64 : world.getMinHeight());
|
||||
int hf = gen.getHeight(x, z, false) + (world == null ? -64 : world.getMinHeight());
|
||||
Location l = switch (getReferenceSpawner().getGroup()) {
|
||||
case NORMAL -> new Location(c.getWorld(), x, hf + 1, z);
|
||||
case CAVE -> findCaveSpawnLocation(gen, c, rng);
|
||||
case UNDERWATER, BEACH -> new Location(c.getWorld(), x, rng.i(h + 1, hf), z);
|
||||
};
|
||||
|
||||
if (l != null) {
|
||||
if (referenceSpawner.getAllowedLightLevels().getMin() > 0 || referenceSpawner.getAllowedLightLevels().getMax() < 15) {
|
||||
if (referenceSpawner.getAllowedLightLevels().contains(l.getBlock().getLightLevel())) {
|
||||
if (spawn100(gen, l) != null) {
|
||||
s++;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (spawn100(gen, l) != null) {
|
||||
s++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
public int spawn(Engine gen, IrisPosition c, RNG rng) {
|
||||
int spawns = LootResolver.inclusive(rng, minSpawns, maxSpawns);
|
||||
int s = 0;
|
||||
|
||||
if (!BukkitWorldBinding.tryBind(gen.getWorld())) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
World world = BukkitWorldBinding.world(gen.getWorld());
|
||||
if (spawns > 0) {
|
||||
|
||||
if (referenceMarker != null && referenceMarker.shouldExhaust()) {
|
||||
if (J.isFolia()) {
|
||||
J.a(() -> gen.getMantle().getMantle().remove(c.getX(), c.getY() - gen.getWorld().minHeight(), c.getZ(), MatterMarker.class));
|
||||
} else {
|
||||
gen.getMantle().getMantle().remove(c.getX(), c.getY() - gen.getWorld().minHeight(), c.getZ(), MatterMarker.class);
|
||||
}
|
||||
}
|
||||
|
||||
for (int id = 0; id < spawns; id++) {
|
||||
Location l = BukkitPlatform.toLocation(c, world).add(0, 1, 0);
|
||||
|
||||
if (referenceSpawner.getAllowedLightLevels().getMin() > 0 || referenceSpawner.getAllowedLightLevels().getMax() < 15) {
|
||||
if (referenceSpawner.getAllowedLightLevels().contains(l.getBlock().getLightLevel())) {
|
||||
if (spawn100(gen, l, true) != null) {
|
||||
s++;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (spawn100(gen, l, true) != null) {
|
||||
s++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
public IrisEntity getRealEntity(Engine g) {
|
||||
return ent.aquire(() -> g.getData().getEntityLoader().load(getEntity()));
|
||||
}
|
||||
|
||||
public Entity spawn(Engine g, Location at) {
|
||||
if (getRealEntity(g) == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (LootResolver.oneIn(rng.aquire(() -> new RNG(g.getSeedManager().getEntity())), getRarity())) {
|
||||
return spawn100(g, at);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
static Location findCaveSpawnLocation(Engine engine, Chunk chunk, RNG rng) {
|
||||
if (J.isFolia()) {
|
||||
return null;
|
||||
}
|
||||
KList<IrisPosition> markers = engine.getMantle().findMarkers(chunk.getX(), chunk.getZ(), MarkerMatter.CAVE_FLOOR);
|
||||
return selectCaveSpawnLocation(markers, chunk.getWorld(), rng);
|
||||
}
|
||||
|
||||
static Location selectCaveSpawnLocation(KList<IrisPosition> markers, World world, RNG rng) {
|
||||
return markers.convert((marker) -> BukkitPlatform.toLocation(marker, world).add(0, 1, 0)).getRandom(rng);
|
||||
}
|
||||
|
||||
private Entity spawn100(Engine g, Location at) {
|
||||
return spawn100(g, at, false);
|
||||
}
|
||||
|
||||
private Entity spawn100(Engine g, Location at, boolean ignoreSurfaces) {
|
||||
try {
|
||||
IrisEntity irisEntity = getRealEntity(g);
|
||||
if (irisEntity == null) { // No entity
|
||||
IrisLogging.debug(" You are trying to spawn an entity that does not exist!");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!ignoreSurfaces && !irisEntity.getSurface().matches(at.clone().subtract(0, 1, 0).getBlock())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Vector3d boundingBox = BukkitPlatform.entityBoundingBox(irisEntity.getBukkitType());
|
||||
if (!ignoreSurfaces && boundingBox != null) {
|
||||
boolean isClearForSpawn = isAreaClearForSpawn(at, boundingBox);
|
||||
if (!isClearForSpawn) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Entity e = irisEntity.spawn(g, at.add(0.5, 0.5, 0.5), rng.aquire(() -> new RNG(g.getSeedManager().getEntity())));
|
||||
if (e != null) {
|
||||
IrisLogging.debug("Spawned " + C.DARK_AQUA + "Entity<" + getEntity() + "> " + C.GREEN + e.getType() + C.LIGHT_PURPLE + " @ " + C.GRAY + e.getLocation().getX() + ", " + e.getLocation().getY() + ", " + e.getLocation().getZ());
|
||||
}
|
||||
|
||||
return e;
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError(e);
|
||||
IrisLogging.error(" Failed to retrieve real entity @ " + at + " (entity: " + getEntity() + ")");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private 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);
|
||||
|
||||
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;
|
||||
return ent.aquire(() -> SpawnResources.entity(g.getData(), getEntity()));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package art.arcane.iris.engine.object.entity.spawn;
|
||||
|
||||
import art.arcane.iris.engine.spawn.SpawnResources;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.volmlib.util.collection.KMap;
|
||||
import lombok.EqualsAndHashCode;
|
||||
@@ -23,7 +24,7 @@ public class IrisSpawnerCooldowns {
|
||||
|
||||
public void cleanup(Engine engine) {
|
||||
cooldowns.values().removeIf(cd -> {
|
||||
IrisSpawner sp = engine.getData().getSpawnerLoader().load(cd.getSpawner());
|
||||
IrisSpawner sp = SpawnResources.spawner(engine.getData(), cd.getSpawner());
|
||||
return sp == null || cd.canSpawn(sp.getMaximumRate());
|
||||
});
|
||||
}
|
||||
|
||||
@@ -19,9 +19,6 @@
|
||||
package art.arcane.iris.engine.object.entity.spawn;
|
||||
|
||||
import art.arcane.iris.engine.object.annotations.Desc;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.block.data.Waterlogged;
|
||||
|
||||
@Desc("The type of surface entities should spawn on")
|
||||
public enum IrisSurface {
|
||||
@@ -40,29 +37,4 @@ public enum IrisSurface {
|
||||
|
||||
@Desc("Within lava")
|
||||
LAVA;
|
||||
|
||||
/**
|
||||
* Check if this Iris surface matches the blockstate provided
|
||||
*
|
||||
* @param state The blockstate
|
||||
* @return True if it matches
|
||||
*/
|
||||
public boolean matches(Block state) {
|
||||
Material type = state.getType();
|
||||
if (type.isSolid()) {
|
||||
return this == LAND || this == OVERWORLD || (this == ANIMAL
|
||||
&& (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));
|
||||
}
|
||||
if (type == Material.LAVA) return this == LAVA;
|
||||
if (type == Material.WATER || type == Material.SEAGRASS
|
||||
|| type == Material.TALL_SEAGRASS || type == Material.KELP_PLANT
|
||||
|| type == Material.KELP ||
|
||||
(state instanceof Waterlogged && ((Waterlogged) state).isWaterlogged()))
|
||||
return this == WATER || this == OVERWORLD;
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import art.arcane.iris.engine.object.material.IrisBlockData;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.engine.data.cache.AtomicCache;
|
||||
import art.arcane.iris.engine.framework.LootResolver;
|
||||
import art.arcane.iris.engine.loot.LootItems;
|
||||
import art.arcane.iris.engine.object.annotations.ArrayType;
|
||||
import art.arcane.iris.engine.object.annotations.Desc;
|
||||
import art.arcane.iris.engine.object.annotations.Required;
|
||||
@@ -33,8 +34,9 @@ import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import lombok.experimental.Accessors;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import com.volmit.item.ItemDrop;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Snippet("block-drops")
|
||||
@Accessors(chain = true)
|
||||
@@ -43,7 +45,7 @@ import org.bukkit.inventory.ItemStack;
|
||||
@Desc("Represents a block drop list")
|
||||
@Data
|
||||
public class IrisBlockDrops {
|
||||
private final transient AtomicCache<KList<BlockData>> data = new AtomicCache<>();
|
||||
private final transient AtomicCache<KList<PlatformBlockState>> data = new AtomicCache<>();
|
||||
@Required
|
||||
@ArrayType(min = 1, type = IrisBlockData.class)
|
||||
@Desc("The blocks that drop loot")
|
||||
@@ -58,23 +60,23 @@ public class IrisBlockDrops {
|
||||
@Desc("Removes the default vanilla block drops and only drops the given items & any parent loot tables specified for this block type.")
|
||||
private boolean replaceVanillaDrops = false;
|
||||
|
||||
public boolean shouldDropFor(BlockData data, IrisData rdata) {
|
||||
KList<BlockData> list = this.data.aquire(() -> {
|
||||
KList<BlockData> b = new KList<>();
|
||||
public boolean shouldDropFor(PlatformBlockState broken, IrisData rdata) {
|
||||
KList<PlatformBlockState> list = this.data.aquire(() -> {
|
||||
KList<PlatformBlockState> b = new KList<>();
|
||||
|
||||
for (IrisBlockData i : getBlocks()) {
|
||||
PlatformBlockState state = i.getBlockData(rdata);
|
||||
|
||||
if (state != null) {
|
||||
b.add((BlockData) state.nativeHandle());
|
||||
b.add(state);
|
||||
}
|
||||
}
|
||||
|
||||
return b.removeDuplicates();
|
||||
});
|
||||
|
||||
for (BlockData i : list) {
|
||||
if (exactBlocks ? i.equals(data) : i.getMaterial().equals(data.getMaterial())) {
|
||||
for (PlatformBlockState i : list) {
|
||||
if (exactBlocks ? i.key().equals(broken.key()) : materialOf(i).equals(materialOf(broken))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -82,11 +84,22 @@ public class IrisBlockDrops {
|
||||
return false;
|
||||
}
|
||||
|
||||
public void fillDrops(boolean debug, KList<ItemStack> d) {
|
||||
/** Adds the items of the drops that pass their rarity to {@code d}. */
|
||||
public void fillDrops(LootItems items, List<ItemDrop> d) {
|
||||
for (IrisLoot i : getDrops()) {
|
||||
if (LootResolver.oneIn(RNG.r, i.getRarity())) {
|
||||
d.add(i.get(debug, RNG.r));
|
||||
if (!LootResolver.oneIn(RNG.r, i.getRarity())) {
|
||||
continue;
|
||||
}
|
||||
ItemDrop drop = items.give(i, RNG.r);
|
||||
if (drop != null) {
|
||||
d.add(drop);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String materialOf(PlatformBlockState state) {
|
||||
String key = state.key();
|
||||
int properties = key.indexOf('[');
|
||||
return properties < 0 ? key : key.substring(0, properties);
|
||||
}
|
||||
}
|
||||
@@ -31,13 +31,7 @@ import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.Registry;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
|
||||
@Snippet("enchantment")
|
||||
@@ -65,40 +59,6 @@ public class IrisEnchantment {
|
||||
@Desc("The chance that this enchantment is applied (0 to 1)")
|
||||
private double chance = 1;
|
||||
|
||||
public void apply(RNG rng, ItemMeta meta) {
|
||||
try {
|
||||
Enchantment enchant = resolve();
|
||||
if (enchant == null) {
|
||||
IrisLogging.warn("Unknown Enchantment: " + getEnchantment());
|
||||
return;
|
||||
}
|
||||
if (rng.nextDouble() < chance) {
|
||||
if (meta instanceof EnchantmentStorageMeta) {
|
||||
((EnchantmentStorageMeta) meta).addStoredEnchant(enchant, getLevel(rng), true);
|
||||
return;
|
||||
}
|
||||
meta.addEnchant(enchant, getLevel(rng), true);
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError(e);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the authored key against the live enchantment registry. Accepts a bare path
|
||||
* ({@code sharpness}) or a full namespaced key ({@code mymod:vorpal}) - parity with the modded resolver.
|
||||
*/
|
||||
private Enchantment resolve() {
|
||||
String raw = getEnchantment();
|
||||
if (raw == null || 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);
|
||||
}
|
||||
|
||||
public int getLevel(RNG rng) {
|
||||
return LootResolver.inclusive(rng, getMinLevel(), getMaxLevel());
|
||||
}
|
||||
|
||||
@@ -19,13 +19,6 @@
|
||||
package art.arcane.iris.engine.object.loot;
|
||||
|
||||
import art.arcane.iris.engine.object.entity.IrisAttributeModifier;
|
||||
import art.arcane.iris.platform.bukkit.BukkitBlockResolution;
|
||||
|
||||
import art.arcane.iris.spi.IrisServices;
|
||||
import art.arcane.iris.core.link.Identifier;
|
||||
import art.arcane.iris.core.service.ExternalDataSVC;
|
||||
import art.arcane.iris.engine.data.cache.AtomicCache;
|
||||
import art.arcane.iris.engine.framework.LootResolver;
|
||||
import art.arcane.iris.engine.object.annotations.ArrayType;
|
||||
import art.arcane.iris.engine.object.annotations.Desc;
|
||||
import art.arcane.iris.engine.object.annotations.MaxNumber;
|
||||
@@ -33,32 +26,14 @@ import art.arcane.iris.engine.object.annotations.MinNumber;
|
||||
import art.arcane.iris.engine.object.annotations.RegistryListItemType;
|
||||
import art.arcane.iris.engine.object.annotations.Required;
|
||||
import art.arcane.iris.engine.object.annotations.Snippet;
|
||||
import art.arcane.iris.platform.bukkit.BukkitPlatform;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.collection.KMap;
|
||||
import art.arcane.iris.util.common.format.C;
|
||||
import art.arcane.volmlib.util.format.Form;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.ToString;
|
||||
import lombok.experimental.Accessors;
|
||||
import org.bukkit.DyeColor;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.inventory.ItemFlag;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.Damageable;
|
||||
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.Optional;
|
||||
|
||||
@Snippet("loot")
|
||||
@Accessors(chain = true)
|
||||
@@ -71,7 +46,6 @@ import java.util.Optional;
|
||||
public class IrisLoot {
|
||||
public static final int MAX_AMOUNT = 64;
|
||||
|
||||
private final transient AtomicCache<DyeColor> dyeColorResolved = new AtomicCache<>();
|
||||
@Desc("The target inventory slot types to fill this loot with. World generation only ever fills STORAGE; the other values are inert during worldgen.")
|
||||
private InventorySlotType slotTypes = InventorySlotType.STORAGE;
|
||||
@MinNumber(1)
|
||||
@@ -123,175 +97,17 @@ public class IrisLoot {
|
||||
@Desc("Defines a custom NBT Tag for the item.")
|
||||
private KMap<String, Object> customNbt;
|
||||
|
||||
public Material getType() {
|
||||
return BukkitBlockResolution.getMaterial(type);
|
||||
}
|
||||
|
||||
/**
|
||||
* The authored item key, exactly as written in the pack. Platform-neutral: {@link #getType()} resolves it against
|
||||
* Bukkit, mod loaders resolve it against their own item registry.
|
||||
* The authored item key, exactly as written in the pack. Each platform resolves it against its own item registry.
|
||||
*/
|
||||
public String getTypeKey() {
|
||||
return type;
|
||||
}
|
||||
|
||||
/**
|
||||
* The authored dye colour name, or null when unset. Platform-neutral counterpart to {@link #getDyeColor()}.
|
||||
* The authored dye colour name, or null when unset.
|
||||
*/
|
||||
public String getDyeColorKey() {
|
||||
return dyeColor;
|
||||
}
|
||||
|
||||
public DyeColor getDyeColor() {
|
||||
if (dyeColor == null) {
|
||||
return null;
|
||||
}
|
||||
return dyeColorResolved.aquire(() -> {
|
||||
try {
|
||||
return DyeColor.valueOf(dyeColor);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private KList<ItemFlag> getResolvedItemFlags() {
|
||||
KList<ItemFlag> resolved = new KList<>();
|
||||
for (String flag : itemFlags) {
|
||||
if (flag == null) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
resolved.add(ItemFlag.valueOf(flag));
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
}
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
public ItemStack get(boolean debug, RNG rng) {
|
||||
try {
|
||||
ItemStack is = getItemStack(rng);
|
||||
if (is == null)
|
||||
return new ItemStack(Material.AIR);
|
||||
is.setItemMeta(applyProperties(is, rng, debug, null));
|
||||
return BukkitPlatform.applyCustomNbt(is, customNbt);
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError(e);
|
||||
return new ItemStack(Material.AIR);
|
||||
}
|
||||
}
|
||||
|
||||
public ItemStack get(boolean debug, IrisLootTable table, RNG rng, long lootSeed, int entryIndex, int x, int y, int z) {
|
||||
long combinedRarity = LootResolver.combinedRarity(rarity, table.getRarity());
|
||||
if (!LootResolver.spatialOneIn(lootSeed, table, entryIndex, x, y, z, combinedRarity)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
ItemStack is = getItemStack(rng);
|
||||
if (is == null)
|
||||
return null;
|
||||
is.setItemMeta(applyProperties(is, rng, debug, table));
|
||||
return BukkitPlatform.applyCustomNbt(is, customNbt);
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError(e);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// TODO Better Third Party Item Acquisition
|
||||
private ItemStack getItemStack(RNG rng) {
|
||||
if (!type.startsWith("minecraft:") && type.contains(":")) {
|
||||
Optional<ItemStack> opt = IrisServices.get(ExternalDataSVC.class).getItemStack(Identifier.fromString(type), customNbt);
|
||||
if (opt.isEmpty()) {
|
||||
IrisLogging.warn("Unknown Material: " + type);
|
||||
return new ItemStack(Material.AIR);
|
||||
}
|
||||
ItemStack is = opt.get();
|
||||
is.setAmount(Math.max(1, LootResolver.inclusive(rng, getMinAmount(), getMaxAmount())));
|
||||
return is;
|
||||
}
|
||||
return new ItemStack(getType(), Math.max(1, LootResolver.inclusive(rng, getMinAmount(), getMaxAmount())));
|
||||
}
|
||||
|
||||
private ItemMeta applyProperties(ItemStack is, RNG rng, boolean debug, IrisLootTable table) {
|
||||
ItemMeta m = is.getItemMeta();
|
||||
if (m == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (IrisEnchantment i : getEnchantments()) {
|
||||
i.apply(rng, m);
|
||||
}
|
||||
|
||||
for (IrisAttributeModifier i : getAttributes()) {
|
||||
i.apply(rng, m);
|
||||
}
|
||||
|
||||
m.setUnbreakable(isUnbreakable());
|
||||
for (ItemFlag i : getResolvedItemFlags()) {
|
||||
m.addItemFlags(i);
|
||||
}
|
||||
|
||||
if (getCustomModel() != null) {
|
||||
CustomModelDataComponent customModelData = m.getCustomModelDataComponent();
|
||||
customModelData.setFloats(List.of(getCustomModel().floatValue()));
|
||||
m.setCustomModelDataComponent(customModelData);
|
||||
}
|
||||
|
||||
if (is.getType().getMaxDurability() > 0 && m instanceof Damageable d) {
|
||||
int max = is.getType().getMaxDurability();
|
||||
d.setDamage((int) Math.round(Math.max(0, Math.min(max, (1D - rng.d(getMinDurability(), getMaxDurability())) * max))));
|
||||
}
|
||||
|
||||
if (getLeatherColor() != null && m instanceof LeatherArmorMeta leather) {
|
||||
Color c = Color.decode(getLeatherColor());
|
||||
leather.setColor(org.bukkit.Color.fromRGB(c.getRed(), c.getGreen(), c.getBlue()));
|
||||
}
|
||||
|
||||
if (getDyeColor() != null && m instanceof Colorable colorable) {
|
||||
colorable.setColor(getDyeColor());
|
||||
}
|
||||
|
||||
if (displayName != null) {
|
||||
m.setDisplayName(C.translateAlternateColorCodes('&', displayName));
|
||||
}
|
||||
|
||||
KList<String> lore = new KList<>();
|
||||
|
||||
getLore().forEach((i) ->
|
||||
{
|
||||
String mf = C.translateAlternateColorCodes('&', i);
|
||||
|
||||
if (mf.length() > 24) {
|
||||
for (String g : Form.wrapWords(mf, 24).split("\\Q\n\\E")) {
|
||||
lore.add(g.trim());
|
||||
}
|
||||
} else {
|
||||
lore.add(mf);
|
||||
}
|
||||
});
|
||||
|
||||
if (debug) {
|
||||
if (table == null) {
|
||||
if (lore.isNotEmpty()) {
|
||||
lore.add(C.GRAY + "--------------------");
|
||||
}
|
||||
lore.add(C.GRAY + "1 in " + (getRarity()) + " Chance (" + Form.pc(1D / (getRarity()), 5) + ")");
|
||||
} else {
|
||||
if (lore.isNotEmpty()) {
|
||||
lore.add(C.GRAY + "--------------------");
|
||||
}
|
||||
|
||||
lore.add(C.GRAY + "From: " + table.getName() + " (" + Form.pc(1D / table.getRarity(), 5) + ")");
|
||||
lore.add(C.GRAY + "1 in " + (table.getRarity() * getRarity()) + " Chance (" + Form.pc(1D / (table.getRarity() * getRarity()), 5) + ")");
|
||||
}
|
||||
}
|
||||
|
||||
m.setLore(lore);
|
||||
|
||||
return m;
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
package art.arcane.iris.engine.object.loot;
|
||||
|
||||
import art.arcane.iris.engine.loot.LootResources;
|
||||
import art.arcane.iris.engine.data.cache.AtomicCache;
|
||||
import art.arcane.iris.engine.object.annotations.ArrayType;
|
||||
import art.arcane.iris.engine.object.annotations.Desc;
|
||||
@@ -59,7 +60,7 @@ public class IrisLootReference {
|
||||
KList<IrisLootTable> t = new KList<>();
|
||||
|
||||
for (String i : tables) {
|
||||
t.add(g.getData().getLootLoader().load(i));
|
||||
t.add(LootResources.table(g.getData(), i));
|
||||
}
|
||||
|
||||
return t;
|
||||
|
||||
@@ -19,22 +19,17 @@
|
||||
package art.arcane.iris.engine.object.loot;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisRegistrant;
|
||||
import art.arcane.iris.engine.framework.LootResolver;
|
||||
import art.arcane.iris.engine.object.annotations.ArrayType;
|
||||
import art.arcane.iris.engine.object.annotations.Desc;
|
||||
import art.arcane.iris.engine.object.annotations.MaxNumber;
|
||||
import art.arcane.iris.engine.object.annotations.MinNumber;
|
||||
import art.arcane.iris.engine.object.annotations.Required;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@@ -74,35 +69,6 @@ public class IrisLootTable extends IrisRegistrant {
|
||||
@ArrayType(min = 1, type = IrisLoot.class)
|
||||
private KList<IrisLoot> loot = new KList<>();
|
||||
|
||||
public KList<ItemStack> getLoot(boolean debug, long lootSeed, InventorySlotType slot, World world, int x, int y, int z) {
|
||||
KList<ItemStack> lootf = new KList<>();
|
||||
if (loot.isEmpty() || maxTries <= 0) {
|
||||
return lootf;
|
||||
}
|
||||
|
||||
RNG rng = LootResolver.tableRng(lootSeed, this, x, y, z);
|
||||
int m = 0;
|
||||
int c = 0;
|
||||
int mx = Math.max(0, LootResolver.inclusive(rng, getMinPicked(), getMaxPicked()));
|
||||
|
||||
while (m < mx && c++ < getMaxTries()) {
|
||||
int num = rng.nextInt(loot.size());
|
||||
|
||||
IrisLoot l = loot.get(num);
|
||||
|
||||
if (l != null && l.getSlotTypes() == slot) {
|
||||
ItemStack item = l.get(debug, this, rng, lootSeed, num, x, y, z);
|
||||
|
||||
if (item != null && item.getType() != Material.AIR) {
|
||||
lootf.add(item);
|
||||
m++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return lootf;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFolderName() {
|
||||
return "loot";
|
||||
|
||||
@@ -1,20 +1,9 @@
|
||||
package art.arcane.iris.engine.object.loot;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.engine.data.cache.AtomicCache;
|
||||
import art.arcane.iris.engine.framework.LootResolver;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.loot.LootContext;
|
||||
import org.bukkit.loot.LootTable;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
@@ -25,22 +14,13 @@ public class IrisVanillaLootTable extends IrisLootTable {
|
||||
* The vanilla loot table key ("minecraft:chests/simple_dungeon"), not the LootTable itself. A
|
||||
* raw org.bukkit.loot.LootTable field - and the constructor lombok would generate for it - makes
|
||||
* every reflective walk over the IrisLootTable hierarchy (Gson, schema generation, the purity
|
||||
* gate) resolve a Bukkit class. The table is resolved lazily at pull time, which only ever
|
||||
* happens on Bukkit. The key text is identical to what {@code LootTable.getKey().toString()}
|
||||
* produced before, so {@code LootResolver.tableIdentity} (which falls back to
|
||||
* gate) resolve a Bukkit class. The host resolves the table when it pulls loot from it. The key text is
|
||||
* identical to what {@code LootTable.getKey().toString()} produced before, so
|
||||
* {@code LootTables.identity} (which falls back to
|
||||
* {@link #getName()}) yields the same loot seed.
|
||||
*/
|
||||
private final String lootTableKey;
|
||||
|
||||
/**
|
||||
* The resolved table, looked up once. Every chest pull resolved it again - a NamespacedKey parse plus a registry
|
||||
* lookup per container, and a dungeon room is a lot of containers.
|
||||
* <p>
|
||||
* Transient for the same reason the field above is a String: it keeps the Bukkit type argument out of the Gson
|
||||
* field walk and out of the pack purity gate, both of which resolve generic field types for the fields they visit.
|
||||
*/
|
||||
private final transient AtomicCache<LootTable> resolvedTable = new AtomicCache<>();
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "Vanilla " + lootTableKey;
|
||||
@@ -71,24 +51,6 @@ public class IrisVanillaLootTable extends IrisLootTable {
|
||||
return new KList<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public KList<ItemStack> getLoot(boolean debug, long lootSeed, InventorySlotType slot, World world, int x, int y, int z) {
|
||||
LootTable table = resolveTable();
|
||||
if (table == null) {
|
||||
IrisLogging.warn("Unknown vanilla loot table " + lootTableKey);
|
||||
return new KList<>();
|
||||
}
|
||||
RNG rng = LootResolver.tableRng(lootSeed, this, x, y, z);
|
||||
return new KList<>(table.populateLoot(rng, new LootContext.Builder(new Location(world, x, y, z)).build()));
|
||||
}
|
||||
|
||||
private LootTable resolveTable() {
|
||||
return resolvedTable.aquire(() -> {
|
||||
NamespacedKey key = NamespacedKey.fromString(lootTableKey);
|
||||
return key == null ? null : Bukkit.getLootTable(key);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFolderName() {
|
||||
throw new UnsupportedOperationException("VanillaLootTables do not have a folder name");
|
||||
|
||||
@@ -24,9 +24,8 @@ import art.arcane.iris.engine.object.annotations.ArrayType;
|
||||
import art.arcane.iris.engine.object.annotations.Desc;
|
||||
import art.arcane.iris.engine.object.annotations.Required;
|
||||
import art.arcane.iris.engine.object.annotations.Snippet;
|
||||
import art.arcane.iris.spi.IrisPlatforms;
|
||||
import art.arcane.iris.spi.PlatformWorld;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
import art.arcane.iris.util.common.scheduling.ConsoleCommands;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
@@ -68,19 +67,6 @@ public class IrisCommand {
|
||||
return;
|
||||
}
|
||||
|
||||
for (String command : commands) {
|
||||
command = (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));
|
||||
final String finalCommand = command;
|
||||
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(finalCommand), safeRepeatDelay), safeDelay);
|
||||
} else {
|
||||
J.s(() -> IrisPlatforms.get().dispatchConsoleCommand(finalCommand), safeDelay);
|
||||
}
|
||||
}
|
||||
ConsoleCommands.run(commands, delay, repeat, repeatDelay, x, y, z);
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
package art.arcane.iris.engine.object.placement;
|
||||
|
||||
import art.arcane.iris.engine.spawn.SpawnResources;
|
||||
import art.arcane.iris.builtin.IrisStages;
|
||||
import art.arcane.iris.builtin.blocks.ObjectMarkers;
|
||||
import art.arcane.iris.builtin.blocks.WrittenBlocks;
|
||||
@@ -196,7 +197,7 @@ public final class BlocksModule implements IrisModule {
|
||||
RNG markerRandom = new RNG(context.random().nextLong());
|
||||
int salt = 0;
|
||||
for (IrisObjectMarker markerConfig : config.getMarkers()) {
|
||||
IrisMarker marker = placement.object().getLoader().getMarkerLoader().load(markerConfig.getMarker());
|
||||
IrisMarker marker = SpawnResources.marker(placement.object().getLoader(), markerConfig.getMarker());
|
||||
int markerSalt = salt++;
|
||||
if (marker == null) {
|
||||
continue;
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
package art.arcane.iris.engine.object.placement;
|
||||
|
||||
import art.arcane.iris.engine.loot.LootResources;
|
||||
import art.arcane.iris.core.modules.ModuleSettings;
|
||||
import art.arcane.iris.engine.object.loot.IObjectLoot;
|
||||
import art.arcane.iris.engine.object.loot.IrisLootTable;
|
||||
@@ -271,6 +272,11 @@ public class IrisObjectPlacement {
|
||||
return g.getData().getObjectLoader().load(place.get(random.nextInt(place.size())));
|
||||
}
|
||||
|
||||
/** Whether a tree placement grows the species the platform calls {@code species} for a sapling area of {@code size}. */
|
||||
public boolean matches(IrisTreeSize size, String species) {
|
||||
return matches(size, TreeType.valueOf(species));
|
||||
}
|
||||
|
||||
public boolean matches(IrisTreeSize size, TreeType type) {
|
||||
for (IrisTree i : getTrees()) {
|
||||
if (i.matches(size, type)) {
|
||||
@@ -301,7 +307,7 @@ public class IrisObjectPlacement {
|
||||
TableCache cache = new TableCache();
|
||||
|
||||
cache.merge(getCache(manager, getVanillaLoot(), IrisObjectPlacement::getVanillaTable));
|
||||
cache.merge(getCache(manager, getLoot(), manager.getLootLoader()::load));
|
||||
cache.merge(getCache(manager, getLoot(), key -> LootResources.table(manager, key)));
|
||||
|
||||
return cache;
|
||||
});
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
|
||||
package art.arcane.iris.engine.object.prefab;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.object.annotations.Desc;
|
||||
import art.arcane.iris.engine.object.annotations.MaxNumber;
|
||||
import art.arcane.iris.engine.object.annotations.MinNumber;
|
||||
@@ -49,11 +49,6 @@ public class IrisObjectScale {
|
||||
private static final long CACHE_VARIANT_ESTIMATED_BYTES = 256L;
|
||||
private static final long CACHE_ESTIMATED_BYTES_PER_VOXEL = 128L;
|
||||
private static final int CACHE_LOAD_LOCK_COUNT = 256;
|
||||
private static final ScaleCache CACHE = new ScaleCache(resolveCacheMaximumEstimatedBytes());
|
||||
|
||||
public static void invalidate(IrisData owner) {
|
||||
CACHE.invalidate(owner);
|
||||
}
|
||||
|
||||
@MinNumber(0.01)
|
||||
@MaxNumber(50)
|
||||
@@ -99,7 +94,8 @@ public class IrisObjectScale {
|
||||
return Math.max(minimumScale, maximumScale);
|
||||
}
|
||||
|
||||
public IrisObject get(RNG rng, IrisObject origin) {
|
||||
/** The scaled variant of {@code origin} this scale picks, built once per world and kept in the world's cache. */
|
||||
public IrisObject get(RNG rng, IrisObject origin, Engine engine) {
|
||||
if (origin == null) {
|
||||
return null;
|
||||
}
|
||||
@@ -110,40 +106,33 @@ public class IrisObjectScale {
|
||||
}
|
||||
|
||||
int variantIndex = request.selectVariant(rng);
|
||||
CacheKey key = CACHE.key(origin, request, variantIndex);
|
||||
CacheLookup lookup = CACHE.lookup(key);
|
||||
if (lookup.variant() != null) {
|
||||
return lookup.variant();
|
||||
ScaleCache cache = cacheOf(engine);
|
||||
CacheKey key = cache.key(origin, request, variantIndex);
|
||||
IrisObject cached = cache.lookup(key);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
synchronized (CACHE.loadLock(key)) {
|
||||
CacheLookup afterWait = CACHE.lookup(key);
|
||||
if (afterWait.variant() != null) {
|
||||
return afterWait.variant();
|
||||
synchronized (cache.loadLock(key)) {
|
||||
IrisObject afterWait = cache.lookup(key);
|
||||
if (afterWait != null) {
|
||||
return afterWait;
|
||||
}
|
||||
|
||||
IrisObject variant = origin.scaled(request.scaleAt(variantIndex), request.interpolation());
|
||||
long estimatedBytes = estimateVariant(variant);
|
||||
return CACHE.putIfCurrent(key, variant, estimatedBytes, lookup.generation());
|
||||
return cache.putIfAbsent(key, variant, estimatedBytes);
|
||||
}
|
||||
}
|
||||
|
||||
static ScaleCache cacheOf(Engine engine) {
|
||||
return engine.getGeneration().state(ScaleCache.class, world -> new ScaleCache(resolveCacheMaximumEstimatedBytes()));
|
||||
}
|
||||
|
||||
public boolean canScaleBeyond() {
|
||||
return shouldScale() && getMaxScale() > 1;
|
||||
}
|
||||
|
||||
static int cacheEntryCount() {
|
||||
return CACHE.size();
|
||||
}
|
||||
|
||||
static long cacheEstimatedBytes() {
|
||||
return CACHE.estimatedBytes();
|
||||
}
|
||||
|
||||
static boolean isOriginCached(IrisObject origin) {
|
||||
return CACHE.containsOrigin(origin);
|
||||
}
|
||||
|
||||
private ScaleRequest snapshotRequest() {
|
||||
IrisObjectPlacementScaleInterpolator configuredInterpolation = interpolation == null
|
||||
? IrisObjectPlacementScaleInterpolator.NONE
|
||||
@@ -217,7 +206,6 @@ public class IrisObjectScale {
|
||||
}
|
||||
|
||||
static final class CacheKey extends WeakReference<IrisObject> {
|
||||
private final IrisData owner;
|
||||
private final ScaleRequest request;
|
||||
private final int variantIndex;
|
||||
private final int originRevision;
|
||||
@@ -231,22 +219,16 @@ public class IrisObjectScale {
|
||||
CacheKey(IrisObject origin, ScaleRequest request, int variantIndex,
|
||||
ReferenceQueue<IrisObject> collectedOrigins) {
|
||||
super(origin, collectedOrigins);
|
||||
this.owner = origin.getLoader();
|
||||
this.request = request;
|
||||
this.variantIndex = variantIndex;
|
||||
this.originRevision = originRevision(origin);
|
||||
int result = System.identityHashCode(origin);
|
||||
result = (31 * result) + System.identityHashCode(owner);
|
||||
result = (31 * result) + originRevision;
|
||||
result = (31 * result) + request.hashCode();
|
||||
this.loadHashCode = result;
|
||||
this.hashCode = (31 * result) + variantIndex;
|
||||
}
|
||||
|
||||
boolean belongsTo(IrisData candidate) {
|
||||
return owner == candidate;
|
||||
}
|
||||
|
||||
boolean hasOrigin(IrisObject candidate) {
|
||||
return get() == candidate;
|
||||
}
|
||||
@@ -262,7 +244,6 @@ public class IrisObjectScale {
|
||||
IrisObject origin = get();
|
||||
return origin != null
|
||||
&& origin == other.get()
|
||||
&& owner == other.owner
|
||||
&& originRevision == other.originRevision
|
||||
&& request.equals(other.request)
|
||||
&& variantIndex == other.variantIndex;
|
||||
@@ -300,16 +281,12 @@ public class IrisObjectScale {
|
||||
}
|
||||
}
|
||||
|
||||
record CacheLookup(IrisObject variant, long generation) {
|
||||
}
|
||||
|
||||
static final class ScaleCache {
|
||||
private final long maximumEstimatedBytes;
|
||||
private final LinkedHashMap<CacheKey, CacheValue> entries;
|
||||
private final Object[] loadLocks;
|
||||
private final ReferenceQueue<IrisObject> collectedOrigins;
|
||||
private long estimatedBytes;
|
||||
private long generation;
|
||||
|
||||
ScaleCache(long maximumEstimatedBytes) {
|
||||
if (maximumEstimatedBytes <= 0L) {
|
||||
@@ -332,20 +309,19 @@ public class IrisObjectScale {
|
||||
return loadLocks[key.loadHashCode() & (loadLocks.length - 1)];
|
||||
}
|
||||
|
||||
synchronized CacheLookup lookup(CacheKey key) {
|
||||
synchronized IrisObject lookup(CacheKey key) {
|
||||
drainCollectedOrigins();
|
||||
CacheValue value = entries.get(key);
|
||||
return new CacheLookup(value == null ? null : value.variant(), generation);
|
||||
return value == null ? null : value.variant();
|
||||
}
|
||||
|
||||
synchronized IrisObject putIfCurrent(CacheKey key, IrisObject variant,
|
||||
long entryEstimatedBytes, long expectedGeneration) {
|
||||
synchronized IrisObject putIfAbsent(CacheKey key, IrisObject variant, long entryEstimatedBytes) {
|
||||
drainCollectedOrigins();
|
||||
CacheValue present = entries.get(key);
|
||||
if (present != null) {
|
||||
return present.variant();
|
||||
}
|
||||
if (generation != expectedGeneration || entryEstimatedBytes > maximumEstimatedBytes) {
|
||||
if (entryEstimatedBytes > maximumEstimatedBytes) {
|
||||
return variant;
|
||||
}
|
||||
|
||||
@@ -355,19 +331,6 @@ public class IrisObjectScale {
|
||||
return variant;
|
||||
}
|
||||
|
||||
synchronized void invalidate(IrisData owner) {
|
||||
drainCollectedOrigins();
|
||||
generation++;
|
||||
Iterator<Map.Entry<CacheKey, CacheValue>> iterator = entries.entrySet().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Map.Entry<CacheKey, CacheValue> entry = iterator.next();
|
||||
if (entry.getKey().belongsTo(owner)) {
|
||||
estimatedBytes -= entry.getValue().estimatedBytes();
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
synchronized int size() {
|
||||
drainCollectedOrigins();
|
||||
return entries.size();
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.spawn;
|
||||
|
||||
import art.arcane.iris.engine.framework.LootResolver;
|
||||
import art.arcane.iris.engine.loot.LootItems;
|
||||
import art.arcane.iris.engine.object.entity.IrisAttributeModifier;
|
||||
import art.arcane.iris.engine.object.entity.IrisEffect;
|
||||
import art.arcane.iris.engine.object.entity.IrisEntity;
|
||||
import art.arcane.iris.engine.object.loot.IrisLoot;
|
||||
import art.arcane.iris.engine.object.marker.IrisCommand;
|
||||
import art.arcane.iris.spi.PlatformWorld;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import com.volmit.entity.EntitySpec;
|
||||
import com.volmit.item.ItemAttribute;
|
||||
import com.volmit.item.ItemDrop;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Turns an entity of the pack into the {@link EntitySpec} the host spawns, making every random choice in the order Iris
|
||||
* always made them: the passengers, the attribute modifiers, the leash holder and then the six pieces of equipment.
|
||||
*/
|
||||
final class EntityResolution {
|
||||
private static final long PASSENGER_STREAM_BASE = 234858L;
|
||||
private static final long LEASH_HOLDER_STREAM = 234548L;
|
||||
|
||||
private final LootItems items;
|
||||
private final PlatformWorld world;
|
||||
|
||||
/** @param world the world the entity appears in, whose time and weather decide which of its commands run */
|
||||
EntityResolution(LootItems items, PlatformWorld world) {
|
||||
this.items = items;
|
||||
this.world = world;
|
||||
}
|
||||
|
||||
EntitySpec resolve(IrisEntity entity, RNG rng) {
|
||||
List<EntitySpec> passengers = new ArrayList<>();
|
||||
long passengerIndex = 0;
|
||||
for (IrisEntity passenger : entity.getPassengers()) {
|
||||
passengers.add(resolve(passenger, rng.nextParallelRNG(PASSENGER_STREAM_BASE + passengerIndex++)));
|
||||
}
|
||||
|
||||
List<ItemAttribute> attributes = drawAttributes(entity, rng);
|
||||
List<String> lootTables = List.copyOf(entity.getLoot().getTables());
|
||||
long lootShuffleSeed = lootTables.isEmpty() ? 0L : rng.nextLong();
|
||||
EntitySpec leashHolder = entity.getLeashHolder() == null ? null : resolve(entity.getLeashHolder(), rng.nextParallelRNG(LEASH_HOLDER_STREAM));
|
||||
EntitySpec.Equipment equipment = new EntitySpec.Equipment(
|
||||
equip(entity.getHelmet(), rng), equip(entity.getChestplate(), rng), equip(entity.getLeggings(), rng),
|
||||
equip(entity.getBoots(), rng), equip(entity.getMainHand(), rng), equip(entity.getOffHand(), rng));
|
||||
|
||||
return new EntitySpec(
|
||||
entity.getType() == null ? "" : entity.getType(),
|
||||
entity.getSpecialType() == null ? "" : entity.getSpecialType(),
|
||||
entity.getReason(),
|
||||
entity.getCustomName() == null ? "" : entity.getCustomName(),
|
||||
flagsOf(entity), equipment, passengers, attributes, lootTables, lootShuffleSeed, leashHolder,
|
||||
spawnEffectOf(entity), entity.isSpawnEffectRiseOutOfGround(), entity.getPandaMainGene(),
|
||||
entity.getPandaHiddenGene(), entity.isApplySettingsToCustomMobAnyways(), commandsOf(entity));
|
||||
}
|
||||
|
||||
private static EntitySpec.Flags flagsOf(IrisEntity entity) {
|
||||
return new EntitySpec.Flags(entity.isCustomNameVisible(), entity.isAware(), entity.isAi(), entity.isGlowing(),
|
||||
entity.isGravity(), entity.isInvulnerable(), entity.isSilent(), entity.isPickupItems(), entity.isRemovable(),
|
||||
entity.isKeepEntity(), entity.isBaby());
|
||||
}
|
||||
|
||||
private static List<ItemAttribute> drawAttributes(IrisEntity entity, RNG rng) {
|
||||
List<ItemAttribute> attributes = new ArrayList<>();
|
||||
for (IrisAttributeModifier modifier : entity.getAttributes()) {
|
||||
if (rng.nextDouble() >= modifier.getChance()) {
|
||||
continue;
|
||||
}
|
||||
String attribute = modifier.getAttribute();
|
||||
if (attribute == null || attribute.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
attributes.add(new ItemAttribute(attribute, modifier.getName(), modifier.getOperation(), modifier.getAmount(rng)));
|
||||
}
|
||||
return attributes;
|
||||
}
|
||||
|
||||
private ItemDrop equip(IrisLoot piece, RNG rng) {
|
||||
if (piece == null || !LootResolver.oneIn(rng, piece.getRarity())) {
|
||||
return null;
|
||||
}
|
||||
return items.give(piece, rng);
|
||||
}
|
||||
|
||||
/** The entity's spawn effect when it shows this time: an effect only shows now and then, as its interval and chance say. */
|
||||
private static EntitySpec.SpawnEffect spawnEffectOf(IrisEntity entity) {
|
||||
IrisEffect effect = entity.getSpawnEffect();
|
||||
if (effect == null || !effect.shouldApplyNow()) {
|
||||
return null;
|
||||
}
|
||||
return new EntitySpec.SpawnEffect(effect.getSoundKey(), effect.getSoundDistance(), effect.getMinPitch(),
|
||||
effect.getMaxPitch(), effect.getVolume(), effect.getParticleEffectKey(), effect.getParticleOffset(),
|
||||
effect.getParticleCount(), effect.getParticleAltX(), effect.getParticleAltY(), effect.getParticleAltZ(),
|
||||
effect.isRandomAltX(), effect.isRandomAltY(), effect.isRandomAltZ(), effect.getExtra());
|
||||
}
|
||||
|
||||
private List<EntitySpec.Command> commandsOf(IrisEntity entity) {
|
||||
List<EntitySpec.Command> commands = new ArrayList<>();
|
||||
for (IrisCommand command : entity.getRawCommands()) {
|
||||
if (command.isValid(world)) {
|
||||
commands.add(new EntitySpec.Command(command.getCommands(), command.getDelay(), command.isRepeat(), command.getRepeatDelay()));
|
||||
}
|
||||
}
|
||||
return commands;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.spawn;
|
||||
|
||||
import art.arcane.iris.core.modules.IrisPackWorld;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.framework.LootResolver;
|
||||
import art.arcane.iris.engine.loot.LootItems;
|
||||
import art.arcane.iris.engine.object.entity.IrisEntity;
|
||||
import art.arcane.iris.engine.object.entity.IrisEntitySpawn;
|
||||
import art.arcane.iris.engine.object.entity.spawn.IrisSpawner;
|
||||
import art.arcane.iris.engine.object.entity.spawn.IrisSurface;
|
||||
import art.arcane.iris.engine.object.marker.IrisMarker;
|
||||
import art.arcane.iris.engine.object.value.IRare;
|
||||
import art.arcane.iris.engine.object.value.IrisPosition;
|
||||
import art.arcane.iris.engine.object.value.IrisRange;
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
import art.arcane.iris.engine.object.world.region.IrisRegion;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import art.arcane.volmlib.util.matter.slices.MarkerMatter;
|
||||
import com.volmit.entity.EntitySpec;
|
||||
import com.volmit.service.EntitySpawns;
|
||||
import com.volmit.world.BlockPosition;
|
||||
import com.volmit.world.PackWorld;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* How {@code iris:spawn} spawns entities: the spawners of the dimension, region and surface biome that may fire in a
|
||||
* chunk, or the spawners of a marker, each with the entities it spawns and the places it picks for them. What the
|
||||
* platform decides (light, the surface, free space, the entity itself) is the host's, the plan only names it.
|
||||
*/
|
||||
public final class EntitySpawning implements EntitySpawns {
|
||||
private static final int BLOCKS_TO_CHUNK_CENTRE = 8;
|
||||
private static final int CHUNK_SIZE = 16;
|
||||
private static final String CAVE_FLOOR_MARKER = "cave_floor";
|
||||
private static final String CAVE_CEILING_MARKER = "cave_ceiling";
|
||||
private static final int AIR_ABOVE_MARKER = 1;
|
||||
|
||||
@Override
|
||||
public Optional<Plan> plan(PackWorld world, Site site) {
|
||||
Engine engine = engine(world);
|
||||
return switch (site) {
|
||||
case Chunk chunk -> planChunk(world, engine, chunk);
|
||||
case Marker marker -> planMarker(world, engine, marker);
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void spawned(PackWorld world, Plan plan, int count) {
|
||||
if (count <= 0) {
|
||||
return;
|
||||
}
|
||||
IrisSpawner spawner = SpawnResources.spawner(engine(world).getData(), plan.spawner());
|
||||
if (spawner != null) {
|
||||
spawner.spawn(engine(world), plan.chunkX(), plan.chunkZ());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<EntitySpec> entity(PackWorld world, String key) {
|
||||
IrisEntity entity = SpawnResources.entity(engine(world).getData(), key);
|
||||
if (entity == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(resolution(world, engine(world)).resolve(entity, entityRandom(world).rng()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<MarkerRule> marker(PackWorld world, String tag) {
|
||||
if (tag.equals(CAVE_FLOOR_MARKER) || tag.equals(CAVE_CEILING_MARKER)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Engine engine = engine(world);
|
||||
IrisMarker marker = SpawnResources.marker(engine.getData(), tag);
|
||||
if (marker == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
List<String> spawners = new ArrayList<>();
|
||||
for (String key : marker.getSpawners()) {
|
||||
if (SpawnResources.spawner(engine.getData(), key) == null) {
|
||||
IrisLogging.error("Cannot load spawner: " + key + " for marker " + tag);
|
||||
continue;
|
||||
}
|
||||
spawners.add(key);
|
||||
}
|
||||
return Optional.of(new MarkerRule(spawners, marker.isEmptyAbove(), marker.isRemoveOnChange()));
|
||||
}
|
||||
|
||||
private Optional<Plan> planChunk(PackWorld world, Engine engine, Chunk chunk) {
|
||||
Predicate<IrisSpawner> canSpawn = spawner -> spawner.canSpawn(engine, chunk.chunkX(), chunk.chunkZ());
|
||||
int blockX = PowerOfTwoCoordinates.chunkToBlock(chunk.chunkX());
|
||||
int blockZ = PowerOfTwoCoordinates.chunkToBlock(chunk.chunkZ());
|
||||
IrisBiome centreBiome = engine.getSurfaceBiome(blockX + BLOCKS_TO_CHUNK_CENTRE, blockZ + BLOCKS_TO_CHUNK_CENTRE);
|
||||
IrisRegion region = engine.getRegion(blockX, blockZ);
|
||||
IrisBiome biome = engine.getSurfaceBiome(blockX, blockZ);
|
||||
|
||||
List<IrisSpawner> candidates = Stream.concat(
|
||||
shuffled(engine, engine.getDimension().getEntitySpawners()).stream()
|
||||
.filter(canSpawn).filter(spawner -> spawner.isValid(centreBiome)),
|
||||
Stream.concat(
|
||||
shuffled(engine, region.getEntitySpawners()).stream().filter(canSpawn),
|
||||
shuffled(engine, biome.getEntitySpawners()).stream().filter(canSpawn)))
|
||||
.filter(spawner -> chunk.livingEntities() < spawner.getMaxEntitiesPerChunk())
|
||||
.toList();
|
||||
|
||||
List<Candidate> spawns = candidates.stream().flatMap(spawner -> spawnsOf(spawner, chunk.initial())).collect(Collectors.toList());
|
||||
Candidate chosen = IRare.expandWeighted(spawns).getRandom();
|
||||
if (chosen == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return planChunkSpawn(world, engine, chunk, chosen);
|
||||
}
|
||||
|
||||
private Optional<Plan> planChunkSpawn(PackWorld world, Engine engine, Chunk chunk, Candidate chosen) {
|
||||
IrisSpawner spawner = chosen.spawner();
|
||||
IrisEntitySpawn spawn = chosen.spawn();
|
||||
int count = LootResolver.inclusive(RNG.r, spawn.getMinSpawns(), spawn.getMaxSpawns());
|
||||
List<Attempt> attempts = new ArrayList<>();
|
||||
for (int i = 0; i < count; i++) {
|
||||
int x = (chunk.chunkX() * CHUNK_SIZE) + RNG.r.i(CHUNK_SIZE);
|
||||
int z = (chunk.chunkZ() * CHUNK_SIZE) + RNG.r.i(CHUNK_SIZE);
|
||||
BlockPosition at = spawnPosition(engine, spawner, chunk.chunkX(), chunk.chunkZ(), x, z);
|
||||
if (at != null) {
|
||||
addAttempt(attempts, world, engine, chosen, at, true);
|
||||
}
|
||||
}
|
||||
return attempts.isEmpty() ? Optional.empty() : Optional.of(new Plan(spawner.getLoadKey(), chunk.chunkX(), chunk.chunkZ(), false, attempts));
|
||||
}
|
||||
|
||||
/** Where a spawner of its group puts an entity at the column; null when it has no place for one. */
|
||||
private static BlockPosition spawnPosition(Engine engine, IrisSpawner spawner, int chunkX, int chunkZ, int x, int z) {
|
||||
int height = engine.getHeight(x, z, true);
|
||||
int heightWithFluid = engine.getHeight(x, z, false);
|
||||
return switch (spawner.getGroup()) {
|
||||
case NORMAL -> new BlockPosition(x, heightWithFluid + 1, z);
|
||||
case CAVE -> caveSpawnPosition(engine, chunkX, chunkZ);
|
||||
case UNDERWATER, BEACH -> new BlockPosition(x, RNG.r.i(height + 1, heightWithFluid), z);
|
||||
};
|
||||
}
|
||||
|
||||
static BlockPosition caveSpawnPosition(Engine engine, int chunkX, int chunkZ) {
|
||||
if (J.isFolia()) {
|
||||
return null;
|
||||
}
|
||||
KList<IrisPosition> floors = engine.getMantle().findMarkers(chunkX, chunkZ, MarkerMatter.CAVE_FLOOR);
|
||||
IrisPosition floor = floors.getRandom(RNG.r);
|
||||
return floor == null ? null : new BlockPosition(floor.getX(), floor.getY() - engine.getMinHeight() + AIR_ABOVE_MARKER, floor.getZ());
|
||||
}
|
||||
|
||||
private Optional<Plan> planMarker(PackWorld world, Engine engine, Marker marker) {
|
||||
IrisSpawner spawner = SpawnResources.spawner(engine.getData(), marker.spawner());
|
||||
IrisMarker irisMarker = SpawnResources.marker(engine.getData(), marker.marker());
|
||||
if (spawner == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
KList<IrisEntitySpawn> candidates = marker.initial() ? spawner.getInitialSpawns() : spawner.getSpawns();
|
||||
if (candidates.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
IrisEntitySpawn spawn = IRare.expandWeighted(candidates).getRandom();
|
||||
|
||||
BlockPosition position = marker.position();
|
||||
int chunkX = PowerOfTwoCoordinates.blockToChunkFloor(position.x());
|
||||
int chunkZ = PowerOfTwoCoordinates.blockToChunkFloor(position.z());
|
||||
if (!spawner.canSpawn(engine, chunkX, chunkZ)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
int count = LootResolver.inclusive(RNG.r, spawn.getMinSpawns(), spawn.getMaxSpawns());
|
||||
if (count <= 0) {
|
||||
return Optional.empty();
|
||||
}
|
||||
boolean exhaustsMarker = irisMarker != null && irisMarker.shouldExhaust();
|
||||
List<Attempt> attempts = new ArrayList<>();
|
||||
BlockPosition above = new BlockPosition(position.x(), position.y() + AIR_ABOVE_MARKER, position.z());
|
||||
for (int i = 0; i < count; i++) {
|
||||
addAttempt(attempts, world, engine, new Candidate(spawner, spawn), above, false);
|
||||
}
|
||||
return attempts.isEmpty() ? Optional.empty() : Optional.of(new Plan(spawner.getLoadKey(), chunkX, chunkZ, exhaustsMarker, attempts));
|
||||
}
|
||||
|
||||
private void addAttempt(List<Attempt> attempts, PackWorld world, Engine engine, Candidate candidate, BlockPosition at, boolean checkSurface) {
|
||||
IrisEntity entity = candidate.spawn().getRealEntity(engine);
|
||||
if (entity == null) {
|
||||
IrisLogging.debug(" You are trying to spawn an entity that does not exist!");
|
||||
return;
|
||||
}
|
||||
|
||||
IrisRange light = candidate.spawner().getAllowedLightLevels();
|
||||
EntitySpec spec = resolution(world, engine).resolve(entity, entityRandom(world).rng());
|
||||
attempts.add(new Attempt(at, spec, surfaceOf(entity.getSurface()),
|
||||
(int) Math.ceil(light.getMin()), (int) Math.floor(light.getMax()), checkSurface));
|
||||
}
|
||||
|
||||
private static EntityResolution resolution(PackWorld world, Engine engine) {
|
||||
LootItems items = new LootItems(world.resources().items(), engine.isStudio());
|
||||
return new EntityResolution(items, engine.getWorld().platformWorld());
|
||||
}
|
||||
|
||||
private static EntityRandom entityRandom(PackWorld world) {
|
||||
return world.state(EntityRandom.class, EntityRandom::new);
|
||||
}
|
||||
|
||||
private static Surface surfaceOf(IrisSurface surface) {
|
||||
return Surface.valueOf(surface.name());
|
||||
}
|
||||
|
||||
private static KList<IrisSpawner> shuffled(Engine engine, KList<String> keys) {
|
||||
return SpawnResources.spawners(engine.getData(), keys).shuffleCopy(RNG.r);
|
||||
}
|
||||
|
||||
private static Stream<Candidate> spawnsOf(IrisSpawner spawner, boolean initial) {
|
||||
KList<IrisEntitySpawn> spawns = initial ? spawner.getInitialSpawns() : spawner.getSpawns();
|
||||
return spawns.stream().map(spawn -> new Candidate(spawner, spawn));
|
||||
}
|
||||
|
||||
/** A spawn of a spawner, which picks as often as the spawn's rarity says. */
|
||||
private record Candidate(IrisSpawner spawner, IrisEntitySpawn spawn) implements IRare {
|
||||
@Override
|
||||
public int getRarity() {
|
||||
return spawn.getRarity();
|
||||
}
|
||||
}
|
||||
|
||||
private static Engine engine(PackWorld world) {
|
||||
return IrisPackWorld.of(world).engine();
|
||||
}
|
||||
|
||||
/** The random stream entities are made from, seeded from the world like Iris always seeded it; one per world. */
|
||||
private static final class EntityRandom {
|
||||
private final RNG rng;
|
||||
|
||||
private EntityRandom(PackWorld world) {
|
||||
this.rng = new RNG(IrisPackWorld.of(world).engine().getSeedManager().getEntity());
|
||||
}
|
||||
|
||||
private RNG rng() {
|
||||
return rng;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.spawn;
|
||||
|
||||
import com.volmit.FeatureRegistry;
|
||||
import com.volmit.IrisModule;
|
||||
import com.volmit.ModuleInfo;
|
||||
import com.volmit.service.EntitySpawns;
|
||||
import com.volmit.stage.StageGraph;
|
||||
|
||||
/**
|
||||
* Module {@code iris:spawn}: the spawners, entities and markers of the pack ({@link SpawnResources}), and the entities that appear in the world
|
||||
* over time because of them. It has no generation stage; Iris asks it through {@link EntitySpawns} when it looks for
|
||||
* something to spawn in a chunk or at a marker.
|
||||
*/
|
||||
public final class SpawnModule implements IrisModule {
|
||||
private static final String VERSION = "built-in";
|
||||
|
||||
@Override
|
||||
public ModuleInfo info() {
|
||||
return ModuleInfo.of("iris:spawn", "Spawn", VERSION);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void install(StageGraph graph) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void register(FeatureRegistry registry) {
|
||||
SpawnResources.kinds().forEach(registry::registerResourceKind);
|
||||
registry.registerService(EntitySpawns.class, new EntitySpawning());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.engine.spawn;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.modules.IrisPackResources;
|
||||
import art.arcane.iris.engine.object.entity.IrisEntity;
|
||||
import art.arcane.iris.engine.object.entity.spawn.IrisSpawner;
|
||||
import art.arcane.iris.engine.object.marker.IrisMarker;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.resource.ResourceKind;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The resource kinds of module {@code iris:spawn}, which keep the folders and files Iris packs have always used, and
|
||||
* lookups by pack key for code that still names spawners, entities and markers by key. Every lookup goes through the
|
||||
* pack's {@link com.volmit.resource.PackResources}, so it sees the pack's current snapshot.
|
||||
* <p>
|
||||
* Lookups answer null where Iris's loaders did: for a blank key, a key the pack has no file for, and a file that fails
|
||||
* to load, which was reported when it was read.
|
||||
*/
|
||||
public final class SpawnResources {
|
||||
/** Spawners, in {@code spawners/}. */
|
||||
public static final ResourceKind<IrisSpawner> SPAWNERS = ResourceKind.of("iris:spawn/spawner", "spawners", IrisSpawner.class);
|
||||
/** Entities, in {@code entities/}. */
|
||||
public static final ResourceKind<IrisEntity> ENTITIES = ResourceKind.of("iris:spawn/entity", "entities", IrisEntity.class);
|
||||
/** Markers, in {@code markers/}. */
|
||||
public static final ResourceKind<IrisMarker> MARKERS = ResourceKind.of("iris:spawn/marker", "markers", IrisMarker.class);
|
||||
|
||||
private SpawnResources() {
|
||||
}
|
||||
|
||||
/** Every resource kind of the spawn module. */
|
||||
public static List<ResourceKind<?>> kinds() {
|
||||
return List.of(SPAWNERS, ENTITIES, MARKERS);
|
||||
}
|
||||
|
||||
public static IrisSpawner spawner(IrisData data, String key) {
|
||||
return find(data, SPAWNERS, key);
|
||||
}
|
||||
|
||||
public static IrisEntity entity(IrisData data, String key) {
|
||||
return find(data, ENTITIES, key);
|
||||
}
|
||||
|
||||
public static IrisMarker marker(IrisData data, String key) {
|
||||
return find(data, MARKERS, key);
|
||||
}
|
||||
|
||||
/** The spawners of the pack named by {@code keys}, in order, without the ones the pack lacks. */
|
||||
public static KList<IrisSpawner> spawners(IrisData data, List<String> keys) {
|
||||
KList<IrisSpawner> spawners = new KList<>();
|
||||
for (String key : keys) {
|
||||
IrisSpawner spawner = spawner(data, key);
|
||||
if (spawner != null) {
|
||||
spawners.add(spawner);
|
||||
}
|
||||
}
|
||||
return spawners;
|
||||
}
|
||||
|
||||
/** The key of every entity of the pack, in key order. */
|
||||
public static List<String> entityKeys(IrisData data) {
|
||||
return keys(data, ENTITIES);
|
||||
}
|
||||
|
||||
/** The key of every spawner of the pack, in key order. */
|
||||
public static List<String> spawnerKeys(IrisData data) {
|
||||
return keys(data, SPAWNERS);
|
||||
}
|
||||
|
||||
/** The key of every marker of the pack, in key order. */
|
||||
public static List<String> markerKeys(IrisData data) {
|
||||
return keys(data, MARKERS);
|
||||
}
|
||||
|
||||
private static <T> T find(IrisData data, ResourceKind<T> kind, String key) {
|
||||
if (key == null || key.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
IrisPackResources resources = data.getPackResources();
|
||||
try {
|
||||
return resources.find(kind.key(resources.idOf(key))).orElse(null);
|
||||
} catch (IllegalStateException failedToLoad) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** A key's id has the key as its path, so the path names the resource again wherever a key is expected. */
|
||||
private static List<String> keys(IrisData data, ResourceKind<?> kind) {
|
||||
return data.getPackResources().ids(kind.type()).stream().map(ResourceId::path).toList();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user