Apply IrisApi's typed keys, grouped values and @Ref(kind)

Batch 6, findings 41 and 42.

- Bukkit items, attributes, ambient effects and entities read ResourceIds,
  ContentKeys and the grouped ItemDrop and EntitySpec; Iris-only entity
  knobs come from the IrisEntityExtras extension.
- Iris serves the host kinds EXPRESSIONS and IMAGE_MAPS; noise styles map
  their ids back to the exact pack keys of the snapshot.
- Studio completes @Ref(kind = ...) of host kinds through Iris's loaders
  and @IrisStructureRef with the structure-model keys.
- Markers, sapling species, upper dimensions and jigsaw start pools are ids.
- Modded attribute lookup strips the minecraft namespace before the legacy
  generic prefixes, now that keys arrive namespaced.
- Loot and entity pins retaken: printed the old way, the new values still
  hash to the old numbers (recorded in the tests).
This commit is contained in:
piexel committed 2026-10-24 06:06:59 +02:00
1 parent ca07b8ce0b
commit dc0d61ce63
39 files changed
+523 -320

No files matched your search

@@ -63,6 +63,7 @@ import java.util.concurrent.ConcurrentHashMap;
public final class ModdedItemTranslator {
private static final Set<String> WARNED = ConcurrentHashMap.newKeySet();
private static final String COLOR_CODES = "0123456789AaBbCcDdEeFfKkLlMmNnOoRrXx";
private static final String VANILLA_NAMESPACE = "minecraft:";
private ModdedItemTranslator() {
}
@@ -224,11 +225,12 @@ public final class ModdedItemTranslator {
if (direct != null) {
return direct;
}
if (value.startsWith("generic_")) {
return lookupAttribute(registry, Identifier.tryParse("minecraft:" + value.substring("generic_".length())));
String path = value.startsWith(VANILLA_NAMESPACE) ? value.substring(VANILLA_NAMESPACE.length()) : value;
if (path.startsWith("generic_")) {
return lookupAttribute(registry, Identifier.tryParse(VANILLA_NAMESPACE + path.substring("generic_".length())));
}
if (value.startsWith("generic.")) {
return lookupAttribute(registry, Identifier.tryParse("minecraft:" + value.substring("generic.".length())));
if (path.startsWith("generic.")) {
return lookupAttribute(registry, Identifier.tryParse(VANILLA_NAMESPACE + path.substring("generic.".length())));
}
return null;
}
@@ -18,6 +18,7 @@
package art.arcane.iris.core.content;
import art.arcane.iris.builtin.spawn.IrisEntityExtras;
import art.arcane.iris.core.modules.IrisPackResources;
import art.arcane.iris.core.modules.ModuleServices;
import art.arcane.iris.core.modules.PlatformBlockStates;
@@ -27,6 +28,7 @@ import com.volmit.entity.EntitySpec;
import com.volmit.item.ItemAttribute;
import com.volmit.item.ItemDrop;
import com.volmit.item.ItemEnchantment;
import com.volmit.resource.ContentKey;
import com.volmit.resource.ResourceId;
import com.volmit.service.AmbientEffects;
import com.volmit.service.BlockDrops;
@@ -44,6 +46,8 @@ import java.util.Optional;
* fill containers, drop blocks, spawn mobs and play effects themselves, ask here instead of reading the pack's classes.
*/
public final class ContentServices {
private static final String LEATHER_COLOR_FORMAT = "#%06x";
private ContentServices() {
}
@@ -61,7 +65,7 @@ public final class ContentServices {
for (Loot.Source source : ModuleServices.lootTables(engine, site)) {
switch (source) {
case Loot.Table table -> parts.add(new ContentLoot.Items(tableItems(engine, x, worldY, z, table.id())));
case Loot.PlatformTable table -> parts.add(new ContentLoot.PlatformTable(table.key(), table.seed()));
case Loot.PlatformTable table -> parts.add(new ContentLoot.PlatformTable(table.table().toString(), table.seed()));
}
}
return parts;
@@ -91,8 +95,8 @@ public final class ContentServices {
/** What the first module that knows the spawner plans at the marker block. */
public static Optional<ContentSpawns.Plan> planMarkerSpawn(Engine engine, int x, int worldY, int z, String marker, String spawner, boolean initial) {
ResourceId spawnerId = engine.getData().getPackResources().idOf(spawner);
return planned(engine, new EntitySpawns.Marker(position(engine, x, worldY, z), marker, spawnerId, initial));
IrisPackResources resources = engine.getData().getPackResources();
return planned(engine, new EntitySpawns.Marker(position(engine, x, worldY, z), resources.idOf(marker), resources.idOf(spawner), initial));
}
/** What the marker with the tag {@code tag} does; empty for a tag no module knows. */
@@ -131,21 +135,24 @@ public final class ContentServices {
return new BlockPosition(x, worldY - engine.getMinHeight(), z);
}
/** The adapters' item names everything by text: keys as written by their ids, the leather colour as {@code #rrggbb}. */
private static ContentItem itemOf(ItemDrop drop) {
return new ContentItem(drop.item(), drop.amount(), drop.displayName().orElse(null), drop.lore(),
ItemDrop.Look look = drop.look();
return new ContentItem(drop.item().toString(), drop.amount(), look.displayName().orElse(null), look.lore(),
drop.enchantments().stream().map(ContentServices::enchantmentOf).toList(),
drop.attributes().stream().map(ContentServices::attributeOf).toList(), drop.unbreakable(), drop.flags(),
drop.customModel().isPresent() ? drop.customModel().getAsInt() : null,
drop.damage().isPresent() ? drop.damage().getAsDouble() : null,
drop.leatherColor().orElse(null), drop.dyeColor().orElse(null), drop.customNbt());
drop.attributes().stream().map(ContentServices::attributeOf).toList(), drop.wear().unbreakable(), drop.extras().flags(),
look.customModel().isPresent() ? look.customModel().getAsInt() : null,
drop.wear().damage().isPresent() ? drop.wear().damage().getAsDouble() : null,
look.leatherColor().isPresent() ? String.format(LEATHER_COLOR_FORMAT, look.leatherColor().getAsInt()) : null,
look.dyeColor().map(Enum::name).orElse(null), drop.extras().customNbt());
}
private static ContentItem.Enchantment enchantmentOf(ItemEnchantment enchantment) {
return new ContentItem.Enchantment(enchantment.key(), enchantment.level());
return new ContentItem.Enchantment(enchantment.key().toString(), enchantment.level());
}
private static ContentItem.Attribute attributeOf(ItemAttribute attribute) {
return new ContentItem.Attribute(attribute.attribute(), attribute.name(), attribute.operation(), attribute.amount());
return new ContentItem.Attribute(attribute.attribute().toString(), attribute.name(), attribute.operation().name(), attribute.amount());
}
/**
@@ -154,19 +161,26 @@ public final class ContentServices {
* {@link #tableItems} for them again.
*/
private static ContentEntity entityOf(EntitySpec spec) {
return new ContentEntity(spec.type().orElse(""), spec.specialType().orElse(""), spec.reason().orElse(null),
spec.customName().orElse(""), flagsOf(spec.flags()),
equipmentOf(spec.equipment()), spec.passengers().stream().map(ContentServices::entityOf).toList(),
IrisEntityExtras extras = spec.extension(IrisEntityExtras.class).orElse(IrisEntityExtras.NONE);
String type = spec.type() instanceof ContentKey.Registered registered ? registered.id().toString() : "";
String provided = spec.type() instanceof ContentKey.Provided mob ? mob.toString() : "";
return new ContentEntity(type, provided, extras.reason().orElse(null),
spec.appearance().customName().orElse(""), flagsOf(spec),
equipmentOf(spec.equipment()), spec.company().passengers().stream().map(ContentServices::entityOf).toList(),
spec.attributes().stream().map(ContentServices::attributeOf).toList(),
spec.lootTables().stream().map(ResourceId::path).toList(), spec.lootShuffleSeed(),
spec.leashHolder().map(ContentServices::entityOf).orElse(null), spec.spawnEffect().map(ContentServices::spawnEffectOf).orElse(null),
spec.riseOutOfGround(), spec.pandaMainGene().orElse(null), spec.pandaHiddenGene().orElse(null), spec.applySettingsToSpecial(),
spec.commands().stream().map(ContentServices::commandOf).toList());
spec.drops().lootTables().stream().map(ResourceId::path).toList(), spec.drops().shuffleSeed(),
spec.company().leashHolder().map(ContentServices::entityOf).orElse(null),
spec.arrival().effect().map(ContentServices::spawnEffectOf).orElse(null),
extras.riseOutOfGround(), extras.pandaMainGene().orElse(null), extras.pandaHiddenGene().orElse(null),
extras.applySettingsToProvidedMob(), spec.arrival().commands().stream().map(ContentServices::commandOf).toList());
}
private static ContentEntity.Flags flagsOf(EntitySpec.Flags flags) {
return new ContentEntity.Flags(flags.customNameVisible(), flags.aware(), flags.ai(), flags.glowing(), flags.gravity(),
flags.invulnerable(), flags.silent(), flags.pickupItems(), flags.removable(), flags.keepEntity(), flags.baby());
private static ContentEntity.Flags flagsOf(EntitySpec spec) {
EntitySpec.Appearance appearance = spec.appearance();
EntitySpec.Behaviour behaviour = spec.behaviour();
return new ContentEntity.Flags(appearance.nameVisible(), behaviour.aware(), behaviour.ai(), appearance.glowing(), behaviour.gravity(),
behaviour.invulnerable(), behaviour.silent(), behaviour.pickupItems(), behaviour.removable(), behaviour.keepEntity(),
appearance.baby());
}
private static ContentEntity.Equipment equipmentOf(EntitySpec.Equipment equipment) {
@@ -179,10 +193,19 @@ public final class ContentServices {
return drop.map(ContentServices::itemOf).orElse(null);
}
/** The adapters' spawn effect holds both parts in one record; a part that is absent has no key and zeros. */
private static ContentEntity.SpawnEffect spawnEffectOf(EntitySpec.SpawnEffect effect) {
return new ContentEntity.SpawnEffect(effect.sound().orElse(null), effect.soundDistance(), effect.minPitch(), effect.maxPitch(),
effect.volume(), effect.particle().orElse(null), effect.particleOffset(), effect.particleCount(), effect.altX(), effect.altY(),
effect.altZ(), effect.randomAltX(), effect.randomAltY(), effect.randomAltZ(), effect.extra());
Optional<EntitySpec.SpawnEffect.Sound> sound = effect.sound();
Optional<EntitySpec.SpawnEffect.Burst> burst = effect.particles();
Optional<EntitySpec.SpawnEffect.Motion> motion = burst.map(EntitySpec.SpawnEffect.Burst::motion);
return new ContentEntity.SpawnEffect(sound.map(present -> present.key().toString()).orElse(null),
sound.map(EntitySpec.SpawnEffect.Sound::distance).orElse(0), sound.map(EntitySpec.SpawnEffect.Sound::minPitch).orElse(0D),
sound.map(EntitySpec.SpawnEffect.Sound::maxPitch).orElse(0D), sound.map(EntitySpec.SpawnEffect.Sound::volume).orElse(0D),
burst.map(present -> present.key().toString()).orElse(null), burst.map(EntitySpec.SpawnEffect.Burst::offset).orElse(0),
burst.map(EntitySpec.SpawnEffect.Burst::count).orElse(0), motion.map(EntitySpec.SpawnEffect.Motion::x).orElse(0D),
motion.map(EntitySpec.SpawnEffect.Motion::y).orElse(0D), motion.map(EntitySpec.SpawnEffect.Motion::z).orElse(0D),
motion.map(EntitySpec.SpawnEffect.Motion::randomX).orElse(false), motion.map(EntitySpec.SpawnEffect.Motion::randomY).orElse(false),
motion.map(EntitySpec.SpawnEffect.Motion::randomZ).orElse(false), burst.map(EntitySpec.SpawnEffect.Burst::extra).orElse(0D));
}
private static ContentEntity.Command commandOf(EntitySpec.Command command) {
@@ -194,17 +217,18 @@ public final class ContentServices {
effect.particles().map(ContentServices::particlesOf).orElse(null),
effect.commands().stream().map(command -> new ContentEffect.Command(commandOf(command.command()),
command.offsetX(), command.offsetY(), command.offsetZ())).toList(),
effect.potion().map(potion -> new ContentEffect.Potion(potion.key(), potion.strength(), potion.ticks())).orElse(null));
effect.potion().map(potion -> new ContentEffect.Potion(potion.key().toString(), potion.strength(), potion.ticks())).orElse(null));
}
private static ContentEffect.Sound soundOf(AmbientEffects.Sound sound) {
return new ContentEffect.Sound(sound.key(), sound.offsetX(), sound.offsetY(), sound.offsetZ(),
return new ContentEffect.Sound(sound.key().toString(), sound.offsetX(), sound.offsetY(), sound.offsetZ(),
sound.volume(), sound.pitch());
}
private static ContentEffect.Particles particlesOf(AmbientEffects.Particles particles) {
return new ContentEffect.Particles(particles.key(), particles.forward(), particles.sideways(),
particles.jitterX(), particles.jitterZ(), particles.lift(), particles.count(), particles.altX(), particles.altY(),
particles.altZ(), particles.extra());
AmbientEffects.Spot spot = particles.spot();
AmbientEffects.Spread spread = particles.spread();
return new ContentEffect.Particles(particles.key().toString(), spot.forward(), spot.sideways(),
spot.jitterX(), spot.jitterZ(), spot.lift(), particles.count(), spread.x(), spread.y(), spread.z(), particles.extra());
}
}
@@ -57,14 +57,19 @@ final class IrisBlockRegistry implements BlockRegistry {
private static final int PALETTE_CACHE_SIZE = 256;
private final IrisData data;
private final IrisPackResources resources;
private final Map<BlockSpec, IrisBlockData> specs = new ConcurrentHashMap<>();
/** Stages ask about every block of a chunk; the platform's state of each block is found once per snapshot. */
private final Map<BlockState, PlatformBlockState> platformStates = new ConcurrentHashMap<>();
private final LazyBoundedCache<SeededPalette, PaletteSampler> palettes = new LazyBoundedCache<>(PALETTE_CACHE_SIZE);
/** @param data the pack whose {@code blocks} folder custom blocks come from */
IrisBlockRegistry(IrisData data) {
/**
* @param data the pack whose {@code blocks} folder custom blocks come from
* @param resources the snapshot whose keys the expressions and image maps of palette styles name
*/
IrisBlockRegistry(IrisData data, IrisPackResources resources) {
this.data = data;
this.resources = resources;
}
@Override
@@ -96,7 +101,7 @@ final class IrisBlockRegistry implements BlockRegistry {
if (seeded.spec().palette().stream().noneMatch(block -> block.weight() > 0)) {
throw new IllegalArgumentException("Palette " + seeded.spec() + " has no block to pick: each block needs a weight of at least 1");
}
IrisMaterialPalette palette = IrisValues.materialPalette(seeded.spec());
IrisMaterialPalette palette = IrisValues.materialPalette(seeded.spec(), resources);
RNG rng = new RNG(seeded.seed());
return (x, y, z) -> BlockState.parse(PlatformBlockStates.namespaced(palette.get(rng, x, y, z, data).key()));
}
@@ -24,33 +24,40 @@ import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.IrisServices;
import art.arcane.iris.spi.PlatformItem;
import com.volmit.item.ItemRegistry;
import com.volmit.resource.ContentKey;
import java.util.OptionalInt;
/**
* IrisApi's view of the bound platform's items: the platform's registry for plain keys, and the item providers of
* Iris's external data service for keys with a namespace of their own ({@code itemsadder:ruby}), which is how packs name
* custom items.
* IrisApi's view of the bound platform's items: the platform's registry for keys of its own namespace, and the item
* providers of Iris's external data service for every other item ({@code itemsadder:ruby}, {@code mmoitems_SWORD:KATANA}),
* which is how packs name custom items.
*/
public final class IrisItemRegistry implements ItemRegistry {
private static final String MINECRAFT_PREFIX = "minecraft:";
private static final char NAMESPACE_SEPARATOR = ':';
private static final String PLATFORM_NAMESPACE = "minecraft";
@Override
public OptionalInt maxDurability(String key) {
if (isCustomItem(key)) {
return customItemDurability(key);
public OptionalInt maxDurability(ContentKey item) {
if (isCustomItem(item)) {
return IrisServices.get(ExternalDataSVC.class).maxDurability(identifierOf(item));
}
PlatformItem item = IrisPlatforms.get().registries().item(key);
return item == null ? OptionalInt.empty() : OptionalInt.of(item.maxDurability());
PlatformItem platform = IrisPlatforms.get().registries().item(item.toString());
return platform == null ? OptionalInt.empty() : OptionalInt.of(platform.maxDurability());
}
/** Whether {@code key} names an item of an external provider, which resolves it, rather than of the platform. */
public static boolean isCustomItem(String key) {
return !key.startsWith(MINECRAFT_PREFIX) && key.indexOf(NAMESPACE_SEPARATOR) >= 0;
/** Whether {@code item} is one an external provider resolves rather than the platform. */
public static boolean isCustomItem(ContentKey item) {
return switch (item) {
case ContentKey.Provided ignored -> true;
case ContentKey.Registered registered -> !PLATFORM_NAMESPACE.equals(registered.id().namespace());
};
}
private static OptionalInt customItemDurability(String key) {
return IrisServices.get(ExternalDataSVC.class).maxDurability(Identifier.fromString(key));
/** {@code item} as Iris's external data service names it. */
public static Identifier identifierOf(ContentKey item) {
return switch (item) {
case ContentKey.Provided provided -> new Identifier(provided.provider(), provided.name());
case ContentKey.Registered registered -> new Identifier(registered.id().namespace(), registered.id().path());
};
}
}
@@ -40,15 +40,18 @@ final class IrisNoiseFactory implements NoiseFactory {
private static final double NO_EXTRA_SCALE = 1D;
private final IrisData data;
private final IrisPackResources resources;
private final Map<NoiseStyle, IrisGeneratorStyle> styles = new ConcurrentHashMap<>();
IrisNoiseFactory(IrisData data) {
/** @param resources the snapshot whose keys the expressions and image maps of styles name */
IrisNoiseFactory(IrisData data, IrisPackResources resources) {
this.data = data;
this.resources = resources;
}
@Override
public NoiseSampler sampler(NoiseStyle style, long seed) {
IrisGeneratorStyle iris = styles.computeIfAbsent(style, IrisValues::generatorStyle);
IrisGeneratorStyle iris = styles.computeIfAbsent(style, unbuilt -> IrisValues.generatorStyle(unbuilt, resources));
try {
return new CngSampler(iris.create(new RNG(seed), data), () -> iris.createNoCache(new RNG(seed), data), NO_EXTRA_SCALE);
} catch (RuntimeException failure) {
@@ -21,6 +21,8 @@ package art.arcane.iris.core.modules;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.loader.IrisRegistrant;
import art.arcane.iris.core.loader.ResourceLoader;
import art.arcane.iris.engine.object.image.IrisImageMap;
import art.arcane.iris.engine.object.noise.expression.IrisExpression;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.region.IrisRegion;
@@ -28,6 +30,8 @@ import com.volmit.block.BlockRegistry;
import com.volmit.host.ResourceKindRegistration;
import com.volmit.item.ItemRegistry;
import com.volmit.noise.NoiseFactory;
import com.volmit.noise.PackExpression;
import com.volmit.noise.PackImageMap;
import com.volmit.object.GeneratedObject;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
@@ -52,7 +56,8 @@ import java.util.function.Supplier;
* does every reload of its module resources ({@link IrisData#dump()}, {@link IrisData#invalidateStructureResources()}).
* <p>
* Served by kind: the host kinds {@link #OBJECTS} (a pack object, as its geometry), {@link #BIOMES} and
* {@link #REGIONS}, and every {@link ResourceKind} the pack's modules register, read from the kind's folder
* {@link #REGIONS}, {@link #EXPRESSIONS} and {@link #IMAGE_MAPS} (each only as its id, which noise styles name), and
* every {@link ResourceKind} the pack's modules register, read from the kind's folder
* ({@link ModuleResourceFiles}). All use the id {@code <pack namespace>:<key>} that {@link PackResourceIds}
* gives the pack's biomes in a biome sample, so one id can name a biome and a region. An id the pack lacks, or of
* another namespace, is absent; any other kind fails with {@link IllegalArgumentException}. A resource that exists
@@ -63,7 +68,7 @@ import java.util.function.Supplier;
* styles through Iris's generators, expressions and image maps ({@link IrisNoiseFactory}), both kept per snapshot.
*/
public final class IrisPackResources implements PackResources {
private static final String SERVED_TYPES = "the host kinds (objects, biomes, regions) and the pack's module resource kinds";
private static final String SERVED_TYPES = "the host kinds (objects, biomes, regions, expressions, image maps) and the pack's module resource kinds";
private final IrisData data;
private final PackResourceIds ids;
@@ -89,12 +94,14 @@ public final class IrisPackResources implements PackResources {
this.data = data;
this.ids = new PackResourceIds(data.getDataFolder());
this.moduleKindList = moduleKinds;
this.blocks = new IrisBlockRegistry(data);
this.noise = new IrisNoiseFactory(data);
this.blocks = new IrisBlockRegistry(data, this);
this.noise = new IrisNoiseFactory(data, this);
this.irisKinds = Map.of(
OBJECTS.id(), Kind.<IrisObject, GeneratedObject>ofLoader(ids, data::getObjectLoader, (id, object) -> object.getGeometry()),
BIOMES.id(), Kind.<IrisBiome, PackBiome>ofLoader(ids, data::getBiomeLoader, this::biomeOf),
REGIONS.id(), Kind.<IrisRegion, PackRegion>ofLoader(ids, data::getRegionLoader, this::regionOf));
REGIONS.id(), Kind.<IrisRegion, PackRegion>ofLoader(ids, data::getRegionLoader, this::regionOf),
EXPRESSIONS.id(), Kind.<IrisExpression, PackExpression>ofLoader(ids, data::getExpressionLoader, (id, expression) -> new PackExpression(id)),
IMAGE_MAPS.id(), Kind.<IrisImageMap, PackImageMap>ofLoader(ids, data::getImageMapLoader, (id, image) -> new PackImageMap(id)));
}
@Override
@@ -49,8 +49,8 @@ final class IrisUpperDimension implements UpperDimension {
}
@Override
public String key() {
return upper.getDimension().getLoadKey();
public ResourceId id() {
return resources.idOf(upper.getDimension().getLoadKey());
}
@Override
@@ -34,6 +34,7 @@ import com.volmit.block.PaletteSpec;
import com.volmit.config.Range;
import com.volmit.noise.StyledRange;
import com.volmit.geometry.BlockPosition;
import com.volmit.resource.PackResources;
import java.util.List;
import java.util.Map;
@@ -77,10 +78,10 @@ public final class IrisValues {
}
/** {@code spec} as the material palette Iris picks blocks from: its noise style, zoom and weighted blocks. */
static IrisMaterialPalette materialPalette(PaletteSpec spec) {
static IrisMaterialPalette materialPalette(PaletteSpec spec, IrisPackResources resources) {
KList<IrisBlockData> blocks = new KList<>();
spec.palette().forEach(block -> blocks.add(blockData(block)));
return new IrisMaterialPalette().setStyle(generatorStyle(spec.style())).setZoom(spec.zoom()).setPalette(blocks);
return new IrisMaterialPalette().setStyle(generatorStyle(spec.style(), resources)).setZoom(spec.zoom()).setPalette(blocks);
}
/** Iris's maps hold no null values; a JSON null in a map reads as absent, as it does for Iris's own fields. */
@@ -97,16 +98,17 @@ public final class IrisValues {
/**
* {@code style} as the generator style Iris builds noise from; a style name Iris does not know is flat. For behaviour that
* reads Iris's generator itself, such as the cave carvers' signed 3D reads, which {@code PackResources.noise()} does not offer.
* The expression and image map ids become the pack keys of {@code resources} that have them.
*/
public static IrisGeneratorStyle generatorStyle(com.volmit.noise.NoiseStyle style) {
public static IrisGeneratorStyle generatorStyle(com.volmit.noise.NoiseStyle style, IrisPackResources resources) {
IrisGeneratorStyle iris = new IrisGeneratorStyle(irisStyle(style.style()));
iris.setCellularFrequency(style.cellularFrequency());
iris.setCellularZoom(style.cellularZoom());
iris.setZoom(style.zoom());
iris.setExpression(style.expression().orElse(null));
iris.setImageMap(style.imageMap().orElse(null));
iris.setExpression(style.expression().map(id -> resources.keyOf(PackResources.EXPRESSIONS, id)).orElse(null));
iris.setImageMap(style.imageMap().map(id -> resources.keyOf(PackResources.IMAGE_MAPS, id)).orElse(null));
iris.setMultiplier(style.multiplier());
iris.setFracture(style.fracture().map(IrisValues::generatorStyle).orElse(null));
iris.setFracture(style.fracture().map(fracture -> generatorStyle(fracture, resources)).orElse(null));
iris.setExponent(style.exponent());
iris.setCacheSize(style.cacheSize());
return iris;
@@ -115,7 +117,7 @@ public final class IrisValues {
/** The noise style of each layer of the biome's surface, top first, as Iris's generators know them. */
public static List<art.arcane.iris.engine.object.noise.NoiseStyle> layerStyles(art.arcane.iris.engine.object.world.biome.IrisBiome biome) {
return LayerLoad.layersOf(biome.getModuleSettings().find(LayersSettings.class).orElse(null)).stream()
.map(layer -> generatorStyle(layer.style()).getStyle()).toList();
.map(layer -> irisStyle(layer.style().style())).toList();
}
/** {@code range} as the range Iris reads the same JSON into. */
@@ -124,8 +126,8 @@ public final class IrisValues {
}
/** {@code range} as the styled range Iris reads the same JSON into. */
public static IrisStyledRange styledRange(StyledRange range) {
return new IrisStyledRange(range.min(), range.max(), generatorStyle(range.style()));
public static IrisStyledRange styledRange(StyledRange range, IrisPackResources resources) {
return new IrisStyledRange(range.min(), range.max(), generatorStyle(range.style(), resources));
}
private static NoiseStyle irisStyle(String name) {
@@ -203,8 +203,9 @@ public final class ModuleServices {
/** What the first module that knows the marker {@code tag} says it does. */
public static Optional<EntitySpawns.MarkerRule> markerRule(Engine engine, String tag) {
ResourceId id = engine.getData().getPackResources().idOf(tag);
for (Provider<EntitySpawns> provider : providers(engine, EntitySpawns.class)) {
Optional<EntitySpawns.MarkerRule> rule = provider.service().marker(provider.world(), tag);
Optional<EntitySpawns.MarkerRule> rule = provider.service().marker(provider.world(), id);
if (rule.isPresent()) {
return rule;
}
@@ -66,6 +66,8 @@ import java.util.function.Function;
public final class ModuleVanillaStructures {
private static final Map<Engine, ModuleVanillaStructures> WORLDS = Collections.synchronizedMap(new WeakHashMap<>());
private static final int START_TERRAIN_REACH_BLOCKS = 8;
/** How the native structure factory hears that the start connector constraint is removed. */
private static final String NO_START_JIGSAW = "NONE";
private final PackResources snapshot;
private final List<ServiceRegistration> providers;
@@ -223,8 +225,8 @@ public final class ModuleVanillaStructures {
private static NativeJigsawOverrides jigsaw(JigsawOverrides overrides) {
return new NativeJigsawOverrides(
overrides.startPool(),
overrides.startJigsawName(),
overrides.startPool().map(ResourceId::toString).orElse(""),
overrides.removesStartJigsaw() ? NO_START_JIGSAW : overrides.startJigsawName().map(ResourceId::toString).orElse(""),
boxed(overrides.maxDepth()),
boxed(overrides.maxDistanceHorizontal()),
boxed(overrides.maxDistanceVertical()),
@@ -18,6 +18,7 @@
package art.arcane.iris.core.pack;
import art.arcane.iris.builtin.structure.IrisStructureRef;
import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.loader.IrisRegistrant;
import art.arcane.iris.core.modules.IrisPackResources;
@@ -27,8 +28,6 @@ import art.arcane.volmlib.util.io.IO;
import art.arcane.volmlib.util.json.JSONObject;
import com.google.gson.Gson;
import com.volmit.config.Ref;
import com.volmit.config.Reference;
import com.volmit.config.ResourceRef;
import com.volmit.host.ResourceKindRegistration;
import com.volmit.resource.ResourceKind;
@@ -50,8 +49,8 @@ import java.util.TreeSet;
/**
* The resources of the pack's module resource kinds that a pack export has to carry: what the settings of the
* exported dimension, regions and biomes (and anything else handed to {@link #follow}) name by {@link ResourceRef} or
* {@link RegistryListResource}, and what those resources name in turn. Core does not know the kinds: it follows the
* exported dimension, regions and biomes (and anything else handed to {@link #follow}) name by {@code @Ref(kind = ...)},
* {@link IrisStructureRef} or {@link RegistryListResource}, and what those resources name in turn. Core does not know the kinds: it follows the
* references the modules declare on their classes.
*/
public final class ModuleResourceClosure {
@@ -170,12 +169,11 @@ public final class ModuleResourceClosure {
/** The class of the resources the field names by key, or null when it names none. */
private static Class<?> referencedType(Field field) {
ResourceRef reference = field.getAnnotation(ResourceRef.class);
if (reference != null) {
return reference.value();
Ref reference = field.getAnnotation(Ref.class);
if (reference != null && reference.kind() != void.class) {
return reference.kind();
}
Ref packReference = field.getAnnotation(Ref.class);
if (packReference != null && packReference.value() == Reference.PACK_STRUCTURE) {
if (field.isAnnotationPresent(IrisStructureRef.class)) {
return IrisStructure.class;
}
RegistryListResource registry = field.getAnnotation(RegistryListResource.class);
@@ -60,6 +60,11 @@ final class ModuleSchemaRenderer {
void complete(JSONObject property, ResourceId kind);
}
/** Points an option's string values at the completion list an Iris-extension annotation on its field names, if any. */
interface ExtensionCompletions {
void complete(JSONObject property, String typeName, String optionName);
}
/** The definition key of Iris's own description of one of its classes, built the first time it is asked for. */
interface HostDefinitions {
String definition(String typeName);
@@ -69,6 +74,7 @@ final class ModuleSchemaRenderer {
private final Map<String, JSONObject> definitions;
private final ReferenceCompletions references;
private final ResourceCompletions resources;
private final ExtensionCompletions extensions;
private final HostDefinitions hostDefinitions;
private final Function<String, Optional<String>> sameJsonHostTypes;
private final Function<String, List<String>> snippetFiles;
@@ -78,12 +84,13 @@ final class ModuleSchemaRenderer {
* @param snippetFiles lists the snippet references a pack has for a snippet folder, such as {@code snippet/thick}
*/
ModuleSchemaRenderer(PackSchema schema, Map<String, JSONObject> definitions, ReferenceCompletions references,
ResourceCompletions resources, HostDefinitions hostDefinitions,
ResourceCompletions resources, ExtensionCompletions extensions, HostDefinitions hostDefinitions,
Function<String, Optional<String>> sameJsonHostTypes, Function<String, List<String>> snippetFiles) {
this.schema = schema;
this.definitions = definitions;
this.references = references;
this.resources = resources;
this.extensions = extensions;
this.hostDefinitions = hostDefinitions;
this.sameJsonHostTypes = sameJsonHostTypes;
this.snippetFiles = snippetFiles;
@@ -166,7 +173,9 @@ final class ModuleSchemaRenderer {
JSONObject properties = new JSONObject();
JSONArray required = new JSONArray();
for (SchemaOption option : type.options()) {
properties.put(option.name(), optionSchema(option));
JSONObject property = optionSchema(option);
extensions.complete(stringValuesOf(property), type.name(), option.name());
properties.put(option.name(), property);
if (option.required()) {
required.put(option.name());
}
@@ -178,6 +187,11 @@ final class ModuleSchemaRenderer {
return object;
}
/** The schema of the strings an option holds: its items for a list, itself otherwise. */
private static JSONObject stringValuesOf(JSONObject property) {
return property.has("items") ? property.getJSONObject("items") : property;
}
private JSONObject optionSchema(SchemaOption option) {
JSONObject property = valueSchema(option.kind());
if (!option.description().isEmpty()) {
@@ -18,6 +18,7 @@
package art.arcane.iris.core.project;
import art.arcane.iris.builtin.structure.IrisStructureRef;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.PlatformBlockProperty;
@@ -64,6 +65,7 @@ import com.volmit.host.schema.ObjectType;
import com.volmit.host.schema.ResourceKindSchema;
import com.volmit.host.schema.TextFormat;
import com.volmit.host.schema.ValueKind;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKind;
import org.jetbrains.annotations.NotNull;
@@ -90,6 +92,12 @@ public class SchemaBuilder {
/** Namespaced key or family/namespace prefix: "minecraft:village_plains", "minecraft:village", "nova_structures:". */
private static final String VANILLA_STRUCTURE_PREFIX_PATTERN = "^[a-z0-9_.-]+:[a-z0-9_./-]*$";
private static final String LOOT_TABLE_DEFINITION = "loot-table-key";
private static final Map<ResourceId, Class<?>> IRIS_TYPES_OF_HOST_KINDS = Map.of(
PackResources.BIOMES.id(), IrisBiome.class,
PackResources.REGIONS.id(), IrisRegion.class,
PackResources.OBJECTS.id(), IrisObject.class,
PackResources.EXPRESSIONS.id(), IrisExpression.class,
PackResources.IMAGE_MAPS.id(), IrisImageMap.class);
private static volatile JSONArray fontTypes;
private final KMap<String, JSONObject> definitions;
private final Class<?> root;
@@ -389,7 +397,7 @@ public class SchemaBuilder {
private ModuleSchemaRenderer moduleSchemas() {
if (moduleSchemas == null) {
moduleSchemas = new ModuleSchemaRenderer(data.getModules().pack().schema(), definitions,
this::completeReference, this::completeResourceReference, this::hostDefinition,
this::completeReference, this::completeResourceReference, this::completeIrisExtension, this::hostDefinition,
typeName -> IrisValues.irisClassOf(typeName).map(Class::getName), data::getPossibleSnippets);
}
return moduleSchemas;
@@ -452,13 +460,24 @@ public class SchemaBuilder {
case POTION_EFFECT -> putRegistryEnumRef(property, "enum-potion-effect-type", this::potionTypes);
case ENCHANTMENT -> putRegistryEnumRef(property, "enum-enchantment", this::enchantTypes);
case LOOT_TABLE -> putRegistryEnumRef(property, LOOT_TABLE_DEFINITION, this::lootTableKeys);
case PACK_BIOME -> putPackResourceRef(property, IrisBiome.class);
case PACK_REGION -> putPackResourceRef(property, IrisRegion.class);
case PACK_OBJECT -> putPackResourceRef(property, IrisObject.class);
case NOISE_STYLE -> addEnum(NoiseStyle.class, property, new KList<>(), enumNames(NoiseStyle.class), Function.identity());
case PACK_EXPRESSION -> putPackResourceRef(property, IrisExpression.class);
case PACK_IMAGE_MAP -> putPackResourceRef(property, IrisImageMap.class);
case PACK_STRUCTURE -> putPackResourceRef(property, IrisStructure.class);
}
}
/** Completion for an option whose field carries an Iris-extension annotation, such as {@link IrisStructureRef}. */
private void completeIrisExtension(JSONObject property, String typeName, String optionName) {
Optional<Field> field = declaredField(typeName, optionName);
if (field.isEmpty() || !field.get().isAnnotationPresent(IrisStructureRef.class)) {
return;
}
putPackResourceRef(property, IrisStructure.class);
}
private static Optional<Field> declaredField(String typeName, String fieldName) {
try {
return Optional.of(Class.forName(typeName, false, SchemaBuilder.class.getClassLoader()).getDeclaredField(fieldName));
} catch (ClassNotFoundException | NoSuchFieldException notIris) {
return Optional.empty();
}
}
@@ -483,8 +502,13 @@ public class SchemaBuilder {
.orElse(null);
}
/** Completion for a module option naming a resource of the module resource kind {@code kindId}. */
/** Completion for a module option naming a resource of the host or module resource kind {@code kindId}. */
private void completeResourceReference(JSONObject property, ResourceId kindId) {
Class<?> irisType = IRIS_TYPES_OF_HOST_KINDS.get(kindId);
if (irisType != null) {
putPackResourceRef(property, irisType);
return;
}
moduleKinds().stream()
.filter(kind -> kind.id().equals(kindId))
.findFirst()
@@ -32,6 +32,7 @@ import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.collection.KMap;
import art.arcane.volmlib.util.data.Cuboid;
import com.volmit.placement.PlacedBlock;
import com.volmit.resource.ResourceId;
import com.volmit.service.SaplingGrowth;
import art.arcane.volmlib.util.math.BlockPosition;
import art.arcane.iris.util.common.plugin.IrisService;
@@ -122,7 +123,7 @@ public class TreeSVC implements IrisService {
SaplingGrowth.Sapling sapling = new SaplingGrowth.Sapling(
relativePosition(event.getLocation(), minHeight),
relativePosition(saplingPlane.getCenter(), minHeight),
event.getSpecies().name());
ResourceId.ofPlatformKey(event.getSpecies().name()));
Optional<SaplingGrowth.Growth> growth = ModuleServices.growSapling(engine, sapling, new WorldSurroundings(event.getWorld(), saplingPlane));
if (growth.isEmpty()) {
@@ -54,7 +54,7 @@ final class MarkerSpawnScanner {
}
/** A spawner a marker names, and the marker. */
record MarkerSpawner(String marker, ResourceId spawner) {
record MarkerSpawner(ResourceId marker, ResourceId spawner) {
}
Map<IrisPosition, List<MarkerSpawner>> getSpawnersFromMarkers(Chunk c) {
@@ -82,7 +82,7 @@ final class MarkerSpawnScanner {
}
for (ResourceId spawner : rule.get().spawners()) {
addOnce(p.computeIfAbsent(pos, (k) -> new ArrayList<>()), new MarkerSpawner(t.getTag(), spawner));
addOnce(p.computeIfAbsent(pos, (k) -> new ArrayList<>()), new MarkerSpawner(markerId(t), spawner));
}
});
@@ -101,6 +101,10 @@ final class MarkerSpawnScanner {
return ModuleServices.markerRule(manager.getEngine(), marker.getTag());
}
private ResourceId markerId(MatterMarker marker) {
return manager.getEngine().getData().getPackResources().idOf(marker.getTag());
}
void forEachMarkerSpawner(Chunk c, BiConsumer<IrisPosition, List<MarkerSpawner>> consumer) {
if (c == null || consumer == null) {
return;
@@ -180,7 +184,7 @@ final class MarkerSpawnScanner {
data.requiresEmptyAbove = data.requiresEmptyAbove || rule.get().emptyAbove();
for (ResourceId spawner : rule.get().spawners()) {
addOnce(data.spawners, new MarkerSpawner(t.getTag(), spawner));
addOnce(data.spawners, new MarkerSpawner(markerId(t), spawner));
}
});
@@ -38,8 +38,10 @@ import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.M;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.scheduling.PrecisionStopwatch;
import art.arcane.iris.builtin.spawn.IrisEntityExtras;
import com.volmit.entity.EntitySpec;
import com.volmit.item.ItemAttribute;
import com.volmit.resource.ContentKey;
import com.volmit.resource.ResourceId;
import com.volmit.service.Loot;
import com.volmit.geometry.BlockPosition;
@@ -102,17 +104,18 @@ public final class BukkitEntitySpawner {
if (!Chunks.isSafe(at)) {
return null;
}
if (spec.riseOutOfGround()) {
IrisEntityExtras extras = spec.extension(IrisEntityExtras.class).orElse(IrisEntityExtras.NONE);
if (extras.riseOutOfGround()) {
at = startBelowGroundWhenWatched(at);
}
Entity ee = doSpawn(spec, at);
Entity ee = doSpawn(spec, extras, at);
if (ee == null && !Chunks.isSafe(at)) {
return null;
}
if (spec.isSpecial() && !spec.applySettingsToSpecial()) {
if (spec.type() instanceof ContentKey.Provided && !extras.applySettingsToProvidedMob()) {
return ee;
}
@@ -130,7 +133,7 @@ public final class BukkitEntitySpawner {
}
}
if (e instanceof Lootable lootable && !spec.lootTables().isEmpty()) {
if (e instanceof Lootable lootable && !spec.drops().lootTables().isEmpty()) {
bindLoot(spec, gen, lootable, at);
}
@@ -138,13 +141,13 @@ public final class BukkitEntitySpawner {
applyLivingState(gen, living, spec, at);
}
if (e instanceof Ageable ageable && spec.flags().baby()) {
if (e instanceof Ageable ageable && spec.appearance().baby()) {
ageable.setBaby();
}
if (e instanceof Panda panda) {
panda.setMainGene(resolveGene(spec.pandaMainGene().orElse(null)));
panda.setHiddenGene(resolveGene(spec.pandaHiddenGene().orElse(null)));
panda.setMainGene(resolveGene(extras.pandaMainGene().orElse(null)));
panda.setHiddenGene(resolveGene(extras.pandaHiddenGene().orElse(null)));
}
if (e instanceof Villager villager) {
@@ -153,16 +156,16 @@ public final class BukkitEntitySpawner {
}
if (e instanceof Mob mob) {
mob.setAware(spec.flags().aware());
mob.setAware(spec.behaviour().aware());
}
spec.spawnEffect().ifPresent(effect -> showSpawnEffect(e, effect));
spec.arrival().effect().ifPresent(effect -> showSpawnEffect(e, effect));
runCommands(spec, at);
Location riseFrom = at;
J.runEntity(e, () -> {
if (spec.riseOutOfGround() && e instanceof LivingEntity living && Chunks.hasPlayersNearby(riseFrom)) {
if (extras.riseOutOfGround() && e instanceof LivingEntity living && Chunks.hasPlayersNearby(riseFrom)) {
riseOutOfGround(e, living, riseFrom);
}
});
@@ -190,18 +193,19 @@ public final class BukkitEntitySpawner {
}
private static void applyFlags(Entity e, EntitySpec spec) {
EntitySpec.Flags flags = spec.flags();
e.setCustomName(spec.customName().map(name -> C.translateAlternateColorCodes('&', name)).orElse(null));
e.setCustomNameVisible(flags.customNameVisible());
e.setGlowing(flags.glowing());
e.setGravity(flags.gravity());
e.setInvulnerable(flags.invulnerable());
e.setSilent(flags.silent());
e.setPersistent(flags.keepEntity() || IrisSettings.get().getWorld().isForcePersistEntities());
EntitySpec.Appearance appearance = spec.appearance();
EntitySpec.Behaviour behaviour = spec.behaviour();
e.setCustomName(appearance.customName().map(name -> C.translateAlternateColorCodes('&', name)).orElse(null));
e.setCustomNameVisible(appearance.nameVisible());
e.setGlowing(appearance.glowing());
e.setGravity(behaviour.gravity());
e.setInvulnerable(behaviour.invulnerable());
e.setSilent(behaviour.silent());
e.setPersistent(behaviour.keepEntity() || IrisSettings.get().getWorld().isForcePersistEntities());
}
private static void addPassengers(Engine gen, Entity e, EntitySpec spec, Location at) {
for (EntitySpec passengerSpec : spec.passengers()) {
for (EntitySpec passengerSpec : spec.company().passengers()) {
Entity passenger = spawn(gen, passengerSpec, at);
if (passenger == null) {
continue;
@@ -216,12 +220,12 @@ public final class BukkitEntitySpawner {
}
private static void applyLivingState(Engine gen, LivingEntity l, EntitySpec spec, Location at) {
l.setAI(spec.flags().ai());
l.setCanPickupItems(spec.flags().pickupItems());
l.setAI(spec.behaviour().ai());
l.setCanPickupItems(spec.behaviour().pickupItems());
spec.leashHolder().ifPresent(holder -> l.setLeashHolder(spawn(gen, holder, at)));
spec.company().leashHolder().ifPresent(holder -> l.setLeashHolder(spawn(gen, holder, at)));
l.setRemoveWhenFarAway(spec.flags().removable());
l.setRemoveWhenFarAway(spec.behaviour().removable());
EntitySpec.Equipment equipment = spec.equipment();
equipment.helmet().ifPresent(item -> l.getEquipment().setHelmet(BukkitItemStacks.create(item)));
@@ -233,7 +237,7 @@ public final class BukkitEntitySpawner {
}
private static void runCommands(EntitySpec spec, Location at) {
for (EntitySpec.Command command : spec.commands()) {
for (EntitySpec.Command command : spec.arrival().commands()) {
ConsoleCommands.run(command.commands(), command.delay(), command.repeat(), command.repeatDelay(),
at.getBlockX(), at.getBlockY(), at.getBlockZ());
}
@@ -289,12 +293,12 @@ public final class BukkitEntitySpawner {
EntityRiseSVC.clearStamp(entity);
}
private static Entity doSpawn(EntitySpec spec, Location at) {
private static Entity doSpawn(EntitySpec spec, IrisEntityExtras extras, Location at) {
if (!Chunks.isSafe(at)) {
return null;
}
if (EntityType.UNKNOWN.equals(bukkitType(spec)) && !spec.isSpecial()) {
if (EntityType.UNKNOWN.equals(bukkitType(spec)) && !(spec.type() instanceof ContentKey.Provided)) {
return null;
}
@@ -304,7 +308,7 @@ public final class BukkitEntitySpawner {
AtomicReference<Entity> ae = new AtomicReference<>();
try {
if (!J.runAt(at, () -> ae.set(doSpawn(spec, at)))) {
if (!J.runAt(at, () -> ae.set(doSpawn(spec, extras, at)))) {
return null;
}
} catch (Throwable e) {
@@ -323,31 +327,24 @@ public final class BukkitEntitySpawner {
return ae.get();
}
if (spec.isSpecial()) {
return IrisServices.get(ExternalDataSVC.class).spawnMob(at, Identifier.fromString(spec.specialType().orElseThrow()));
if (spec.type() instanceof ContentKey.Provided mob) {
return IrisServices.get(ExternalDataSVC.class).spawnMob(at, new Identifier(mob.provider(), mob.name()));
}
return BukkitPlatform.spawnEntity(at, bukkitType(spec), bukkitReason(spec));
return BukkitPlatform.spawnEntity(at, bukkitType(spec), bukkitReason(extras));
}
/** The platform's entity type of the spec, unknown when it names none. */
/** The platform's entity type of the spec, unknown for a provider's mob or a type the platform lacks. */
public static EntityType bukkitType(EntitySpec spec) {
String type = spec.type().orElse("");
if (type.isBlank()) {
if (!(spec.type() instanceof ContentKey.Registered registered)) {
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);
EntityType entityType = RegistryUtil.lookup(EntityType.class).get(new NamespacedKey(registered.id().namespace(), registered.id().path()));
return entityType == null ? EntityType.UNKNOWN : entityType;
}
private static CreatureSpawnEvent.SpawnReason bukkitReason(EntitySpec spec) {
String reason = spec.reason().orElse("");
private static CreatureSpawnEvent.SpawnReason bukkitReason(IrisEntityExtras extras) {
String reason = extras.reason().orElse("");
if (reason.isBlank()) {
return CreatureSpawnEvent.SpawnReason.NATURAL;
}
@@ -373,33 +370,42 @@ public final class BukkitEntitySpawner {
private static void showSpawnEffect(Entity p, EntitySpec.SpawnEffect fx) {
J.runEntity(p, () -> {
Sound soundType = fx.sound().map(sound -> resolveKeyed(Sound.class, sound)).orElse(null);
Particle particleType = fx.particle().map(particle -> resolveKeyed(Particle.class, particle)).orElse(null);
if (soundType != null) {
Location part = p.getLocation().clone().add(RNG.r.i(-fx.soundDistance(), fx.soundDistance()), RNG.r.i(-fx.soundDistance(), fx.soundDistance()), RNG.r.i(-fx.soundDistance(), fx.soundDistance()));
p.getWorld().playSound(part, soundType, (float) fx.volume(), (float) RNG.r.d(fx.minPitch(), fx.maxPitch()));
}
if (particleType != null) {
Location part = p.getLocation().clone().add(0, 0.25, 0).add(new Vector(1, 1, 1).multiply(RNG.r.d())).subtract(new Vector(1, 1, 1).multiply(RNG.r.d()));
part.add(RNG.r.d(), 0, RNG.r.d());
double motionX = fx.randomAltX() ? RNG.r.d(-fx.altX(), fx.altX()) : fx.altX();
double motionY = fx.randomAltY() ? RNG.r.d(-fx.altY(), fx.altY()) : fx.altY();
double motionZ = fx.randomAltZ() ? RNG.r.d(-fx.altZ(), fx.altZ()) : fx.altZ();
if (fx.extra() != 0) {
p.getWorld().spawnParticle(particleType, part.getX(), part.getY() + RNG.r.i(fx.particleOffset()), part.getZ(),
fx.particleCount(), motionX, motionY, motionZ, fx.extra());
} else {
p.getWorld().spawnParticle(particleType, part.getX(), part.getY() + RNG.r.i(fx.particleOffset()), part.getZ(),
fx.particleCount(), motionX, motionY, motionZ);
}
}
fx.sound().ifPresent(sound -> playSpawnSound(p, sound));
fx.particles().ifPresent(burst -> showSpawnParticles(p, burst));
});
}
private static <T> T resolveKeyed(Class<T> type, String key) {
NamespacedKey namespacedKey = NamespacedKey.fromString(key);
return namespacedKey == null ? null : RegistryUtil.lookup(type).get(namespacedKey);
private static void playSpawnSound(Entity p, EntitySpec.SpawnEffect.Sound sound) {
Sound type = resolveKeyed(Sound.class, sound.key());
if (type == null) {
return;
}
int distance = sound.distance();
Location part = p.getLocation().clone().add(RNG.r.i(-distance, distance), RNG.r.i(-distance, distance), RNG.r.i(-distance, distance));
p.getWorld().playSound(part, type, (float) sound.volume(), (float) RNG.r.d(sound.minPitch(), sound.maxPitch()));
}
private static void showSpawnParticles(Entity p, EntitySpec.SpawnEffect.Burst burst) {
Particle type = resolveKeyed(Particle.class, burst.key());
if (type == null) {
return;
}
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());
EntitySpec.SpawnEffect.Motion motion = burst.motion();
double motionX = motion.randomX() ? RNG.r.d(-motion.x(), motion.x()) : motion.x();
double motionY = motion.randomY() ? RNG.r.d(-motion.y(), motion.y()) : motion.y();
double motionZ = motion.randomZ() ? RNG.r.d(-motion.z(), motion.z()) : motion.z();
double y = part.getY() + RNG.r.i(burst.offset());
if (burst.extra() != 0) {
p.getWorld().spawnParticle(type, part.getX(), y, part.getZ(), burst.count(), motionX, motionY, motionZ, burst.extra());
} else {
p.getWorld().spawnParticle(type, part.getX(), y, part.getZ(), burst.count(), motionX, motionY, motionZ);
}
}
private static <T> T resolveKeyed(Class<T> type, ResourceId key) {
return RegistryUtil.lookup(type).get(new NamespacedKey(key.namespace(), key.path()));
}
private static void bindLoot(EntitySpec spec, Engine gen, Lootable lootable, Location finalAt) {
@@ -415,7 +421,7 @@ public final class BukkitEntitySpawner {
Loot.Site site = new Loot.Site(position, Optional.empty(), false, gen.isStudio());
KList<ItemStack> items = new KList<>();
for (ResourceId table : spec.lootTables()) {
for (ResourceId table : spec.drops().lootTables()) {
items.addAll(BukkitItemStacks.createAll(ModuleServices.lootItems(gen, site, table)));
}
@@ -428,7 +434,7 @@ public final class BukkitEntitySpawner {
inventory.addItem(i);
}
EngineBukkitOps.scramble(gen, inventory, new RNG(spec.lootShuffleSeed()));
EngineBukkitOps.scramble(gen, inventory, new RNG(spec.drops().shuffleSeed()));
}
});
}
@@ -486,10 +486,9 @@ public final class EngineBukkitOps {
}
private static List<ItemStack> platformLoot(Loot.PlatformTable table, World world, int x, int y, int z) {
NamespacedKey key = NamespacedKey.fromString(table.key());
LootTable platformTable = key == null ? null : Bukkit.getLootTable(key);
LootTable platformTable = Bukkit.getLootTable(new NamespacedKey(table.table().namespace(), table.table().path()));
if (platformTable == null) {
IrisLogging.warn("Unknown vanilla loot table " + table.key());
IrisLogging.warn("Unknown vanilla loot table " + table.table());
return List.of();
}
return new KList<>(platformTable.populateLoot(new RNG(table.seed()), new LootContext.Builder(new Location(world, x, y, z)).build()));
@@ -24,6 +24,7 @@ import art.arcane.iris.util.common.data.registry.RegistryUtil;
import art.arcane.iris.util.common.scheduling.ConsoleCommands;
import art.arcane.iris.util.common.scheduling.J;
import com.volmit.entity.EntitySpec;
import com.volmit.resource.ResourceId;
import com.volmit.service.AmbientEffects;
import org.bukkit.Location;
import org.bukkit.NamespacedKey;
@@ -74,21 +75,23 @@ public final class BukkitAmbientEffects {
if (type == null) {
return;
}
AmbientEffects.Spot where = particles.spot();
AmbientEffects.Spread spread = particles.spread();
Location location = player.getLocation();
Vector direction = location.getDirection();
Location spot = location.clone()
.add(direction.clone().multiply(particles.forward()))
.add(direction.clone().rotateAroundY(QUARTER_TURN_RADIANS).multiply(particles.sideways()));
.add(direction.clone().multiply(where.forward()))
.add(direction.clone().rotateAroundY(QUARTER_TURN_RADIANS).multiply(where.sideways()));
spot.setY(Math.round(engine.getHeight(spot.getBlockX(), spot.getBlockZ())) + ABOVE_SURFACE_BLOCKS);
spot.add(particles.jitterX(), 0, particles.jitterZ());
spot.add(where.jitterX(), 0, where.jitterZ());
double x = spot.getX();
double y = spot.getY() + player.getWorld().getMinHeight() + particles.lift();
double y = spot.getY() + player.getWorld().getMinHeight() + where.lift();
double z = spot.getZ();
if (particles.extra() != 0) {
player.spawnParticle(type, x, y, z, particles.count(), particles.altX(), particles.altY(), particles.altZ(), particles.extra());
player.spawnParticle(type, x, y, z, particles.count(), spread.x(), spread.y(), spread.z(), particles.extra());
return;
}
player.spawnParticle(type, x, y, z, particles.count(), particles.altX(), particles.altY(), particles.altZ());
player.spawnParticle(type, x, y, z, particles.count(), spread.x(), spread.y(), spread.z());
}
private static void runCommand(Player player, AmbientEffects.Command command) {
@@ -110,12 +113,9 @@ public final class BukkitAmbientEffects {
player.addPotionEffect(new PotionEffect(type, potion.ticks(), potion.strength(), true, false, false));
}
/** The potion effect type a pack names, or luck for a name the platform does not know, with a warning once. */
private static PotionEffectType potionType(String name) {
if (name == null || name.isEmpty()) {
return PotionEffectType.LUCK;
}
/** The potion effect type a pack names, also by its legacy names, or luck for one the platform does not know, with a warning once. */
private static PotionEffectType potionType(ResourceId key) {
String name = key.toString();
try {
PotionEffectType resolved = PotionEffectTypes.resolve(name);
if (resolved != null) {
@@ -131,8 +131,7 @@ public final class BukkitAmbientEffects {
return PotionEffectType.LUCK;
}
private static <T> T lookup(Class<T> type, String key) {
NamespacedKey namespacedKey = NamespacedKey.fromString(key);
return namespacedKey == null ? null : RegistryUtil.lookup(type).get(namespacedKey);
private static <T> T lookup(Class<T> type, ResourceId key) {
return RegistryUtil.lookup(type).get(new NamespacedKey(key.namespace(), key.path()));
}
}
@@ -20,6 +20,7 @@ package art.arcane.iris.platform.bukkit;
import art.arcane.iris.spi.IrisLogging;
import com.volmit.item.ItemAttribute;
import com.volmit.resource.ResourceId;
import org.bukkit.NamespacedKey;
import org.bukkit.Registry;
import org.bukkit.attribute.Attributable;
@@ -29,6 +30,7 @@ import org.bukkit.attribute.AttributeModifier;
import org.bukkit.inventory.EquipmentSlotGroup;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.UUID;
@@ -37,8 +39,7 @@ import java.util.concurrent.ConcurrentHashMap;
/** Applies the attribute modifiers a module decided on to Bukkit items and entities. */
public final class BukkitAttributes {
private static final Set<String> WARNED_ATTRIBUTES = ConcurrentHashMap.newKeySet();
private static final String GENERIC_UNDERSCORE = "generic_";
private static final String GENERIC_DOT = "generic.";
private static final List<String> GENERIC_PREFIXES = List.of("generic_", "generic.");
private static final int MAX_NAME_LENGTH = 32;
private static final String DEFAULT_NAME = "modifier";
@@ -63,41 +64,39 @@ public final class BukkitAttributes {
}
}
/** The attribute the key names; a vanilla key may still carry the {@code generic_} or {@code generic.} prefix older versions had. */
private static Attribute resolveAttribute(ItemAttribute modifier) {
String value = modifier.attribute().trim().toLowerCase(Locale.ROOT);
Attribute resolved;
if (value.contains(":")) {
NamespacedKey key = NamespacedKey.fromString(value);
resolved = key == null ? null : Registry.ATTRIBUTE.get(key);
} else {
resolved = Registry.ATTRIBUTE.get(NamespacedKey.minecraft(value));
if (resolved == null && value.startsWith(GENERIC_UNDERSCORE)) {
resolved = Registry.ATTRIBUTE.get(NamespacedKey.minecraft(value.substring(GENERIC_UNDERSCORE.length())));
}
if (resolved == null && value.startsWith(GENERIC_DOT)) {
resolved = Registry.ATTRIBUTE.get(NamespacedKey.minecraft(value.substring(GENERIC_DOT.length())));
}
ResourceId id = modifier.attribute();
Attribute resolved = Registry.ATTRIBUTE.get(new NamespacedKey(id.namespace(), id.path()));
if (resolved == null && id.namespace().equals(NamespacedKey.MINECRAFT)) {
resolved = withoutGenericPrefix(id.path());
}
if (resolved == null && WARNED_ATTRIBUTES.add(value)) {
IrisLogging.warn("Unknown attribute '" + modifier.attribute() + "' in attribute-modifier '" + modifier.name() + "'");
if (resolved == null && WARNED_ATTRIBUTES.add(id.toString())) {
IrisLogging.warn("Unknown attribute '" + id + "' in attribute-modifier '" + modifier.name() + "'");
}
return resolved;
}
private static AttributeModifier create(ItemAttribute modifier) {
NamespacedKey key = NamespacedKey.minecraft(uniqueKey(modifier.name()));
return new AttributeModifier(key, modifier.amount(), resolveOperation(modifier.operation()), EquipmentSlotGroup.ANY);
private static Attribute withoutGenericPrefix(String path) {
for (String prefix : GENERIC_PREFIXES) {
if (path.startsWith(prefix)) {
return Registry.ATTRIBUTE.get(NamespacedKey.minecraft(path.substring(prefix.length())));
}
}
return null;
}
private static AttributeModifier.Operation resolveOperation(String operation) {
if (operation.isBlank()) {
return AttributeModifier.Operation.ADD_NUMBER;
}
try {
return AttributeModifier.Operation.valueOf(operation.trim().toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException e) {
return AttributeModifier.Operation.ADD_NUMBER;
}
private static AttributeModifier create(ItemAttribute modifier) {
NamespacedKey key = NamespacedKey.minecraft(uniqueKey(modifier.name()));
return new AttributeModifier(key, modifier.amount(), operationOf(modifier.operation()), EquipmentSlotGroup.ANY);
}
private static AttributeModifier.Operation operationOf(ItemAttribute.Operation operation) {
return switch (operation) {
case ADD_VALUE -> AttributeModifier.Operation.ADD_NUMBER;
case ADD_MULTIPLIED_BASE -> AttributeModifier.Operation.ADD_SCALAR;
case ADD_MULTIPLIED_TOTAL -> AttributeModifier.Operation.MULTIPLY_SCALAR_1;
};
}
private static String uniqueKey(String name) {
@@ -18,7 +18,6 @@
package art.arcane.iris.platform.bukkit;
import art.arcane.iris.core.link.Identifier;
import art.arcane.iris.core.modules.IrisItemRegistry;
import art.arcane.iris.core.service.ExternalDataSVC;
import art.arcane.iris.spi.IrisLogging;
@@ -30,6 +29,7 @@ import art.arcane.volmlib.util.format.Form;
import com.volmit.item.ItemAttribute;
import com.volmit.item.ItemDrop;
import com.volmit.item.ItemEnchantment;
import com.volmit.resource.ResourceId;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
@@ -44,9 +44,8 @@ import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.inventory.meta.components.CustomModelDataComponent;
import org.bukkit.material.Colorable;
import java.awt.Color;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
/** Creates the Bukkit item stacks that module {@link ItemDrop}s describe. */
@@ -66,7 +65,7 @@ public final class BukkitItemStacks {
return new ItemStack(Material.AIR);
}
stack.setItemMeta(applyProperties(stack, drop));
return BukkitPlatform.applyCustomNbt(stack, drop.customNbt().isEmpty() ? null : new KMap<>(drop.customNbt()));
return BukkitPlatform.applyCustomNbt(stack, customNbtOf(drop));
} catch (Throwable e) {
IrisLogging.reportError(e);
return new ItemStack(Material.AIR);
@@ -88,7 +87,7 @@ public final class BukkitItemStacks {
private static ItemStack baseStack(ItemDrop drop) {
if (IrisItemRegistry.isCustomItem(drop.item())) {
Optional<ItemStack> custom = IrisServices.get(ExternalDataSVC.class)
.getItemStack(Identifier.fromString(drop.item()), drop.customNbt().isEmpty() ? null : new KMap<>(drop.customNbt()));
.getItemStack(IrisItemRegistry.identifierOf(drop.item()), customNbtOf(drop));
if (custom.isEmpty()) {
IrisLogging.warn("Unknown Material: " + drop.item());
return null;
@@ -97,7 +96,12 @@ public final class BukkitItemStacks {
stack.setAmount(drop.amount());
return stack;
}
return new ItemStack(BukkitBlockResolution.getMaterial(drop.item()), drop.amount());
return new ItemStack(BukkitBlockResolution.getMaterial(drop.item().toString()), drop.amount());
}
private static KMap<String, Object> customNbtOf(ItemDrop drop) {
Map<String, Object> customNbt = drop.extras().customNbt();
return customNbt.isEmpty() ? null : new KMap<>(customNbt);
}
private static ItemMeta applyProperties(ItemStack stack, ItemDrop drop) {
@@ -111,31 +115,31 @@ public final class BukkitItemStacks {
BukkitAttributes.apply(attribute, meta);
}
meta.setUnbreakable(drop.unbreakable());
ItemDrop.Look look = drop.look();
ItemDrop.Wear wear = drop.wear();
meta.setUnbreakable(wear.unbreakable());
flags(drop).forEach(meta::addItemFlags);
if (drop.customModel().isPresent()) {
if (look.customModel().isPresent()) {
CustomModelDataComponent customModelData = meta.getCustomModelDataComponent();
customModelData.setFloats(List.of((float) drop.customModel().getAsInt()));
customModelData.setFloats(List.of((float) look.customModel().getAsInt()));
meta.setCustomModelDataComponent(customModelData);
}
int maxDurability = stack.getType().getMaxDurability();
if (drop.damage().isPresent() && maxDurability > 0 && meta instanceof Damageable damageable) {
damageable.setDamage((int) Math.round(Math.max(0, Math.min(maxDurability, drop.damage().getAsDouble() * maxDurability))));
if (wear.damage().isPresent() && maxDurability > 0 && meta instanceof Damageable damageable) {
damageable.setDamage((int) Math.round(Math.max(0, Math.min(maxDurability, wear.damage().getAsDouble() * maxDurability))));
}
if (drop.leatherColor().isPresent() && meta instanceof LeatherArmorMeta leather) {
Color c = Color.decode(drop.leatherColor().get());
leather.setColor(org.bukkit.Color.fromRGB(c.getRed(), c.getGreen(), c.getBlue()));
if (look.leatherColor().isPresent() && meta instanceof LeatherArmorMeta leather) {
leather.setColor(org.bukkit.Color.fromRGB(look.leatherColor().getAsInt()));
}
DyeColor dye = dyeColor(drop);
if (dye != null && meta instanceof Colorable colorable) {
colorable.setColor(dye);
if (look.dyeColor().isPresent() && meta instanceof Colorable colorable) {
colorable.setColor(DyeColor.valueOf(look.dyeColor().get().name()));
}
drop.displayName().ifPresent(name -> meta.setDisplayName(C.translateAlternateColorCodes('&', name)));
look.displayName().ifPresent(name -> meta.setDisplayName(C.translateAlternateColorCodes('&', name)));
meta.setLore(lore(drop));
return meta;
@@ -158,19 +162,13 @@ public final class BukkitItemStacks {
}
}
/** A bare path ({@code sharpness}) or a full namespaced key ({@code mymod:vorpal}), as the modded resolver accepts. */
private static Enchantment resolveEnchantment(String raw) {
if (raw.isBlank()) {
return null;
}
String value = raw.trim().toLowerCase(Locale.ROOT).replace(' ', '_');
NamespacedKey key = value.indexOf(':') >= 0 ? NamespacedKey.fromString(value) : NamespacedKey.minecraft(value);
return key == null ? null : Registry.ENCHANTMENT.get(key);
private static Enchantment resolveEnchantment(ResourceId key) {
return Registry.ENCHANTMENT.get(new NamespacedKey(key.namespace(), key.path()));
}
private static List<ItemFlag> flags(ItemDrop drop) {
KList<ItemFlag> resolved = new KList<>();
for (String flag : drop.flags()) {
for (String flag : drop.extras().flags()) {
if (flag == null) {
continue;
}
@@ -182,20 +180,9 @@ public final class BukkitItemStacks {
return resolved;
}
private static DyeColor dyeColor(ItemDrop drop) {
if (drop.dyeColor().isEmpty()) {
return null;
}
try {
return DyeColor.valueOf(drop.dyeColor().get());
} catch (IllegalArgumentException e) {
return null;
}
}
private static KList<String> lore(ItemDrop drop) {
KList<String> lore = new KList<>();
for (String line : drop.lore()) {
for (String line : drop.look().lore()) {
String colored = C.translateAlternateColorCodes('&', line);
if (colored.length() > LORE_WRAP_WIDTH) {
for (String wrapped : Form.wrapWords(colored, LORE_WRAP_WIDTH).split("\\Q\n\\E")) {
@@ -35,6 +35,7 @@ import art.arcane.iris.engine.spawn.SpawnModule;
import art.arcane.iris.engine.spawn.SpawnResources;
import art.arcane.iris.spi.PlatformWorld;
import com.volmit.item.ItemRegistry;
import com.volmit.resource.ContentKey;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
@@ -46,7 +47,7 @@ import java.util.OptionalInt;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -71,7 +72,7 @@ public class ContentServicesTest {
ModuleResourceFixture fixture = ModuleResourceFixture.serve(data);
ModuleResourceFixture.serveModules(data, new SpawnModule(), new LootModule());
ItemRegistry items = mock(ItemRegistry.class);
when(items.maxDurability(anyString())).thenReturn(OptionalInt.of(0));
when(items.maxDurability(any(ContentKey.class))).thenReturn(OptionalInt.of(0));
when(data.getPackResources().items()).thenReturn(items);
when(engine.getData()).thenReturn(data);
IrisWorld engineWorld = mock(IrisWorld.class);
@@ -103,8 +104,8 @@ public class ContentServicesTest {
assertTrue(guard.flags().baby());
assertTrue(guard.flags().glowing());
assertFalse(guard.isSpecial());
assertEquals("iron_helmet", guard.equipment().helmet().item());
assertEquals(List.of(new ContentItem.Enchantment("protection", 3)), guard.equipment().helmet().enchantments());
assertEquals("minecraft:iron_helmet", guard.equipment().helmet().item());
assertEquals(List.of(new ContentItem.Enchantment("minecraft:protection", 3)), guard.equipment().helmet().enchantments());
assertEquals(List.of("guard/drops"), guard.lootTables());
assertEquals(List.of(new ContentEntity.Command(List.of("say hi {x}"), 4, true, 20)), guard.commands());
assertTrue(ContentServices.entity(engine, "nobody").isEmpty());
@@ -125,7 +126,7 @@ public class ContentServicesTest {
List<ContentItem> items = ContentServices.tableItems(engine, 10, 64, -3, "guard/drops");
assertEquals(1, items.size());
assertEquals("bread", items.getFirst().item());
assertEquals("minecraft:bread", items.getFirst().item());
assertEquals(3, items.getFirst().amount());
assertEquals(items, ContentServices.tableItems(engine, 10, 64, -3, "guard/drops"));
assertTrue(ContentServices.tableItems(engine, 10, 64, -3, "missing").isEmpty());
@@ -119,7 +119,7 @@ public class BuiltInModulesJarServicesTest {
assertNotSame(BlockDropping.class, drops.getClass());
BlockDrops.Result result = drops.drops(world, new BlockDrops.Broken(AT, new BlockState("minecraft:stone")));
assertEquals(1, result.drops().size());
assertEquals("gravel", result.drops().getFirst().item());
assertEquals("minecraft:gravel", result.drops().getFirst().item().toString());
assertEquals(2, result.drops().getFirst().amount());
assertTrue(result.replacesVanillaDrops());
assertEquals(BlockDrops.Result.NONE, drops.drops(world, new BlockDrops.Broken(AT, new BlockState("minecraft:dirt"))));
@@ -160,12 +160,13 @@ public final class CarveTestWorld implements PackWorld {
IrisData pack = mock(IrisData.class);
ResourceLoader<IrisBlockData> blocks = mock(ResourceLoader.class);
when(pack.getBlockLoader()).thenReturn(blocks);
when(pack.getDataFolder()).thenReturn(new java.io.File(NAMESPACE));
return pack;
}
private final class Resources implements PackResources {
private final UUID snapshot = UUID.randomUUID();
private final NoiseFactory noise = new IrisNoiseFactory(data);
private final NoiseFactory noise = new IrisNoiseFactory(data, new IrisPackResources(data, java.util.List::of));
@Override
public ResourceId packId() {
@@ -27,7 +27,7 @@ import static org.mockito.Mockito.when;
/** IrisApi's blocks are the bound platform's, through their keys, and so are its traits, tags and face support. */
public class IrisBlockRegistryTest {
private final IrisBlockRegistry blocks = new IrisBlockRegistry(mock(art.arcane.iris.core.loader.IrisData.class));
private final IrisBlockRegistry blocks = new IrisBlockRegistry(mock(art.arcane.iris.core.loader.IrisData.class), mock(IrisPackResources.class));
private PlatformRegistries registries;
private PlatformBlockState stone;
private PlatformBlockState sand;
@@ -67,7 +67,7 @@ public class IrisValuesTest {
@Test
public void blockSpecsResolveThroughThePlatformWithTheirProperties() {
UsableBlockPlatform.bind();
IrisBlockRegistry blocks = new IrisBlockRegistry(packWithoutCustomBlocks());
IrisBlockRegistry blocks = blocksOf(packWithoutCustomBlocks());
assertEquals(BlockState.parse("minecraft:iron_ore"), blocks.resolve(BlockSpec.of("iron_ore")));
assertEquals(BlockState.parse("minecraft:oak_log[axis=y]"), blocks.resolve(BlockSpec.of("minecraft:oak_log").withProperty("axis", "y")));
@@ -84,7 +84,7 @@ public class IrisValuesTest {
bind(registries);
IrisData data = packWithoutCustomBlocks();
when(data.getBlockLoader().load("glowing_stone", false)).thenReturn(new IrisBlockData("minecraft:stone").setData(new KMap<String, Object>().qput("lit", true)));
IrisBlockRegistry blocks = new IrisBlockRegistry(data);
IrisBlockRegistry blocks = blocksOf(data);
assertEquals(BlockState.parse("minecraft:stone[lit=true]"), blocks.resolve(BlockSpec.of("glowing_stone")));
assertEquals(BlockState.parse("minecraft:cobblestone"), blocks.resolve(BlockSpec.of("mod:missing").withBackup(BlockSpec.of("cobblestone"))));
@@ -95,7 +95,7 @@ public class IrisValuesTest {
UsableBlockPlatform.bind();
TileData.TileFactory previous = TileData.bindPlatformFactory((state, properties) -> new TileData(state.key(), properties));
try {
IrisBlockRegistry blocks = new IrisBlockRegistry(packWithoutCustomBlocks());
IrisBlockRegistry blocks = blocksOf(packWithoutCustomBlocks());
BlockSpec spawner = BlockSpec.of("spawner").withTileData(Map.of("Delay", 20.0));
assertEquals(Optional.empty(), blocks.blockEntity(BlockSpec.of("stone")));
@@ -105,7 +105,7 @@ public class IrisValuesTest {
PlatformRegistries registries = mock(PlatformRegistries.class);
when(registries.block(anyString())).thenReturn(withEntity);
bind(registries);
BlockEntityData entity = new IrisBlockRegistry(packWithoutCustomBlocks()).blockEntity(BlockSpec.of("chest").withTileData(Map.of("Lock", "key")))
BlockEntityData entity = blocksOf(packWithoutCustomBlocks()).blockEntity(BlockSpec.of("chest").withTileData(Map.of("Lock", "key")))
.orElseThrow();
assertEquals(BlockEntities.TILE_FORMAT, entity.format());
} finally {
@@ -120,7 +120,7 @@ public class IrisValuesTest {
IrisData data = packWithoutCustomBlocks();
NoiseStyle style = new Gson().fromJson(json, NoiseStyle.class);
CNG iris = new Gson().fromJson(json, IrisGeneratorStyle.class).create(new RNG(1337), data);
NoiseSampler sampler = new IrisNoiseFactory(data).sampler(style, 1337);
NoiseSampler sampler = noiseOf(data).sampler(style, 1337);
for (double[] column : COLUMNS) {
assertEquals(iris.noise(column[0], column[1]), sampler.sample(column[0], column[1]), 0);
@@ -133,7 +133,7 @@ public class IrisValuesTest {
String json = "{\"style\": \"SIMPLEX\", \"zoom\": 4, \"exponent\": 1.5, \"fracture\": {\"style\": \"PERLIN\", \"zoom\": 2, \"multiplier\": 3}}";
IrisData data = packWithoutCustomBlocks();
CNG iris = new Gson().fromJson(json, IrisGeneratorStyle.class).create(new RNG(1337), data);
NoiseSampler sampler = new IrisNoiseFactory(data).sampler(new Gson().fromJson(json, NoiseStyle.class), 1337);
NoiseSampler sampler = noiseOf(data).sampler(new Gson().fromJson(json, NoiseStyle.class), 1337);
for (double[] column : COLUMNS) {
assertEquals(iris.noiseFastSigned2D(column[0], column[1]), sampler.signed(column[0], column[1]), 0);
@@ -148,7 +148,7 @@ public class IrisValuesTest {
IrisData data = packWithoutCustomBlocks();
double scale = 1.5D;
CNG baked = new Gson().fromJson(json, IrisGeneratorStyle.class).createNoCache(new RNG(4242), data).bake().scale(scale).bake();
NoiseSampler plain = new IrisNoiseFactory(data).sampler(new Gson().fromJson(json, NoiseStyle.class), 4242);
NoiseSampler plain = noiseOf(data).sampler(new Gson().fromJson(json, NoiseStyle.class), 4242);
NoiseSampler scaled = plain.scaled(scale);
for (int x = -30; x <= 30; x += 3) {
@@ -160,7 +160,7 @@ public class IrisValuesTest {
@Test
public void theIrisStyleIsTheSignatureNoiseOfTheSeedThatSetsTheThicknessOfBiomeLayers() {
IrisNoiseFactory factory = new IrisNoiseFactory(packWithoutCustomBlocks());
IrisNoiseFactory factory = noiseOf(packWithoutCustomBlocks());
long mismatches = 0;
for (long seed : new long[]{1, 7235, -3999281L, 1337L * 31, 987654321987L}) {
CNG signature = CNG.signature(new RNG(seed));
@@ -178,7 +178,7 @@ public class IrisValuesTest {
@Test
public void aStyleNameIrisDoesNotKnowIsFlat() {
IrisData data = packWithoutCustomBlocks();
IrisNoiseFactory noise = new IrisNoiseFactory(data);
IrisNoiseFactory noise = noiseOf(data);
NoiseSampler unknown = noise.sampler(NoiseStyle.of("NOT_A_STYLE"), 7);
NoiseSampler flat = noise.sampler(NoiseStyle.of(NoiseStyle.FLAT), 7);
@@ -194,7 +194,7 @@ public class IrisValuesTest {
+ "{\"block\": \"stone\"}, {\"block\": \"andesite\", \"weight\": 2}, {\"block\": \"granite\", \"weight\": 3}]}";
IrisData data = packWithoutCustomBlocks();
IrisMaterialPalette iris = new Gson().fromJson(json, IrisMaterialPalette.class);
PaletteSampler sampler = new IrisBlockRegistry(data).palette(new Gson().fromJson(json, PaletteSpec.class), 1337);
PaletteSampler sampler = blocksOf(data).palette(new Gson().fromJson(json, PaletteSpec.class), 1337);
assertTrue("the positions cover several blocks", picksLike(iris, sampler, data, 1337).size() > 1);
}
@@ -203,7 +203,7 @@ public class IrisValuesTest {
public void aPaletteWithoutOptionsIsOneStoneEverywhereLikeIris() {
UsableBlockPlatform.bind();
IrisData data = packWithoutCustomBlocks();
PaletteSampler sampler = new IrisBlockRegistry(data).palette(new Gson().fromJson("{}", PaletteSpec.class), 7);
PaletteSampler sampler = blocksOf(data).palette(new Gson().fromJson("{}", PaletteSpec.class), 7);
picksLike(new Gson().fromJson("{}", IrisMaterialPalette.class), sampler, data, 7);
assertEquals(BlockState.parse("minecraft:stone"), sampler.at(3, 4, 5));
@@ -212,7 +212,7 @@ public class IrisValuesTest {
@Test
public void palettesAreBuiltOncePerSpecAndSeed() {
UsableBlockPlatform.bind();
IrisBlockRegistry blocks = new IrisBlockRegistry(packWithoutCustomBlocks());
IrisBlockRegistry blocks = blocksOf(packWithoutCustomBlocks());
PaletteSpec spec = PaletteSpec.of(List.of(BlockSpec.of("stone"), BlockSpec.of("dirt")));
assertSame(blocks.palette(spec, 1), blocks.palette(PaletteSpec.of(spec.palette()), 1));
@@ -222,7 +222,7 @@ public class IrisValuesTest {
@Test
public void aPaletteWithNoBlockToPickIsRefused() {
UsableBlockPlatform.bind();
IrisBlockRegistry blocks = new IrisBlockRegistry(packWithoutCustomBlocks());
IrisBlockRegistry blocks = blocksOf(packWithoutCustomBlocks());
assertThrows(IllegalArgumentException.class, () -> blocks.palette(PaletteSpec.of(List.of()), 1));
assertThrows(IllegalArgumentException.class, () -> blocks.palette(PaletteSpec.of(List.of(BlockSpec.of("stone").withWeight(0))), 1));
@@ -245,9 +245,18 @@ public class IrisValuesTest {
@SuppressWarnings("unchecked")
ResourceLoader<IrisBlockData> blocks = mock(ResourceLoader.class);
when(data.getBlockLoader()).thenReturn(blocks);
when(data.getDataFolder()).thenReturn(new java.io.File("test-pack"));
return data;
}
private static IrisBlockRegistry blocksOf(IrisData data) {
return new IrisBlockRegistry(data, new IrisPackResources(data, List::of));
}
private static IrisNoiseFactory noiseOf(IrisData data) {
return new IrisNoiseFactory(data, new IrisPackResources(data, List::of));
}
private static void bind(PlatformRegistries registries) {
UsableBlockPlatform.unbind();
IrisPlatform platform = mock(IrisPlatform.class);
@@ -56,7 +56,7 @@ public class PackModuleResourceKindTest {
public final class Keep {
@Desc("Towers on the walls") @MinNumber(1)
private int towers = 4;
@ResourceRef(Keep.class)
@Ref(kind = Keep.class)
private String next = "";
public int towers() { return towers; }
@@ -20,6 +20,7 @@ package art.arcane.iris.core.project;
import art.arcane.iris.builtin.structure.StructureSettings;
import art.arcane.iris.core.modules.StructureModelModule;
import art.arcane.iris.engine.framework.structure.StructureResources;
import art.arcane.iris.engine.mantle.components.StructureModule;
import art.arcane.iris.engine.object.placement.IrisObjectPlacement;
import art.arcane.iris.core.loader.IrisData;
@@ -213,6 +214,11 @@ public class SchemaBuilderParityTest {
assertEquals(4064, maxDepth.getInt("maximum"));
assertFalse(properties.has("rotation"));
assertFalse(properties.has("translate"));
assertEquals("@IrisStructureRef completes the keys of Iris's structure model",
"#/definitions/erz" + StructureResources.STRUCTURES.folder(),
properties.getJSONObject("structures").getJSONObject("items").getString("$ref"));
assertEquals("@Ref(kind = PackBiome.class) completes the pack's biome keys", "#/definitions/erzbiomes",
properties.getJSONObject("caveBiomes").getJSONObject("items").getString("$ref"));
assertFalse(properties.has("scale"));
}
@@ -518,8 +524,13 @@ public class SchemaBuilderParityTest {
ModuleResourceFixture.serve(data);
ResourceLoader<IrisExpression> expressionLoader = mock(ResourceLoader.class);
ResourceLoader<IrisBlockData> blockLoader = mock(ResourceLoader.class);
ResourceLoader<IrisBiome> biomeLoader = mock(ResourceLoader.class);
KMap<Class<? extends IrisRegistrant>, ResourceLoader<? extends IrisRegistrant>> loaders = new KMap<>();
loaders.put(IrisExpression.class, expressionLoader);
loaders.put(IrisBiome.class, biomeLoader);
when(biomeLoader.getPossibleKeys()).thenReturn(new String[]{"plains"});
when(biomeLoader.getFolderName()).thenReturn("biomes");
when(biomeLoader.getResourceTypeName()).thenReturn("Biome");
when(data.getBlockLoader()).thenReturn(blockLoader);
when(data.getLoaders()).thenReturn(loaders);
when(data.getPossibleSnippets(anyString())).thenReturn(new KList<>());
@@ -11,6 +11,7 @@ import art.arcane.iris.engine.terrain.TerrainTestSettings;
import art.arcane.iris.engine.terrain.TestPackWorld;
import com.volmit.config.FeatureSettings;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.world.UpperDimension;
import org.junit.After;
import org.junit.Before;
@@ -117,8 +118,8 @@ public class TerrainPalettesPinTest {
}
@Override
public String key() {
return UPPER_DIMENSION_KEY;
public ResourceId id() {
return resources.idOf(UPPER_DIMENSION_KEY);
}
@Override
@@ -12,6 +12,7 @@ import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.volmlib.util.collection.KList;
import com.google.gson.Gson;
import com.volmit.host.LoadedPack;
import com.volmit.resource.ResourceId;
import com.volmit.vanilla.JigsawOverrides;
import org.junit.After;
import org.junit.Rule;
@@ -137,7 +138,7 @@ public class NativeStructureStartsTest {
+ "{\"block\":\"minecraft:tuff\"}]}}", StructureTerrain.class);
StructureStilts stilt = GSON.fromJson("{\"maxDepth\":40,\"spacing\":2,"
+ "\"palette\":{\"palette\":[{\"block\":\"minecraft:stone_bricks\"}]}}", StructureStilts.class);
JigsawOverrides jigsaw = JigsawOverrides.none().withStartPool("minecraft:village/plains/town_centers")
JigsawOverrides jigsaw = JigsawOverrides.none().withStartPool(ResourceId.parse("minecraft:village/plains/town_centers"))
.withMaxDepth(5).withHeightmap(JigsawOverrides.Heightmap.OCEAN_FLOOR_WG).withExpansionHack(false);
StructurePlacement fitted = TestSettings.with(placement("fitted", true, -40, -20, 1D,
TestSettings.with(source("minecraft:ancient_city", 1), "jigsaw", jigsaw)), "terrain", terrain, "stilt", stilt);
@@ -21,7 +21,10 @@ package art.arcane.iris.engine.loot;
import art.arcane.iris.builtin.loot.LootTable;
import com.google.gson.Gson;
import com.volmit.item.ItemDrop;
import com.volmit.host.ModuleLogs;
import com.volmit.item.ItemRegistry;
import com.volmit.resource.ContentKey;
import com.volmit.resource.ResourceId;
import org.junit.Before;
import org.junit.Test;
@@ -30,7 +33,7 @@ import java.util.List;
import java.util.OptionalInt;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -39,6 +42,9 @@ import static org.mockito.Mockito.when;
* before the loot classes became settings of the loot module; a change in them changes the loot of existing worlds.
* They were retaken once when an item's absent values became {@code Optional}s: the items printed the old way (absent
* values as {@code null}) still hashed to the old numbers, -492887340, -92432338, -1096436977, -1436497629 and -1714085578.
* They were retaken again when item, enchantment and attribute keys became ids and colours typed values: the items
* printed the old way (keys by path, operations by Bukkit name, colours as written) still hashed to -1656514080,
* 672855254, -359051997, -717275247 and 1936773406.
*/
public class LootDrawPinTest {
private static final long LOOT_SEED = 8123456789L;
@@ -62,17 +68,21 @@ public class LootDrawPinTest {
@Before
public void knowTheItems() {
registry = mock(ItemRegistry.class);
when(registry.maxDurability(anyString())).thenReturn(OptionalInt.empty());
when(registry.maxDurability("diamond_sword")).thenReturn(OptionalInt.of(1561));
when(registry.maxDurability("diamond")).thenReturn(OptionalInt.of(0));
when(registry.maxDurability("bread")).thenReturn(OptionalInt.of(0));
when(registry.maxDurability("stick")).thenReturn(OptionalInt.of(0));
when(registry.maxDurability(any(ContentKey.class))).thenReturn(OptionalInt.empty());
when(registry.maxDurability(platformItem("diamond_sword"))).thenReturn(OptionalInt.of(1561));
when(registry.maxDurability(platformItem("diamond"))).thenReturn(OptionalInt.of(0));
when(registry.maxDurability(platformItem("bread"))).thenReturn(OptionalInt.of(0));
when(registry.maxDurability(platformItem("stick"))).thenReturn(OptionalInt.of(0));
}
private static ContentKey platformItem(String name) {
return new ContentKey.Registered(ResourceId.ofPlatformKey(name));
}
@Test
public void aTableGivesThePinnedItemsAtEachSpot() {
LootTable table = new Gson().fromJson(TABLE, LootTable.class);
LootItems items = new LootItems(registry, false);
LootItems items = new LootItems(registry, false, ModuleLogs.discarding());
List<Integer> hashes = new ArrayList<>();
for (int[] spot : SPOTS) {
@@ -80,6 +90,6 @@ public class LootDrawPinTest {
hashes.add(drops.toString().hashCode());
}
assertEquals(List.of(-1656514080, 672855254, -359051997, -717275247, 1936773406), hashes);
assertEquals(List.of(532699340, 1454887894, -1673240838, 1965175800, 1414053514), hashes);
}
}
@@ -4,8 +4,13 @@ import art.arcane.iris.builtin.loot.LootEntry;
import art.arcane.iris.builtin.loot.LootTable;
import art.arcane.iris.engine.object.TestSettings;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.host.ModuleLogs;
import com.volmit.item.DyeColor;
import com.volmit.item.ItemAttribute;
import com.volmit.item.ItemDrop;
import com.volmit.item.ItemRegistry;
import com.volmit.resource.ContentKey;
import com.volmit.resource.ResourceId;
import org.junit.Before;
import org.junit.Test;
@@ -16,7 +21,7 @@ import java.util.OptionalInt;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -29,9 +34,9 @@ public class LootItemsTest {
@Before
public void knowTheItems() {
registry = mock(ItemRegistry.class);
when(registry.maxDurability(anyString())).thenReturn(OptionalInt.empty());
when(registry.maxDurability("diamond_sword")).thenReturn(OptionalInt.of(1561));
when(registry.maxDurability("diamond")).thenReturn(OptionalInt.of(0));
when(registry.maxDurability(any(ContentKey.class))).thenReturn(OptionalInt.empty());
when(registry.maxDurability(swordKey())).thenReturn(OptionalInt.of(1561));
when(registry.maxDurability(new ContentKey.Registered(ResourceId.parse("minecraft:diamond")))).thenReturn(OptionalInt.of(0));
}
@Test
@@ -48,12 +53,51 @@ public class LootItemsTest {
double bonus = expected.d(2, 6);
double damage = 1D - expected.d(0.25, 0.75);
ItemDrop drop = new LootItems(registry, false).give(entry, new RNG(5L));
ItemDrop drop = new LootItems(registry, false, ModuleLogs.discarding()).give(entry, new RNG(5L));
assertEquals(amount, drop.amount());
assertEquals(level, drop.enchantments().getFirst().level());
assertEquals(bonus, drop.attributes().getFirst().amount(), 0D);
assertEquals(damage, drop.damage().orElseThrow(), 0D);
assertEquals(damage, drop.wear().damage().orElseThrow(), 0D);
}
@Test
public void packKeysReachTheHostAsNamespacedTypedValues() {
LootEntry entry = entry("""
{"type": "Diamond_Sword", "leatherColor": "#FF8000", "dyeColor": "red",
"enchantments": [{"enchantment": "SHARPNESS", "chance": 1}],
"attributes": [{"attribute": "max_health", "operation": "MULTIPLY_SCALAR_1", "chance": 1}]}""");
ItemDrop drop = new LootItems(registry, false, ModuleLogs.discarding()).give(entry, new RNG(5L));
assertEquals(swordKey(), drop.item());
assertEquals(ResourceId.parse("minecraft:sharpness"), drop.enchantments().getFirst().key());
assertEquals(ResourceId.parse("minecraft:max_health"), drop.attributes().getFirst().attribute());
assertEquals(ItemAttribute.Operation.ADD_MULTIPLIED_TOTAL, drop.attributes().getFirst().operation());
assertEquals(OptionalInt.of(0xFF8000), drop.look().leatherColor());
assertEquals(Optional.of(DyeColor.RED), drop.look().dyeColor());
}
@Test
public void aColourThatDoesNotReadIsLeftOutInsteadOfLosingTheItem() {
ItemDrop drop = new LootItems(registry, false, ModuleLogs.discarding())
.give(entry("{\"type\": \"diamond\", \"leatherColor\": \"orange\", \"dyeColor\": \"mauve\"}"), new RNG(5L));
assertTrue(drop.look().leatherColor().isEmpty());
assertTrue(drop.look().dyeColor().isEmpty());
}
@Test
public void anItemOfAnotherProviderIsProvidedByName() {
when(registry.maxDurability(new ContentKey.Provided("Nexo", "Ruby Sword"))).thenReturn(OptionalInt.of(0));
ItemDrop drop = new LootItems(registry, false, ModuleLogs.discarding()).give(entry("{\"type\": \"Nexo:Ruby Sword\"}"), new RNG(5L));
assertEquals(new ContentKey.Provided("Nexo", "Ruby Sword"), drop.item());
}
private static ContentKey swordKey() {
return new ContentKey.Registered(ResourceId.parse("minecraft:diamond_sword"));
}
@Test
@@ -62,10 +106,10 @@ public class LootItemsTest {
RNG rng = new RNG(9L);
RNG untouched = new RNG(9L);
ItemDrop drop = new LootItems(registry, false).give(entry, rng);
ItemDrop drop = new LootItems(registry, false, ModuleLogs.discarding()).give(entry, rng);
assertEquals(2, drop.amount());
assertTrue(drop.damage().isEmpty());
assertTrue(drop.wear().damage().isEmpty());
assertEquals(untouched.nextLong(), rng.nextLong());
}
@@ -74,8 +118,8 @@ public class LootItemsTest {
RNG rng = new RNG(9L);
RNG untouched = new RNG(9L);
assertNull(new LootItems(registry, false).give(entry("{\"type\": \"not_an_item\"}"), rng));
assertNull(new LootItems(registry, false).give(entry("{\"type\": \"air\"}"), rng));
assertNull(new LootItems(registry, false, ModuleLogs.discarding()).give(entry("{\"type\": \"not_an_item\"}"), rng));
assertNull(new LootItems(registry, false, ModuleLogs.discarding()).give(entry("{\"type\": \"air\"}"), rng));
assertEquals(untouched.nextLong(), rng.nextLong());
}
@@ -83,19 +127,19 @@ public class LootItemsTest {
public void debugItemsSayWhereTheyCameFrom() {
LootTable table = table("{\"name\": \"dungeon\", \"rarity\": 4, \"minPicked\": 1, \"maxPicked\": 1, \"loot\": [{\"type\": \"diamond\", \"rarity\": 3}]}");
List<ItemDrop> drops = new LootItems(registry, true).draw("dungeon", table, LOOT_SEED, 0, 64, 0);
List<ItemDrop> drops = new LootItems(registry, true, ModuleLogs.discarding()).draw("dungeon", table, LOOT_SEED, 0, 64, 0);
for (ItemDrop drop : drops) {
assertEquals(Optional.of(new ItemDrop.Source(Optional.of("dungeon"), 4, 3)), drop.source());
}
assertTrue(new LootItems(registry, false).draw("dungeon", table, LOOT_SEED, 0, 64, 0).stream().allMatch(drop -> drop.source().isEmpty()));
assertTrue(new LootItems(registry, false, ModuleLogs.discarding()).draw("dungeon", table, LOOT_SEED, 0, 64, 0).stream().allMatch(drop -> drop.source().isEmpty()));
}
@Test
public void aTableGivesTheSameItemsAtTheSameSpotAndSeed() {
LootTable table = table("{\"name\": \"tools\", \"minPicked\": 2, \"maxPicked\": 4, \"loot\": [{\"type\": \"diamond\", \"maxAmount\": 5}, {\"type\": \"diamond_sword\"}]}");
LootItems items = new LootItems(registry, false);
LootItems items = new LootItems(registry, false, ModuleLogs.discarding());
assertEquals(items.draw("tools", table, LOOT_SEED, 10, 64, -30), items.draw("tools", table, LOOT_SEED, 10, 64, -30));
}
@@ -18,6 +18,7 @@ import art.arcane.iris.engine.object.world.region.IrisRegion;
import com.volmit.config.Desc;
import com.volmit.config.MaxNumber;
import art.arcane.volmlib.util.math.RNG;
import com.volmit.host.ModuleLogs;
import com.volmit.item.ItemRegistry;
import com.volmit.world.PackWorld;
import org.junit.Test;
@@ -252,7 +253,7 @@ public class LootResolverTest {
public void emptyLootTableReturnsNoItems() {
LootTable table = TestSettings.of(LootTable.class, "{\"name\": \"empty\"}");
assertTrue(new LootItems(mock(ItemRegistry.class), false).draw("empty", table, 7L, 0, 64, 0).isEmpty());
assertTrue(new LootItems(mock(ItemRegistry.class), false, ModuleLogs.discarding()).draw("empty", table, 7L, 0, 64, 0).isEmpty());
}
@Test
@@ -30,6 +30,7 @@ import com.volmit.block.BlockRegistry;
import com.volmit.block.BlockSpec;
import com.volmit.block.BlockState;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.service.Loot;
import org.junit.Before;
import org.junit.Test;
@@ -122,7 +123,7 @@ public class PlacementLootTest {
Loot.Source picked = pick(platform, List.of(), CHEST);
assertEquals(new Loot.PlatformTable("minecraft:chests/simple_dungeon",
assertEquals(new Loot.PlatformTable(ResourceId.parse("minecraft:chests/simple_dungeon"),
LootTables.seed(LOOT_SEED, "Vanilla minecraft:chests/simple_dungeon", 0, 64, 0)), picked);
}
@@ -48,7 +48,7 @@ import static org.mockito.Mockito.when;
/** Trees only replace the platform's growth when the dimension asks for it and a placement of the area grows that species. */
public class TreeGrowingTest {
private static final SaplingGrowth.Sapling OAK_SAPLING = new SaplingGrowth.Sapling(
new BlockPosition(10, 70, 20), new BlockPosition(10, 70, 20), "TREE");
new BlockPosition(10, 70, 20), new BlockPosition(10, 70, 20), ResourceId.ofPlatformKey("TREE"));
private static final ResourceId SOURCE = ResourceId.parse("test:dimension/overworld");
private static final ResourceId BIOME = ResourceId.parse("test:plains");
private static final ResourceId REGION = ResourceId.parse("test:overworld");
@@ -378,8 +378,8 @@ public final class ApiChunk implements GenerationContext {
}
@Override
public String key() {
return "overworld";
public ResourceId id() {
return ResourceId.parse("test:overworld");
}
@Override
@@ -5,6 +5,7 @@ import art.arcane.iris.builtin.IrisSeeds;
import art.arcane.iris.builtin.carve.CarvingEntry;
import art.arcane.iris.builtin.carve.CarvingSettings;
import art.arcane.iris.core.modules.CarveTestWorld;
import art.arcane.iris.core.modules.IrisPackResources;
import art.arcane.iris.core.modules.IrisValues;
import art.arcane.iris.engine.object.value.IRare;
import art.arcane.iris.util.project.noise.CNG;
@@ -281,7 +282,7 @@ public class CarvingResolverParityTest {
long generatorSeed = seed ^ (idHash << 32) ^ CHILD_GENERATOR_SALT;
double scale = Math.max(MIN_CHILD_SCALE, settings.childShrinkFactor());
RNG random = new RNG(generatorSeed);
return IrisValues.generatorStyle(settings.childStyle()).createNoCache(random.nextParallelRNG(CHILD_GENERATOR_SIGNATURE), world.data())
return IrisValues.generatorStyle(settings.childStyle(), new IrisPackResources(world.data())).createNoCache(random.nextParallelRNG(CHILD_GENERATOR_SIGNATURE), world.data())
.bake().scale(scale).bake();
}
}
@@ -28,6 +28,7 @@ import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.world.IrisWorld;
import art.arcane.iris.builtin.spawn.EffectSettings;
import art.arcane.iris.spi.PlatformWorld;
import com.volmit.resource.ResourceId;
import com.volmit.service.AmbientEffects;
import com.volmit.geometry.BlockPosition;
import com.volmit.world.PackWorld;
@@ -93,11 +94,11 @@ public class AmbientEffectingTest {
assertEquals(1, due.size());
AmbientEffects.Sound sound = due.getFirst().sound().orElseThrow();
assertEquals("ambient.cave", sound.key());
assertEquals(ResourceId.parse("minecraft:ambient.cave"), sound.key());
assertTrue(Math.abs(sound.offsetX()) <= 4 && Math.abs(sound.offsetY()) <= 4 && Math.abs(sound.offsetZ()) <= 4);
assertEquals(2F, sound.volume(), 0);
assertEquals(0.5F, sound.pitch(), 0);
assertEquals(Optional.of(new AmbientEffects.Potion("luck", 1, 100)), due.getFirst().potion());
assertEquals(Optional.of(new AmbientEffects.Potion(ResourceId.parse("minecraft:luck"), 1, 100)), due.getFirst().potion());
assertTrue(due.getFirst().particles().isEmpty());
assertTrue(due.getFirst().commands().isEmpty());
}
@@ -110,10 +111,10 @@ public class AmbientEffectingTest {
AmbientEffects.Effect effect = new AmbientEffecting().due(world, AT).getFirst();
AmbientEffects.Particles particles = effect.particles().orElseThrow();
assertEquals("flame", particles.key());
assertEquals(5, particles.forward(), 0);
assertEquals(0, particles.sideways(), 0);
assertEquals(0.5, particles.altX(), 0);
assertEquals(ResourceId.parse("minecraft:flame"), particles.key());
assertEquals(5, particles.spot().forward(), 0);
assertEquals(0, particles.spot().sideways(), 0);
assertEquals(0.5, particles.spread().x(), 0);
assertEquals(0.25, particles.extra(), 0);
assertEquals(2, particles.count());
assertEquals(1, effect.commands().size());
@@ -23,8 +23,11 @@ import art.arcane.iris.builtin.spawn.EntityDefinition;
import art.arcane.iris.builtin.LiveWorld.Sky;
import art.arcane.volmlib.util.math.RNG;
import com.google.gson.Gson;
import com.volmit.ModuleLog;
import com.volmit.entity.EntitySpec;
import com.volmit.host.ModuleLogs;
import com.volmit.item.ItemRegistry;
import com.volmit.resource.ContentKey;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import org.junit.Test;
@@ -33,6 +36,7 @@ import java.util.Optional;
import java.util.OptionalInt;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -42,6 +46,8 @@ import static org.mockito.Mockito.when;
* classes became settings of the spawn module; a change in it changes the equipment, attributes and passengers worlds spawn.
* It was retaken once when absent values became {@code Optional}s and loot tables ids: the spec printed the old way (empty
* texts as {@code ""}, other absent values as {@code null}, tables by key) still hashed to the old number, -819231818.
* It was retaken again when the spec was grouped, its keys became ids and content keys and the Iris-only knobs an
* extension: the spec printed the old way (flat fields, keys as written, operations by Bukkit name) still hashed to 1441930785.
*/
public class EntityResolutionPinTest {
private static final long STREAM_SEED = 4321L;
@@ -65,17 +71,23 @@ public class EntityResolutionPinTest {
@Test
public void anEntityResolvesToThePinnedSpec() {
ItemRegistry registry = mock(ItemRegistry.class);
when(registry.maxDurability(anyString())).thenReturn(OptionalInt.of(0));
when(registry.maxDurability("iron_helmet")).thenReturn(OptionalInt.of(165));
when(registry.maxDurability("diamond_sword")).thenReturn(OptionalInt.of(1561));
when(registry.maxDurability(any(ContentKey.class))).thenReturn(OptionalInt.of(0));
when(registry.maxDurability(platformItem("iron_helmet"))).thenReturn(OptionalInt.of(165));
when(registry.maxDurability(platformItem("diamond_sword"))).thenReturn(OptionalInt.of(1561));
Optional<Sky> sky = Optional.of(new Sky(0L, false, false));
EntityDefinition entity = new Gson().fromJson(ENTITY, EntityDefinition.class);
PackResources resources = mock(PackResources.class);
when(resources.idOf(anyString())).thenAnswer(invocation -> new ResourceId("test", invocation.getArgument(0)));
EntitySpec spec = new EntityResolution(resources, new LootItems(registry, false), sky, new EffectTimers()).resolve(entity, new RNG(STREAM_SEED));
ModuleLog log = ModuleLogs.discarding();
EntitySpec spec = new EntityResolution(resources, new LootItems(registry, false, log), sky, new EffectTimers(), log)
.resolve(entity, new RNG(STREAM_SEED)).orElseThrow();
assertEquals(1441930785, spec.toString().hashCode());
assertEquals(-847596166, spec.toString().hashCode());
}
private static ContentKey platformItem(String name) {
return new ContentKey.Registered(ResourceId.ofPlatformKey(name));
}
}
@@ -26,6 +26,7 @@ import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineGeneration;
import art.arcane.iris.engine.framework.SeedManager;
import art.arcane.iris.builtin.spawn.EntityDefinition;
import art.arcane.iris.builtin.spawn.IrisEntityExtras;
import art.arcane.iris.builtin.spawn.SpawnMarker;
import art.arcane.iris.builtin.spawn.Spawner;
import art.arcane.iris.engine.object.TestSettings;
@@ -34,6 +35,8 @@ import art.arcane.iris.engine.object.world.IrisWorld;
import art.arcane.iris.spi.PlatformWorld;
import com.volmit.entity.EntitySpec;
import com.volmit.item.ItemRegistry;
import com.volmit.resource.ContentKey;
import com.volmit.resource.ResourceId;
import com.volmit.service.EntitySpawns;
import com.volmit.geometry.BlockPosition;
import com.volmit.world.PackWorld;
@@ -101,7 +104,7 @@ public class EntitySpawningTest {
fixture.resource(SpawnResources.MARKERS, "camp", marker);
fixture.resource(SpawnResources.SPAWNERS, "zombies", new Spawner());
EntitySpawns.MarkerRule rule = new EntitySpawning().marker(world, "camp").orElseThrow();
EntitySpawns.MarkerRule rule = new EntitySpawning().marker(world, world.resources().idOf("camp")).orElseThrow();
assertEquals("a spawner the pack lacks is left out", List.of(world.resources().idOf("zombies")), rule.spawners());
assertTrue(rule.emptyAbove());
@@ -110,8 +113,8 @@ public class EntitySpawningTest {
@Test
public void markersNoModuleKnowsAndTheCaveMarkersMeanNothing() {
assertTrue(new EntitySpawning().marker(world, "unknown").isEmpty());
assertTrue(new EntitySpawning().marker(world, "cave_floor").isEmpty());
assertTrue(new EntitySpawning().marker(world, world.resources().idOf("unknown")).isEmpty());
assertTrue(new EntitySpawning().marker(world, world.resources().idOf("cave_floor")).isEmpty());
}
@Test
@@ -123,7 +126,7 @@ public class EntitySpawningTest {
when(engine.getMinHeight()).thenReturn(-64);
EntitySpawns.Plan plan = new EntitySpawning()
.plan(world, new EntitySpawns.Marker(MARKER_BLOCK, "camp", world.resources().idOf("camp/zombies"), false))
.plan(world, new EntitySpawns.Marker(MARKER_BLOCK, world.resources().idOf("camp"), world.resources().idOf("camp/zombies"), false))
.orElseThrow();
assertEquals(world.resources().idOf("camp/zombies"), plan.spawner());
@@ -132,7 +135,7 @@ public class EntitySpawningTest {
for (EntitySpawns.Attempt attempt : plan.attempts()) {
assertEquals(new BlockPosition(40, 71, -12), attempt.at());
assertFalse(attempt.checkSurface());
assertEquals(Optional.of("minecraft:zombie"), attempt.entity().type());
assertEquals(vanilla("zombie"), attempt.entity().type());
}
}
@@ -140,7 +143,7 @@ public class EntitySpawningTest {
public void aSpawnerThatCannotFireOrHasNoEntitiesPlansNothing() {
fixture.resource(SpawnResources.SPAWNERS, "empty", new Spawner());
Optional<EntitySpawns.Plan> plan = new EntitySpawning().plan(world, new EntitySpawns.Marker(MARKER_BLOCK, "camp", world.resources().idOf("empty"), false));
Optional<EntitySpawns.Plan> plan = new EntitySpawning().plan(world, new EntitySpawns.Marker(MARKER_BLOCK, world.resources().idOf("camp"), world.resources().idOf("empty"), false));
assertTrue(plan.isEmpty());
}
@@ -152,9 +155,31 @@ public class EntitySpawningTest {
EntitySpec spec = new EntitySpawning().entity(world, world.resources().idOf("cow")).orElseThrow();
assertEquals(Optional.of("minecraft:cow"), spec.type());
assertEquals(Optional.of("&6Bessie"), spec.customName());
assertTrue(spec.flags().baby());
assertEquals(vanilla("cow"), spec.type());
assertEquals(Optional.of("&6Bessie"), spec.appearance().customName());
assertTrue(spec.appearance().baby());
assertTrue(new EntitySpawning().entity(world, world.resources().idOf("nothing")).isEmpty());
}
@Test
public void aMobOfAnotherProviderIsProvidedByNameWithItsIrisExtras() {
fixture.resource(SpawnResources.ENTITIES, "king", TestSettings.of(EntityDefinition.class,
"{\"type\": \"minecraft:zombie\", \"specialType\": \"MythicMobs:Skeleton King\", \"reason\": \"CUSTOM\"}"));
EntitySpec spec = new EntitySpawning().entity(world, world.resources().idOf("king")).orElseThrow();
assertEquals(new ContentKey.Provided("MythicMobs", "Skeleton King"), spec.type());
assertEquals(Optional.of("CUSTOM"), spec.extension(IrisEntityExtras.class).orElseThrow().reason());
}
@Test
public void anEntityWithoutAValidTypeIsNotSpawned() {
fixture.resource(SpawnResources.ENTITIES, "broken", TestSettings.of(EntityDefinition.class, "{\"type\": \"not a key!\"}"));
assertTrue(new EntitySpawning().entity(world, world.resources().idOf("broken")).isEmpty());
}
private static ContentKey vanilla(String name) {
return new ContentKey.Registered(ResourceId.parse("minecraft:" + name));
}
}