From 4bacc306e9bb9f5ba6f3645680403bad903ec24c Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 24 Oct 2026 00:17:24 +0200 Subject: [PATCH] Batch 3 of the API review: Iris offers its facades as extensions - IrisPackWorld offers IrisSeeds, LiveWorld, ObjectHost, FloatingHost, StructureHost (and the engine to the structure built-ins) through extension(); IrisPackSettings the facades a reach needs. withLog, the Source interfaces and the of(...) casts are gone (HostExtensions). - The invocation inputs offer IrisChunk / IrisMantleChunk, MatterMantle and ObjectPlacement; IrisChunk.current(), IrisMantleChunk.current() and IrisPlacement.runBound are gone. A chunk stage's MatterMantle is its own chunk plus the loaded neighbours (OwnChunkMatter). - IrisPackResources serves find(kind, id) / ids(kind) and maps ids back to pack keys at the host's edge (keyOf); ModuleServices, ContentServices, the settings decoder (a bare ResourceId is the pack's id), ModuleSettings and CaveBiomeAnswers convert there. - MantleCaverns, IrisModuleMantle and PlacementMantle answer isCarved. - Starts get a StartKey per platform start (weakly held). - Bukkit adapters read the Optional-valued items, entities and effects. - Tests follow; the loot and entity pins are retaken after checking that the old printing of the new values gives the old hashes. --- .../iris/core/content/ContentServices.java | 64 +++++++++------ .../arcane/iris/core/modules/BiomeModule.java | 2 +- .../iris/core/modules/CaveBiomeAnswers.java | 12 +-- .../iris/core/modules/CustomModule.java | 2 +- .../iris/core/modules/HostExtensions.java | 32 ++++++++ .../arcane/iris/core/modules/IrisChunk.java | 18 +---- .../iris/core/modules/IrisFloatingHost.java | 29 ++++--- .../core/modules/IrisGenerationContext.java | 26 +++++- .../iris/core/modules/IrisMantleChunk.java | 20 +---- .../modules/IrisMantleGenerationContext.java | 19 ++++- .../iris/core/modules/IrisModuleMantle.java | 8 +- .../iris/core/modules/IrisObjectHost.java | 5 +- .../iris/core/modules/IrisPackResources.java | 63 +++++++++------ .../iris/core/modules/IrisPackSettings.java | 41 +++++----- .../iris/core/modules/IrisPackWorld.java | 74 ++++++++--------- .../iris/core/modules/IrisPlacement.java | 8 +- .../core/modules/IrisPlacementInputs.java | 17 +++- .../iris/core/modules/IrisStructureHost.java | 5 +- .../iris/core/modules/MantleCaverns.java | 80 ++----------------- .../core/modules/ModuleChunkGeneration.java | 6 +- .../core/modules/ModuleMantleComponent.java | 12 ++- .../core/modules/ModuleObjectPlacement.java | 7 +- .../iris/core/modules/ModuleServices.java | 74 ++++++++++++----- .../iris/core/modules/ModuleSettings.java | 20 +++-- .../core/modules/ModuleSettingsDecoder.java | 10 ++- .../core/modules/ModuleStructureFitting.java | 9 ++- .../iris/core/modules/OwnChunkMatter.java | 52 ++++++++++++ .../iris/core/modules/PlacementMantle.java | 7 +- .../arcane/iris/core/modules/ToolWorld.java | 18 +---- .../iris/core/pack/ModuleResourceClosure.java | 2 +- .../iris/core/project/SchemaBuilder.java | 2 +- .../service/tree/TreeDefinitionIndex.java | 20 +++-- .../iris/engine/MarkerSpawnScanner.java | 7 +- .../iris/engine/framework/HintedLocator.java | 2 +- .../engine/platform/BukkitEntitySpawner.java | 60 ++++++-------- .../iris/engine/platform/EngineBukkitOps.java | 11 +-- .../platform/bukkit/BukkitAmbientEffects.java | 12 +-- .../platform/bukkit/BukkitItemStacks.java | 28 +++---- .../specialhandlers/EntityKeyHandler.java | 4 +- .../BuiltInModulesJarServicesTest.java | 5 +- .../modules/CarveSettingsDecodingTest.java | 5 +- .../iris/core/modules/CarveTestWorld.java | 26 +++--- .../core/modules/DimensionBottomTest.java | 4 +- .../modules/FloatingSettingsDecodingTest.java | 10 ++- .../iris/core/modules/IrisLiveWorldTest.java | 2 +- .../core/modules/IrisModuleMantleTest.java | 44 +++------- .../core/modules/IrisPackResourcesTest.java | 43 +++++----- .../iris/core/modules/IrisValuesTest.java | 2 +- .../core/modules/IrisWorldFacadesTest.java | 9 +-- .../iris/core/modules/ModuleLogTest.java | 20 ++--- .../core/modules/ModuleResourceFixture.java | 15 +++- .../iris/core/modules/ModuleServicesTest.java | 30 +++---- .../iris/core/modules/ModuleWorldsTest.java | 2 +- .../modules/PackModuleResourceKindTest.java | 20 ++--- .../core/modules/PackResourceFixture.java | 33 +++++++- .../iris/core/modules/ToolWorldTest.java | 11 ++- .../service/tree/TreeDefinitionIndexTest.java | 1 + .../engine/decorator/BiomeDecoratorsTest.java | 3 +- .../engine/framework/EngineCaveBiomeTest.java | 18 +++-- .../engine/framework/HintedLocatorTest.java | 1 + .../structure/StructureResourcesTest.java | 6 +- .../framework/structure/fit/FitFixture.java | 5 +- .../iris/engine/loot/LootDrawPinTest.java | 4 +- .../iris/engine/loot/LootItemsTest.java | 9 ++- .../iris/engine/loot/LootValidatorTest.java | 2 +- .../iris/engine/loot/PlacementLootTest.java | 17 ++-- ...oatingObjectPlacingBoundaryRadiusTest.java | 17 ++-- .../mantle/components/ObjectWarmUpTest.java | 11 +-- .../mantle/components/TreeGrowingTest.java | 5 +- .../arcane/iris/engine/modifier/ApiChunk.java | 78 +++++------------- .../engine/modifier/CaveBiomeBandsTest.java | 10 +-- .../engine/modifier/FloatingIslandsTest.java | 11 +-- .../IrisObjectPlacementRegressionTest.java | 16 ++-- .../carving/CarvingResolverParityTest.java | 4 +- .../IrisDimensionReachableBiomesTest.java | 7 ++ .../world/region/IrisRegionBiomeTreeTest.java | 5 ++ .../engine/spawn/AmbientEffectingTest.java | 25 +++--- .../engine/spawn/EntityResolutionPinTest.java | 11 ++- .../iris/engine/spawn/EntitySpawningTest.java | 18 ++--- .../iris/engine/spawn/SpawnerGateTest.java | 4 +- .../iris/engine/terrain/TestLayerBlocks.java | 5 -- .../iris/engine/terrain/TestPackWorld.java | 14 ++-- 82 files changed, 783 insertions(+), 693 deletions(-) create mode 100644 core/src/main/java/art/arcane/iris/core/modules/HostExtensions.java create mode 100644 core/src/main/java/art/arcane/iris/core/modules/OwnChunkMatter.java diff --git a/core/src/main/java/art/arcane/iris/core/content/ContentServices.java b/core/src/main/java/art/arcane/iris/core/content/ContentServices.java index 3741733c6..cd8f6b2e4 100644 --- a/core/src/main/java/art/arcane/iris/core/content/ContentServices.java +++ b/core/src/main/java/art/arcane/iris/core/content/ContentServices.java @@ -18,6 +18,7 @@ package art.arcane.iris.core.content; +import art.arcane.iris.core.modules.IrisPackResources; import art.arcane.iris.core.modules.ModuleServices; import art.arcane.iris.core.modules.PlatformBlockStates; import art.arcane.iris.engine.framework.Engine; @@ -26,6 +27,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.ResourceId; import com.volmit.service.AmbientEffects; import com.volmit.service.BlockDrops; import com.volmit.service.EntitySpawns; @@ -51,12 +53,14 @@ public final class ContentServices { * @param containerKey the platform's key for the block when it is a storage chest an object may have given loot, else null */ public static List containerLoot(Engine engine, int x, int worldY, int z, String containerKey, boolean nativeLootDefined) { - BlockState container = containerKey == null ? null : BlockState.parse(PlatformBlockStates.namespaced(containerKey)); + Optional container = containerKey == null + ? Optional.empty() + : Optional.of(BlockState.parse(PlatformBlockStates.namespaced(containerKey))); Loot.Site site = new Loot.Site(position(engine, x, worldY, z), container, nativeLootDefined, false); List parts = new ArrayList<>(); 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.key()))); + 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())); } } @@ -65,8 +69,12 @@ public final class ContentServices { /** The items the pack's loot table {@code tableKey} gives at the spot. */ public static List tableItems(Engine engine, int x, int worldY, int z, String tableKey) { - Loot.Site site = new Loot.Site(position(engine, x, worldY, z), null, false, false); - return ModuleServices.lootItems(engine, site, tableKey).stream().map(ContentServices::itemOf).toList(); + return tableItems(engine, x, worldY, z, engine.getData().getPackResources().idOf(tableKey)); + } + + private static List tableItems(Engine engine, int x, int worldY, int z, ResourceId table) { + Loot.Site site = new Loot.Site(position(engine, x, worldY, z), Optional.empty(), false, false); + return ModuleServices.lootItems(engine, site, table).stream().map(ContentServices::itemOf).toList(); } /** What the modules drop for the block with the platform's key {@code blockKey} broken at the spot. */ @@ -83,13 +91,16 @@ public final class ContentServices { /** What the first module that knows the spawner plans at the marker block. */ public static Optional planMarkerSpawn(Engine engine, int x, int worldY, int z, String marker, String spawner, boolean initial) { - return planned(engine, new EntitySpawns.Marker(position(engine, x, worldY, z), marker, spawner, initial)); + ResourceId spawnerId = engine.getData().getPackResources().idOf(spawner); + return planned(engine, new EntitySpawns.Marker(position(engine, x, worldY, z), marker, spawnerId, initial)); } /** What the marker with the tag {@code tag} does; empty for a tag no module knows. */ public static Optional markerRule(Engine engine, String tag) { + IrisPackResources resources = engine.getData().getPackResources(); return ModuleServices.markerRule(engine, tag) - .map(rule -> new ContentSpawns.MarkerRule(rule.spawners(), rule.emptyAbove(), rule.removeOnChange())); + .map(rule -> new ContentSpawns.MarkerRule(rule.spawners().stream().map(resources::keyOf).toList(), + rule.emptyAbove(), rule.removeOnChange())); } /** The entity of the pack named {@code key} as a module would spawn it; empty for an unknown key. */ @@ -121,10 +132,12 @@ public final class ContentServices { } private static ContentItem itemOf(ItemDrop drop) { - return new ContentItem(drop.item(), drop.amount(), drop.displayName(), drop.lore(), + return new ContentItem(drop.item(), drop.amount(), drop.displayName().orElse(null), drop.lore(), drop.enchantments().stream().map(ContentServices::enchantmentOf).toList(), drop.attributes().stream().map(ContentServices::attributeOf).toList(), drop.unbreakable(), drop.flags(), - drop.customModel(), drop.damage(), drop.leatherColor(), drop.dyeColor(), drop.customNbt()); + drop.customModel().isPresent() ? drop.customModel().getAsInt() : null, + drop.damage().isPresent() ? drop.damage().getAsDouble() : null, + drop.leatherColor().orElse(null), drop.dyeColor().orElse(null), drop.customNbt()); } private static ContentItem.Enchantment enchantmentOf(ItemEnchantment enchantment) { @@ -135,12 +148,19 @@ public final class ContentServices { return new ContentItem.Attribute(attribute.attribute(), attribute.name(), attribute.operation(), attribute.amount()); } + /** + * The adapters' entity keeps their conventions: a missing type, special type or name is empty text, anything else + * missing is {@code null}. Loot tables are named by their ids' paths, which is how the adapters ask + * {@link #tableItems} for them again. + */ private static ContentEntity entityOf(EntitySpec spec) { - return new ContentEntity(spec.type(), spec.specialType(), spec.reason(), spec.customName(), flagsOf(spec.flags()), + 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(), - spec.attributes().stream().map(ContentServices::attributeOf).toList(), spec.lootTables(), spec.lootShuffleSeed(), - spec.leashHolder() == null ? null : entityOf(spec.leashHolder()), spawnEffectOf(spec.spawnEffect()), - spec.riseOutOfGround(), spec.pandaMainGene(), spec.pandaHiddenGene(), spec.applySettingsToSpecial(), + 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()); } @@ -155,16 +175,13 @@ public final class ContentServices { optionalItem(equipment.offHand())); } - private static ContentItem optionalItem(ItemDrop drop) { - return drop == null ? null : itemOf(drop); + private static ContentItem optionalItem(Optional drop) { + return drop.map(ContentServices::itemOf).orElse(null); } private static ContentEntity.SpawnEffect spawnEffectOf(EntitySpec.SpawnEffect effect) { - if (effect == null) { - return null; - } - return new ContentEntity.SpawnEffect(effect.sound(), effect.soundDistance(), effect.minPitch(), effect.maxPitch(), - effect.volume(), effect.particle(), effect.particleOffset(), effect.particleCount(), effect.altX(), effect.altY(), + 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()); } @@ -173,19 +190,20 @@ public final class ContentServices { } private static ContentEffect effectOf(AmbientEffects.Effect effect) { - return new ContentEffect(soundOf(effect.sound()), particlesOf(effect.particles()), + return new ContentEffect(effect.sound().map(ContentServices::soundOf).orElse(null), + 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() == null ? null : new ContentEffect.Potion(effect.potion().key(), effect.potion().strength(), effect.potion().ticks())); + effect.potion().map(potion -> new ContentEffect.Potion(potion.key(), potion.strength(), potion.ticks())).orElse(null)); } private static ContentEffect.Sound soundOf(AmbientEffects.Sound sound) { - return sound == null ? null : new ContentEffect.Sound(sound.key(), sound.offsetX(), sound.offsetY(), sound.offsetZ(), + return new ContentEffect.Sound(sound.key(), sound.offsetX(), sound.offsetY(), sound.offsetZ(), sound.volume(), sound.pitch()); } private static ContentEffect.Particles particlesOf(AmbientEffects.Particles particles) { - return particles == null ? null : new ContentEffect.Particles(particles.key(), particles.forward(), particles.sideways(), + 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()); } diff --git a/core/src/main/java/art/arcane/iris/core/modules/BiomeModule.java b/core/src/main/java/art/arcane/iris/core/modules/BiomeModule.java index 44cf87f9b..7a0fbc4a6 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/BiomeModule.java +++ b/core/src/main/java/art/arcane/iris/core/modules/BiomeModule.java @@ -57,7 +57,7 @@ public final class BiomeModule implements IrisModule { } private static void write(ChunkStageContext context) { - IrisChunk chunk = IrisChunk.current(); + IrisChunk chunk = context.extension(IrisChunk.class).orElseThrow(); chunk.state(BiomeWriter.class, BiomeWriter::new).write(chunk.originX(), chunk.originZ(), chunk.biomes(), chunk.context()); } diff --git a/core/src/main/java/art/arcane/iris/core/modules/CaveBiomeAnswers.java b/core/src/main/java/art/arcane/iris/core/modules/CaveBiomeAnswers.java index 8c777b631..8e4fd70f3 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/CaveBiomeAnswers.java +++ b/core/src/main/java/art/arcane/iris/core/modules/CaveBiomeAnswers.java @@ -21,6 +21,8 @@ package art.arcane.iris.core.modules; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.world.biome.IrisBiome; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import com.volmit.service.CaveBiomes; import com.volmit.world.PackWorld; @@ -36,12 +38,12 @@ import java.util.concurrent.ConcurrentHashMap; public final class CaveBiomeAnswers { private static final CaveBiomes NO_PROVIDER = new CaveBiomes() { @Override - public Optional overriddenBiome(PackWorld world, int x, int y, int z) { + public Optional overriddenBiome(PackWorld world, int x, int y, int z) { return Optional.empty(); } @Override - public int minDepthBelowSurface(PackWorld world, String biomeKey) { + public int minDepthBelowSurface(PackWorld world, ResourceId biome) { return 0; } }; @@ -60,8 +62,8 @@ public final class CaveBiomeAnswers { /** The pack biome the module puts at the position whatever the regions say; null where it overrides nothing or names a biome the pack lacks. {@code y} is the height above the dimension's bottom. */ public IrisBiome overriddenBiome(int x, int y, int z) { - Optional key = provider.overriddenBiome(world, x, y, z); - return key.isEmpty() ? null : overridingBiome(key.get()); + Optional biome = provider.overriddenBiome(world, x, y, z); + return biome.isEmpty() ? null : overridingBiome(data.getPackResources().keyOf(PackResources.BIOMES, biome.get())); } /** How many blocks below the surface the caves of the pack biome {@code biomeKey} begin; 0 where nothing limits them. */ @@ -70,7 +72,7 @@ public final class CaveBiomeAnswers { if (depth != null) { return depth; } - return minDepths.computeIfAbsent(biomeKey, key -> provider.minDepthBelowSurface(world, key)); + return minDepths.computeIfAbsent(biomeKey, key -> provider.minDepthBelowSurface(world, world.resources().idOf(key))); } private IrisBiome overridingBiome(String key) { diff --git a/core/src/main/java/art/arcane/iris/core/modules/CustomModule.java b/core/src/main/java/art/arcane/iris/core/modules/CustomModule.java index 5e7582e10..083ce51d8 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/CustomModule.java +++ b/core/src/main/java/art/arcane/iris/core/modules/CustomModule.java @@ -55,7 +55,7 @@ public final class CustomModule implements IrisModule { } private static void record(ChunkStageContext context) { - IrisChunk chunk = IrisChunk.current(); + IrisChunk chunk = context.extension(IrisChunk.class).orElseThrow(); if (chunk.bypassesMantleStages()) { return; } diff --git a/core/src/main/java/art/arcane/iris/core/modules/HostExtensions.java b/core/src/main/java/art/arcane/iris/core/modules/HostExtensions.java new file mode 100644 index 000000000..e4bb6b652 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/modules/HostExtensions.java @@ -0,0 +1,32 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.modules; + +import java.util.Optional; + +/** How Iris answers IrisApi's {@code extension(type)}: what it offers for a type, when it is of that type. */ +final class HostExtensions { + private HostExtensions() { + } + + /** {@code offered} as a {@code type}; empty when Iris offers nothing for the type (null) or something else. */ + static Optional as(Class type, Object offered) { + return type.isInstance(offered) ? Optional.of(type.cast(offered)) : Optional.empty(); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisChunk.java b/core/src/main/java/art/arcane/iris/core/modules/IrisChunk.java index 577279d9d..0e2c9dfcd 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisChunk.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisChunk.java @@ -28,13 +28,11 @@ import java.util.function.Function; /** * Iris's own view of the chunk whose module stages are running: the engine, Iris's block and biome hunks and - * the chunk's sampled context. Iris's built-in chunk stages read them through {@link #current()}, bound on the - * generating thread while the chunk graph runs, and work on Iris's types directly; pack modules cannot see + * the chunk's sampled context. Iris offers it as an extension of the chunk invocation, so its built-in chunk stages + * read it with {@code context.extension(IrisChunk.class)} and work on Iris's types directly; pack modules cannot see * this class. */ public final class IrisChunk { - private static final ScopedValue CURRENT = ScopedValue.newInstance(); - private final Engine engine; private final int originX; private final int originZ; @@ -54,18 +52,6 @@ public final class IrisChunk { this.context = context; } - /** The chunk generating on this thread. */ - public static IrisChunk current() { - if (!CURRENT.isBound()) { - throw new IllegalStateException("No Iris chunk is generating on this thread"); - } - return CURRENT.get(); - } - - void runBound(Runnable generation) { - ScopedValue.where(CURRENT, this).run(generation); - } - public Engine engine() { return engine; } diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisFloatingHost.java b/core/src/main/java/art/arcane/iris/core/modules/IrisFloatingHost.java index 18f6b624c..928e3b82d 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisFloatingHost.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisFloatingHost.java @@ -46,6 +46,7 @@ import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.matter.MatterBiomeInject; import art.arcane.volmlib.util.matter.slices.BiomeInjectMatter; import com.volmit.ModuleLog; +import com.volmit.generation.InvocationContext; import com.volmit.resource.ResourceId; import java.util.Map; @@ -128,11 +129,12 @@ final class IrisFloatingHost implements FloatingHost { } @Override - public void placeFloating(PlaceableObject object, int worldX, int worldZ, ObjectPlacement placement, RNG random) { + public void placeFloating(InvocationContext context, PlaceableObject object, int worldX, int worldZ, ObjectPlacement placement, + RNG random) { IrisObject placed = (IrisObject) object; IrisData data = engine.getData(); IrisObjectPlacement floating = ObjectPlacements.host(placement, data).toPlacement(placed.getLoadKey()); - MantleWriter writer = IrisMantleChunk.current().writer(); + MantleWriter writer = writerOf(context); int id = random.i(0, Integer.MAX_VALUE); try { placed.place(worldX, FLOATING_OBJECT_Y, worldZ, writer, floating, random, (block, state) -> writeMarker(writer, placed, id, block.getX(), @@ -143,20 +145,25 @@ final class IrisFloatingHost implements FloatingHost { } @Override - public void placeOnTop(PlaceableObject object, int worldX, int y, int worldZ, ObjectPlacement placement, IslandAnchor anchor, RNG random) { - placeAgainstIsland((IrisObject) object, worldX, y, worldZ, placement, NO_ROTATION, anchor, random, "anchored"); + public void placeOnTop(InvocationContext context, PlaceableObject object, int worldX, int y, int worldZ, ObjectPlacement placement, + IslandAnchor anchor, RNG random) { + placeAgainstIsland(writerOf(context), (IrisObject) object, worldX, y, worldZ, placement, NO_ROTATION, anchor, random, "anchored"); } @Override - public void placeUnder(PlaceableObject object, int worldX, int y, int worldZ, int yRotation, ObjectPlacement placement, - IslandAnchor anchor, RNG random) { - placeAgainstIsland((IrisObject) object, worldX, y, worldZ, placement, IrisObjectRotation.xFlip180WithY(yRotation), anchor, random, - "inverted"); + public void placeUnder(InvocationContext context, PlaceableObject object, int worldX, int y, int worldZ, int yRotation, + ObjectPlacement placement, IslandAnchor anchor, RNG random) { + placeAgainstIsland(writerOf(context), (IrisObject) object, worldX, y, worldZ, placement, IrisObjectRotation.xFlip180WithY(yRotation), + anchor, random, "inverted"); + } + + private static MantleWriter writerOf(InvocationContext context) { + return context.extension(IrisMantleChunk.class).orElseThrow().writer(); } /** Places the object through a transaction that writes nothing unless every block lands where the anchor allows. */ - private void placeAgainstIsland(IrisObject object, int worldX, int y, int worldZ, ObjectPlacement placement, IrisObjectRotation rotation, - IslandAnchor anchor, RNG random, String kind) { + private void placeAgainstIsland(MantleWriter writer, IrisObject object, int worldX, int y, int worldZ, ObjectPlacement placement, + IrisObjectRotation rotation, IslandAnchor anchor, RNG random, String kind) { IrisData data = engine.getData(); IrisObjectPlacement anchored = ObjectPlacements.host(placement, data).toPlacement(object.getLoadKey()); anchored.setMode(anchored.getMode().onFloatingIsland()); @@ -166,7 +173,7 @@ final class IrisFloatingHost implements FloatingHost { anchored.setBottom(false); FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction( - new IslandAnchorPlacer(IrisMantleChunk.current().writer(), anchor)); + new IslandAnchorPlacer(writer, anchor)); int id = random.i(0, Integer.MAX_VALUE); try { int resultY = object.place(worldX, y, worldZ, transaction, anchored, random, (block, state) -> writeMarker(transaction, object, id, diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisGenerationContext.java b/core/src/main/java/art/arcane/iris/core/modules/IrisGenerationContext.java index 8eb2f3f85..eff3ee107 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisGenerationContext.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisGenerationContext.java @@ -18,6 +18,7 @@ package art.arcane.iris.core.modules; +import art.arcane.iris.builtin.MatterMantle; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.spi.PlatformBlockState; import com.volmit.block.BlockState; @@ -30,10 +31,11 @@ import com.volmit.world.PackWorld; import com.volmit.world.TerrainSampler; import java.util.Collection; +import java.util.Optional; /** * One chunk of an Iris engine as an IrisApi chunk invocation: the chunk's block hunk, Iris's terrain - * streams, the pack's module settings and the chunk's mantle, which IrisApi gives chunk stages read-only. + * streams, the pack's module settings and the chunk's mantle, which IrisApi lets chunk stages write in their own chunk only. * Pack resources are the pack snapshot's, shared by every invocation of it. */ final class IrisGenerationContext implements GenerationContext { @@ -42,6 +44,7 @@ final class IrisGenerationContext implements GenerationContext { /** The mantle too reaches this far around the chunk; chunks beyond its own are pinned when a stage first reads them. */ private static final int MANTLE_MARGIN_BLOCKS = 16; private static final int CHUNK_WIDTH = 16; + private static final int CHUNK_SHIFT = 4; private final Engine engine; private final int originX; @@ -50,13 +53,19 @@ final class IrisGenerationContext implements GenerationContext { private final IrisTerrainSampler terrain; private final ChunkModuleSettings settings; private final IrisModuleMantle mantle; + private final IrisChunk irisChunk; private PackWorld world; - /** {@code states} convert the chunk's blocks, in the hunk and in the planned blocks of its mantle alike. */ + /** + * {@code states} convert the chunk's blocks, in the hunk and in the planned blocks of its mantle alike; + * {@code irisChunk} is what Iris's built-in chunk stages see of the chunk as an extension. + */ IrisGenerationContext(Engine engine, int originX, int originZ, art.arcane.iris.util.project.hunk.Hunk blocks, - PlatformBlockStates states, IrisModuleMantle.Chunks mantleChunks, Collection> mantleLayers) { + PlatformBlockStates states, IrisModuleMantle.Chunks mantleChunks, Collection> mantleLayers, + IrisChunk irisChunk) { PackResourceIds ids = new PackResourceIds(engine.getData().getDataFolder()); this.engine = engine; + this.irisChunk = irisChunk; this.originX = originX; this.originZ = originZ; this.blocks = new BlockStateHunk(blocks, states); @@ -101,6 +110,17 @@ final class IrisGenerationContext implements GenerationContext { return (com.volmit.hunk.Hunk) blocks; } + /** Iris's own view of the chunk, and the matter of its own chunk with loaded-only reads of its neighbours. */ + @Override + public Optional extension(Class type) { + if (type == IrisChunk.class) { + return HostExtensions.as(type, irisChunk); + } + if (type == MatterMantle.class) { + return HostExtensions.as(type, new OwnChunkMatter(mantle, originX >> CHUNK_SHIFT, originZ >> CHUNK_SHIFT)); + } + return Optional.empty(); + } /** The world this invocation first asked for; it keeps it if the world restarts meanwhile. */ @Override diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisMantleChunk.java b/core/src/main/java/art/arcane/iris/core/modules/IrisMantleChunk.java index 58f7b37d0..2285c752e 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisMantleChunk.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisMantleChunk.java @@ -26,13 +26,11 @@ import java.util.function.Function; /** * Iris's own view of the chunk whose mantle stages are running: the engine, the mantle writer prepared around - * the chunk and the generating chunk's sampled context. Iris's built-in mantle stages read them through - * {@link #current()}, bound on the thread running the mantle graph, and write Iris's own mantle data; pack - * modules cannot see this class. + * the chunk and the generating chunk's sampled context. Iris offers it as an extension of the mantle invocation, so + * its built-in mantle stages and the hosts they call read it with {@code context.extension(IrisMantleChunk.class)} and + * write Iris's own mantle data; pack modules cannot see this class. */ public final class IrisMantleChunk { - private static final ScopedValue CURRENT = ScopedValue.newInstance(); - private final Engine engine; private final MantleWriter writer; private final int chunkX; @@ -47,18 +45,6 @@ public final class IrisMantleChunk { this.context = context; } - /** The mantle chunk whose stages run on this thread. */ - public static IrisMantleChunk current() { - if (!CURRENT.isBound()) { - throw new IllegalStateException("No Iris mantle chunk is generating on this thread"); - } - return CURRENT.get(); - } - - void runBound(Runnable generation) { - ScopedValue.where(CURRENT, this).run(generation); - } - public Engine engine() { return engine; } diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisMantleGenerationContext.java b/core/src/main/java/art/arcane/iris/core/modules/IrisMantleGenerationContext.java index 738d85393..eaea3f383 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisMantleGenerationContext.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisMantleGenerationContext.java @@ -18,6 +18,7 @@ package art.arcane.iris.core.modules; +import art.arcane.iris.builtin.MatterMantle; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.util.common.data.B; import com.volmit.config.FeatureSettings; @@ -29,6 +30,7 @@ import com.volmit.world.PackWorld; import com.volmit.world.TerrainSampler; import java.util.Collection; +import java.util.Optional; /** * One chunk of an Iris engine as an IrisApi mantle invocation: the mantle around the chunk as far as the @@ -47,12 +49,15 @@ final class IrisMantleGenerationContext implements MantleGenerationContext { private final IrisTerrainSampler terrain; private final ChunkModuleSettings settings; private final IrisModuleMantle mantle; + private final IrisMantleChunk irisChunk; private PackWorld world; + /** {@code irisChunk} is what Iris's built-in mantle stages see of the chunk as an extension. */ IrisMantleGenerationContext(Engine engine, int chunkX, int chunkZ, int reachBlocks, IrisModuleMantle.Chunks chunks, - Collection> layers) { + Collection> layers, IrisMantleChunk irisChunk) { PackResourceIds ids = new PackResourceIds(engine.getData().getDataFolder()); this.engine = engine; + this.irisChunk = irisChunk; this.originX = chunkX << CHUNK_SHIFT; this.originZ = chunkZ << CHUNK_SHIFT; this.terrain = new IrisTerrainSampler(engine, ids, originX, originZ, Math.max(reachBlocks, TERRAIN_MARGIN_BLOCKS)); @@ -88,6 +93,18 @@ final class IrisMantleGenerationContext implements MantleGenerationContext { return mantle; } + /** Iris's own view of the chunk, and the matter of the mantle as far as the stage reaches. */ + @Override + public Optional extension(Class type) { + if (type == IrisMantleChunk.class) { + return HostExtensions.as(type, irisChunk); + } + if (type == MatterMantle.class) { + return HostExtensions.as(type, mantle); + } + return Optional.empty(); + } + /** The world this invocation first asked for; it keeps it if the world restarts meanwhile. */ @Override diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisModuleMantle.java b/core/src/main/java/art/arcane/iris/core/modules/IrisModuleMantle.java index 12ffe8277..96c59fd01 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisModuleMantle.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisModuleMantle.java @@ -112,8 +112,8 @@ final class IrisModuleMantle implements Mantle, MatterMantle { } @Override - public MantleLayer caverns() { - return new MantleCaverns(bounds, chunks); + public boolean isCarved(int x, int y, int z) { + return new MantleCaverns(bounds, chunks).isCarved(x, y, z); } @Override @@ -262,9 +262,9 @@ final class IrisModuleMantle implements Mantle, MatterMantle { } @Override - public MantleLayer caverns() { + public boolean isCarved(int x, int y, int z) { requireOpen(); - return new MantleCaverns(bounds, chunks); + return new MantleCaverns(bounds, chunks).isCarved(x, y, z); } @Override diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisObjectHost.java b/core/src/main/java/art/arcane/iris/core/modules/IrisObjectHost.java index 85157252d..c1582c581 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisObjectHost.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisObjectHost.java @@ -45,6 +45,7 @@ import art.arcane.iris.util.project.noise.NoiseType; import art.arcane.volmlib.util.cache.CacheKey; import art.arcane.volmlib.util.math.RNG; import com.volmit.config.Level; +import com.volmit.generation.InvocationContext; import com.volmit.IrisFeature; import com.volmit.ModuleLog; import com.volmit.config.FeatureSettings; @@ -117,8 +118,8 @@ final class IrisObjectHost implements ObjectHost { } @Override - public ObjectChunk chunk() { - IrisMantleChunk chunk = IrisMantleChunk.current(); + public ObjectChunk chunk(InvocationContext context) { + IrisMantleChunk chunk = context.extension(IrisMantleChunk.class).orElseThrow(); return new IrisObjectChunk(chunk.engine(), chunk.writer(), log, this::options); } diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java b/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java index fb074dbdf..42f323244 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java @@ -31,7 +31,6 @@ import com.volmit.noise.NoiseFactory; import com.volmit.object.GeneratedObject; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; -import com.volmit.resource.ResourceKey; import com.volmit.resource.ResourceKind; import com.volmit.world.PackBiome; import com.volmit.world.PackRegion; @@ -52,11 +51,11 @@ import java.util.function.Supplier; * snapshot shares. Each load or hotload of the pack's data makes a new one, with a new {@link #snapshotId()}, and so * does every reload of its module resources ({@link IrisData#dump()}, {@link IrisData#invalidateStructureResources()}). *

- * Served by the type the key asks for: {@link GeneratedObject} (a pack object, as its geometry), {@link PackBiome}, - * {@link PackRegion}, and the type of every {@link ResourceKind} the pack's modules register, read from the kind's - * folder ({@link ModuleResourceFiles}). All use the id {@code :} that {@link PackResourceIds} + * 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 ModuleResourceFiles}). All use the id {@code :} 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 type fails with {@link IllegalArgumentException}. A resource that exists + * another namespace, is absent; any other kind fails with {@link IllegalArgumentException}. A resource that exists * but cannot be loaded fails with {@link IllegalStateException}. Each resource is built once and kept for the * snapshot. The module kinds are looked up the first time one is asked for, which loads the pack's modules. *

@@ -64,7 +63,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 = "GeneratedObject, PackBiome, PackRegion and the types of the pack's module resource kinds"; + private static final String SERVED_TYPES = "the host kinds (objects, biomes, regions) and the pack's module resource kinds"; private final IrisData data; private final PackResourceIds ids; @@ -73,9 +72,9 @@ public final class IrisPackResources implements PackResources { private final BlockRegistry blocks; private final ItemRegistry items = new IrisItemRegistry(); private final NoiseFactory noise; - private final Map, Kind> irisKinds; + private final Map> irisKinds; private final Supplier>> moduleKindList; - private volatile Map, Kind> moduleKinds; + private volatile Map> moduleKinds; private volatile List moduleFolders; private boolean announcedToModules; @@ -93,9 +92,9 @@ public final class IrisPackResources implements PackResources { this.blocks = new IrisBlockRegistry(data); this.noise = new IrisNoiseFactory(data); this.irisKinds = Map.of( - GeneratedObject.class, Kind.ofLoader(ids, data::getObjectLoader, (id, object) -> object.getGeometry()), - PackBiome.class, Kind.ofLoader(ids, data::getBiomeLoader, this::biomeOf), - PackRegion.class, Kind.ofLoader(ids, data::getRegionLoader, this::regionOf)); + OBJECTS.id(), Kind.ofLoader(ids, data::getObjectLoader, (id, object) -> object.getGeometry()), + BIOMES.id(), Kind.ofLoader(ids, data::getBiomeLoader, this::biomeOf), + REGIONS.id(), Kind.ofLoader(ids, data::getRegionLoader, this::regionOf)); } @Override @@ -141,14 +140,14 @@ public final class IrisPackResources implements PackResources { } @Override - @SuppressWarnings("unchecked") // The kinds are keyed by the type they serve. - public Optional find(ResourceKey key) { - return ((Kind) kindOf(key.type())).find(key.id()); + @SuppressWarnings("unchecked") // A kind's id names the one kind registered under it, which serves the kind's type. + public Optional find(ResourceKind kind, ResourceId id) { + return ((Kind) kindOf(kind)).find(id); } @Override - public List ids(Class type) { - return kindOf(type).ids(); + public List ids(ResourceKind kind) { + return kindOf(kind).ids(); } /** The id of the resource the pack names by {@code packKey}, such as {@code overworld:castle/keep} for {@code castle/keep}. */ @@ -167,27 +166,27 @@ public final class IrisPackResources implements PackResources { return folders; } - private Kind kindOf(Class type) { - Kind iris = irisKinds.get(type); + private Kind kindOf(ResourceKind kind) { + Kind iris = irisKinds.get(kind.id()); if (iris != null) { return iris; } - Kind module = moduleKinds().get(type); + Kind module = moduleKinds().get(kind.id()); if (module == null) { - throw new IllegalArgumentException("Iris serves pack resources of " + SERVED_TYPES + ", not " + type.getName()); + throw new IllegalArgumentException("Iris serves pack resources of " + SERVED_TYPES + ", not " + kind.id()); } return module; } - private Map, Kind> moduleKinds() { - Map, Kind> kinds = moduleKinds; + private Map> moduleKinds() { + Map> kinds = moduleKinds; if (kinds != null) { return kinds; } synchronized (this) { if (moduleKinds == null) { - Map, Kind> found = new HashMap<>(); - moduleKindList.get().forEach(kind -> found.put(kind.type(), moduleKind(kind))); + Map> found = new HashMap<>(); + moduleKindList.get().forEach(kind -> found.put(kind.id(), moduleKind(kind))); moduleKinds = Map.copyOf(found); } return moduleKinds; @@ -201,10 +200,24 @@ public final class IrisPackResources implements PackResources { /** Iris's own biome that {@code id}, as a {@code BiomeSample} gives it, names; for host code that reads what the biome declares. */ Optional irisBiome(ResourceId id) { - String key = irisKinds.get(PackBiome.class).keyOf(id); + String key = irisKinds.get(BIOMES.id()).keyOf(id); return key == null ? Optional.empty() : Optional.ofNullable(data.getBiomeLoader().load(key)); } + /** + * The key Iris's own code names {@code id} by, a resource of {@code kind}: the pack key that has the id, else the + * id's path when it is of the pack's namespace, else the id as written ({@code minecraft:village}). + */ + public String keyOf(ResourceKind kind, ResourceId id) { + String key = kindOf(kind).keyOf(id); + return key == null ? keyOf(id) : key; + } + + /** The key Iris's own code names {@code id} by when no index of keys is at hand: its path in the pack's namespace, else the id as written. */ + public String keyOf(ResourceId id) { + return id.namespace().equals(ids.namespace()) ? id.path() : id.toString(); + } + private PackBiome biomeOf(ResourceId id, IrisBiome biome) { return new PackBiome(id, biome.getName(), ResourceId.parse(biome.getDerivativeKey()), ResourceId.parse(biome.getVanillaDerivativeKey()), biome.getRarity(), idsOf(biome.getChildren())); diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisPackSettings.java b/core/src/main/java/art/arcane/iris/core/modules/IrisPackSettings.java index 29974a9be..6a578c95e 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisPackSettings.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisPackSettings.java @@ -36,13 +36,15 @@ import com.volmit.resource.ResourceId; import java.util.ArrayList; import java.util.List; +import java.util.Optional; /** * The settings an engine's pack declares, for working out mantle stage reaches when the pack loads and for vanilla * structure hooks: the engine's dimension, then every region it can reach, then every biome. Iris's built-in modules - * decide from Iris's own pack data instead of module settings; they reach the engine through {@link #of(PackSettings)}. + * decide from Iris's own pack data instead of module settings; they reach it through the object, floating and structure + * hosts the settings offer as {@linkplain #extension extensions}. */ -public final class IrisPackSettings implements PackSettings, ObjectHost.Source, FloatingHost.Source, StructureHost.Source { +public final class IrisPackSettings implements PackSettings { static final String DIMENSION = "dimension"; static final String REGION = "region"; static final String BIOME = "biome"; @@ -55,32 +57,31 @@ public final class IrisPackSettings implements PackSettings, ObjectHost.Source, this.ids = new PackResourceIds(engine.getData().getDataFolder()); } - /** Iris's own view of {@code settings}, which Iris hands to every reach it works out. */ - public static IrisPackSettings of(PackSettings settings) { - if (!(settings instanceof IrisPackSettings irisSettings)) { - throw new IllegalArgumentException("Built-in modules read an Iris engine's pack, not " + settings); - } - return irisSettings; - } - /** The engine whose pack is loading. */ public Engine engine() { return engine; } @Override - public ObjectHost objects() { - return new IrisObjectHost(engine, IrisApiLogger.hostLog()); + public Optional extension(Class type) { + return HostExtensions.as(type, offered(type)); } - @Override - public FloatingHost floating() { - return new IrisFloatingHost(engine, IrisApiLogger.hostLog()); - } - - @Override - public StructureHost structures() { - return new IrisStructureHost(engine, IrisApiLogger.hostLog()); + /** The engine is offered only for the structure built-ins, which drive Iris's structure locator themselves. */ + private Object offered(Class type) { + if (type == Engine.class) { + return engine; + } + if (type == ObjectHost.class) { + return new IrisObjectHost(engine, IrisApiLogger.hostLog()); + } + if (type == FloatingHost.class) { + return new IrisFloatingHost(engine, IrisApiLogger.hostLog()); + } + if (type == StructureHost.class) { + return new IrisStructureHost(engine, IrisApiLogger.hostLog()); + } + return null; } @Override diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java b/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java index 5482bf786..636d69e41 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java @@ -19,6 +19,7 @@ package art.arcane.iris.core.modules; import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.iris.builtin.LiveWorld; import art.arcane.iris.builtin.floating.FloatingHost; import art.arcane.iris.builtin.structure.StructureHost; @@ -29,47 +30,33 @@ import com.volmit.ModuleLog; import com.volmit.config.PackSettings; import com.volmit.host.WorldStates; import com.volmit.world.PackWorld; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; +import java.util.Optional; import java.util.function.Function; /** * One Iris world as modules see it: an engine runtime generating with one snapshot of its pack's resources, and the * state modules keep for it. {@link ModuleWorlds} makes one when the runtime is built and a new one whenever the - * pack's resources reload under it. Iris's built-in modules reach the engine through {@link #of(PackWorld)}, as built-in - * reaches do through {@link IrisPackSettings#of}. + * pack's resources reload under it. Iris's built-in modules reach what they need of Iris through its + * {@linkplain #extension extensions}: the world's seeds, its live view and the object, floating and structure hosts. */ -public final class IrisPackWorld implements PackWorld, IrisSeed.Source, LiveWorld.Source, ObjectHost.Source, FloatingHost.Source, StructureHost.Source { +public final class IrisPackWorld implements PackWorld { private final Engine engine; private final IrisPackResources resources; private final WorldStates states; private final ModuleLog log; - private final Map viewsByLog; private final LiveWorld liveWorld; + private final IrisSeeds seeds; private volatile IrisObjectHost objectHost; private volatile IrisFloatingHost floatingHost; private volatile IrisStructureHost structureHost; IrisPackWorld(Engine engine) { - this(engine, engine.getData().getPackResources(), new WorldStates(), IrisApiLogger.hostLog(), new ConcurrentHashMap<>()); - } - - private IrisPackWorld(Engine engine, IrisPackResources resources, WorldStates states, ModuleLog log, - Map viewsByLog) { this.engine = engine; - this.resources = resources; - this.states = states; - this.log = log; - this.viewsByLog = viewsByLog; + this.resources = engine.getData().getPackResources(); + this.states = new WorldStates(); + this.log = IrisApiLogger.hostLog(); this.liveWorld = new IrisLiveWorld(engine, resources); - } - - /** Iris's own view of {@code world}, which Iris hands to every stage, service and lifecycle hook. */ - public static IrisPackWorld of(PackWorld world) { - if (!(world instanceof IrisPackWorld irisWorld)) { - throw new IllegalArgumentException("Built-in modules work in worlds Iris generates, not " + world); - } - return irisWorld; + this.seeds = this::seedOf; } /** The engine generating this world. */ @@ -107,19 +94,35 @@ public final class IrisPackWorld implements PackWorld, IrisSeed.Source, LiveWorl return log; } - /** One view per log, since the services ask for a module's view on every call. */ @Override - public IrisPackWorld withLog(ModuleLog log) { - return viewsByLog.computeIfAbsent(log, moduleLog -> new IrisPackWorld(engine, resources, states, moduleLog, viewsByLog)); + public Optional extension(Class type) { + return HostExtensions.as(type, offered(type)); } - @Override - public LiveWorld liveWorld() { - return liveWorld; + /** The engine is offered only for the structure built-ins, which drive Iris's structure locator themselves. */ + private Object offered(Class type) { + if (type == Engine.class) { + return engine; + } + if (type == IrisSeeds.class) { + return seeds; + } + if (type == LiveWorld.class) { + return liveWorld; + } + if (type == ObjectHost.class) { + return objects(); + } + if (type == FloatingHost.class) { + return floating(); + } + if (type == StructureHost.class) { + return structures(); + } + return null; } - @Override - public long seed(IrisSeed seed) { + private long seedOf(IrisSeed seed) { SeedManager seeds = engine.getSeedManager(); return switch (seed) { case BIOME -> seeds.getBiome(); @@ -136,8 +139,7 @@ public final class IrisPackWorld implements PackWorld, IrisSeed.Source, LiveWorl }; } - @Override - public ObjectHost objects() { + private ObjectHost objects() { IrisObjectHost host = objectHost; if (host == null) { host = new IrisObjectHost(engine, log); @@ -146,8 +148,7 @@ public final class IrisPackWorld implements PackWorld, IrisSeed.Source, LiveWorl return host; } - @Override - public FloatingHost floating() { + private FloatingHost floating() { IrisFloatingHost host = floatingHost; if (host == null) { host = new IrisFloatingHost(engine, log); @@ -156,8 +157,7 @@ public final class IrisPackWorld implements PackWorld, IrisSeed.Source, LiveWorl return host; } - @Override - public StructureHost structures() { + private StructureHost structures() { IrisStructureHost host = structureHost; if (host == null) { host = new IrisStructureHost(engine, log); diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisPlacement.java b/core/src/main/java/art/arcane/iris/core/modules/IrisPlacement.java index ec8e37b1b..b80bd93c3 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisPlacement.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisPlacement.java @@ -43,12 +43,11 @@ import com.volmit.resource.PackResources; import com.volmit.world.BlockPosition; import java.util.Optional; -import java.util.function.Supplier; /** * Iris's own inputs of the object placement being run: the placement settings, object, placer and cave that IrisApi - * does not describe, answered to Iris's built-in placement stages as an {@link ObjectPlacement}, bound on the placing - * thread while the placement graph runs. Pack modules cannot see this class. + * does not describe, answered to Iris's built-in placement stages as an {@link ObjectPlacement}, the extension of the + * placement invocation. Pack modules cannot see this class. */ public final class IrisPlacement implements ObjectPlacement { private static final int NOT_ANCHORED = Integer.MIN_VALUE; @@ -87,9 +86,6 @@ public final class IrisPlacement implements ObjectPlacement { this.terrain = new IrisPlacementTerrain(placer, object.getLoader(), data, states); } - T runBound(Supplier placement) { - return ObjectPlacement.runBound(this, placement); - } @Override public ObjectShape object() { diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisPlacementInputs.java b/core/src/main/java/art/arcane/iris/core/modules/IrisPlacementInputs.java index 7028d73e4..7ce1f937d 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisPlacementInputs.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisPlacementInputs.java @@ -18,6 +18,7 @@ package art.arcane.iris.core.modules; +import art.arcane.iris.builtin.placement.ObjectPlacement; import art.arcane.iris.engine.framework.Engine; import com.volmit.config.FeatureSettings; import com.volmit.mantle.BlockBox; @@ -30,6 +31,7 @@ import com.volmit.world.TerrainSample; import com.volmit.world.PackWorld; import com.volmit.world.TerrainSampler; +import java.util.Optional; import java.util.OptionalInt; import java.util.function.Supplier; @@ -40,14 +42,25 @@ final class IrisPlacementInputs implements PlacementContext { private final FeatureSettings settings; private final BlockView blocks; private final Supplier worldSource; + private final ObjectPlacement placement; private PackWorld world; - /** @param worldSource the world the placement generates in, asked for the first time a stage needs it */ - IrisPlacementInputs(TerrainSampler terrain, FeatureSettings settings, BlockView blocks, Supplier worldSource) { + /** + * @param worldSource the world the placement generates in, asked for the first time a stage needs it + * @param placement what Iris's built-in placement stages see of the placement as an extension + */ + IrisPlacementInputs(TerrainSampler terrain, FeatureSettings settings, BlockView blocks, Supplier worldSource, + ObjectPlacement placement) { this.terrain = terrain; this.settings = settings; this.blocks = blocks; this.worldSource = worldSource; + this.placement = placement; + } + + @Override + public Optional extension(Class type) { + return type == ObjectPlacement.class ? HostExtensions.as(type, placement) : Optional.empty(); } /** The world of the engine's runtime, as it is when the placement first asks. */ diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisStructureHost.java b/core/src/main/java/art/arcane/iris/core/modules/IrisStructureHost.java index ed9d29479..1a55d328d 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisStructureHost.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisStructureHost.java @@ -22,6 +22,7 @@ import art.arcane.iris.builtin.structure.StructureHost; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.mantle.components.StructurePlacing; import com.volmit.ModuleLog; +import com.volmit.generation.InvocationContext; /** Iris's {@link StructureHost}: the engine's {@link StructurePlacing}, one per engine runtime, places and sizes its structures. */ final class IrisStructureHost implements StructureHost { @@ -34,8 +35,8 @@ final class IrisStructureHost implements StructureHost { } @Override - public void placeChunk() { - IrisMantleChunk chunk = IrisMantleChunk.current(); + public void placeChunk(InvocationContext context) { + IrisMantleChunk chunk = context.extension(IrisMantleChunk.class).orElseThrow(); placing().place(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); } diff --git a/core/src/main/java/art/arcane/iris/core/modules/MantleCaverns.java b/core/src/main/java/art/arcane/iris/core/modules/MantleCaverns.java index 47c0ed488..27b7fd169 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/MantleCaverns.java +++ b/core/src/main/java/art/arcane/iris/core/modules/MantleCaverns.java @@ -15,31 +15,22 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ + package art.arcane.iris.core.modules; import art.arcane.volmlib.util.mantle.runtime.MantleChunk; import art.arcane.volmlib.util.matter.Matter; import art.arcane.volmlib.util.matter.MatterCavern; import com.volmit.mantle.BlockBox; -import com.volmit.mantle.MantleLayer; -import com.volmit.mantle.MantleVisitor; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Objects; /** - * The voids Iris's mantle holds for chunks to take over, IrisApi's {@link com.volmit.mantle.Mantle#caverns()}: where the cave - * planner marked a cavern in the mantle's cavern slice, whatever the cavern holds (air, fluid, lava). Stages only read them. + * The voids Iris's mantle holds for chunks to take over, IrisApi's {@link com.volmit.mantle.Mantle#isCarved}: where the + * cave planner marked a cavern in the mantle's cavern slice, whatever the cavern holds (air, fluid, lava). */ -final class MantleCaverns implements MantleLayer { +final class MantleCaverns { private static final int CHUNK_SHIFT = 4; private static final int SECTION_SHIFT = 4; private static final int LOCAL_MASK = 15; - private static final String READ_ONLY = "Stages read the caverns; the cave planner writes them"; - private static final Comparator VISIT_ORDER = Comparator.comparingInt(Position::x) - .thenComparingInt(Position::y).thenComparingInt(Position::z); private final BlockBox bounds; private final IrisModuleMantle.Chunks chunks; @@ -49,58 +40,9 @@ final class MantleCaverns implements MantleLayer { this.chunks = chunks; } - @Override - public Boolean get(int x, int y, int z) { + boolean isCarved(int x, int y, int z) { requireInside(x, y, z); - return cavernAt(requireChunk(x >> CHUNK_SHIFT, z >> CHUNK_SHIFT), x, y, z) ? Boolean.TRUE : null; - } - - @Override - public void visit(BlockBox area, MantleVisitor visitor) { - Objects.requireNonNull(visitor, "visitor"); - requireInside(area); - for (Position carved : carvedIn(area)) { - visitor.accept(carved.x(), carved.y(), carved.z(), Boolean.TRUE); - } - } - - @Override - public void set(int x, int y, int z, Boolean value) { - throw new UnsupportedOperationException(READ_ONLY); - } - - @Override - public void remove(int x, int y, int z) { - throw new UnsupportedOperationException(READ_ONLY); - } - - @Override - public void clear(BlockBox area) { - throw new UnsupportedOperationException(READ_ONLY); - } - - /** The carved positions in {@code area}, ordered by x, then y, then z, as {@link MantleLayer#visit} promises. */ - private List carvedIn(BlockBox area) { - List carved = new ArrayList<>(); - for (int chunkX = area.minX() >> CHUNK_SHIFT; chunkX <= (area.maxX() - 1) >> CHUNK_SHIFT; chunkX++) { - for (int chunkZ = area.minZ() >> CHUNK_SHIFT; chunkZ <= (area.maxZ() - 1) >> CHUNK_SHIFT; chunkZ++) { - collect(chunkX, chunkZ, area, carved); - } - } - carved.sort(VISIT_ORDER); - return carved; - } - - private void collect(int chunkX, int chunkZ, BlockBox area, List carved) { - int originX = chunkX << CHUNK_SHIFT; - int originZ = chunkZ << CHUNK_SHIFT; - requireChunk(chunkX, chunkZ).iterate(MatterCavern.class, (localX, y, localZ, cavern) -> { - int x = originX + localX; - int z = originZ + localZ; - if (cavern != null && area.contains(x, y, z)) { - carved.add(new Position(x, y, z)); - } - }); + return cavernAt(requireChunk(x >> CHUNK_SHIFT, z >> CHUNK_SHIFT), x, y, z); } private static boolean cavernAt(MantleChunk chunk, int x, int y, int z) { @@ -128,14 +70,4 @@ final class MantleCaverns implements MantleLayer { throw new IndexOutOfBoundsException("Block " + x + ", " + y + ", " + z + " is outside the mantle this invocation prepared, " + bounds); } } - - private void requireInside(BlockBox area) { - Objects.requireNonNull(area, "area"); - if (!bounds.contains(area)) { - throw new IndexOutOfBoundsException("Area " + area + " is not inside the mantle this invocation prepared, " + bounds); - } - } - - private record Position(int x, int y, int z) { - } } diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleChunkGeneration.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleChunkGeneration.java index 6d620e9e0..3fef32e69 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleChunkGeneration.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleChunkGeneration.java @@ -61,10 +61,10 @@ public final class ModuleChunkGeneration { int chunkZ = z >> CHUNK_SHIFT; long seed = ModuleSeeds.chunk(engine.getSeedManager().getSeed(), chunkX, chunkZ); try (PinnedMantleChunks mantle = new PinnedMantleChunks(engine)) { + IrisChunk irisChunk = new IrisChunk(engine, x, z, blocks, biomes, multicore, context); IrisGenerationContext inputs = new IrisGenerationContext(engine, x, z, blocks, new PlatformBlockStates(platformStates), mantle, - pack.catalog().mantle()); - StageMetrics metrics = new StageMetrics(engine.getMetrics()); - new IrisChunk(engine, x, z, blocks, biomes, multicore, context).runBound(() -> new ChunkRunner(chunk).generate(inputs, seed, metrics)); + pack.catalog().mantle(), irisChunk); + new ChunkRunner(chunk).generate(inputs, seed, new StageMetrics(engine.getMetrics())); } } } diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleMantleComponent.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleMantleComponent.java index 8abc548b2..209a22c83 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleMantleComponent.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleMantleComponent.java @@ -112,12 +112,16 @@ public final class ModuleMantleComponent implements MantleComponent { @Override public void generateLayer(MantleWriter writer, int x, int z, ChunkContext context) { - new IrisMantleChunk(engine, writer, x, z, context).runBound(() -> generate(x, z, writer::acquireChunk)); + generate(x, z, writer::acquireChunk, new IrisMantleChunk(engine, writer, x, z, context)); } - /** Runs the stage for chunk {@code x}, {@code z}, with the mantle chunks within the stage's reach of it. */ - void generate(int x, int z, IrisModuleMantle.Chunks chunks) { - IrisMantleGenerationContext inputs = new IrisMantleGenerationContext(engine, x, z, reachBlocks, chunks, pack.catalog().mantle()); + /** + * Runs the stage for chunk {@code x}, {@code z}, with the mantle chunks within the stage's reach of it and + * {@code irisChunk} as Iris's own view of the chunk. + */ + void generate(int x, int z, IrisModuleMantle.Chunks chunks, IrisMantleChunk irisChunk) { + IrisMantleGenerationContext inputs = new IrisMantleGenerationContext(engine, x, z, reachBlocks, chunks, pack.catalog().mantle(), + irisChunk); runner.generate(stage.stage(), inputs, ModuleSeeds.chunk(engine.getSeedManager().getSeed(), x, z), new StageMetrics(engine.getMetrics())); } diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleObjectPlacement.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleObjectPlacement.java index dc7c2ad8e..81c7f98b5 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleObjectPlacement.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleObjectPlacement.java @@ -90,9 +90,10 @@ public final class ModuleObjectPlacement { try (ToolWorld toolWorld = engine == null ? new ToolWorld(worldSeed, data.getPackResources(), new PackDeclaredSettings(data)) : null) { IrisPlacementInputs inputs = new IrisPlacementInputs(terrain(engine, ids, area), new PlacementModuleSettings(worldSettings(engine, ids), config.getModuleSettings(), source), - new PlacerBlockView(placer, area, states), engine != null ? IrisPlacementInputs.worldOf(engine) : () -> toolWorld); - PlacementOutcome outcome = placement.runBound(() -> new PlacementRunner(graph) - .place(request, edit, inputs, seed, config.getModuleSettings().placement(source), metrics)); + new PlacerBlockView(placer, area, states), engine != null ? IrisPlacementInputs.worldOf(engine) : () -> toolWorld, + placement); + PlacementOutcome outcome = new PlacementRunner(graph) + .place(request, edit, inputs, seed, config.getModuleSettings().placement(source), metrics); return outcome.isPlaced() ? ObjectPlacementResult.placed(placement.anchorY()) : ObjectPlacementResult.rejected(outcome.rejection().orElseThrow()); diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleServices.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleServices.java index 41fe5b326..fc19f5570 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleServices.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleServices.java @@ -24,6 +24,7 @@ import com.volmit.host.FeatureCatalog; import com.volmit.host.ServiceRegistration; import com.volmit.entity.EntitySpec; import com.volmit.item.ItemDrop; +import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; import com.volmit.service.AmbientEffects; import com.volmit.service.BlockDrops; @@ -98,23 +99,30 @@ public final class ModuleServices { /** The objects every module would place in the chunk at {@code chunkX}, {@code chunkZ}, guessed without generating it. */ public static Set objectsAt(Engine engine, int chunkX, int chunkZ) { + IrisPackResources resources = engine.getData().getPackResources(); Set keys = new LinkedHashSet<>(); for (Provider provider : providers(engine, ObjectsAt.class)) { - keys.addAll(provider.service().objectsAt(provider.world(), chunkX, chunkZ)); + provider.service().objectsAt(provider.world(), chunkX, chunkZ).forEach(id -> keys.add(resources.keyOf(PackResources.OBJECTS, id))); } return keys; } - /** The biomes and regions of the engine's layout that every module says place the object {@code objectKey}. */ - public static ObjectsAt.PlacedBy objectPlacers(Engine engine, String objectKey) { + /** The keys of the biomes and regions of the engine's layout that every module says place the object {@code objectKey}. */ + public static ObjectPlacers objectPlacers(Engine engine, String objectKey) { + IrisPackResources resources = engine.getData().getPackResources(); + ResourceId object = resources.idOf(objectKey); Set biomes = new LinkedHashSet<>(); Set regions = new LinkedHashSet<>(); for (Provider provider : providers(engine, ObjectsAt.class)) { - ObjectsAt.PlacedBy placedBy = provider.service().placedBy(provider.world(), objectKey); - biomes.addAll(placedBy.biomes()); - regions.addAll(placedBy.regions()); + ObjectsAt.PlacedBy placedBy = provider.service().placedBy(provider.world(), object); + placedBy.biomes().forEach(id -> biomes.add(resources.keyOf(PackResources.BIOMES, id))); + placedBy.regions().forEach(id -> regions.add(resources.keyOf(PackResources.REGIONS, id))); } - return new ObjectsAt.PlacedBy(biomes, regions); + return new ObjectPlacers(biomes, regions); + } + + /** The keys of the biomes and regions that place an object. */ + public record ObjectPlacers(Set biomes, Set regions) { } /** The loot tables the modules say the container at {@code site} draws from, in module order. */ @@ -126,11 +134,11 @@ public final class ModuleServices { return tables; } - /** The items loot table {@code key} gives at {@code site}, from the module that knows the table. */ - public static List lootItems(Engine engine, Loot.Site site, String key) { + /** The items loot table {@code table} gives at {@code site}, from the module that knows the table. */ + public static List lootItems(Engine engine, Loot.Site site, ResourceId table) { List items = new ArrayList<>(); for (Provider provider : providers(engine, Loot.class)) { - items.addAll(provider.service().items(provider.world(), site, key)); + items.addAll(provider.service().items(provider.world(), site, table)); } return items; } @@ -160,8 +168,8 @@ public final class ModuleServices { /** The objects every module places as trees. */ public static SaplingGrowth.TreeObjects treeObjects(Engine engine) { - Set objects = new LinkedHashSet<>(); - Set procedural = new LinkedHashSet<>(); + Set objects = new LinkedHashSet<>(); + Set procedural = new LinkedHashSet<>(); for (Provider provider : providers(engine, SaplingGrowth.class)) { SaplingGrowth.TreeObjects trees = provider.service().treeObjects(provider.world()); objects.addAll(trees.objects()); @@ -181,10 +189,11 @@ public final class ModuleServices { return Optional.empty(); } - /** The entity {@code key} as the first module that knows it would spawn it. */ + /** The entity the pack names {@code key} as the first module that knows it would spawn it. */ public static Optional entity(Engine engine, String key) { + ResourceId id = engine.getData().getPackResources().idOf(key); for (Provider provider : providers(engine, EntitySpawns.class)) { - Optional entity = provider.service().entity(provider.world(), key); + Optional entity = provider.service().entity(provider.world(), id); if (entity.isPresent()) { return entity; } @@ -223,7 +232,7 @@ public final class ModuleServices { public static Set structureKeys(IrisData data) { Set keys = new LinkedHashSet<>(); for (StructureLocator provider : catalog(data).services(StructureLocator.class)) { - keys.addAll(provider.structures(data.getPackResources())); + keys.addAll(structureKeysOf(data, provider.structures(data.getPackResources()))); } return keys; } @@ -232,7 +241,7 @@ public final class ModuleServices { public static Set locatableStructures(Engine engine) { Set keys = new LinkedHashSet<>(); for (Provider provider : providers(engine, StructureLocator.class)) { - keys.addAll(provider.service().locatable(provider.world())); + keys.addAll(structureKeysOf(engine.getData(), provider.service().locatable(provider.world()))); } return keys; } @@ -249,7 +258,7 @@ public final class ModuleServices { public static Set placedStructures(Engine engine) { Set keys = new LinkedHashSet<>(); for (Provider provider : providers(engine, StructureLocator.class)) { - keys.addAll(provider.service().placed(provider.world())); + keys.addAll(structureKeysOf(engine.getData(), provider.service().placed(provider.world()))); } return keys; } @@ -265,7 +274,8 @@ public final class ModuleServices { */ public static StructureSearch locateStructure(Engine engine, String key, int fromX, int fromZ, int maxRadiusChunks) { LocateResult result = structureLocatorOf(engine, key, StructureLocator::placed) - .map(provider -> provider.service().locate(provider.world(), key, fromX, fromZ, maxRadiusChunks)) + .map(provider -> provider.service().locate(provider.world(), structureIdOf(engine.getData(), key), fromX, fromZ, + maxRadiusChunks)) .orElse(LocateResult.NOT_FOUND); return StructureSearch.of(result, engine); } @@ -339,21 +349,41 @@ public final class ModuleServices { } } - /** The first provider, in the catalog's order, whose structures of the kind {@code keys} lists hold {@code key}. */ + /** The first provider, in the catalog's order, whose structures of the kind {@code structures} lists hold {@code key}. */ private static Optional> structureLocatorOf(Engine engine, String key, - BiFunction> keys) { + BiFunction> structures) { if (key == null || key.isBlank()) { return Optional.empty(); } - String wanted = normalized(key); + ResourceId wanted = structureIdOf(engine.getData(), key); for (Provider provider : providers(engine, StructureLocator.class)) { - if (keys.apply(provider.service(), provider.world()).stream().map(ModuleServices::normalized).anyMatch(wanted::equals)) { + if (structures.apply(provider.service(), provider.world()).contains(wanted)) { return Optional.of(provider); } } return Optional.empty(); } + /** + * The id of the structure Iris's commands name {@code key}: a key with a namespace is that id + * ({@code minecraft:village}), any other a structure of the pack. Ids are lower case, so keys match without regard + * to case. + */ + private static ResourceId structureIdOf(IrisData data, String key) { + String trimmed = key.trim(); + return trimmed.indexOf(':') >= 0 ? ResourceId.parse(normalized(trimmed)) : data.getPackResources().idOf(trimmed); + } + + /** The keys Iris's commands show for {@code structures}: a pack structure by its path, any other by its id. */ + private static Set structureKeysOf(IrisData data, Set structures) { + IrisPackResources resources = data.getPackResources(); + Set keys = new LinkedHashSet<>(); + for (ResourceId structure : structures) { + keys.add(resources.keyOf(structure)); + } + return keys; + } + /** The platform structures every provider lists with {@code structures}, as lower-case registry keys. */ private static Set platformStructures(Engine engine, BiFunction> structures) { Set keys = new LinkedHashSet<>(); diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleSettings.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleSettings.java index 9496089f5..ea91b3bfe 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleSettings.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleSettings.java @@ -21,6 +21,7 @@ package art.arcane.iris.core.modules; import com.volmit.IrisFeature; import com.volmit.config.LinkedBiomes; import com.volmit.host.ConfiguredSettings; +import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; import java.util.Collection; @@ -60,21 +61,24 @@ public final class ModuleSettings { return values.isEmpty(); } - /** The biomes these settings add to the biome tree of the owner's regions ({@link LinkedBiomes#treeBiomes}), in a fixed order. */ - public Set treeBiomes() { - return linkedBiomes(LinkedBiomes::treeBiomes); + /** + * The keys of the biomes these settings add to the biome tree of the owner's regions ({@link LinkedBiomes#treeBiomes}), + * in a fixed order. + */ + public Set treeBiomes(IrisPackResources resources) { + return linkedBiomes(resources, linked -> linked.treeBiomes(resources)); } /** - * The biomes these settings use besides ({@link LinkedBiomes#usedBiomes}), in a fixed order. + * The keys of the biomes these settings use besides ({@link LinkedBiomes#usedBiomes}), in a fixed order. * * @param dimension the settings of the dimension the owner is part of */ - public Set usedBiomes(ModuleSettings dimension) { - return linkedBiomes(linked -> linked.usedBiomes(dimension.values())); + public Set usedBiomes(IrisPackResources resources, ModuleSettings dimension) { + return linkedBiomes(resources, linked -> linked.usedBiomes(resources, dimension.values())); } - private Set linkedBiomes(Function> pick) { + private Set linkedBiomes(IrisPackResources resources, Function> pick) { if (values.isEmpty()) { return Set.of(); } @@ -82,7 +86,7 @@ public final class ModuleSettings { values.values().stream() .filter(LinkedBiomes.class::isInstance) .sorted(Comparator.comparing(value -> value.getClass().getName())) - .forEach(value -> biomes.addAll(pick.apply((LinkedBiomes) value))); + .forEach(value -> pick.apply((LinkedBiomes) value).forEach(id -> biomes.add(resources.keyOf(PackResources.BIOMES, id)))); return biomes; } diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleSettingsDecoder.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleSettingsDecoder.java index 7b0271065..9e3bf57ac 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleSettingsDecoder.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleSettingsDecoder.java @@ -34,11 +34,11 @@ import com.google.gson.stream.JsonWriter; import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.block.BlockState; -import com.volmit.config.OptionsMetadata; import com.volmit.config.Snippet; import com.volmit.host.FeatureCatalog; import com.volmit.host.FeatureDescriptor; import com.volmit.host.ObjectRegistration; +import com.volmit.host.OptionsMetadata; import com.volmit.resource.ResourceId; import java.io.IOException; @@ -83,9 +83,10 @@ public final class ModuleSettingsDecoder { ModuleSettingsDecoder(FeatureCatalog catalog, Path packFolder, Supplier irisGson) { this.packFolder = packFolder; this.irisGson = irisGson; + PackResourceIds packIds = new PackResourceIds(packFolder.toFile()); this.gson = new GsonBuilder() .registerTypeAdapter(BlockState.class, textAdapter(BlockState::parse, BlockState::key)) - .registerTypeAdapter(ResourceId.class, textAdapter(ResourceId::parse, ResourceId::toString)) + .registerTypeAdapter(ResourceId.class, textAdapter(text -> resourceIdOf(packIds, text), ResourceId::toString)) .registerTypeAdapterFactory(new HostTypes()) .registerTypeAdapterFactory(new SnippetReferences()) .create(); @@ -95,6 +96,11 @@ public final class ModuleSettingsDecoder { } } + /** A resource id as written: {@code namespace:path}, or a pack key such as {@code desert/dunes}, which names a resource of the pack. */ + private static ResourceId resourceIdOf(PackResourceIds packIds, String text) { + return text.indexOf(':') >= 0 ? ResourceId.parse(text) : packIds.of(text); + } + /** Every JSON key the pack's modules read at {@code target}: the keys of their features, object generators' included. */ public Set keys(Level target) { return keys.get(target); diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleStructureFitting.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleStructureFitting.java index 09fdf3587..f39128abf 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleStructureFitting.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleStructureFitting.java @@ -41,6 +41,7 @@ import com.volmit.resource.ResourceId; import com.volmit.service.VanillaStructures; import com.volmit.vanilla.DecorationStep; import com.volmit.vanilla.PieceKind; +import com.volmit.vanilla.StartKey; import com.volmit.vanilla.StartMemo; import com.volmit.vanilla.StructureFit; import com.volmit.vanilla.TemplateCells; @@ -51,12 +52,14 @@ import com.volmit.world.BlockPosition; import com.volmit.world.PackWorld; import java.util.ArrayList; +import java.util.Collections; import java.util.EnumMap; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; @@ -66,6 +69,8 @@ import java.util.function.Supplier; * states and back through caches, so a provider can read and write blocks without allocating per block. */ public final class ModuleStructureFitting implements NativeStructureFitting { + /** One key per platform start for as long as the platform keeps the start, so a start fitted in many chunks is known again. */ + private static final Map START_KEYS = Collections.synchronizedMap(new WeakHashMap<>()); private static final Map API_STATES = new ConcurrentHashMap<>(); private static final Map NATIVE_STATES = new ConcurrentHashMap<>(); private static final Map NATIVE_TRAITS = new ConcurrentHashMap<>(); @@ -360,8 +365,8 @@ public final class ModuleStructureFitting implements NativeStructureFitting { } @Override - public Object key() { - return start.key(); + public StartKey key() { + return START_KEYS.computeIfAbsent(start.key(), ignored -> StartKey.create()); } } diff --git a/core/src/main/java/art/arcane/iris/core/modules/OwnChunkMatter.java b/core/src/main/java/art/arcane/iris/core/modules/OwnChunkMatter.java new file mode 100644 index 000000000..08acfe568 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/modules/OwnChunkMatter.java @@ -0,0 +1,52 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.modules; + +import art.arcane.iris.builtin.MatterMantle; +import art.arcane.volmlib.util.mantle.runtime.MantleChunk; +import art.arcane.volmlib.util.matter.Matter; + +/** + * The matter mantle of a chunk invocation: its own chunk, which a chunk stage writes as it writes the mantle layers of + * its own chunk, and its neighbours only as far as the world already holds them in memory. + */ +final class OwnChunkMatter implements MatterMantle { + private final MatterMantle mantle; + private final int chunkX; + private final int chunkZ; + + OwnChunkMatter(MatterMantle mantle, int chunkX, int chunkZ) { + this.mantle = mantle; + this.chunkX = chunkX; + this.chunkZ = chunkZ; + } + + @Override + public MantleChunk chunk(int chunkX, int chunkZ) { + if (chunkX != this.chunkX || chunkZ != this.chunkZ) { + return null; + } + return mantle.chunk(chunkX, chunkZ); + } + + @Override + public MantleChunk loadedChunk(int chunkX, int chunkZ) { + return mantle.loadedChunk(chunkX, chunkZ); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/modules/PlacementMantle.java b/core/src/main/java/art/arcane/iris/core/modules/PlacementMantle.java index 2f7f493ba..fbc908877 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/PlacementMantle.java +++ b/core/src/main/java/art/arcane/iris/core/modules/PlacementMantle.java @@ -71,8 +71,11 @@ final class PlacementMantle implements Mantle, AutoCloseable { } @Override - public MantleLayer caverns() { - return new StoredRange<>(placement.caverns()); + public boolean isCarved(int x, int y, int z) { + if (!bounds.contains(x, y, z)) { + throw new IndexOutOfBoundsException("Block " + x + ", " + y + ", " + z + " is outside the placement area " + bounds); + } + return y >= storedBounds.minY() && y < storedBounds.maxY() && placement.isCarved(x, y, z); } @Override diff --git a/core/src/main/java/art/arcane/iris/core/modules/ToolWorld.java b/core/src/main/java/art/arcane/iris/core/modules/ToolWorld.java index f90689d75..7ee7ebdad 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ToolWorld.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ToolWorld.java @@ -24,8 +24,6 @@ import com.volmit.host.WorldStates; import com.volmit.resource.PackResources; import com.volmit.world.PackWorld; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; /** @@ -39,20 +37,13 @@ final class ToolWorld implements PackWorld, AutoCloseable { private final PackSettings settings; private final WorldStates states; private final ModuleLog log; - private final Map viewsByLog; ToolWorld(long seed, PackResources resources, PackSettings settings) { - this(seed, resources, settings, new WorldStates(), IrisApiLogger.hostLog(), new ConcurrentHashMap<>()); - } - - private ToolWorld(long seed, PackResources resources, PackSettings settings, WorldStates states, ModuleLog log, - Map viewsByLog) { this.seed = seed; this.resources = resources; this.settings = settings; - this.states = states; - this.log = log; - this.viewsByLog = viewsByLog; + this.states = new WorldStates(); + this.log = IrisApiLogger.hostLog(); } @Override @@ -80,11 +71,6 @@ final class ToolWorld implements PackWorld, AutoCloseable { return log; } - @Override - public PackWorld withLog(ModuleLog log) { - return viewsByLog.computeIfAbsent(log, moduleLog -> new ToolWorld(seed, resources, settings, states, moduleLog, viewsByLog)); - } - @Override public void close() { states.close(); diff --git a/core/src/main/java/art/arcane/iris/core/pack/ModuleResourceClosure.java b/core/src/main/java/art/arcane/iris/core/pack/ModuleResourceClosure.java index 742542541..623002ca7 100644 --- a/core/src/main/java/art/arcane/iris/core/pack/ModuleResourceClosure.java +++ b/core/src/main/java/art/arcane/iris/core/pack/ModuleResourceClosure.java @@ -217,7 +217,7 @@ public final class ModuleResourceClosure { private Object lookup(ResourceKind kind, String key) { IrisPackResources resources = data.getPackResources(); try { - return resources.find(kind.key(resources.idOf(key))).orElse(null); + return resources.find(kind, resources.idOf(key)).orElse(null); } catch (IllegalStateException failedToLoad) { return null; } diff --git a/core/src/main/java/art/arcane/iris/core/project/SchemaBuilder.java b/core/src/main/java/art/arcane/iris/core/project/SchemaBuilder.java index efbddfdb1..1f509b6d5 100644 --- a/core/src/main/java/art/arcane/iris/core/project/SchemaBuilder.java +++ b/core/src/main/java/art/arcane/iris/core/project/SchemaBuilder.java @@ -492,7 +492,7 @@ public class SchemaBuilder { } private PackResourceList putModuleResourceRef(JSONObject property, ResourceKind kind) { - List keys = data.getPackResources().ids(kind.type()).stream().map(ResourceId::path).toList(); + List keys = data.getPackResources().ids(kind).stream().map(ResourceId::path).toList(); return putResourceKeys(property, new PackResourceList(kind.folder(), ModuleResourceFiles.typeName(kind)), keys); } diff --git a/core/src/main/java/art/arcane/iris/core/service/tree/TreeDefinitionIndex.java b/core/src/main/java/art/arcane/iris/core/service/tree/TreeDefinitionIndex.java index 2ba6956cc..40b24448b 100644 --- a/core/src/main/java/art/arcane/iris/core/service/tree/TreeDefinitionIndex.java +++ b/core/src/main/java/art/arcane/iris/core/service/tree/TreeDefinitionIndex.java @@ -3,6 +3,8 @@ package art.arcane.iris.core.service.tree; import art.arcane.iris.core.modules.ModuleServices; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.builtin.structure.StructurePlacementMarker; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import com.volmit.service.SaplingGrowth; import java.util.Set; @@ -10,17 +12,19 @@ import java.util.Set; public final class TreeDefinitionIndex { private static final String PROCEDURAL_TREE_PREFIX = "procedural/tree/"; - private final Set explicitObjectKeys; - private final Set proceduralTreeKeys; + private final PackResources resources; + private final Set explicitObjects; + private final Set proceduralTrees; - private TreeDefinitionIndex(Set explicitObjectKeys, Set proceduralTreeKeys) { - this.explicitObjectKeys = Set.copyOf(explicitObjectKeys); - this.proceduralTreeKeys = Set.copyOf(proceduralTreeKeys); + private TreeDefinitionIndex(PackResources resources, Set explicitObjects, Set proceduralTrees) { + this.resources = resources; + this.explicitObjects = Set.copyOf(explicitObjects); + this.proceduralTrees = Set.copyOf(proceduralTrees); } public static TreeDefinitionIndex build(Engine engine) { SaplingGrowth.TreeObjects trees = ModuleServices.treeObjects(engine); - return new TreeDefinitionIndex(trees.objects(), trees.procedural()); + return new TreeDefinitionIndex(engine.getData().getPackResources(), trees.objects(), trees.procedural()); } public boolean isTreeMarker(String marker) { @@ -31,11 +35,11 @@ public final class TreeDefinitionIndex { String objectKey = decoded.objectKey(); if (objectKey.startsWith(PROCEDURAL_TREE_PREFIX)) { - return proceduralTreeKeys.contains(objectKey); + return proceduralTrees.contains(resources.idOf(objectKey)); } if (objectKey.startsWith("procedural/")) { return false; } - return objectKey.startsWith("trees/") || explicitObjectKeys.contains(objectKey); + return objectKey.startsWith("trees/") || explicitObjects.contains(resources.idOf(objectKey)); } } diff --git a/core/src/main/java/art/arcane/iris/engine/MarkerSpawnScanner.java b/core/src/main/java/art/arcane/iris/engine/MarkerSpawnScanner.java index b89405a85..93f8ee8bd 100644 --- a/core/src/main/java/art/arcane/iris/engine/MarkerSpawnScanner.java +++ b/core/src/main/java/art/arcane/iris/engine/MarkerSpawnScanner.java @@ -26,6 +26,7 @@ import art.arcane.iris.util.common.plugin.Chunks; import art.arcane.iris.util.common.scheduling.J; import art.arcane.volmlib.util.collection.KMap; import art.arcane.volmlib.util.collection.KSet; +import com.volmit.resource.ResourceId; import com.volmit.service.EntitySpawns; import art.arcane.volmlib.util.matter.MatterMarker; import org.bukkit.Chunk; @@ -53,7 +54,7 @@ final class MarkerSpawnScanner { } /** A spawner a marker names, and the marker. */ - record MarkerSpawner(String marker, String spawner) { + record MarkerSpawner(String marker, ResourceId spawner) { } Map> getSpawnersFromMarkers(Chunk c) { @@ -80,7 +81,7 @@ final class MarkerSpawnScanner { return; } - for (String spawner : rule.get().spawners()) { + for (ResourceId spawner : rule.get().spawners()) { addOnce(p.computeIfAbsent(pos, (k) -> new ArrayList<>()), new MarkerSpawner(t.getTag(), spawner)); } }); @@ -178,7 +179,7 @@ final class MarkerSpawnScanner { MarkerSpawnData data = markerData.computeIfAbsent(position, k -> new MarkerSpawnData()); data.requiresEmptyAbove = data.requiresEmptyAbove || rule.get().emptyAbove(); - for (String spawner : rule.get().spawners()) { + for (ResourceId spawner : rule.get().spawners()) { addOnce(data.spawners, new MarkerSpawner(t.getTag(), spawner)); } }); diff --git a/core/src/main/java/art/arcane/iris/engine/framework/HintedLocator.java b/core/src/main/java/art/arcane/iris/engine/framework/HintedLocator.java index bf6f22d5d..931760502 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/HintedLocator.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/HintedLocator.java @@ -391,7 +391,7 @@ public final class HintedLocator implements Locator { } IrisComplex complex = engine.getComplex(); - ObjectsAt.PlacedBy placers = ModuleServices.objectPlacers(engine, objectKey); + ModuleServices.ObjectPlacers placers = ModuleServices.objectPlacers(engine, objectKey); BiomeSource source = new BiomeSource(engine); KSet landHosts = new KSet<>(); KSet seaHosts = new KSet<>(); diff --git a/core/src/main/java/art/arcane/iris/engine/platform/BukkitEntitySpawner.java b/core/src/main/java/art/arcane/iris/engine/platform/BukkitEntitySpawner.java index c4f418e37..a71cc76eb 100644 --- a/core/src/main/java/art/arcane/iris/engine/platform/BukkitEntitySpawner.java +++ b/core/src/main/java/art/arcane/iris/engine/platform/BukkitEntitySpawner.java @@ -40,6 +40,7 @@ import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; import com.volmit.entity.EntitySpec; import com.volmit.item.ItemAttribute; +import com.volmit.resource.ResourceId; import com.volmit.service.Loot; import com.volmit.world.BlockPosition; import org.bukkit.Bukkit; @@ -67,6 +68,7 @@ import org.bukkit.util.Vector; import java.util.Collection; import java.util.List; import java.util.Locale; +import java.util.Optional; import java.util.Random; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; @@ -141,8 +143,8 @@ public final class BukkitEntitySpawner { } if (e instanceof Panda panda) { - panda.setMainGene(resolveGene(spec.pandaMainGene())); - panda.setHiddenGene(resolveGene(spec.pandaHiddenGene())); + panda.setMainGene(resolveGene(spec.pandaMainGene().orElse(null))); + panda.setHiddenGene(resolveGene(spec.pandaHiddenGene().orElse(null))); } if (e instanceof Villager villager) { @@ -154,9 +156,7 @@ public final class BukkitEntitySpawner { mob.setAware(spec.flags().aware()); } - if (spec.spawnEffect() != null) { - showSpawnEffect(e, spec.spawnEffect()); - } + spec.spawnEffect().ifPresent(effect -> showSpawnEffect(e, effect)); runCommands(spec, at); @@ -191,7 +191,7 @@ public final class BukkitEntitySpawner { private static void applyFlags(Entity e, EntitySpec spec) { EntitySpec.Flags flags = spec.flags(); - e.setCustomName(spec.customName() != null ? C.translateAlternateColorCodes('&', spec.customName()) : null); + e.setCustomName(spec.customName().map(name -> C.translateAlternateColorCodes('&', name)).orElse(null)); e.setCustomNameVisible(flags.customNameVisible()); e.setGlowing(flags.glowing()); e.setGravity(flags.gravity()); @@ -219,31 +219,17 @@ public final class BukkitEntitySpawner { l.setAI(spec.flags().ai()); l.setCanPickupItems(spec.flags().pickupItems()); - if (spec.leashHolder() != null) { - l.setLeashHolder(spawn(gen, spec.leashHolder(), at)); - } + spec.leashHolder().ifPresent(holder -> l.setLeashHolder(spawn(gen, holder, at))); l.setRemoveWhenFarAway(spec.flags().removable()); EntitySpec.Equipment equipment = spec.equipment(); - if (equipment.helmet() != null) { - l.getEquipment().setHelmet(BukkitItemStacks.create(equipment.helmet())); - } - if (equipment.chestplate() != null) { - l.getEquipment().setChestplate(BukkitItemStacks.create(equipment.chestplate())); - } - if (equipment.leggings() != null) { - l.getEquipment().setLeggings(BukkitItemStacks.create(equipment.leggings())); - } - if (equipment.boots() != null) { - l.getEquipment().setBoots(BukkitItemStacks.create(equipment.boots())); - } - if (equipment.mainHand() != null) { - l.getEquipment().setItemInMainHand(BukkitItemStacks.create(equipment.mainHand())); - } - if (equipment.offHand() != null) { - l.getEquipment().setItemInOffHand(BukkitItemStacks.create(equipment.offHand())); - } + equipment.helmet().ifPresent(item -> l.getEquipment().setHelmet(BukkitItemStacks.create(item))); + equipment.chestplate().ifPresent(item -> l.getEquipment().setChestplate(BukkitItemStacks.create(item))); + equipment.leggings().ifPresent(item -> l.getEquipment().setLeggings(BukkitItemStacks.create(item))); + equipment.boots().ifPresent(item -> l.getEquipment().setBoots(BukkitItemStacks.create(item))); + equipment.mainHand().ifPresent(item -> l.getEquipment().setItemInMainHand(BukkitItemStacks.create(item))); + equipment.offHand().ifPresent(item -> l.getEquipment().setItemInOffHand(BukkitItemStacks.create(item))); } private static void runCommands(EntitySpec spec, Location at) { @@ -338,7 +324,7 @@ public final class BukkitEntitySpawner { } if (spec.isSpecial()) { - return IrisServices.get(ExternalDataSVC.class).spawnMob(at, Identifier.fromString(spec.specialType())); + return IrisServices.get(ExternalDataSVC.class).spawnMob(at, Identifier.fromString(spec.specialType().orElseThrow())); } return BukkitPlatform.spawnEntity(at, bukkitType(spec), bukkitReason(spec)); @@ -346,11 +332,12 @@ public final class BukkitEntitySpawner { /** The platform's entity type of the spec, unknown when it names none. */ public static EntityType bukkitType(EntitySpec spec) { - if (spec.type().isBlank()) { + String type = spec.type().orElse(""); + if (type.isBlank()) { return EntityType.UNKNOWN; } - NamespacedKey key = NamespacedKey.fromString(spec.type().trim().toLowerCase(Locale.ROOT)); + NamespacedKey key = NamespacedKey.fromString(type.trim().toLowerCase(Locale.ROOT)); if (key == null) { return EntityType.UNKNOWN; } @@ -360,12 +347,13 @@ public final class BukkitEntitySpawner { } private static CreatureSpawnEvent.SpawnReason bukkitReason(EntitySpec spec) { - if (spec.reason() == null || spec.reason().isBlank()) { + String reason = spec.reason().orElse(""); + if (reason.isBlank()) { return CreatureSpawnEvent.SpawnReason.NATURAL; } try { - return CreatureSpawnEvent.SpawnReason.valueOf(spec.reason().trim().toUpperCase(Locale.ROOT)); + return CreatureSpawnEvent.SpawnReason.valueOf(reason.trim().toUpperCase(Locale.ROOT)); } catch (IllegalArgumentException e) { return CreatureSpawnEvent.SpawnReason.NATURAL; } @@ -385,8 +373,8 @@ public final class BukkitEntitySpawner { private static void showSpawnEffect(Entity p, EntitySpec.SpawnEffect fx) { J.runEntity(p, () -> { - Sound soundType = fx.sound() == null ? null : resolveKeyed(Sound.class, fx.sound()); - Particle particleType = fx.particle() == null ? null : resolveKeyed(Particle.class, fx.particle()); + 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())); @@ -424,10 +412,10 @@ public final class BukkitEntitySpawner { @Override public Collection populateLoot(Random random, LootContext context) { BlockPosition position = new BlockPosition(finalAt.getBlockX(), finalAt.getBlockY() - gen.getMinHeight(), finalAt.getBlockZ()); - Loot.Site site = new Loot.Site(position, null, false, gen.isStudio()); + Loot.Site site = new Loot.Site(position, Optional.empty(), false, gen.isStudio()); KList items = new KList<>(); - for (String table : spec.lootTables()) { + for (ResourceId table : spec.lootTables()) { items.addAll(BukkitItemStacks.createAll(ModuleServices.lootItems(gen, site, table))); } diff --git a/core/src/main/java/art/arcane/iris/engine/platform/EngineBukkitOps.java b/core/src/main/java/art/arcane/iris/engine/platform/EngineBukkitOps.java index 47de91f2b..b0c47701e 100644 --- a/core/src/main/java/art/arcane/iris/engine/platform/EngineBukkitOps.java +++ b/core/src/main/java/art/arcane/iris/engine/platform/EngineBukkitOps.java @@ -82,6 +82,7 @@ import org.bukkit.loot.Lootable; import java.lang.reflect.Method; import java.util.List; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; @@ -420,9 +421,9 @@ public final class EngineBukkitOps { private static Loot.Site lootSite(Engine engine, Block b, boolean nativeLootDefined) { BlockPosition position = new BlockPosition(b.getX(), b.getY() - engine.getMinHeight(), b.getZ()); BlockData data = b.getBlockData(); - com.volmit.block.BlockState container = BukkitBlockResolution.isStorageChest(data) - ? com.volmit.block.BlockState.parse(PlatformBlockStates.namespaced(BukkitBlockState.of(data).key())) - : null; + Optional container = BukkitBlockResolution.isStorageChest(data) + ? Optional.of(com.volmit.block.BlockState.parse(PlatformBlockStates.namespaced(BukkitBlockState.of(data).key()))) + : Optional.empty(); return new Loot.Site(position, container, nativeLootDefined, false); } @@ -473,11 +474,11 @@ public final class EngineBukkitOps { /** The items of {@code tables} at the spot, in the tables' order: the modules' for pack tables, the platform's own for platform tables. */ private static List lootItems(Engine engine, boolean debug, List tables, World world, int x, int y, int z) { - Loot.Site site = new Loot.Site(new BlockPosition(x, y - engine.getMinHeight(), z), null, false, debug); + Loot.Site site = new Loot.Site(new BlockPosition(x, y - engine.getMinHeight(), z), Optional.empty(), false, debug); List items = new KList<>(); for (Loot.Source source : tables) { switch (source) { - case Loot.Table table -> items.addAll(BukkitItemStacks.createAll(ModuleServices.lootItems(engine, site, table.key()))); + case Loot.Table table -> items.addAll(BukkitItemStacks.createAll(ModuleServices.lootItems(engine, site, table.id()))); case Loot.PlatformTable table -> items.addAll(platformLoot(table, world, x, y, z)); } } diff --git a/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitAmbientEffects.java b/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitAmbientEffects.java index c791f1e0c..17526a636 100644 --- a/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitAmbientEffects.java +++ b/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitAmbientEffects.java @@ -54,16 +54,10 @@ public final class BukkitAmbientEffects { } private static void playOnEntityThread(Player player, Engine engine, AmbientEffects.Effect effect) { - if (effect.sound() != null) { - playSound(player, effect.sound()); - } - if (effect.particles() != null) { - showParticles(player, engine, effect.particles()); - } + effect.sound().ifPresent(sound -> playSound(player, sound)); + effect.particles().ifPresent(particles -> showParticles(player, engine, particles)); effect.commands().forEach(command -> runCommand(player, command)); - if (effect.potion() != null) { - givePotion(player, effect.potion()); - } + effect.potion().ifPresent(potion -> givePotion(player, potion)); } private static void playSound(Player player, AmbientEffects.Sound sound) { diff --git a/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitItemStacks.java b/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitItemStacks.java index 39331c6de..18242d131 100644 --- a/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitItemStacks.java +++ b/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitItemStacks.java @@ -114,19 +114,19 @@ public final class BukkitItemStacks { meta.setUnbreakable(drop.unbreakable()); flags(drop).forEach(meta::addItemFlags); - if (drop.customModel() != null) { + if (drop.customModel().isPresent()) { CustomModelDataComponent customModelData = meta.getCustomModelDataComponent(); - customModelData.setFloats(List.of(drop.customModel().floatValue())); + customModelData.setFloats(List.of((float) drop.customModel().getAsInt())); meta.setCustomModelDataComponent(customModelData); } int maxDurability = stack.getType().getMaxDurability(); - if (drop.damage() != null && maxDurability > 0 && meta instanceof Damageable damageable) { - damageable.setDamage((int) Math.round(Math.max(0, Math.min(maxDurability, drop.damage() * maxDurability)))); + if (drop.damage().isPresent() && maxDurability > 0 && meta instanceof Damageable damageable) { + damageable.setDamage((int) Math.round(Math.max(0, Math.min(maxDurability, drop.damage().getAsDouble() * maxDurability)))); } - if (drop.leatherColor() != null && meta instanceof LeatherArmorMeta leather) { - Color c = Color.decode(drop.leatherColor()); + 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())); } @@ -135,9 +135,7 @@ public final class BukkitItemStacks { colorable.setColor(dye); } - if (drop.displayName() != null) { - meta.setDisplayName(C.translateAlternateColorCodes('&', drop.displayName())); - } + drop.displayName().ifPresent(name -> meta.setDisplayName(C.translateAlternateColorCodes('&', name))); meta.setLore(lore(drop)); return meta; @@ -185,11 +183,11 @@ public final class BukkitItemStacks { } private static DyeColor dyeColor(ItemDrop drop) { - if (drop.dyeColor() == null) { + if (drop.dyeColor().isEmpty()) { return null; } try { - return DyeColor.valueOf(drop.dyeColor()); + return DyeColor.valueOf(drop.dyeColor().get()); } catch (IllegalArgumentException e) { return null; } @@ -207,9 +205,7 @@ public final class BukkitItemStacks { lore.add(colored); } } - if (drop.source() != null) { - addSourceLore(lore, drop.source()); - } + drop.source().ifPresent(source -> addSourceLore(lore, source)); return lore; } @@ -217,12 +213,12 @@ public final class BukkitItemStacks { if (lore.isNotEmpty()) { lore.add(LORE_RULE); } - if (source.table() == null) { + if (source.table().isEmpty()) { lore.add(C.GRAY + "1 in " + source.entryRarity() + " Chance (" + Form.pc(1D / source.entryRarity(), CHANCE_DIGITS) + ")"); return; } long combined = (long) source.tableRarity() * source.entryRarity(); - lore.add(C.GRAY + "From: " + source.table() + " (" + Form.pc(1D / source.tableRarity(), CHANCE_DIGITS) + ")"); + lore.add(C.GRAY + "From: " + source.table().get() + " (" + Form.pc(1D / source.tableRarity(), CHANCE_DIGITS) + ")"); lore.add(C.GRAY + "1 in " + combined + " Chance (" + Form.pc(1D / combined, CHANCE_DIGITS) + ")"); } } diff --git a/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/EntityKeyHandler.java b/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/EntityKeyHandler.java index 99a8421f9..b7b76a317 100644 --- a/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/EntityKeyHandler.java +++ b/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/EntityKeyHandler.java @@ -21,7 +21,7 @@ package art.arcane.iris.util.common.director.specialhandlers; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.modules.PackModulesException; import art.arcane.iris.core.pack.PackDirectoryResolver; -import art.arcane.iris.builtin.spawn.EntityDefinition; +import art.arcane.iris.engine.spawn.SpawnResources; import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.util.common.director.DirectorParameterHandler; import art.arcane.volmlib.util.collection.KList; @@ -70,7 +70,7 @@ public final class EntityKeyHandler implements DirectorParameterHandler /** A pack whose modules fail to load has no entities to offer; its failure was reported when it loaded. */ private static void addEntityKeys(Set keys, IrisData data) { try { - data.getPackResources().ids(EntityDefinition.class).forEach(id -> keys.add(id.path())); + data.getPackResources().ids(SpawnResources.ENTITIES).forEach(id -> keys.add(id.path())); } catch (PackModulesException ignored) { } } diff --git a/core/src/test/java/art/arcane/iris/core/modules/BuiltInModulesJarServicesTest.java b/core/src/test/java/art/arcane/iris/core/modules/BuiltInModulesJarServicesTest.java index a4a1d1039..ee4ec3d29 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/BuiltInModulesJarServicesTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/BuiltInModulesJarServicesTest.java @@ -50,6 +50,7 @@ import org.junit.rules.TemporaryFolder; import java.io.IOException; import java.nio.file.Path; import java.util.List; +import java.util.Optional; import java.util.OptionalInt; import static org.junit.Assert.assertEquals; @@ -133,9 +134,9 @@ public class BuiltInModulesJarServicesTest { try (LoadedPack loaded = load()) { Loot loot = loaded.catalog().services(Loot.class).getFirst(); - List tables = loot.tables(world, new Loot.Site(AT, null, false, false)); + List tables = loot.tables(world, new Loot.Site(AT, Optional.empty(), false, false)); - assertEquals(List.of(new Loot.Table("dungeon/chest")), tables); + assertEquals(List.of(new Loot.Table(world.resources().idOf("dungeon/chest"))), tables); } } diff --git a/core/src/test/java/art/arcane/iris/core/modules/CarveSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/CarveSettingsDecodingTest.java index d96a8a7ac..ba43f044d 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/CarveSettingsDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/CarveSettingsDecodingTest.java @@ -186,8 +186,9 @@ public class CarveSettingsDecodingTest { ModuleSettings settings = decoder.decode(Level.BIOME, new JSONObject("{\"carvingBiome\": \"carving/mushroom\"}"), "biome test"); assertEquals("carving/mushroom", settings.find(CarvingBiomeSettings.class).orElseThrow().biome()); - assertEquals(Set.of("carving/mushroom"), settings.treeBiomes()); - assertEquals(Set.of(), settings.usedBiomes(ModuleSettings.NONE)); + IrisPackResources resources = PackResourceFixture.empty(packFolder.toFile()); + assertEquals(Set.of("carving/mushroom"), settings.treeBiomes(resources)); + assertEquals(Set.of(), settings.usedBiomes(resources, ModuleSettings.NONE)); } @Test diff --git a/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java b/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java index f8b6130ee..63ec5a646 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java +++ b/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java @@ -19,6 +19,7 @@ package art.arcane.iris.core.modules; import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.ResourceLoader; import art.arcane.iris.engine.object.material.IrisBlockData; @@ -40,7 +41,7 @@ import com.volmit.item.ItemRegistry; import com.volmit.noise.NoiseFactory; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; -import com.volmit.resource.ResourceKey; +import com.volmit.resource.ResourceKind; import com.volmit.world.PackBiome; import com.volmit.world.PackWorld; import com.volmit.object.BlockEntityData; @@ -62,7 +63,7 @@ import static org.mockito.Mockito.when; * own noise over an empty pack, a few blocks by name and the world's seeds, all in memory, so the module is tested through IrisApi alone. * Biomes and regions have the ids {@code test:}; a declaration made for {@code } has the source {@code test:/}. */ -public final class CarveTestWorld implements PackWorld, IrisSeed.Source { +public final class CarveTestWorld implements PackWorld { public static final String NAMESPACE = "test"; public static final int MIN_HEIGHT = -64; private static final Set AIRS = Set.of("minecraft:air", "minecraft:cave_air", "minecraft:void_air"); @@ -149,13 +150,9 @@ public final class CarveTestWorld implements PackWorld, IrisSeed.Source { } @Override - public PackWorld withLog(ModuleLog log) { - return this; - } - - @Override - public long seed(IrisSeed seed) { - return seed == IrisSeed.CARVE ? carveSeed : carveSeed + seed.ordinal(); + public Optional extension(Class type) { + IrisSeeds seeds = seed -> seed == IrisSeed.CARVE ? carveSeed : carveSeed + seed.ordinal(); + return type == IrisSeeds.class ? Optional.of(type.cast(seeds)) : Optional.empty(); } @SuppressWarnings("unchecked") @@ -196,17 +193,16 @@ public final class CarveTestWorld implements PackWorld, IrisSeed.Source { } @Override - @SuppressWarnings("unchecked") - public Optional find(ResourceKey key) { - if (key.type() != PackBiome.class) { + public Optional find(ResourceKind kind, ResourceId id) { + if (!kind.equals(BIOMES)) { return Optional.empty(); } - return Optional.ofNullable((T) biomes.get(key.id())); + return Optional.ofNullable(kind.type().cast(biomes.get(id))); } @Override - public List ids(Class type) { - return type == PackBiome.class ? biomes.keySet().stream().sorted().toList() : List.of(); + public List ids(ResourceKind kind) { + return kind.equals(BIOMES) ? biomes.keySet().stream().sorted().toList() : List.of(); } } diff --git a/core/src/test/java/art/arcane/iris/core/modules/DimensionBottomTest.java b/core/src/test/java/art/arcane/iris/core/modules/DimensionBottomTest.java index d6f1b711e..646ddbec5 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/DimensionBottomTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/DimensionBottomTest.java @@ -124,7 +124,7 @@ public class DimensionBottomTest { graph.define(Stage.placement("test:bottom/placement")).run(context -> { record(context.terrain()); viewBounds.add(context.access().bounds()); - ObjectPlacement.current().anchoredAt(BOTTOM); + context.extension(ObjectPlacement.class).orElseThrow().anchoredAt(BOTTOM); context.access().set(new PlacedBlock(new BlockPosition(0, BOTTOM, 0), STONE, Optional.empty())); context.access().mantle().layer(MARKS).set(0, BOTTOM, 0, "bottom"); }); @@ -187,7 +187,7 @@ public class DimensionBottomTest { public void aMantleStageWritingAtHeightZeroHitsTheBottomOfTheMantle() { ModuleMantleComponent.forPack(engine, pack, Set.of()).stream() .filter(component -> component.stage().stage().id().toString().equals("test:bottom/mantle")) - .forEach(component -> component.generate(0, 0, storage::chunk)); + .forEach(component -> component.generate(0, 0, storage::chunk, new IrisMantleChunk(engine, null, 0, 0, null))); assertEquals("bottom", storage.value(MARKS, TEXT, 0, BOTTOM, 0)); assertSamplesAndBoundsAgree(); diff --git a/core/src/test/java/art/arcane/iris/core/modules/FloatingSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/FloatingSettingsDecodingTest.java index c3f27d9ef..4c1f323c9 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/FloatingSettingsDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/FloatingSettingsDecodingTest.java @@ -120,10 +120,11 @@ public class FloatingSettingsDecodingTest { ModuleSettings biomeSettings = decoder.decode(Level.BIOME, biome, "biome magnetics/plains"); ModuleSettings dimensionSettings = decoder.decode(Level.DIMENSION, file("dimensions/overworld.json"), "dimension overworld"); - Set used = biomeSettings.usedBiomes(dimensionSettings); + IrisPackResources resources = PackResourceFixture.empty(packFolder.toFile()); + Set used = biomeSettings.usedBiomes(resources, dimensionSettings); assertEquals(new LinkedHashSet<>(List.of("mushroom/forest", "carving/mushroom", "tropical/wilds", "carving/lush-child")), used); - assertEquals(Set.of(), biomeSettings.treeBiomes()); + assertEquals(Set.of(), biomeSettings.treeBiomes(resources)); } @Test @@ -133,9 +134,10 @@ public class FloatingSettingsDecodingTest { ModuleSettings biomeSettings = BuiltInPack.settings(new FloatingChildSettings(List.of(child))); ModuleSettings dimensionSettings = BuiltInPack.settings(new CarvingSettings(List.of(band))); - assertEquals(new LinkedHashSet<>(List.of("floating/target", "carving/deep")), biomeSettings.usedBiomes(dimensionSettings)); + IrisPackResources resources = PackResourceFixture.empty(packFolder.toFile()); + assertEquals(new LinkedHashSet<>(List.of("floating/target", "carving/deep")), biomeSettings.usedBiomes(resources, dimensionSettings)); assertEquals("without bands the name is taken as a biome key", new LinkedHashSet<>(List.of("floating/target", "deep")), - biomeSettings.usedBiomes(ModuleSettings.NONE)); + biomeSettings.usedBiomes(resources, ModuleSettings.NONE)); } @Test diff --git a/core/src/test/java/art/arcane/iris/core/modules/IrisLiveWorldTest.java b/core/src/test/java/art/arcane/iris/core/modules/IrisLiveWorldTest.java index ce9cef4cc..b982974db 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/IrisLiveWorldTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/IrisLiveWorldTest.java @@ -86,7 +86,7 @@ public class IrisLiveWorldTest { ModuleResourceFixture.serve(data); when(engine.getData()).thenReturn(data); when(engine.getMinHeight()).thenReturn(BOTTOM); - live = LiveWorld.of(new EngineGeneration(engine).world()); + live = new EngineGeneration(engine).world().extension(LiveWorld.class).orElseThrow(); } @Test diff --git a/core/src/test/java/art/arcane/iris/core/modules/IrisModuleMantleTest.java b/core/src/test/java/art/arcane/iris/core/modules/IrisModuleMantleTest.java index 54c8ae34e..1c41eb4cc 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/IrisModuleMantleTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/IrisModuleMantleTest.java @@ -118,11 +118,20 @@ public class IrisModuleMantleTest { @Test public void theMatterSideGivesTheMantleChunksTheInvocationReachesAndNoOthers() { IrisModuleMantle mantle = mantle(new BlockBox(0, 0, 0, 16, HEIGHT, 16)); - MatterMantle matter = MatterMantle.of(mantle); + MatterMantle matter = mantle; org.junit.Assert.assertSame(chunk(3, 4), matter.chunk(3, 4)); org.junit.Assert.assertNull("nothing is loaded that the host did not say is", matter.loadedChunk(3, 4)); - org.junit.Assert.assertThrows(IllegalArgumentException.class, () -> MatterMantle.of(new InMemoryOnly())); + } + + @Test + public void aChunkInvocationsMatterHoldsItsOwnChunkAndReadsNeighboursOnlyWhenLoaded() { + IrisModuleMantle mantle = mantle(new BlockBox(-16, 0, -16, 48, HEIGHT, 48)); + MatterMantle own = new OwnChunkMatter(mantle, 1, 1); + + org.junit.Assert.assertSame(chunk(1, 1), own.chunk(1, 1)); + org.junit.Assert.assertNull("a neighbour is no chunk of the invocation's own", own.chunk(2, 1)); + org.junit.Assert.assertNull("a neighbour the world does not hold is not read", own.loadedChunk(2, 1)); } @Test @@ -299,7 +308,8 @@ public class IrisModuleMantleTest { try (LoadedPack pack = LoadedPack.load(folder.newFolder("pack").toPath(), ModuleHost.of(List.of(veins)).copyingJarsTo(folder.newFolder("copies").toPath()))) { - ModuleMantleComponent.forPack(engine, pack, Set.of()).getFirst().generate(0, 0, this::chunk); + ModuleMantleComponent.forPack(engine, pack, Set.of()).getFirst().generate(0, 0, this::chunk, + new IrisMantleChunk(engine, null, 0, 0, null)); BlockBox neighborBounds = new BlockBox(16, 0, 0, 32, HEIGHT, 16); IrisModuleMantle neighbor = new IrisModuleMantle(neighborBounds, this::chunk, pack.catalog().mantle(), PlannedBlocks.none(neighborBounds)); @@ -317,32 +327,4 @@ public class IrisModuleMantleTest { private static DataInputStream input(byte[] bytes) { return new DataInputStream(new ByteArrayInputStream(bytes)); } - - /** A mantle that is none of Iris's. */ - private static final class InMemoryOnly implements com.volmit.mantle.Mantle { - @Override - public BlockBox bounds() { - return new BlockBox(0, 0, 0, 0, 0, 0); - } - - @Override - public MantleLayer layer(MantleKey key) { - throw new UnsupportedOperationException(); - } - - @Override - public MantleLayer blocks() { - throw new UnsupportedOperationException(); - } - - @Override - public MantleLayer caverns() { - throw new UnsupportedOperationException(); - } - - @Override - public MantleEdit edit() { - throw new UnsupportedOperationException(); - } - } } diff --git a/core/src/test/java/art/arcane/iris/core/modules/IrisPackResourcesTest.java b/core/src/test/java/art/arcane/iris/core/modules/IrisPackResourcesTest.java index abc1b5cee..f6904c2c7 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/IrisPackResourcesTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/IrisPackResourcesTest.java @@ -10,8 +10,9 @@ import com.volmit.block.BlockState; import com.volmit.mantle.BlockBox; import com.volmit.object.GeneratedObject; import com.volmit.object.ObjectBlock; +import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; -import com.volmit.resource.ResourceKey; +import com.volmit.resource.ResourceKind; import com.volmit.world.BlockPosition; import com.volmit.world.PackBiome; import com.volmit.world.PackRegion; @@ -109,21 +110,21 @@ public class IrisPackResourcesTest { @Test public void aPackObjectIsItsGeometry() { - Optional found = resources.find(new ResourceKey<>(id("trees/oak"), GeneratedObject.class)); + Optional found = resources.find(PackResources.OBJECTS, id("trees/oak")); assertSame(tree, found.orElseThrow()); } @Test public void aPackBiomeIsBuiltFromTheBiomeFile() { - PackBiome biome = resources.require(new ResourceKey<>(id("desert/dunes"), PackBiome.class)); + PackBiome biome = resources.require(PackResources.BIOMES, id("desert/dunes")); assertEquals(new PackBiome(id("desert/dunes"), "Dunes", ResourceId.parse("minecraft:desert"), 3, List.of(id("desert/oasis"))), biome); } @Test public void aPackRegionIsBuiltFromTheRegionFileWithItsFourBiomeListsAsPackIds() { - PackRegion region = resources.require(new ResourceKey<>(id("desert"), PackRegion.class)); + PackRegion region = resources.require(PackResources.REGIONS, id("desert")); assertEquals(new PackRegion(id("desert"), "The Desert", 2, List.of(id("desert/dunes")), List.of(id("ocean")), List.of(id("beach")), List.of(id("caves/dry"))), region); @@ -131,8 +132,8 @@ public class IrisPackResourcesTest { @Test public void oneIdCanBeABiomeAndARegion() { - PackBiome biome = resources.require(new ResourceKey<>(id("desert"), PackBiome.class)); - PackRegion region = resources.require(new ResourceKey<>(id("desert"), PackRegion.class)); + PackBiome biome = resources.require(PackResources.BIOMES, id("desert")); + PackRegion region = resources.require(PackResources.REGIONS, id("desert")); assertEquals("Desert biome", biome.name()); assertEquals("The Desert", region.name()); @@ -140,19 +141,27 @@ public class IrisPackResourcesTest { @Test public void anIdThePackLacksForThatKindIsAbsent() { - assertEquals(Optional.empty(), resources.find(new ResourceKey<>(id("desert/dunes"), PackRegion.class))); - assertEquals(Optional.empty(), resources.find(new ResourceKey<>(id("trees/birch"), GeneratedObject.class))); + assertEquals(Optional.empty(), resources.find(PackResources.REGIONS, id("desert/dunes"))); + assertEquals(Optional.empty(), resources.find(PackResources.OBJECTS, id("trees/birch"))); } @Test public void anIdOfAnotherNamespaceIsAbsent() { - assertEquals(Optional.empty(), resources.find(new ResourceKey<>(new ResourceId("other", "trees/oak"), GeneratedObject.class))); + assertEquals(Optional.empty(), resources.find(PackResources.OBJECTS, new ResourceId("other", "trees/oak"))); } @Test - public void aTypeIrisDoesNotServeIsRejectedWhetherOrNotTheIdExists() { - assertThrows(IllegalArgumentException.class, () -> resources.find(new ResourceKey<>(id("trees/oak"), String.class))); - assertThrows(IllegalArgumentException.class, () -> resources.find(new ResourceKey<>(id("missing"), String.class))); + public void aKindIrisDoesNotServeIsRejectedWhetherOrNotTheIdExists() { + ResourceKind unserved = ResourceKind.of("test:unserved", "unserved", GeneratedObject.class); + + assertThrows(IllegalArgumentException.class, () -> resources.find(unserved, id("trees/oak"))); + assertThrows(IllegalArgumentException.class, () -> resources.find(unserved, id("missing"))); + } + + @Test + public void theIdsOfAKindAreThePacksKeysOfThatKindInIdOrder() { + assertEquals(List.of(id("desert"), id("desert/dunes")), resources.ids(PackResources.BIOMES)); + assertEquals(List.of(id("trees/oak")), resources.ids(PackResources.OBJECTS)); } @Test @@ -160,15 +169,13 @@ public class IrisPackResourcesTest { when(objectLoader.getPossibleKeys()).thenReturn(new String[]{"trees/broken"}); IrisPackResources fresh = new IrisPackResources(data, List::of); - assertThrows(IllegalStateException.class, () -> fresh.find(new ResourceKey<>(id("trees/broken"), GeneratedObject.class))); + assertThrows(IllegalStateException.class, () -> fresh.find(PackResources.OBJECTS, id("trees/broken"))); } @Test public void eachResourceIsBuiltOncePerSnapshot() { - ResourceKey key = new ResourceKey<>(id("desert/dunes"), PackBiome.class); - - PackBiome first = resources.require(key); - PackBiome second = resources.require(key); + PackBiome first = resources.require(PackResources.BIOMES, id("desert/dunes")); + PackBiome second = resources.require(PackResources.BIOMES, id("desert/dunes")); assertSame(first, second); verify(biomeLoader, times(1)).load("desert/dunes"); @@ -182,6 +189,6 @@ public class IrisPackResourcesTest { when(objectLoader.load("Trees/Oak")).thenReturn(object); IrisPackResources fresh = new IrisPackResources(data, List::of); - assertSame(tree, fresh.require(new ResourceKey<>(id("trees/oak"), GeneratedObject.class))); + assertSame(tree, fresh.require(PackResources.OBJECTS, id("trees/oak"))); } } diff --git a/core/src/test/java/art/arcane/iris/core/modules/IrisValuesTest.java b/core/src/test/java/art/arcane/iris/core/modules/IrisValuesTest.java index f0a628222..153d18d84 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/IrisValuesTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/IrisValuesTest.java @@ -19,7 +19,7 @@ import com.volmit.block.BlockSpec; import com.volmit.block.BlockState; import com.volmit.block.PaletteSampler; import com.volmit.block.PaletteSpec; -import com.volmit.config.OptionsMetadata; +import com.volmit.host.OptionsMetadata; import com.volmit.noise.NoiseSampler; import com.volmit.noise.NoiseStyle; import com.volmit.object.BlockEntityData; diff --git a/core/src/test/java/art/arcane/iris/core/modules/IrisWorldFacadesTest.java b/core/src/test/java/art/arcane/iris/core/modules/IrisWorldFacadesTest.java index 70c63d7ca..de0d74a35 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/IrisWorldFacadesTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/IrisWorldFacadesTest.java @@ -19,6 +19,7 @@ package art.arcane.iris.core.modules; import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.SeedManager; @@ -30,7 +31,6 @@ import java.util.EnumMap; import java.util.Map; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -60,15 +60,10 @@ public class IrisWorldFacadesTest { } for (IrisSeed seed : IrisSeed.values()) { - assertEquals(seed.name(), expected.get(seed).longValue(), seed.of(world)); + assertEquals(seed.name(), expected.get(seed).longValue(), world.extension(IrisSeeds.class).orElseThrow().seed(seed)); } } - @Test - public void aWorldIrisDoesNotGenerateHasNoIrisSeeds() { - assertThrows(IllegalArgumentException.class, () -> IrisSeed.POST.of(mock(PackWorld.class))); - } - private static Engine engine(IrisDimension dimension) { Engine engine = mock(Engine.class); when(engine.getData()).thenReturn(mock(IrisData.class)); diff --git a/core/src/test/java/art/arcane/iris/core/modules/ModuleLogTest.java b/core/src/test/java/art/arcane/iris/core/modules/ModuleLogTest.java index 8990b6d8e..294363b81 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/ModuleLogTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/ModuleLogTest.java @@ -19,6 +19,7 @@ package art.arcane.iris.core.modules; import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.iris.core.IrisSettings; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.Engine; @@ -131,24 +132,18 @@ public class ModuleLogTest { } @Test - public void aWorldViewCarriesTheModulesLogAndSharesTheWorldsState() { + public void theWorldOffersIrissOwnCodeTheEngineAndItsSeedsAsExtensions() { Engine engine = mock(Engine.class); when(engine.getData()).thenReturn(mock(IrisData.class)); when(engine.getDimension()).thenReturn(new IrisDimension()); SeedManager seeds = mock(SeedManager.class); when(seeds.getPost()).thenReturn(POST_SEED); when(engine.getSeedManager()).thenReturn(seeds); - IrisPackWorld world = new IrisPackWorld(engine); - ModuleLog decorant = log(); + PackWorld world = new IrisPackWorld(engine); - PackWorld view = world.withLog(decorant); - - assertSame(decorant, view.log()); - assertSame("one view per module", view, world.withLog(decorant)); - assertSame(view, view.withLog(decorant)); - assertSame("state is the world's", world.state(Marker.class, ignored -> new Marker()), view.state(Marker.class, ignored -> new Marker())); - assertSame("Iris's own code still reaches the engine through a view", engine, IrisPackWorld.of(view).engine()); - assertEquals("and its seeds", POST_SEED, IrisSeed.POST.of(view)); + assertSame(engine, world.extension(Engine.class).orElseThrow()); + assertEquals(POST_SEED, world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.POST)); + assertTrue("nothing else is offered", world.extension(String.class).isEmpty()); } @Test @@ -172,7 +167,4 @@ public class ModuleLogTest { private String err() { return err.toString(StandardCharsets.UTF_8); } - - private static final class Marker { - } } diff --git a/core/src/test/java/art/arcane/iris/core/modules/ModuleResourceFixture.java b/core/src/test/java/art/arcane/iris/core/modules/ModuleResourceFixture.java index 73774707c..2d4e574f1 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/ModuleResourceFixture.java +++ b/core/src/test/java/art/arcane/iris/core/modules/ModuleResourceFixture.java @@ -20,6 +20,7 @@ import java.util.Locale; import java.util.Map; import java.util.Optional; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -34,7 +35,7 @@ public final class ModuleResourceFixture { private static final Map SERVED = new IdentityHashMap<>(); private final IrisPackResources resources; - private final Map, List> ids = new HashMap<>(); + private final Map, List> ids = new HashMap<>(); private ModuleResourceFixture(IrisPackResources resources) { this.resources = resources; @@ -45,6 +46,8 @@ public final class ModuleResourceFixture { IrisPackResources resources = mock(IrisPackResources.class); when(data.getPackResources()).thenReturn(resources); when(resources.idOf(anyString())).thenAnswer(invocation -> idOf(invocation.getArgument(0))); + when(resources.keyOf(any(ResourceId.class))).thenAnswer(invocation -> keyOf(invocation.getArgument(0))); + when(resources.keyOf(any(ResourceKind.class), any(ResourceId.class))).thenAnswer(invocation -> keyOf(invocation.getArgument(1))); ModuleResourceFixture fixture = new ModuleResourceFixture(resources); SERVED.put(resources, fixture); return fixture; @@ -82,14 +85,18 @@ public final class ModuleResourceFixture { /** Serves {@code resource} as the resource of {@code kind} the pack names by {@code key}. */ public ModuleResourceFixture resource(ResourceKind kind, String key, T resource) { ResourceId id = idOf(key); - when(resources.find(kind.key(id))).thenReturn(Optional.of(resource)); - List kindIds = ids.computeIfAbsent(kind.type(), ignored -> new ArrayList<>()); + when(resources.find(kind, id)).thenReturn(Optional.of(resource)); + List kindIds = ids.computeIfAbsent(kind, ignored -> new ArrayList<>()); kindIds.add(id); - when(resources.ids(kind.type())).thenReturn(kindIds.stream().sorted().toList()); + when(resources.ids(kind)).thenReturn(kindIds.stream().sorted().toList()); return this; } private static ResourceId idOf(String key) { return new ResourceId(NAMESPACE, key.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9_./-]", "_")); } + + private static String keyOf(ResourceId id) { + return id.namespace().equals(NAMESPACE) ? id.path() : id.toString(); + } } diff --git a/core/src/test/java/art/arcane/iris/core/modules/ModuleServicesTest.java b/core/src/test/java/art/arcane/iris/core/modules/ModuleServicesTest.java index a6e120062..0bd01380f 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/ModuleServicesTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/ModuleServicesTest.java @@ -29,6 +29,7 @@ import com.volmit.ModuleSetup; import com.volmit.host.LoadedPack; import com.volmit.host.ModuleHost; import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import com.volmit.service.LocateResult; import com.volmit.service.ObjectsAt; import com.volmit.service.StructureLocator; @@ -88,30 +89,30 @@ public class ModuleServicesTest { var registry = setup.registry(); registry.registerService(ObjectsAt.class, new ObjectsAt() { @Override - public Set objectsAt(PackWorld world, int chunkX, int chunkZ) { + public Set objectsAt(PackWorld world, int chunkX, int chunkZ) { logOwners.add(id + (world.log() == registeredLog ? " has its own log" : " has another module's log")); - return Set.of(object + "@" + chunkX + "," + chunkZ); + return Set.of(world.resources().idOf(object + "/" + chunkX + "/" + chunkZ)); } @Override - public PlacedBy placedBy(PackWorld world, String objectKey) { - return new PlacedBy(Set.of(object + "-biome"), Set.of(id + "-region")); + public PlacedBy placedBy(PackWorld world, ResourceId placedObject) { + return new PlacedBy(Set.of(world.resources().idOf(object + "-biome")), Set.of(world.resources().idOf(id.replace(':', '-') + "-region"))); } }); registry.registerService(StructureLocator.class, new StructureLocator() { @Override - public Set structures(PackResources resources) { - return Set.of(structure, structure + "/unplaced"); + public Set structures(PackResources resources) { + return Set.of(resources.idOf(structure), resources.idOf(structure + "/unplaced")); } @Override - public Set locatable(PackWorld world) { - return Set.of(structure); + public Set locatable(PackWorld world) { + return Set.of(world.resources().idOf(structure)); } @Override - public LocateResult locate(PackWorld world, String key, int fromX, int fromZ, int maxRadiusChunks) { - searches.add(id + " " + key + " " + fromX + " " + fromZ + " " + maxRadiusChunks); + public LocateResult locate(PackWorld world, ResourceId located, int fromX, int fromZ, int maxRadiusChunks) { + searches.add(id + " " + located.path() + " " + fromX + " " + fromZ + " " + maxRadiusChunks); return LocateResult.found(new BlockPosition(fromX + 16, 70, fromZ)); } }); @@ -130,6 +131,7 @@ public class ModuleServicesTest { when(modules.pack()).thenReturn(pack); when(data.getModules()).thenReturn(modules); when(data.getDataFolder()).thenReturn(folder.getRoot()); + PackResourceFixture.holdNoObjectsBiomesOrRegions(data); IrisPackResources resources = new IrisPackResources(data, List::of); when(data.getPackResources()).thenReturn(resources); engine = mock(Engine.class); @@ -148,7 +150,7 @@ public class ModuleServicesTest { @Test public void objectsAtCombinesEveryModulesObjectsInModuleOrder() { - assertEquals(List.of("tree@3,-4", "bush@3,-4", "rock@3,-4"), List.copyOf(ModuleServices.objectsAt(engine, 3, -4))); + assertEquals(List.of("tree/3/-4", "bush/3/-4", "rock/3/-4"),List.copyOf(ModuleServices.objectsAt(engine, 3, -4))); } @Test @@ -160,10 +162,10 @@ public class ModuleServicesTest { @Test public void objectPlacersCombineTheBiomesAndRegionsOfEveryModule() { - ObjectsAt.PlacedBy placers = ModuleServices.objectPlacers(engine, "trees/oak"); + ModuleServices.ObjectPlacers placers = ModuleServices.objectPlacers(engine, "trees/oak"); assertEquals(Set.of("rock-biome", "tree-biome", "bush-biome"), placers.biomes()); - assertEquals(Set.of("test:zeta-region", "test:alpha-region", "test:beta-region"), placers.regions()); + assertEquals(Set.of("test-zeta-region", "test-alpha-region", "test-beta-region"), placers.regions()); } @Test @@ -181,7 +183,7 @@ public class ModuleServicesTest { ModuleServices.StructureSearch result = ModuleServices.locateStructure(engine, "Castle", 100, -200, 64); assertEquals(new ModuleServices.StructureSearch(ModuleServices.StructureSearch.Outcome.FOUND, 116, 70 - 64, -200), result); - assertEquals(List.of("test:beta Castle 100 -200 64"), searches); + assertEquals("the key is read as the pack's lower-case id", List.of("test:beta castle 100 -200 64"), searches); } @Test diff --git a/core/src/test/java/art/arcane/iris/core/modules/ModuleWorldsTest.java b/core/src/test/java/art/arcane/iris/core/modules/ModuleWorldsTest.java index 625d71357..90b355150 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/ModuleWorldsTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/ModuleWorldsTest.java @@ -153,7 +153,7 @@ public class ModuleWorldsTest { assertEquals(List.of("loaded", "started"), calls); assertEquals(SEED, world.seed()); assertSame(data.getPackResources(), world.resources()); - assertSame(engine, IrisPackWorld.of(world).engine()); + assertSame(engine, world.engine()); Remembered built = world.state(Remembered.class, ignored -> new Remembered(calls)); assertSame(built, generation.state(Remembered.class, ignored -> new Remembered(calls))); } diff --git a/core/src/test/java/art/arcane/iris/core/modules/PackModuleResourceKindTest.java b/core/src/test/java/art/arcane/iris/core/modules/PackModuleResourceKindTest.java index 8b3274697..597aeddb5 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/PackModuleResourceKindTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/PackModuleResourceKindTest.java @@ -71,13 +71,13 @@ public class PackModuleResourceKindTest { public final class KeepValidator implements Validator { public void validate(ValidationContext pack) { - for (ResourceId id : pack.resources().ids(Keep.class)) { - Keep keep = pack.resources().require(CastleModule.KEEPS.key(id)); + for (ResourceId id : pack.resources().ids(CastleModule.KEEPS)) { + Keep keep = pack.resources().require(CastleModule.KEEPS, id); if (keep.towers() > 8) { pack.report(Problem.error(Subject.file("keeps/" + id.path() + ".json"), "Keep has " + keep.towers() + " towers; at most 8 fit.")); } ResourceId next = new ResourceId(id.namespace(), keep.next().isEmpty() ? id.path() : keep.next()); - if (pack.resources().find(CastleModule.KEEPS.key(next)).isEmpty()) { + if (pack.resources().find(CastleModule.KEEPS, next).isEmpty()) { pack.report(Problem.warning(Subject.resource(id), "Keep leads to missing keep " + keep.next() + ".")); } } @@ -108,7 +108,7 @@ public class PackModuleResourceKindTest { public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Test - public void aPackModulesKindIsReadFromItsFolderAndServedByType() throws Exception { + public void aPackModulesKindIsReadFromItsFolderAndServedAsThatKind() throws Exception { Path pack = castlePack("castles"); write(pack, "keeps/main.json", "{\"towers\":6,\"next\":\"towers/north\"}"); write(pack, "keeps/towers/north.json", "{}"); @@ -117,14 +117,14 @@ public class PackModuleResourceKindTest { ResourceKind keeps = keepKind(data); ResourceId main = new ResourceId("castles", "main"); - assertEquals(List.of(main, new ResourceId("castles", "towers/north")), data.getPackResources().ids(keeps.type())); - Object keep = data.getPackResources().find(keeps.key(main)).orElseThrow(); + assertEquals(List.of(main, new ResourceId("castles", "towers/north")), data.getPackResources().ids(keeps)); + Object keep = data.getPackResources().find(keeps, main).orElseThrow(); assertEquals(6, keep.getClass().getMethod("towers").invoke(keep)); assertEquals("towers/north", keep.getClass().getMethod("next").invoke(keep)); - Object north = data.getPackResources().find(keeps.key(new ResourceId("castles", "towers/north"))).orElseThrow(); + Object north = data.getPackResources().find(keeps, new ResourceId("castles", "towers/north")).orElseThrow(); assertEquals("an omitted field keeps its default", 4, north.getClass().getMethod("towers").invoke(north)); - assertSame("read once per pack load", keep, data.getPackResources().find(keeps.key(main)).orElseThrow()); - assertTrue(data.getPackResources().find(keeps.key(new ResourceId("castles", "missing"))).isEmpty()); + assertSame("read once per pack load", keep, data.getPackResources().find(keeps, main).orElseThrow()); + assertTrue(data.getPackResources().find(keeps, new ResourceId("castles", "missing")).isEmpty()); assertTrue(data.getPackResources().moduleFolderNames().containsAll(List.of("keeps", "structures"))); assertTrue(data.resourceFolderNames().contains("keeps")); } finally { @@ -140,7 +140,7 @@ public class PackModuleResourceKindTest { try { ResourceKind keeps = keepKind(data); - assertThrows(IllegalStateException.class, () -> data.getPackResources().find(keeps.key(new ResourceId("broken-castles", "main")))); + assertThrows(IllegalStateException.class, () -> data.getPackResources().find(keeps, new ResourceId("broken-castles", "main"))); } finally { data.close(); } diff --git a/core/src/test/java/art/arcane/iris/core/modules/PackResourceFixture.java b/core/src/test/java/art/arcane/iris/core/modules/PackResourceFixture.java index e6f61f012..99f9c3e23 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/PackResourceFixture.java +++ b/core/src/test/java/art/arcane/iris/core/modules/PackResourceFixture.java @@ -3,11 +3,13 @@ package art.arcane.iris.core.modules; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.ResourceLoader; 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; import com.volmit.block.BlockState; import com.volmit.mantle.BlockBox; import com.volmit.object.GeneratedObject; import com.volmit.object.ObjectBlock; -import com.volmit.resource.ResourceKey; +import com.volmit.resource.PackResources; import com.volmit.world.BlockPosition; import java.util.List; @@ -39,8 +41,31 @@ public final class PackResourceFixture { return resources; } - /** The key of the oak in the pack in {@code packFolder}. */ - public static ResourceKey oakKey(java.io.File packFolder) { - return new ResourceKey<>(new PackResourceIds(packFolder).of(OAK_KEY), GeneratedObject.class); + /** The oak {@code resources} serve, as a module finds it by its key. */ + public static GeneratedObject oak(PackResources resources) { + return resources.require(PackResources.OBJECTS, resources.idOf(OAK_KEY)); + } + + /** The resources of a pack in {@code packFolder} without objects, biomes or regions, which names its keys by id. */ + @SuppressWarnings("unchecked") + public static IrisPackResources empty(java.io.File packFolder) { + IrisData data = mock(IrisData.class); + when(data.getDataFolder()).thenReturn(packFolder); + holdNoObjectsBiomesOrRegions(data); + return new IrisPackResources(data, List::of); + } + + /** Makes {@code data} (a mock) a pack without objects, biomes or regions, so resources built over it index none. */ + @SuppressWarnings("unchecked") + public static void holdNoObjectsBiomesOrRegions(IrisData data) { + ResourceLoader objects = mock(ResourceLoader.class); + ResourceLoader biomes = mock(ResourceLoader.class); + ResourceLoader regions = mock(ResourceLoader.class); + when(objects.getPossibleKeys()).thenReturn(new String[0]); + when(biomes.getPossibleKeys()).thenReturn(new String[0]); + when(regions.getPossibleKeys()).thenReturn(new String[0]); + when(data.getObjectLoader()).thenReturn(objects); + when(data.getBiomeLoader()).thenReturn(biomes); + when(data.getRegionLoader()).thenReturn(regions); } } diff --git a/core/src/test/java/art/arcane/iris/core/modules/ToolWorldTest.java b/core/src/test/java/art/arcane/iris/core/modules/ToolWorldTest.java index 8804fa1ca..4b707c1bf 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/ToolWorldTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/ToolWorldTest.java @@ -44,17 +44,16 @@ public class ToolWorldTest { } @Test - public void everyLogViewSharesTheStateAndClosingTheWorldClosesIt() { + public void theWorldKeepsItsStateUntilItIsClosed() { PackResources resources = mock(PackResources.class); Tracked tracked; try (ToolWorld world = new ToolWorld(SEED, resources, mock(PackSettings.class))) { tracked = world.state(Tracked.class, ignored -> new Tracked()); - PackWorld view = world.withLog(mock(ModuleLog.class)); - assertSame(tracked, view.state(Tracked.class, ignored -> new Tracked())); - assertSame(resources, view.resources()); - assertEquals(SEED, view.seed()); - assertEquals(0, view.minHeight()); + assertSame(tracked, world.state(Tracked.class, ignored -> new Tracked())); + assertSame(resources, world.resources()); + assertEquals(SEED, world.seed()); + assertEquals(0, world.minHeight()); assertFalse(tracked.closed); } diff --git a/core/src/test/java/art/arcane/iris/core/service/tree/TreeDefinitionIndexTest.java b/core/src/test/java/art/arcane/iris/core/service/tree/TreeDefinitionIndexTest.java index a9bddf29c..69b40f37d 100644 --- a/core/src/test/java/art/arcane/iris/core/service/tree/TreeDefinitionIndexTest.java +++ b/core/src/test/java/art/arcane/iris/core/service/tree/TreeDefinitionIndexTest.java @@ -43,6 +43,7 @@ public class TreeDefinitionIndexTest { when(engine.getDimension()).thenReturn(dimension); IrisData data = mock(IrisData.class); when(engine.getData()).thenReturn(data); + ModuleResourceFixture.serve(data); ModuleResourceFixture.serveModules(data, new ObjectModule()); when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); when(dimension.getAllRegions(engine)).thenReturn(new KList().qadd(region)); diff --git a/core/src/test/java/art/arcane/iris/engine/decorator/BiomeDecoratorsTest.java b/core/src/test/java/art/arcane/iris/engine/decorator/BiomeDecoratorsTest.java index 52538556b..99ee762fd 100644 --- a/core/src/test/java/art/arcane/iris/engine/decorator/BiomeDecoratorsTest.java +++ b/core/src/test/java/art/arcane/iris/engine/decorator/BiomeDecoratorsTest.java @@ -1,6 +1,7 @@ package art.arcane.iris.engine.decorator; import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.iris.builtin.decorant.DecorantSettings; import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.builtin.decorant.Decorator; @@ -71,7 +72,7 @@ public class BiomeDecoratorsTest { @Test public void everyDecoratorNoiseSeedIsAFunctionOfTheWorldsDecoratorSeedItsBiomeAndItsPlace() { - long decoratorSeed = IrisSeed.DECORATOR.of(world); + long decoratorSeed = world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.DECORATOR); long first = decorators.decorators(meadow, DecorationPart.NONE)[0].seed(); long second = decorators.decorators(meadow, DecorationPart.NONE)[1].seed(); diff --git a/core/src/test/java/art/arcane/iris/engine/framework/EngineCaveBiomeTest.java b/core/src/test/java/art/arcane/iris/engine/framework/EngineCaveBiomeTest.java index e74e0ea06..3b05ef1aa 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/EngineCaveBiomeTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/EngineCaveBiomeTest.java @@ -31,6 +31,7 @@ import art.arcane.iris.util.project.stream.ProceduralStream; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleSetup; +import com.volmit.resource.ResourceId; import com.volmit.service.CaveBiomes; import com.volmit.world.PackWorld; import org.junit.Before; @@ -86,6 +87,7 @@ public class EngineCaveBiomeTest { @SuppressWarnings("unchecked") public void mockEngine() { data = mock(IrisData.class); + ModuleResourceFixture.serve(data); ResourceLoader biomes = mock(ResourceLoader.class); when(data.getBiomeLoader()).thenReturn(biomes); when(biomes.load("band/deep")).thenReturn(band); @@ -112,13 +114,13 @@ public class EngineCaveBiomeTest { private CaveBiomes caves(String overridden, int minDepth) { return new CaveBiomes() { @Override - public Optional overriddenBiome(PackWorld world, int x, int y, int z) { - return Optional.ofNullable(overridden); + public Optional overriddenBiome(PackWorld world, int x, int y, int z) { + return Optional.ofNullable(overridden).map(world.resources()::idOf); } @Override - public int minDepthBelowSurface(PackWorld world, String biomeKey) { - return biomeKey.equals("cave/lush") ? minDepth : 0; + public int minDepthBelowSurface(PackWorld world, ResourceId biome) { + return biome.equals(world.resources().idOf("cave/lush")) ? minDepth : 0; } }; } @@ -170,14 +172,14 @@ public class EngineCaveBiomeTest { CaveBiomes counting = caves(null, 10); serve(new CaveBiomes() { @Override - public Optional overriddenBiome(PackWorld world, int x, int y, int z) { - return y > SURFACE_Y ? Optional.of("band/deep") : Optional.empty(); + public Optional overriddenBiome(PackWorld world, int x, int y, int z) { + return y > SURFACE_Y ? Optional.of(world.resources().idOf("band/deep")) : Optional.empty(); } @Override - public int minDepthBelowSurface(PackWorld world, String biomeKey) { + public int minDepthBelowSurface(PackWorld world, ResourceId biome) { depthQuestions.incrementAndGet(); - return counting.minDepthBelowSurface(world, biomeKey); + return counting.minDepthBelowSurface(world, biome); } }); diff --git a/core/src/test/java/art/arcane/iris/engine/framework/HintedLocatorTest.java b/core/src/test/java/art/arcane/iris/engine/framework/HintedLocatorTest.java index 63236aa38..94cf690a8 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/HintedLocatorTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/HintedLocatorTest.java @@ -95,6 +95,7 @@ public class HintedLocatorTest { when(engine.isClosed()).thenReturn(false); when(engine.acquireGenerationLease(any(String.class))).thenReturn(GenerationSessionLease.noop()); when(data.getBiomeLoader()).thenReturn(biomeLoader); + ModuleResourceFixture.serve(data); ModuleResourceFixture.serveModules(data, new ObjectModule()); when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); stubReachableBiomes(); diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureResourcesTest.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureResourcesTest.java index 51d10c8f8..07eabd0eb 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureResourcesTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureResourcesTest.java @@ -62,7 +62,7 @@ public class StructureResourcesTest { public void theStructureModuleListsThePacksStructuresForIrissIndexThroughItsLocator() throws Exception { IrisData data = IrisData.openValidation(castlePack("listed").toFile()); try { - assertEquals(Set.of("castle"), new StructureLocating().structures(data.getPackResources())); + assertEquals(Set.of(new ResourceId("listed", "castle")), new StructureLocating().structures(data.getPackResources())); assertEquals(Set.of("castle"), ModuleServices.structureKeys(data)); } finally { data.close(); @@ -81,7 +81,7 @@ public class StructureResourcesTest { assertEquals("castle", castle.getLoadKey()); assertEquals(pack.resolve("structures/castle.json").toFile(), castle.getLoadFile()); assertSame(data, castle.getLoader()); - assertSame(castle, data.getPackResources().find(StructureResources.STRUCTURES.key(new ResourceId("castles", "castle"))).orElseThrow()); + assertSame(castle, data.getPackResources().find(StructureResources.STRUCTURES, new ResourceId("castles", "castle")).orElseThrow()); assertEquals("castle/start", StructureResources.pool(data, "castle/start").getPieces().getFirst().getPiece()); assertEquals("castle/start", StructureResources.piece(data, "castle/start").getObject()); assertEquals(List.of("castle"), StructureResources.structureKeys(data)); @@ -101,7 +101,7 @@ public class StructureResourcesTest { try { assertNull(StructureResources.structure(data, "ruin")); assertThrows(IllegalStateException.class, - () -> data.getPackResources().find(StructureResources.STRUCTURES.key(new ResourceId("broken", "ruin")))); + () -> data.getPackResources().find(StructureResources.STRUCTURES, new ResourceId("broken", "ruin"))); } finally { data.close(); } diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/FitFixture.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/FitFixture.java index 572e659ce..58bfc2068 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/FitFixture.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/FitFixture.java @@ -9,6 +9,7 @@ import com.volmit.mantle.BlockBox; import com.volmit.resource.ResourceId; import com.volmit.vanilla.DecorationStep; import com.volmit.vanilla.PieceKind; +import com.volmit.vanilla.StartKey; import com.volmit.vanilla.StartMemo; import com.volmit.vanilla.StructureFit; import com.volmit.vanilla.TemplateCells; @@ -249,7 +250,7 @@ final class FitFixture { Piece... pieces) { StartMemo memo = new StartMemo(terrainJson, stiltsJson); StructureFit.Start start = new StructureFit.Start() { - private final Object key = new Object(); + private final StartKey key = StartKey.create(); @Override public ResourceId structure() { @@ -287,7 +288,7 @@ final class FitFixture { } @Override - public Object key() { + public StartKey key() { return key; } }; diff --git a/core/src/test/java/art/arcane/iris/engine/loot/LootDrawPinTest.java b/core/src/test/java/art/arcane/iris/engine/loot/LootDrawPinTest.java index 81c6a36c1..a3be9d46e 100644 --- a/core/src/test/java/art/arcane/iris/engine/loot/LootDrawPinTest.java +++ b/core/src/test/java/art/arcane/iris/engine/loot/LootDrawPinTest.java @@ -37,6 +37,8 @@ import static org.mockito.Mockito.when; /** * What a loot table gives at fixed spots of a fixed world, as the whole drawn items, hashed. The numbers were taken * 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. */ public class LootDrawPinTest { private static final long LOOT_SEED = 8123456789L; @@ -78,6 +80,6 @@ public class LootDrawPinTest { hashes.add(drops.toString().hashCode()); } - assertEquals(List.of(-492887340, -92432338, -1096436977, -1436497629, -1714085578), hashes); + assertEquals(List.of(-1656514080, 672855254, -359051997, -717275247, 1936773406), hashes); } } diff --git a/core/src/test/java/art/arcane/iris/engine/loot/LootItemsTest.java b/core/src/test/java/art/arcane/iris/engine/loot/LootItemsTest.java index cdb592da4..6c7c27d49 100644 --- a/core/src/test/java/art/arcane/iris/engine/loot/LootItemsTest.java +++ b/core/src/test/java/art/arcane/iris/engine/loot/LootItemsTest.java @@ -10,6 +10,7 @@ import org.junit.Before; import org.junit.Test; import java.util.List; +import java.util.Optional; import java.util.OptionalInt; import static org.junit.Assert.assertEquals; @@ -52,7 +53,7 @@ public class LootItemsTest { assertEquals(amount, drop.amount()); assertEquals(level, drop.enchantments().getFirst().level()); assertEquals(bonus, drop.attributes().getFirst().amount(), 0D); - assertEquals(damage, drop.damage(), 0D); + assertEquals(damage, drop.damage().orElseThrow(), 0D); } @Test @@ -64,7 +65,7 @@ public class LootItemsTest { ItemDrop drop = new LootItems(registry, false).give(entry, rng); assertEquals(2, drop.amount()); - assertNull(drop.damage()); + assertTrue(drop.damage().isEmpty()); assertEquals(untouched.nextLong(), rng.nextLong()); } @@ -85,9 +86,9 @@ public class LootItemsTest { List drops = new LootItems(registry, true).draw("dungeon", table, LOOT_SEED, 0, 64, 0); for (ItemDrop drop : drops) { - assertEquals(new ItemDrop.Source("dungeon", 4, 3), drop.source()); + 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() == null)); + assertTrue(new LootItems(registry, false).draw("dungeon", table, LOOT_SEED, 0, 64, 0).stream().allMatch(drop -> drop.source().isEmpty())); } @Test diff --git a/core/src/test/java/art/arcane/iris/engine/loot/LootValidatorTest.java b/core/src/test/java/art/arcane/iris/engine/loot/LootValidatorTest.java index 36b5c9593..2e9f3daa3 100644 --- a/core/src/test/java/art/arcane/iris/engine/loot/LootValidatorTest.java +++ b/core/src/test/java/art/arcane/iris/engine/loot/LootValidatorTest.java @@ -156,7 +156,7 @@ public class LootValidatorTest { public void aTableThatFailsToLoadIsReportedWithoutStoppingTheCheck() { table("fine", "{\"loot\":[{\"type\":\"stone\"}]}"); table("broken", "{\"loot\":[{\"type\":\"stone\"}]}"); - when(resources.find(LootResources.TABLES.key(new ResourceId("test", "broken")))).thenThrow(new IllegalStateException("Expected an int but was STRING at line 1 column 12 path $.rarity")); + when(resources.find(LootResources.TABLES, new ResourceId("test", "broken"))).thenThrow(new IllegalStateException("Expected an int but was STRING at line 1 column 12 path $.rarity")); assertEquals(List.of("Loot table 'broken' cannot be read: Expected an int but was STRING at line 1 column 12 path $.rarity"), errors()); } diff --git a/core/src/test/java/art/arcane/iris/engine/loot/PlacementLootTest.java b/core/src/test/java/art/arcane/iris/engine/loot/PlacementLootTest.java index b0c655164..0d2e76c94 100644 --- a/core/src/test/java/art/arcane/iris/engine/loot/PlacementLootTest.java +++ b/core/src/test/java/art/arcane/iris/engine/loot/PlacementLootTest.java @@ -54,6 +54,7 @@ public class PlacementLootTest { private static final String EAST_CHEST = "minecraft:chest[facing=east]"; private static final long LOOT_SEED = 99L; + private PackResources resources; private PlacementLoot placement; @Before @@ -63,7 +64,7 @@ public class PlacementLootTest { for (String key : List.of("everywhere", "chests", "this-chest", "other")) { fixture.resource(LootResources.TABLES, key, TestSettings.of(LootTable.class, "{\"name\": \"" + key + "\"}")); } - PackResources resources = data.getPackResources(); + resources = data.getPackResources(); BlockRegistry blocks = mock(BlockRegistry.class); when(resources.blocks()).thenReturn(blocks); when(blocks.resolve(any(BlockState.class))).thenAnswer(invocation -> invocation.getArgument(0)); @@ -71,19 +72,23 @@ public class PlacementLootTest { placement = new PlacementLoot(resources, () -> Set.of("minecraft:chests/simple_dungeon"), LOOT_SEED, ModuleLogs.discarding()); } + private Loot.Table table(String key) { + return new Loot.Table(resources.idOf(key)); + } + @Test public void aTableThatNamesTheExactStateBeatsOneThatNamesTheKindOfBlock() { List pack = List.of(entry("everywhere", 1, false), entry("chests", 1, false, CHEST), entry("this-chest", 1, true, CHEST)); - assertEquals(new Loot.Table("this-chest"), pick(List.of(), pack, CHEST)); - assertEquals(new Loot.Table("chests"), pick(List.of(), pack, EAST_CHEST)); + assertEquals(table("this-chest"), pick(List.of(), pack, CHEST)); + assertEquals(table("chests"), pick(List.of(), pack, EAST_CHEST)); } @Test public void aTableThatNamesNoBlockServesChestsNothingElseNames() { List pack = List.of(entry("everywhere", 1, false), entry("other", 1, false, "minecraft:barrel")); - assertEquals(new Loot.Table("everywhere"), pick(List.of(), pack, CHEST)); + assertEquals(table("everywhere"), pick(List.of(), pack, CHEST)); } @Test @@ -101,10 +106,10 @@ public class PlacementLootTest { for (int i = 0; i < 4000; i++) { Loot.Source picked = placement.pick(List.of(), pack, BlockState.parse(CHEST), rng, 0, 64, 0); - if (picked.equals(new Loot.Table("everywhere"))) { + if (picked.equals(table("everywhere"))) { everywhere++; } else { - assertEquals(new Loot.Table("chests"), picked); + assertEquals(table("chests"), picked); } } diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacingBoundaryRadiusTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacingBoundaryRadiusTest.java index 70549f24d..20020e6a0 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacingBoundaryRadiusTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacingBoundaryRadiusTest.java @@ -56,7 +56,7 @@ public class FloatingObjectPlacingBoundaryRadiusTest { private static PackSettings pack(FloatingChildSettings declared, ObjectHost objects) { FloatingHost floating = mock(FloatingHost.class); - return new FloatingPack() { + return new PackSettings() { @Override @SuppressWarnings("unchecked") public SettingsStack declared(Class featureType) { @@ -65,17 +65,12 @@ public class FloatingObjectPlacingBoundaryRadiusTest { } @Override - public FloatingHost floating() { - return floating; - } - - @Override - public ObjectHost objects() { - return objects; + public Optional extension(Class type) { + if (type == FloatingHost.class) { + return Optional.of(type.cast(floating)); + } + return type == ObjectHost.class ? Optional.of(type.cast(objects)) : Optional.empty(); } }; } - - private interface FloatingPack extends PackSettings, FloatingHost.Source, ObjectHost.Source { - } } diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/ObjectWarmUpTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/ObjectWarmUpTest.java index 7d68b8bac..c94bbb62b 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/ObjectWarmUpTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/ObjectWarmUpTest.java @@ -1,6 +1,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.iris.builtin.objects.ObjectHost; import art.arcane.iris.builtin.objects.ObjectHost.Declaration; import art.arcane.iris.builtin.objects.ObjectPlacement; @@ -14,23 +15,23 @@ import com.volmit.world.PackWorld; import org.junit.Test; import java.util.List; +import java.util.Optional; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import static org.mockito.Mockito.withSettings; /** Object placing builds its placements' noise and its procedural objects' variants before generation asks. */ public class ObjectWarmUpTest { @Test public void everyPlacementAndProceduralObjectOfBiomesAndRegionsIsBuilt() { ObjectHost host = mock(ObjectHost.class); - IrisSeed.Source seeds = mock(IrisSeed.Source.class); - PackWorld world = mock(PackWorld.class, withSettings().extraInterfaces(ObjectHost.Source.class, IrisSeed.Source.class)); - when(((ObjectHost.Source) world).objects()).thenReturn(host); - when(((IrisSeed.Source) world).seed(IrisSeed.COMPONENT)).thenReturn(1337L); + IrisSeeds seeds = seed -> seed == IrisSeed.COMPONENT ? 1337L : 0L; + PackWorld world = mock(PackWorld.class); + when(world.extension(ObjectHost.class)).thenReturn(Optional.of(host)); + when(world.extension(IrisSeeds.class)).thenReturn(Optional.of(seeds)); ObjectPlacement biomePlacement = placement(); ObjectPlacement regionPlacement = placement(); ProceduralObjectSettings biomeProceduralSettings = new ProceduralObjectSettings(); diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/TreeGrowingTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/TreeGrowingTest.java index 8630f13a4..421b8fb77 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/TreeGrowingTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/TreeGrowingTest.java @@ -44,7 +44,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import static org.mockito.Mockito.withSettings; /** 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 { @@ -63,8 +62,8 @@ public class TreeGrowingTest { host = mock(ObjectHost.class); settings = mock(FeatureSettings.class); when(host.columnSettings()).thenReturn(settings); - world = mock(PackWorld.class, withSettings().extraInterfaces(ObjectHost.Source.class)); - when(((ObjectHost.Source) world).objects()).thenReturn(host); + world = mock(PackWorld.class); + when(world.extension(ObjectHost.class)).thenReturn(Optional.of(host)); } @Test diff --git a/core/src/test/java/art/arcane/iris/engine/modifier/ApiChunk.java b/core/src/test/java/art/arcane/iris/engine/modifier/ApiChunk.java index d13766e5a..7a56a86bc 100644 --- a/core/src/test/java/art/arcane/iris/engine/modifier/ApiChunk.java +++ b/core/src/test/java/art/arcane/iris/engine/modifier/ApiChunk.java @@ -23,7 +23,7 @@ import art.arcane.volmlib.util.mantle.runtime.MantleChunk; import art.arcane.volmlib.util.matter.Matter; import com.volmit.noise.NoiseSampler; import art.arcane.iris.builtin.IrisStages; -import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.iris.builtin.floating.FloatingHost; import art.arcane.iris.builtin.objects.ObjectHost; import art.arcane.iris.builtin.post.PostProcessingSlabsSettings; @@ -74,7 +74,7 @@ import com.volmit.object.BlockEntityData; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; import com.volmit.config.FeatureSettings.Entry; -import com.volmit.resource.ResourceKey; +import com.volmit.resource.ResourceKind; import com.volmit.stage.Pipeline; import com.volmit.world.BiomeKind; import com.volmit.world.BiomeSample; @@ -338,6 +338,11 @@ public final class ApiChunk implements GenerationContext { return new ChunkMantle(); } + @Override + public Optional extension(Class type) { + return type == MatterMantle.class ? Optional.of(type.cast(new ChunkMantle())) : Optional.empty(); + } + @Override @SuppressWarnings("unchecked") public Hunk hunk(Class type) { @@ -488,8 +493,8 @@ public final class ApiChunk implements GenerationContext { } @Override - public MantleLayer caverns() { - return new CarvedLayer(); + public boolean isCarved(int x, int y, int z) { + return carved.contains(new BlockPosition(x, y, z)); } @Override @@ -534,55 +539,21 @@ public final class ApiChunk implements GenerationContext { } } - private final class CarvedLayer implements MantleLayer { - @Override - public Boolean get(int x, int y, int z) { - return carved.contains(new BlockPosition(x, y, z)) ? Boolean.TRUE : null; - } - - @Override - public void set(int x, int y, int z, Boolean value) { - throw new UnsupportedOperationException("Caverns are read-only"); - } - - @Override - public void remove(int x, int y, int z) { - throw new UnsupportedOperationException("Caverns are read-only"); - } - - @Override - public void visit(BlockBox area, MantleVisitor visitor) { - List positions = new ArrayList<>(carved); - positions.sort(VISIT_ORDER); - for (BlockPosition position : positions) { - if (area.contains(position.x(), position.y(), position.z())) { - visitor.accept(position.x(), position.y(), position.z(), Boolean.TRUE); - } - } - } - - @Override - public void clear(BlockBox area) { - throw new UnsupportedOperationException("Caverns are read-only"); - } - } - - /** A world of the chunk: its pack's blocks, a state store and Iris's seeds, each the world seed plus its place. */ - /** A world without floating islands: its floating host answers no surface biome, so no column has an island. */ - private final class World implements PackWorld, IrisSeed.Source, FloatingHost.Source, ObjectHost.Source { + /** + * A world of the chunk: its pack's blocks, a state store and Iris's seeds, each the world seed plus its place. It has + * no floating islands: its floating host answers no surface biome, so no column has an island. + */ + private final class World implements PackWorld { private final Resources resources = new Resources(); private final Map, Object> states = new HashMap<>(); + private final IrisSeeds seeds = seed -> SEED + seed.ordinal(); private final FloatingHost floating = mock(FloatingHost.class); private final ObjectHost objects = mock(ObjectHost.class); @Override - public FloatingHost floating() { - return floating; - } - - @Override - public ObjectHost objects() { - return objects; + public Optional extension(Class type) { + Object offered = type == IrisSeeds.class ? seeds : type == FloatingHost.class ? floating : type == ObjectHost.class ? objects : null; + return Optional.ofNullable(offered).map(type::cast); } @Override @@ -620,15 +591,6 @@ public final class ApiChunk implements GenerationContext { return ModuleLogs.discarding(); } - @Override - public PackWorld withLog(ModuleLog log) { - return this; - } - - @Override - public long seed(IrisSeed seed) { - return SEED + seed.ordinal(); - } } private static final class Resources implements PackResources { @@ -670,12 +632,12 @@ public final class ApiChunk implements GenerationContext { } @Override - public Optional find(ResourceKey key) { + public Optional find(ResourceKind kind, ResourceId id) { return Optional.empty(); } @Override - public List ids(Class type) { + public List ids(ResourceKind kind) { return List.of(); } } diff --git a/core/src/test/java/art/arcane/iris/engine/modifier/CaveBiomeBandsTest.java b/core/src/test/java/art/arcane/iris/engine/modifier/CaveBiomeBandsTest.java index 589845bc7..7157824ca 100644 --- a/core/src/test/java/art/arcane/iris/engine/modifier/CaveBiomeBandsTest.java +++ b/core/src/test/java/art/arcane/iris/engine/modifier/CaveBiomeBandsTest.java @@ -57,19 +57,19 @@ public class CaveBiomeBandsTest { public void aPositionInsideAnEnabledBandGetsTheBandsBiomeKey() { CaveBiomeBands bands = new CaveBiomeBands(); - assertEquals("world Y -54 is in the band from -64 to 0", Optional.of("band/shallow"), bands.overriddenBiome(world, 5, 10, 5)); - assertEquals("the band's end is in it", Optional.of("band/shallow"), bands.overriddenBiome(world, 5, 64, 5)); + assertEquals("world Y -54 is in the band from -64 to 0", Optional.of(CarveTestWorld.id("band/shallow")), bands.overriddenBiome(world, 5, 10, 5)); + assertEquals("the band's end is in it", Optional.of(CarveTestWorld.id("band/shallow")), bands.overriddenBiome(world, 5, 64, 5)); assertEquals("above it", Optional.empty(), bands.overriddenBiome(world, 5, 65, 5)); assertEquals("a disabled band overrides nothing", Optional.empty(), bands.overriddenBiome(world, 5, 200 - MIN_HEIGHT - 50, 5)); assertEquals("a band whose biome the pack lacks overrides nothing", Optional.empty(), bands.overriddenBiome(world, 5, 305 - MIN_HEIGHT, 5)); - assertEquals("the key is trimmed as the pack is asked for it", Optional.of("band/padded"), bands.overriddenBiome(world, 5, 550 - MIN_HEIGHT, 5)); + assertEquals("the key is trimmed as the pack is asked for it", Optional.of(CarveTestWorld.id("band/padded")), bands.overriddenBiome(world, 5, 550 - MIN_HEIGHT, 5)); } @Test public void aBiomeKeyHasTheMinimumDepthItsSettingsDeclareAndZeroWhenTheKeyIsUnknown() { CaveBiomeBands bands = new CaveBiomeBands(); - assertEquals(30, bands.minDepthBelowSurface(world, "band/shallow")); - assertEquals(0, bands.minDepthBelowSurface(world, "band/unknown")); + assertEquals(30, bands.minDepthBelowSurface(world, CarveTestWorld.id("band/shallow"))); + assertEquals(0, bands.minDepthBelowSurface(world, CarveTestWorld.id("band/unknown"))); } } diff --git a/core/src/test/java/art/arcane/iris/engine/modifier/FloatingIslandsTest.java b/core/src/test/java/art/arcane/iris/engine/modifier/FloatingIslandsTest.java index 63cb7f4f8..40e019adf 100644 --- a/core/src/test/java/art/arcane/iris/engine/modifier/FloatingIslandsTest.java +++ b/core/src/test/java/art/arcane/iris/engine/modifier/FloatingIslandsTest.java @@ -1,6 +1,6 @@ package art.arcane.iris.engine.modifier; -import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.iris.builtin.floating.FloatingHost; import art.arcane.iris.builtin.objects.ObjectHost; import art.arcane.iris.engine.decorator.BiomeDecorators; @@ -16,6 +16,7 @@ import com.volmit.stage.ChunkStageContext; import com.volmit.world.PackWorld; import org.junit.Test; +import java.util.Optional; import java.util.function.Function; import static org.mockito.ArgumentMatchers.any; @@ -25,7 +26,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import static org.mockito.Mockito.withSettings; /** A column whose biome declares no floating child biomes gets no island: nothing is written or decorated. */ public class FloatingIslandsTest { @@ -60,9 +60,10 @@ public class FloatingIslandsTest { @SuppressWarnings("unchecked") private static PackWorld world(FloatingHost host) { - PackWorld world = mock(PackWorld.class, withSettings().extraInterfaces(FloatingHost.Source.class, ObjectHost.Source.class, IrisSeed.Source.class)); - when(((FloatingHost.Source) world).floating()).thenReturn(host); - when(((ObjectHost.Source) world).objects()).thenReturn(mock(ObjectHost.class)); + PackWorld world = mock(PackWorld.class); + when(world.extension(FloatingHost.class)).thenReturn(Optional.of(host)); + when(world.extension(ObjectHost.class)).thenReturn(Optional.of(mock(ObjectHost.class))); + when(world.extension(IrisSeeds.class)).thenReturn(Optional.of(seed -> 0L)); when(world.resources()).thenReturn(mock(PackResources.class)); PackSettings nothingDeclared = mock(PackSettings.class); when(nothingDeclared.declared(any())).thenAnswer(invocation -> SettingsStack.empty()); diff --git a/core/src/test/java/art/arcane/iris/engine/object/placement/IrisObjectPlacementRegressionTest.java b/core/src/test/java/art/arcane/iris/engine/object/placement/IrisObjectPlacementRegressionTest.java index 74a18393b..b155b6123 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/placement/IrisObjectPlacementRegressionTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/placement/IrisObjectPlacementRegressionTest.java @@ -423,11 +423,9 @@ public class IrisObjectPlacementRegressionTest { /** Looks up the pack's oak through the placement's resources. */ private static final class FindModule implements IrisModule { private static final PlacementStage FIND = Stage.placement("test:find/oak"); - private final java.io.File packFolder; private final List found; - private FindModule(java.io.File packFolder, List found) { - this.packFolder = packFolder; + private FindModule(List found) { this.found = found; } @@ -439,14 +437,14 @@ public class IrisObjectPlacementRegressionTest { @Override public void setup(ModuleSetup setup) { setup.stages().define(FIND).requires(IrisStages.Blocks.COMPLETE).run(context -> - found.add(context.world().resources().find(PackResourceFixture.oakKey(packFolder)).orElseThrow())); + found.add(PackResourceFixture.oak(context.world().resources()))); } } @Test public void aPasteWithoutAnEngineFindsThePacksResourcesThroughItsWorld() throws IOException { List found = new ArrayList<>(); - usePack(List.of(new FindModule(folder.getRoot(), found))); + usePack(List.of(new FindModule(found))); PackResourceFixture.serve(data); ObjectPlacementResult result = place(placement(), ANCHOR_Y, new RecordingPlacer(null), null); @@ -511,11 +509,9 @@ public class IrisObjectPlacementRegressionTest { /** Lays the pack's oak on its side, a quarter turn about X, through the placement's object transformer. */ private static final class TurnModule implements IrisModule { private static final PlacementStage TURN = Stage.placement("test:turn/oak"); - private final java.io.File packFolder; private final List turned; - private TurnModule(java.io.File packFolder, List turned) { - this.packFolder = packFolder; + private TurnModule(List turned) { this.turned = turned; } @@ -527,7 +523,7 @@ public class IrisObjectPlacementRegressionTest { @Override public void setup(ModuleSetup setup) { setup.stages().define(TURN).requires(IrisStages.Blocks.COMPLETE).run(context -> turned.add(context.objects().transform( - context.world().resources().require(PackResourceFixture.oakKey(packFolder)), + PackResourceFixture.oak(context.world().resources()), new ObjectTransform(90, 0, 0, 1, 1, 1, false, false, false)))); } } @@ -535,7 +531,7 @@ public class IrisObjectPlacementRegressionTest { @Test public void aPlacementStageTurnsAnObjectThroughTheObjectTransformer() throws IOException { List turned = new ArrayList<>(); - usePack(List.of(new TurnModule(folder.getRoot(), turned))); + usePack(List.of(new TurnModule(turned))); PackResourceFixture.serve(data); ObjectPlacementResult result = place(placement(), ANCHOR_Y, new RecordingPlacer(null), null); diff --git a/core/src/test/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolverParityTest.java b/core/src/test/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolverParityTest.java index 275413e22..c43b48770 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolverParityTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolverParityTest.java @@ -1,5 +1,7 @@ package art.arcane.iris.engine.object.terrain.carving; +import art.arcane.iris.builtin.IrisSeed; +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; @@ -259,7 +261,7 @@ public class CarvingResolverParityTest { return parent; } - long seed = world.seed(art.arcane.iris.builtin.IrisSeed.CARVE) ^ CHILD_SEED_SALT; + long seed = world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.CARVE) ^ CHILD_SEED_SALT; LegacyCarvingChoice selected = legacyChildrenGenerator(parent, seed).fitRarity(options, worldX, worldZ); if (selected == null || selected.entry == null) { return parent; diff --git a/core/src/test/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionReachableBiomesTest.java b/core/src/test/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionReachableBiomesTest.java index c89f97d8b..f5f1a57f1 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionReachableBiomesTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionReachableBiomesTest.java @@ -9,6 +9,8 @@ import art.arcane.iris.builtin.carve.CarvingEntry; import art.arcane.iris.builtin.carve.CarvingSettings; import art.arcane.iris.builtin.floating.FloatingChildSettings; import art.arcane.iris.core.modules.BuiltInPack; +import art.arcane.iris.core.modules.IrisPackResources; +import art.arcane.iris.core.modules.PackResourceFixture; import com.google.gson.Gson; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.core.loader.IrisData; @@ -17,6 +19,7 @@ import art.arcane.volmlib.util.collection.KList; import com.volmit.IrisFeature; import org.junit.Test; +import java.io.File; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -59,11 +62,13 @@ public class IrisDimensionReachableBiomesTest { IrisBiome disabledDeep = biome("disabled-deep"); IrisBiome unused = biome("unused"); + IrisPackResources resources = PackResourceFixture.empty(new File("pack")); IrisData data = mock(IrisData.class); ResourceLoader regionLoader = mock(ResourceLoader.class); ResourceLoader biomeLoader = mock(ResourceLoader.class); when(data.getRegionLoader()).thenReturn(regionLoader); when(data.getBiomeLoader()).thenReturn(biomeLoader); + when(data.getPackResources()).thenReturn(resources); when(regionLoader.load("reachable")).thenReturn(reachable); when(biomeLoader.load("parent")).thenReturn(parent); when(biomeLoader.load("child")).thenReturn(child); @@ -106,11 +111,13 @@ public class IrisDimensionReachableBiomesTest { IrisBiome d = biome("d", floatingChildren(floating("b"))) .setChildren(new KList<>("a")); + IrisPackResources resources = PackResourceFixture.empty(new File("pack")); IrisData data = mock(IrisData.class); ResourceLoader regionLoader = mock(ResourceLoader.class); ResourceLoader biomeLoader = mock(ResourceLoader.class); when(data.getRegionLoader()).thenReturn(regionLoader); when(data.getBiomeLoader()).thenReturn(biomeLoader); + when(data.getPackResources()).thenReturn(resources); when(regionLoader.load("reachable")).thenReturn(reachable); when(biomeLoader.load("a")).thenReturn(a); when(biomeLoader.load("b")).thenReturn(b); diff --git a/core/src/test/java/art/arcane/iris/engine/object/world/region/IrisRegionBiomeTreeTest.java b/core/src/test/java/art/arcane/iris/engine/object/world/region/IrisRegionBiomeTreeTest.java index 030c4e023..7f22ee14e 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/world/region/IrisRegionBiomeTreeTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/world/region/IrisRegionBiomeTreeTest.java @@ -24,12 +24,15 @@ import art.arcane.iris.builtin.floating.FloatingChildSettings; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.ResourceLoader; import art.arcane.iris.core.modules.BuiltInPack; +import art.arcane.iris.core.modules.IrisPackResources; +import art.arcane.iris.core.modules.PackResourceFixture; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.volmlib.util.collection.KList; import com.google.gson.Gson; import com.volmit.IrisFeature; import org.junit.Test; +import java.io.File; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -51,9 +54,11 @@ public class IrisRegionBiomeTreeTest { IrisBiome mushroom = biome("carving/mushroom", new CarvingBiomeSettings("carving/nested")); IrisBiome nested = biome("carving/nested"); + IrisPackResources resources = PackResourceFixture.empty(new File("pack")); IrisData data = mock(IrisData.class); ResourceLoader biomes = mock(ResourceLoader.class); when(data.getBiomeLoader()).thenReturn(biomes); + when(data.getPackResources()).thenReturn(resources); when(biomes.load("plains")).thenReturn(plains); when(biomes.load("meadow")).thenReturn(meadow); when(biomes.load("carving/mushroom")).thenReturn(mushroom); diff --git a/core/src/test/java/art/arcane/iris/engine/spawn/AmbientEffectingTest.java b/core/src/test/java/art/arcane/iris/engine/spawn/AmbientEffectingTest.java index c3c681d4e..4f43f2db7 100644 --- a/core/src/test/java/art/arcane/iris/engine/spawn/AmbientEffectingTest.java +++ b/core/src/test/java/art/arcane/iris/engine/spawn/AmbientEffectingTest.java @@ -35,9 +35,9 @@ import org.junit.Before; import org.junit.Test; import java.util.List; +import java.util.Optional; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -92,13 +92,13 @@ public class AmbientEffectingTest { List due = new AmbientEffecting().due(world, AT); assertEquals(1, due.size()); - AmbientEffects.Sound sound = due.getFirst().sound(); + AmbientEffects.Sound sound = due.getFirst().sound().orElseThrow(); assertEquals("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(new AmbientEffects.Potion("luck", 1, 100), due.getFirst().potion()); - assertNull(due.getFirst().particles()); + assertEquals(Optional.of(new AmbientEffects.Potion("luck", 1, 100)), due.getFirst().potion()); + assertTrue(due.getFirst().particles().isEmpty()); assertTrue(due.getFirst().commands().isEmpty()); } @@ -109,18 +109,19 @@ public class AmbientEffectingTest { AmbientEffects.Effect effect = new AmbientEffecting().due(world, AT).getFirst(); - assertEquals("flame", effect.particles().key()); - assertEquals(5, effect.particles().forward(), 0); - assertEquals(0, effect.particles().sideways(), 0); - assertEquals(0.5, effect.particles().altX(), 0); - assertEquals(0.25, effect.particles().extra(), 0); - assertEquals(2, effect.particles().count()); + 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(0.25, particles.extra(), 0); + assertEquals(2, particles.count()); assertEquals(1, effect.commands().size()); assertEquals(List.of("say hi {x}"), effect.commands().getFirst().command().commands()); assertEquals(3, effect.commands().getFirst().command().delay()); assertEquals(2, effect.commands().getFirst().offsetX(), 0); - assertNull(effect.sound()); - assertNull(effect.potion()); + assertTrue(effect.sound().isEmpty()); + assertTrue(effect.potion().isEmpty()); } @Test diff --git a/core/src/test/java/art/arcane/iris/engine/spawn/EntityResolutionPinTest.java b/core/src/test/java/art/arcane/iris/engine/spawn/EntityResolutionPinTest.java index f949a8afa..616f1da34 100644 --- a/core/src/test/java/art/arcane/iris/engine/spawn/EntityResolutionPinTest.java +++ b/core/src/test/java/art/arcane/iris/engine/spawn/EntityResolutionPinTest.java @@ -25,6 +25,8 @@ import art.arcane.volmlib.util.math.RNG; import com.google.gson.Gson; import com.volmit.entity.EntitySpec; import com.volmit.item.ItemRegistry; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import org.junit.Test; import java.util.Optional; @@ -38,6 +40,8 @@ import static org.mockito.Mockito.when; /** * What an entity of the pack becomes when it is made from a fixed stream, hashed. The number was taken before the entity * 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. */ public class EntityResolutionPinTest { private static final long STREAM_SEED = 4321L; @@ -67,8 +71,11 @@ public class EntityResolutionPinTest { Optional sky = Optional.of(new Sky(0L, false, false)); EntityDefinition entity = new Gson().fromJson(ENTITY, EntityDefinition.class); - EntitySpec spec = new EntityResolution(new LootItems(registry, false), sky, new EffectTimers()).resolve(entity, new RNG(STREAM_SEED)); + PackResources resources = mock(PackResources.class); + when(resources.idOf(anyString())).thenAnswer(invocation -> new ResourceId("test", invocation.getArgument(0))); - assertEquals(-819231818, spec.toString().hashCode()); + EntitySpec spec = new EntityResolution(resources, new LootItems(registry, false), sky, new EffectTimers()).resolve(entity, new RNG(STREAM_SEED)); + + assertEquals(1441930785, spec.toString().hashCode()); } } diff --git a/core/src/test/java/art/arcane/iris/engine/spawn/EntitySpawningTest.java b/core/src/test/java/art/arcane/iris/engine/spawn/EntitySpawningTest.java index dc26d86e7..136ab1eed 100644 --- a/core/src/test/java/art/arcane/iris/engine/spawn/EntitySpawningTest.java +++ b/core/src/test/java/art/arcane/iris/engine/spawn/EntitySpawningTest.java @@ -103,7 +103,7 @@ public class EntitySpawningTest { EntitySpawns.MarkerRule rule = new EntitySpawning().marker(world, "camp").orElseThrow(); - assertEquals(List.of("zombies"), rule.spawners()); + assertEquals("a spawner the pack lacks is left out", List.of(world.resources().idOf("zombies")), rule.spawners()); assertTrue(rule.emptyAbove()); assertFalse(rule.removeOnChange()); } @@ -123,16 +123,16 @@ public class EntitySpawningTest { when(engine.getMinHeight()).thenReturn(-64); EntitySpawns.Plan plan = new EntitySpawning() - .plan(world, new EntitySpawns.Marker(MARKER_BLOCK, "camp", "camp/zombies", false)) + .plan(world, new EntitySpawns.Marker(MARKER_BLOCK, "camp", world.resources().idOf("camp/zombies"), false)) .orElseThrow(); - assertEquals("camp/zombies", plan.spawner()); + assertEquals(world.resources().idOf("camp/zombies"), plan.spawner()); assertTrue("an exhaustion chance above 1 always uses the marker up", plan.exhaustsMarker()); assertEquals(2, plan.attempts().size()); for (EntitySpawns.Attempt attempt : plan.attempts()) { assertEquals(new BlockPosition(40, 71, -12), attempt.at()); assertFalse(attempt.checkSurface()); - assertEquals("minecraft:zombie", attempt.entity().type()); + assertEquals(Optional.of("minecraft:zombie"), attempt.entity().type()); } } @@ -140,7 +140,7 @@ public class EntitySpawningTest { public void aSpawnerThatCannotFireOrHasNoEntitiesPlansNothing() { fixture.resource(SpawnResources.SPAWNERS, "empty", new Spawner()); - Optional plan = new EntitySpawning().plan(world, new EntitySpawns.Marker(MARKER_BLOCK, "camp", "empty", false)); + Optional plan = new EntitySpawning().plan(world, new EntitySpawns.Marker(MARKER_BLOCK, "camp", world.resources().idOf("empty"), false)); assertTrue(plan.isEmpty()); } @@ -150,11 +150,11 @@ public class EntitySpawningTest { fixture.resource(SpawnResources.ENTITIES, "cow", TestSettings.of(EntityDefinition.class, "{\"type\": \"minecraft:cow\", \"customName\": \"&6Bessie\", \"baby\": true}")); - EntitySpec spec = new EntitySpawning().entity(world, "cow").orElseThrow(); + EntitySpec spec = new EntitySpawning().entity(world, world.resources().idOf("cow")).orElseThrow(); - assertEquals("minecraft:cow", spec.type()); - assertEquals("&6Bessie", spec.customName()); + assertEquals(Optional.of("minecraft:cow"), spec.type()); + assertEquals(Optional.of("&6Bessie"), spec.customName()); assertTrue(spec.flags().baby()); - assertTrue(new EntitySpawning().entity(world, "nothing").isEmpty()); + assertTrue(new EntitySpawning().entity(world, world.resources().idOf("nothing")).isEmpty()); } } diff --git a/core/src/test/java/art/arcane/iris/engine/spawn/SpawnerGateTest.java b/core/src/test/java/art/arcane/iris/engine/spawn/SpawnerGateTest.java index 05c578fd5..4e89a562d 100644 --- a/core/src/test/java/art/arcane/iris/engine/spawn/SpawnerGateTest.java +++ b/core/src/test/java/art/arcane/iris/engine/spawn/SpawnerGateTest.java @@ -51,7 +51,7 @@ public class SpawnerGateTest { when(engine.getWorld()).thenReturn(engineWorld); when(engine.getData()).thenReturn(mock(IrisData.class)); when(engine.getEngineData()).thenReturn(new IrisEngineData()); - live = LiveWorld.of(new EngineGeneration(engine).world()); + live = new EngineGeneration(engine).world().extension(LiveWorld.class).orElseThrow(); } @Test @@ -105,7 +105,7 @@ public class SpawnerGateTest { when(engine.getData()).thenReturn(mock(IrisData.class)); when(engine.getWorld()).thenReturn(mock(IrisWorld.class)); - assertFalse(SpawnerGate.canSpawn("any", spawner("{}"), LiveWorld.of(new EngineGeneration(engine).world()), 0, 0)); + assertFalse(SpawnerGate.canSpawn("any", spawner("{}"), new EngineGeneration(engine).world().extension(LiveWorld.class).orElseThrow(), 0, 0)); } private static Spawner spawner(String json) { diff --git a/core/src/test/java/art/arcane/iris/engine/terrain/TestLayerBlocks.java b/core/src/test/java/art/arcane/iris/engine/terrain/TestLayerBlocks.java index 922e8d2bc..d08fd75d3 100644 --- a/core/src/test/java/art/arcane/iris/engine/terrain/TestLayerBlocks.java +++ b/core/src/test/java/art/arcane/iris/engine/terrain/TestLayerBlocks.java @@ -65,10 +65,5 @@ public final class TestLayerBlocks { public ModuleLog log() { return ModuleLogs.discarding(); } - - @Override - public PackWorld withLog(ModuleLog log) { - return this; - } } } diff --git a/core/src/test/java/art/arcane/iris/engine/terrain/TestPackWorld.java b/core/src/test/java/art/arcane/iris/engine/terrain/TestPackWorld.java index 67adb5c5d..727c402ac 100644 --- a/core/src/test/java/art/arcane/iris/engine/terrain/TestPackWorld.java +++ b/core/src/test/java/art/arcane/iris/engine/terrain/TestPackWorld.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.terrain; -import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.iris.core.modules.ModuleSettings; import com.volmit.config.Level; import com.volmit.IrisFeature; @@ -39,7 +39,7 @@ import java.util.Optional; import java.util.function.Function; /** A world of a pack's resources whose dimension declares the given settings and whose complex and terrain seeds are given, for tests of the terrain's support classes. */ -public final class TestPackWorld implements PackWorld, IrisSeed.Source { +public final class TestPackWorld implements PackWorld { private static final ResourceId DIMENSION = ResourceId.parse("test:dimension/overworld"); private final PackResources resources; @@ -83,11 +83,6 @@ public final class TestPackWorld implements PackWorld, IrisSeed.Source { return seed; } - @Override - public long seed(IrisSeed which) { - return seed; - } - @Override public PackResources resources() { return resources; @@ -109,7 +104,8 @@ public final class TestPackWorld implements PackWorld, IrisSeed.Source { } @Override - public PackWorld withLog(ModuleLog log) { - return this; + public Optional extension(Class type) { + IrisSeeds everySeedIsTheWorlds = which -> seed; + return type == IrisSeeds.class ? Optional.of(type.cast(everySeedIsTheWorlds)) : Optional.empty(); } }