Merge upstream port lane c

This commit is contained in:
piexel committed 2026-11-10 01:31:37 +01:00
commit 55786d6297
50 files changed
+2014 -256

No files matched your search

@@ -10,6 +10,7 @@ import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
import art.arcane.iris.engine.framework.NativeStructureLayouts;
import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting;
import art.arcane.iris.engine.IrisEngine;
import art.arcane.iris.engine.mantle.DeferredPlacementRecords;
import art.arcane.iris.engine.platform.BukkitChunkGenerator;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.nativegen.NativeStructureFitBridge;
@@ -906,7 +907,7 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
private void placeVanillaStructure(WorldGenLevel world, StructureManager structureManager, WorldgenRandom random,
BoundingBox area, ChunkPos chunkPos, String structureId,
NativePlacement placement) {
WorldGenLevel boundedWorld = NativeStructureWorldgenAccess.create(
NativeStructureWorldgenAccess boundedWorld = NativeStructureWorldgenAccess.create(
world, chunkPos, worldgenSurfaceHeight(), worldgenFloorHeight());
world.setCurrentlyGenerating(() -> "Iris native structure " + structureId);
try {
@@ -916,6 +917,7 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
getSeaLevel(), area.minY(), area.maxY() + 1);
start.placeInChunk(boundedWorld, structureManager, this, random, area, chunkPos);
} finally {
DeferredPlacementRecords.clearWritten(engine, boundedWorld.writtenBlocks());
world.setCurrentlyGenerating(null);
}
}
@@ -1,5 +1,6 @@
package art.arcane.iris.core.nms.v26_2_R1;
import art.arcane.iris.engine.mantle.DeferredPlacementRecords.WrittenBlocks;
import art.arcane.iris.nativegen.WorldgenTerrainHeightmaps;
import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
@@ -71,6 +72,7 @@ final class NativeStructureWorldgenAccess implements WorldGenLevel {
private final LevelTickAccess<Fluid> fluidTicks;
private final Long2LongOpenHashMap terrainHeights;
private final Long2ObjectOpenHashMap<ChunkAccess> outsideChunks;
private final WrittenBlocks writtenBlocks = new WrittenBlocks();
private NativeStructureWorldgenAccess(WorldGenLevel delegate, Boundary boundary) {
this.delegate = Objects.requireNonNull(delegate, "Native structure world access requires a delegate");
@@ -424,17 +426,28 @@ final class NativeStructureWorldgenAccess implements WorldGenLevel {
@Override
public boolean setBlock(BlockPos position, BlockState state, int updateFlags, int updateLimit) {
return isWritable(position) && delegate.setBlock(position, state, updateFlags, updateLimit);
return recordWrite(position, isWritable(position) && delegate.setBlock(position, state, updateFlags, updateLimit));
}
@Override
public boolean removeBlock(BlockPos position, boolean move) {
return isWritable(position) && delegate.removeBlock(position, move);
return recordWrite(position, isWritable(position) && delegate.removeBlock(position, move));
}
@Override
public boolean destroyBlock(BlockPos position, boolean drop, Entity source, int updateLimit) {
return isWritable(position) && delegate.destroyBlock(position, drop, source, updateLimit);
return recordWrite(position, isWritable(position) && delegate.destroyBlock(position, drop, source, updateLimit));
}
WrittenBlocks writtenBlocks() {
return writtenBlocks;
}
private boolean recordWrite(BlockPos position, boolean written) {
if (written) {
writtenBlocks.add(position.getX(), position.getY(), position.getZ());
}
return written;
}
@Override
@@ -1,6 +1,10 @@
package art.arcane.iris.api.tree;
public interface TreeFellerRunHooks {
default boolean requiresSneaking() {
return true;
}
TreeFellerRunHooks NONE = new TreeFellerRunHooks() {
@Override
public void onActivationAccepted() {
@@ -333,7 +333,7 @@ public class CommandFind implements DirectorExecutor {
}
Set<String> configuredImportUrls = normalizedImportUrls(
engine.getDimension().getDatapackImports());
DatapackIngestService.configuredImports(engine.getDimension()));
return new StructureExclusionReport(
List.copyOf(exclusions), Set.copyOf(registeredKeys.keySet()),
configuredImportUrls, registeredExcluded, configuredUnregistered,
@@ -520,21 +520,19 @@ public class CommandObject implements DirectorExecutor {
return;
}
if (WandSVC.isHoldingIrisWand(player)) {
Location[] g = WandSVC.getCuboid(player);
Location[] g = WandSVC.getCuboid(player);
if (g == null) {
return;
}
if (!here) {
// TODO: WARNING HEIGHT
g[0] = player.getTargetBlock(null, 256).getLocation().clone();
} else {
g[0] = player.getLocation().getBlock().getLocation().clone().add(0, -1, 0);
}
player.getInventory().setItemInMainHand(WandSVC.createWand(g[0], g[1]));
if (g == null) {
return;
}
if (!here) {
// TODO: WARNING HEIGHT
g[0] = player.getTargetBlock(null, 256).getLocation().clone();
} else {
g[0] = player.getLocation().getBlock().getLocation().clone().add(0, -1, 0);
}
player.getInventory().setItemInMainHand(WandSVC.createWand(g[0], g[1]));
});
}
@@ -112,6 +112,6 @@ public final class DatapackStructureScopeSVC implements IrisService {
return Set.of();
}
return scopeIndex.declaredSources(
generator.getTarget().getDimension().getDatapackImports());
DatapackIngestService.configuredImports(generator.getTarget().getDimension()));
}
}
@@ -220,7 +220,7 @@ public class TreeFellerSVC implements IrisService, IrisTreeFellerService {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void haltWhenSneakingStops(PlayerToggleSneakEvent event) {
if (!event.isSneaking()) {
runner.finishRuns(event.getPlayer().getUniqueId());
runner.finishSneakRuns(event.getPlayer().getUniqueId());
}
}
@@ -526,10 +526,19 @@ final class TreeFellingRunner {
private boolean isRunControlActive(FellingRun run, Player player) {
return player.isOnline()
&& player.getGameMode() == GameMode.SURVIVAL
&& player.isSneaking()
&& (!requiresSneaking(run) || player.isSneaking())
&& player.getWorld().equals(run.candidate.world());
}
private boolean requiresSneaking(FellingRun run) {
try {
return run.runHooks.requiresSneaking();
} catch (RuntimeException error) {
IrisLogging.reportError("An Iris tree-feller integration sneak requirement check failed.", error);
return true;
}
}
private boolean reserveLogCost(FellingRun run) {
try {
return run.runHooks.reserveLogCost();
@@ -611,11 +620,22 @@ final class TreeFellingRunner {
}
void finishRuns(UUID playerId) {
finishRuns(playerId, false);
}
void finishSneakRuns(UUID playerId) {
finishRuns(playerId, true);
}
private void finishRuns(UUID playerId, boolean onlySneakRuns) {
Set<FellingRun> runs = service.activeRuns.get(playerId);
if (runs == null) {
return;
}
for (FellingRun run : List.copyOf(runs)) {
if (onlySneakRuns && !requiresSneaking(run)) {
continue;
}
if (run.abortReason == null) {
run.abortReason = "halted";
}
@@ -27,11 +27,9 @@ import org.bukkit.Particle;
import org.bukkit.Sound;
import org.bukkit.World;
import art.arcane.iris.Iris;
import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.core.localization.IrisLanguage;
import art.arcane.iris.core.localization.RuntimeUiMessages;
import art.arcane.iris.core.edit.DustRevealer;
import art.arcane.iris.core.link.WorldEditLink;
import art.arcane.iris.core.wand.WandSelection;
import art.arcane.iris.engine.object.prefab.IrisObject;
import art.arcane.iris.util.project.matter.WorldMatter;
@@ -333,26 +331,14 @@ public class WandSVC implements IrisService {
}
public static Location[] getCuboid(Player p) {
if (isHoldingIrisWand(p)) {
if (isHoldingWand(p)) {
return getCuboidFromItem(p.getInventory().getItemInMainHand());
}
if (IrisSettings.get().getWorld().worldEditWandCUI) {
Cuboid c = WorldEditLink.getSelection(p);
if (c != null) {
return new Location[]{c.getLowerNE(), c.getUpperSW()};
}
}
return null;
}
public static boolean isHoldingWand(Player p) {
return isHoldingIrisWand(p) || (IrisSettings.get().getWorld().worldEditWandCUI && WorldEditLink.getSelection(p) != null);
}
public static boolean isHoldingIrisWand(Player p) {
ItemStack is = p.getInventory().getItemInMainHand();
return is != null && isWand(is);
}
@@ -567,7 +553,7 @@ public class WandSVC implements IrisService {
if (e.getHand() != EquipmentSlot.HAND)
return;
try {
if (isHoldingIrisWand(e.getPlayer())) {
if (isHoldingWand(e.getPlayer())) {
activePlayers.put(e.getPlayer().getUniqueId(), e.getPlayer());
if (e.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
e.setCancelled(true);
@@ -204,7 +204,7 @@ public class IrisStructureLocateCommandContractTest {
assertTrue(method.contains("non-generating structure candidate(s) and their reasons to the server console"));
assertTrue(method.contains("no chunks were searched"));
assertTrue(method.indexOf("DatapackIngestService.installed()") > method.indexOf("J.a(() ->"));
assertTrue(source.contains("engine.getDimension().getDatapackImports()"));
assertTrue(source.contains("DatapackIngestService.configuredImports(engine.getDimension())"));
assertTrue(source.contains("snapshot.configuredImportUrls().contains(importUrl)"));
assertTrue(source.contains("ModuleServices.structureKeys(engine.getData())"));
assertFalse(method.contains("commandSender.sendMessage(exclusion"));
@@ -0,0 +1,99 @@
package art.arcane.iris.core.service;
import art.arcane.iris.api.tree.TreeFellerRunHooks;
import art.arcane.iris.core.service.TreeFellerModel.TreeCandidate;
import art.arcane.iris.core.service.TreeFellerModel.TreeClaim;
import art.arcane.iris.core.service.tree.TreeMarkerTraversal;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.junit.Test;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TreeFellingRunnerSneakLatchTest {
private static final TreeFellerRunHooks LATCHED_HOOKS = new TreeFellerRunHooks() {
@Override
public boolean requiresSneaking() {
return false;
}
@Override
public void onActivationAccepted() {
}
@Override
public boolean reserveLogCost() {
return true;
}
@Override
public void commitLogCost() {
}
@Override
public void refundLogCost() {
}
};
@Test
public void runHooksRequireSneakingByDefault() {
assertTrue(TreeFellerRunHooks.NONE.requiresSneaking());
}
@Test
public void releasingSneakFinishesOnlyRunsThatRequireIt() {
TreeFellerSVC service = new TreeFellerSVC();
TreeFellingRunner runner = new TreeFellingRunner(service, null);
UUID playerId = UUID.randomUUID();
FellingRun sneakRun = registerRun(service, playerId, TreeFellerRunHooks.NONE, "sneak");
FellingRun latchedRun = registerRun(service, playerId, LATCHED_HOOKS, "latched");
runner.finishSneakRuns(playerId);
assertTrue(sneakRun.finished.get());
assertEquals("halted", sneakRun.abortReason);
assertFalse(latchedRun.finished.get());
assertTrue(service.activeRuns.get(playerId).contains(latchedRun));
}
@Test
public void finishingAllRunsStillEndsLatchedRuns() {
TreeFellerSVC service = new TreeFellerSVC();
TreeFellingRunner runner = new TreeFellingRunner(service, null);
UUID playerId = UUID.randomUUID();
FellingRun latchedRun = registerRun(service, playerId, LATCHED_HOOKS, "latched");
runner.finishRuns(playerId);
assertTrue(latchedRun.finished.get());
assertEquals("halted", latchedRun.abortReason);
}
private FellingRun registerRun(TreeFellerSVC service, UUID playerId, TreeFellerRunHooks hooks, String marker) {
Player player = mock(Player.class);
when(player.getUniqueId()).thenReturn(playerId);
World world = mock(World.class);
TreeCandidate candidate = new TreeCandidate(
null,
world,
player,
mock(ItemStack.class),
null,
new TreeMarkerTraversal.Position(0, 64, 0)
);
TreeClaim claim = new TreeClaim(UUID.randomUUID(), marker);
FellingRun run = new FellingRun(claim, candidate, 0, hooks, 0, new Location(world, 0D, 64D, 0D));
service.activeClaims.add(claim);
service.activeRuns.computeIfAbsent(playerId, ignored -> ConcurrentHashMap.newKeySet()).add(run);
return run;
}
}
@@ -0,0 +1,108 @@
package art.arcane.iris.core.service;
import art.arcane.iris.Iris;
import art.arcane.iris.core.link.WorldEditLink;
import art.arcane.volmlib.util.bukkit.WorldIdentity;
import art.arcane.volmlib.util.data.Cuboid;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataContainer;
import org.bukkit.persistence.PersistentDataType;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockedStatic;
import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.when;
public class WandSVCTest {
private Iris previousPlugin;
private Player player;
private PlayerInventory inventory;
@Before
public void installPlugin() {
previousPlugin = Iris.instance;
Iris plugin = mock(Iris.class);
when(plugin.namespace()).thenReturn("iris");
Iris.instance = plugin;
player = mock(Player.class);
inventory = mock(PlayerInventory.class);
when(player.getInventory()).thenReturn(inventory);
}
@After
public void restorePlugin() {
Iris.instance = previousPlugin;
}
@Test
public void ignoresWorldEditSelectionWhileHoldingAnOrdinaryAxe() {
ItemStack axe = wandItem(false);
when(inventory.getItemInMainHand()).thenReturn(axe);
Cuboid selection = mock(Cuboid.class);
try (MockedStatic<WorldEditLink> worldEdit = mockStatic(WorldEditLink.class)) {
worldEdit.when(() -> WorldEditLink.getSelection(player)).thenReturn(selection);
assertFalse(WandSVC.isHoldingWand(player));
assertNull(WandSVC.getCuboid(player));
}
}
@Test
public void ignoresWorldEditSelectionWithAnEmptyHand() {
Cuboid selection = mock(Cuboid.class);
try (MockedStatic<WorldEditLink> worldEdit = mockStatic(WorldEditLink.class)) {
worldEdit.when(() -> WorldEditLink.getSelection(player)).thenReturn(selection);
assertFalse(WandSVC.isHoldingWand(player));
assertNull(WandSVC.getCuboid(player));
}
}
@Test
public void readsSelectionFromAnIrisMarkedWand() {
ItemStack wand = wandItem(true);
when(inventory.getItemInMainHand()).thenReturn(wand);
World world = mock(World.class);
try (MockedStatic<WorldIdentity> worlds = mockStatic(WorldIdentity.class)) {
worlds.when(() -> WorldIdentity.resolve("minecraft:overworld")).thenReturn(Optional.of(world));
assertTrue(WandSVC.isHoldingWand(player));
assertArrayEquals(new Location[]{new Location(world, 1D, 64D, 2D), new Location(world, 3D, 68D, 4D)},
WandSVC.getCuboid(player));
}
}
private ItemStack wandItem(boolean marked) {
ItemStack item = mock(ItemStack.class);
ItemMeta meta = mock(ItemMeta.class);
PersistentDataContainer data = mock(PersistentDataContainer.class);
when(item.getType()).thenReturn(marked ? Material.BLAZE_ROD : Material.WOODEN_AXE);
when(item.getItemMeta()).thenReturn(meta);
when(meta.getPersistentDataContainer()).thenReturn(data);
when(meta.getLore()).thenReturn(List.of("1,64,2 in minecraft:overworld", "3,68,4 in minecraft:overworld"));
if (marked) {
when(data.get(new NamespacedKey("iris", "wand"), PersistentDataType.BYTE)).thenReturn((byte) 1);
}
return item;
}
}
@@ -179,8 +179,6 @@ public final class IrisModdedChunkGenerator extends ChunkGenerator {
if (level.getChunkSource().getGenerator() != this) {
throw new IllegalArgumentException("ServerLevel does not use Iris generator '" + dimensionKey + "'");
}
requireGlobalStructureGeneration(
level.getServer().getWorldGenSettings().options().generateStructures(), dimensionKey);
Engine replacement = ModdedWorldEngines.prepareReplacement(level, pack, packDimensionKey, seed);
try {
ModdedWorldEngines.installReplacement(level, replacement);
@@ -447,13 +445,6 @@ public final class IrisModdedChunkGenerator extends ChunkGenerator {
private Engine bindEngine(ServerLevel level) {
requireBindingAllowed();
try {
requireGlobalStructureGeneration(
level.getServer().getWorldGenSettings().options().generateStructures(), dimensionKey);
} catch (RuntimeException error) {
engineBinding.fail(error);
throw error;
}
// Cache the owning level so hot paths never scan the level map to find themselves.
boundLevel = level;
Engine cached = engine;
@@ -527,29 +518,6 @@ public final class IrisModdedChunkGenerator extends ChunkGenerator {
}
}
static void requireGlobalStructureGeneration(boolean enabled, String dimensionKey) {
if (enabled) {
return;
}
String remedy = integratedEnvironment()
? "enable 'Generate Structures' for this world; Iris requires it, then deny families through "
+ "importedStructures.disabled or complete keys through importedStructures.disabledExact"
: "set generate-structures=true in server.properties, restart the server, "
+ "then deny families through importedStructures.disabled or complete keys through "
+ "importedStructures.disabledExact";
throw new IllegalStateException("Iris generator '" + dimensionKey
+ "' cannot bind while generate-structures=false; " + remedy);
}
private static boolean integratedEnvironment() {
try {
return ModdedEngineBootstrap.loader().clientEnvironment();
} catch (Throwable e) {
// No loader bound (unit tests, very early boot): assume dedicated wording.
return false;
}
}
Engine engineOrNull() {
requireBindingAllowed();
Engine cached = engine;
@@ -21,6 +21,7 @@ package art.arcane.iris.modded;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.core.modules.ModuleServices;
import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
import art.arcane.iris.engine.mantle.DeferredPlacementRecords;
import art.arcane.iris.engine.framework.NativeStructureLayouts;
import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting;
import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord;
@@ -278,16 +279,6 @@ final class ModdedNativeStructureStage {
}
void placeVanillaStructures(WorldGenLevel world, ChunkAccess chunk, StructureManager structureManager) {
if (!structureManager.shouldGenerateStructures()) {
ChunkPos disabledChunk = chunk.getPos();
throw new IllegalStateException("Iris cannot generate native structures in chunk "
+ disabledChunk.x() + "," + disabledChunk.z()
+ " because generate-structures=false disables them outside the pack. That flag is fixed when "
+ "the world is created (server.properties generate-structures, or the Generate Structures "
+ "toggle in singleplayer), so it cannot be changed for this world: create a new world with "
+ "structures enabled, then deny families through importedStructures.disabled or complete keys "
+ "through importedStructures.disabledExact");
}
ChunkPos chunkPos = chunk.getPos();
SectionPos sectionPos = SectionPos.of(chunkPos, world.getMinSectionY());
BlockPos origin = sectionPos.origin();
@@ -411,7 +402,7 @@ final class ModdedNativeStructureStage {
String structureId, NativePlacement placement) {
Engine current = generator.engine();
int runtimeMinY = world.getMinY();
WorldGenLevel boundedWorld = ModdedNativeStructureWorldgenAccess.create(
ModdedNativeStructureWorldgenAccess boundedWorld = ModdedNativeStructureWorldgenAccess.create(
world, chunkPos,
worldgenSurfaceHeight(current, runtimeMinY),
worldgenFloorHeight(current, runtimeMinY));
@@ -423,6 +414,7 @@ final class ModdedNativeStructureStage {
generator.getSeaLevel(), area.minY(), area.maxY() + 1);
start.placeInChunk(boundedWorld, structureManager, generator, random, area, chunkPos);
} finally {
DeferredPlacementRecords.clearWritten(current, boundedWorld.writtenBlocks());
world.setCurrentlyGenerating(null);
}
}
@@ -1,5 +1,6 @@
package art.arcane.iris.modded;
import art.arcane.iris.engine.mantle.DeferredPlacementRecords.WrittenBlocks;
import art.arcane.iris.nativegen.WorldgenTerrainHeightmaps;
import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
@@ -70,6 +71,7 @@ final class ModdedNativeStructureWorldgenAccess implements WorldGenLevel {
private final LevelTickAccess<Fluid> fluidTicks;
private final Long2LongOpenHashMap terrainHeights;
private final Long2ObjectOpenHashMap<ChunkAccess> outsideChunks;
private final WrittenBlocks writtenBlocks = new WrittenBlocks();
private ModdedNativeStructureWorldgenAccess(WorldGenLevel delegate, Boundary boundary) {
this.delegate = Objects.requireNonNull(delegate, "Native structure world access requires a delegate");
@@ -405,17 +407,28 @@ final class ModdedNativeStructureWorldgenAccess implements WorldGenLevel {
@Override
public boolean setBlock(BlockPos position, BlockState state, int updateFlags, int updateLimit) {
return isWritable(position) && delegate.setBlock(position, state, updateFlags, updateLimit);
return recordWrite(position, isWritable(position) && delegate.setBlock(position, state, updateFlags, updateLimit));
}
@Override
public boolean removeBlock(BlockPos position, boolean move) {
return isWritable(position) && delegate.removeBlock(position, move);
return recordWrite(position, isWritable(position) && delegate.removeBlock(position, move));
}
@Override
public boolean destroyBlock(BlockPos position, boolean drop, Entity source, int updateLimit) {
return isWritable(position) && delegate.destroyBlock(position, drop, source, updateLimit);
return recordWrite(position, isWritable(position) && delegate.destroyBlock(position, drop, source, updateLimit));
}
WrittenBlocks writtenBlocks() {
return writtenBlocks;
}
private boolean recordWrite(BlockPos position, boolean written) {
if (written) {
writtenBlocks.add(position.getX(), position.getY(), position.getZ());
}
return written;
}
@Override
@@ -29,6 +29,7 @@ import art.arcane.iris.modded.ModdedBlockResolution;
import art.arcane.iris.modded.ModdedLootApplier;
import art.arcane.iris.modded.ModdedServerLevels;
import art.arcane.iris.modded.ModdedTileData;
import art.arcane.iris.modded.api.ModdedBlockData;
import art.arcane.iris.modded.api.ModdedCustomContentRegistry;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.util.project.matter.TileWrapper;
@@ -50,6 +51,9 @@ import net.minecraft.world.level.block.EntityBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
@@ -216,10 +220,11 @@ public final class ModdedChunkUpdateService implements ModdedTickableService {
}));
}
private void runCustomPass(Engine engine, ServerLevel level, int chunkX, int chunkZ, MantleChunk<Matter> chunk) {
void runCustomPass(Engine engine, ServerLevel level, int chunkX, int chunkZ, MantleChunk<Matter> chunk) {
int baseX = chunkX << 4;
int baseZ = chunkZ << 4;
int minHeight = engine.getWorld().minHeight();
StaleCarriers stale = new StaleCarriers();
materializeDeferredSlice(chunk, Identifier.class, () ->
chunk.iterate(Identifier.class, (Integer x, Integer yf, Integer z, Identifier identifier) -> {
int y = yf + minHeight;
@@ -227,8 +232,13 @@ public final class ModdedChunkUpdateService implements ModdedTickableService {
return;
}
BlockPos position = new BlockPos(baseX + (x & 15), y, baseZ + (z & 15));
ModdedCustomContentRegistry.processBlockPlacement(engine, level, position, identifier.toString());
String key = identifier.toString();
if (stale.carrierReplaced(key, level.getBlockState(position))) {
return;
}
ModdedCustomContentRegistry.processBlockPlacement(engine, level, position, key);
}));
stale.report(level.dimension().identifier().toString(), chunkX, chunkZ);
}
static void materializeDeferredSlice(MantleChunk<Matter> chunk, Class<?> sliceType, Runnable materializer) {
@@ -374,4 +384,34 @@ public final class ModdedChunkUpdateService implements ModdedTickableService {
level.setBlock(pos, state, Block.UPDATE_ALL);
}
}
private static final class StaleCarriers {
private final Map<String, Optional<Block>> carriers = new HashMap<>();
private int skipped;
private boolean carrierReplaced(String key, BlockState live) {
Optional<Block> carrier = carriers.computeIfAbsent(key, StaleCarriers::carrierBlock);
if (carrier.isEmpty() || carrier.get() == live.getBlock()) {
return false;
}
skipped++;
return true;
}
private void report(String levelName, int chunkX, int chunkZ) {
if (skipped == 0) {
return;
}
IrisLogging.debug("Skipped %d stale custom block records at chunk %d,%d in %s",
skipped, chunkX, chunkZ, levelName);
}
private static Optional<Block> carrierBlock(String key) {
ModdedBlockData resolved = ModdedCustomContentRegistry.resolveBlock(key);
if (resolved == null || resolved.state().isAir()) {
return Optional.empty();
}
return Optional.of(resolved.state().getBlock());
}
}
}
@@ -12,7 +12,6 @@ import java.nio.file.Path;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class NativeStructureFailureContractTest {
@@ -42,18 +41,13 @@ public class NativeStructureFailureContractTest {
}
@Test
public void globalStructureDisableRefusesGeneratorBinding() {
IrisModdedChunkGenerator.requireGlobalStructureGeneration(true, "overworld:overworld");
public void disabledGlobalStructuresNeitherRefuseBindingNorFailPlacement() throws IOException {
String generator = moddedSource("IrisModdedChunkGenerator.java");
String stage = moddedSource("ModdedNativeStructureStage.java");
IllegalStateException error = assertThrows(
IllegalStateException.class,
() -> IrisModdedChunkGenerator.requireGlobalStructureGeneration(
false, "overworld:overworld"));
assertTrue(error.getMessage().contains("overworld:overworld"));
assertTrue(error.getMessage().contains("generate-structures=false"));
assertTrue(error.getMessage().contains("importedStructures.disabled"));
assertTrue(error.getMessage().contains("importedStructures.disabledExact"));
assertFalse(generator.contains("generateStructures()"));
assertFalse(generator.contains("requireGlobalStructureGeneration"));
assertFalse(stage.contains("shouldGenerateStructures()"));
}
@Test
@@ -0,0 +1,210 @@
package art.arcane.iris.modded.service;
import art.arcane.iris.core.link.Identifier;
import art.arcane.iris.engine.IrisEngine;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.object.world.IrisWorld;
import art.arcane.iris.modded.api.ModdedBlockData;
import art.arcane.iris.modded.api.ModdedBlockPlacementContext;
import art.arcane.iris.modded.api.ModdedCustomContentRegistry;
import art.arcane.iris.modded.api.ModdedDataProvider;
import art.arcane.iris.modded.api.ModdedDataType;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.volmlib.util.function.Consumer4;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.mantle.runtime.MantleDataAdapter;
import art.arcane.volmlib.util.mantle.runtime.MantleHooks;
import art.arcane.volmlib.util.matter.Matter;
import net.minecraft.SharedConstants;
import net.minecraft.core.BlockPos;
import net.minecraft.server.Bootstrap;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.NoteBlock;
import net.minecraft.world.level.block.state.BlockState;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.MockedStatic;
import org.mockito.invocation.InvocationOnMock;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.when;
public class ModdedChunkUpdateServiceCarrierTest {
private static final String MOD_ID = "iris_carrier_guard_test";
private static final net.minecraft.resources.Identifier LAMP =
net.minecraft.resources.Identifier.parse(MOD_ID + ":lamp");
private static final net.minecraft.resources.Identifier CHAIR =
net.minecraft.resources.Identifier.parse(MOD_ID + ":chair");
private static final int MIN_HEIGHT = -64;
private static final int RECORD_Y = 70;
private static final List<BlockPos> PLACED = new CopyOnWriteArrayList<>();
@BeforeClass
public static void bootstrapMinecraftRegistries() {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
ModdedCustomContentRegistry.register(new CarrierProvider());
}
@Before
public void clearPlacements() {
PLACED.clear();
}
@Test
public void staleRecordsAreSkippedWhileIntactAndAirCarrierRecordsArePlaced() throws Exception {
RecordMantleChunk chunk = new RecordMantleChunk(List.of(
new Placed(1, LAMP.toString()),
new Placed(2, LAMP.toString()),
new Placed(3, LAMP.toString()),
new Placed(4, CHAIR.toString())));
ServerLevel level = level(Map.of(
1, Blocks.NOTE_BLOCK.defaultBlockState().setValue(NoteBlock.NOTE, 7),
2, Blocks.AIR.defaultBlockState(),
3, Blocks.COBBLESTONE.defaultBlockState(),
4, Blocks.COBBLESTONE.defaultBlockState()));
List<String> debug = new ArrayList<>();
try (MockedStatic<IrisLogging> logging = mockStatic(IrisLogging.class)) {
logging.when(() -> IrisLogging.debug(anyString(), any(Object[].class))).thenAnswer((InvocationOnMock invocation) -> {
Object[] arguments = invocation.getArguments();
debug.add(String.format((String) arguments[0], Arrays.copyOfRange(arguments, 1, arguments.length)));
return null;
});
new ModdedChunkUpdateService().runCustomPass(engine(), level, 0, 0, chunk);
}
assertEquals(List.of(new BlockPos(1, RECORD_Y, 1), new BlockPos(4, RECORD_Y, 4)), PLACED);
assertTrue(chunk.customDeleted());
assertEquals(1, debug.size());
assertTrue(debug.getFirst(), debug.getFirst().contains("2 stale"));
}
private static ServerLevel level(Map<Integer, BlockState> live) {
ServerLevel level = mock(ServerLevel.class);
when(level.getMinY()).thenReturn(MIN_HEIGHT);
when(level.getMaxY()).thenReturn(320);
when(level.dimension()).thenReturn(Level.OVERWORLD);
when(level.getBlockState(any(BlockPos.class))).thenAnswer((InvocationOnMock invocation) -> {
BlockPos position = invocation.getArgument(0);
return live.getOrDefault(position.getX(), Blocks.STONE.defaultBlockState());
});
return level;
}
private static Engine engine() throws Exception {
Field unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
Object unsafe = unsafeField.get(null);
Method allocateInstance = unsafe.getClass().getMethod("allocateInstance", Class.class);
WorldEngine engine = (WorldEngine) allocateInstance.invoke(unsafe, WorldEngine.class);
engine.world = IrisWorld.builder().minHeight(MIN_HEIGHT).build();
return engine;
}
private static final class WorldEngine extends IrisEngine {
private IrisWorld world;
private WorldEngine() {
super(null, InitializationMode.RUNTIME);
}
@Override
public IrisWorld getWorld() {
return world;
}
}
@SuppressWarnings("unchecked")
private static MantleDataAdapter<Matter> emptyAdapter() {
return (MantleDataAdapter<Matter>) Proxy.newProxyInstance(
MantleDataAdapter.class.getClassLoader(),
new Class<?>[]{MantleDataAdapter.class},
(proxy, method, arguments) -> {
throw new UnsupportedOperationException(method.getName());
}
);
}
private record Placed(int offset, String key) {
}
private static final class RecordMantleChunk extends MantleChunk<Matter> {
private final List<Placed> records;
private boolean customDeleted;
private RecordMantleChunk(List<Placed> records) {
super(1, 0, 0, emptyAdapter(), MantleHooks.NONE);
this.records = records;
}
@Override
public <T> void iterate(Class<T> type, Consumer4<Integer, Integer, Integer, T> iterator) {
if (type != Identifier.class) {
return;
}
for (Placed record : records) {
iterator.accept(record.offset(), RECORD_Y - MIN_HEIGHT, record.offset(),
type.cast(Identifier.fromString(record.key())));
}
}
@Override
public void deleteSlices(Class<?> type) {
if (type == Identifier.class) {
customDeleted = true;
}
}
private boolean customDeleted() {
return customDeleted;
}
}
private static final class CarrierProvider implements ModdedDataProvider {
@Override
public String modId() {
return MOD_ID;
}
@Override
public Collection<net.minecraft.resources.Identifier> getTypes(ModdedDataType type) {
return type == ModdedDataType.BLOCK ? List.of(LAMP, CHAIR) : List.of();
}
@Override
public boolean isValidProvider(net.minecraft.resources.Identifier id, ModdedDataType type) {
return type == ModdedDataType.BLOCK && (LAMP.equals(id) || CHAIR.equals(id));
}
@Override
public ModdedBlockData getBlockData(net.minecraft.resources.Identifier blockId, Map<String, String> state) {
BlockState carrier = CHAIR.equals(blockId) ? Blocks.AIR.defaultBlockState() : Blocks.NOTE_BLOCK.defaultBlockState();
return ModdedBlockData.deferred(carrier);
}
@Override
public void processBlockPlacement(ModdedBlockPlacementContext context) {
PLACED.add(context.position());
}
}
}
@@ -200,7 +200,6 @@ public class IrisSettings {
public double targetSpawnEntitiesPerChunk = 0.95;
public boolean markerEntitySpawningSystem = true;
public boolean effectSystem = true;
public boolean worldEditWandCUI = true;
public boolean globalPregenCache = false;
}
@@ -103,6 +103,7 @@ public final class DatapackIngestService {
private static final String TRANSACTION_JOURNAL = "journal.json";
private static final String TRANSACTION_JOURNAL_NEXT = "journal.next.json";
private static final String STARTUP_VALIDATION_CACHE = "startup-validation.json";
private static final String LOCAL_IMPORT_DIRECTORY = "imports";
private static final int OWNERSHIP_SCHEMA = 1;
private static final int TRANSACTION_SCHEMA = 2;
private static final int STARTUP_VALIDATION_SCHEMA = 1;
@@ -159,7 +160,7 @@ public final class DatapackIngestService {
StartupValidationCache cached = readStartupValidationCache(cacheFile);
if (startupValidationContextMatches(
cached, mcVersion, irisVersion, autoIngest, stripOverrides, urls)) {
String localFingerprint = startupValidationFingerprint(root, worldFolders);
String localFingerprint = startupValidationFingerprint(root, worldFolders, urls);
if (startupValidationCacheMatches(
cached,
mcVersion,
@@ -244,7 +245,7 @@ public final class DatapackIngestService {
autoIngest,
stripOverrides,
urls,
startupValidationFingerprint(root, worldFolders));
startupValidationFingerprint(root, worldFolders, urls));
writeStartupValidationCache(cacheFile, cache);
return cache;
} catch (IOException | RuntimeException exception) {
@@ -302,7 +303,7 @@ public final class DatapackIngestService {
validated.autoIngest,
validated.stripOverrides,
validated.urls,
startupValidationFingerprint(root, worldFolders));
startupValidationFingerprint(root, worldFolders, validated.urls));
}
private static StartupValidationCache createStartupValidationCache(
@@ -412,6 +413,14 @@ public final class DatapackIngestService {
}
static String startupValidationFingerprint(File root, KList<File> worldFolders) throws IOException {
return startupValidationFingerprint(root, worldFolders, List.of());
}
static String startupValidationFingerprint(
File root,
KList<File> worldFolders,
Iterable<String> sources
) throws IOException {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
Path manifestPath = new File(root, "manifest.json").toPath();
@@ -457,12 +466,61 @@ public final class DatapackIngestService {
new File(worldFolder, entry.id));
}
}
updateLocalSourceFingerprint(digest, sources);
return hex(digest.digest());
} catch (NoSuchAlgorithmException exception) {
throw new IOException("SHA-256 algorithm unavailable", exception);
}
}
private static void updateLocalSourceFingerprint(
MessageDigest digest,
Iterable<String> sources
) throws IOException {
if (sources == null) {
return;
}
List<String> localSources = new ArrayList<>();
for (String source : sources) {
URI uri = parseSourceUri(source);
if (uri != null && "file".equalsIgnoreCase(uri.getScheme())) {
localSources.add(uri.normalize().toASCIIString());
}
}
localSources.sort(String::compareTo);
byte[] buffer = new byte[HASH_BUFFER_BYTES];
for (String source : localSources) {
Path path = requireLocalDatapackPath(parseSourceUri(source));
updateFingerprintValue(digest, "local-source:" + source);
try (InputStream input = Files.newInputStream(
path,
StandardOpenOption.READ,
LinkOption.NOFOLLOW_LINKS)) {
long bytes = 0;
int length;
while ((length = input.read(buffer)) > 0) {
bytes += length;
if (bytes > MAX_DOWNLOAD_BYTES) {
throw new IOException("Local datapack exceeds " + MAX_DOWNLOAD_BYTES + " bytes: " + path);
}
digest.update(buffer, 0, length);
}
updateDigestLong(digest, bytes);
}
}
}
private static URI parseSourceUri(String source) throws IOException {
if (source == null || source.isBlank()) {
return null;
}
try {
return new URI(source.trim());
} catch (URISyntaxException exception) {
throw new IOException("Invalid datapack URL " + source, exception);
}
}
private static void updateDirectoryFingerprint(
MessageDigest digest,
String identity,
@@ -575,7 +633,7 @@ public final class DatapackIngestService {
private static Report ingestLocked(VolmitSender sender, KList<String> urls, boolean restart) {
Report report = new Report();
if (urls == null || urls.isEmpty()) {
message(sender, C.YELLOW + "No datapackImports configured in any loaded pack. Add Modrinth URLs to a dimension's 'datapackImports' list, then run /iris datapack ingest.");
message(sender, C.YELLOW + "No external datapacks found. Add a Modrinth, HTTP(S) or file URL to a dimension's 'datapackImports', or place a ZIP in Iris/datapacks/imports, then run /iris datapack ingest.");
return report;
}
@@ -677,7 +735,7 @@ public final class DatapackIngestService {
if (report.changed()) {
message(sender, C.YELLOW + "New datapack structures were installed. A server restart is required for them to register and generate.");
message(sender, C.GRAY + "After the restart they generate natively only in Iris dimensions that declare their source URL - no import needed. To get editable Iris copies (jigsaw pools, pieces & objects written into the pack) run /iris structure import <dimension>, or set general.autoImportDatapackStructures=true to do it on every ingest. Place any registered key directly with a 'structures' placement using nativeStructures.");
message(sender, C.GRAY + "After the restart they generate natively in Iris dimensions that declare their source URL; ZIPs from Iris/datapacks/imports are enabled for every Iris dimension. To get editable Iris copies (jigsaw pools, pieces & objects written into the pack) run /iris structure import <dimension>, or set general.autoImportDatapackStructures=true to do it on every ingest. Place any registered key directly with a 'structures' placement using nativeStructures.");
message(sender, C.GRAY + "Datapacks replace matching vanilla structure keys by default. Set 'importedStructures.datapackOverrides' to false to keep minecraft-namespaced structure definitions untouched; deny non-minecraft datapack and mod structure families with importedStructures.disabled or complete keys with importedStructures.disabledExact.");
if (!restart) {
message(sender, C.GRAY + "Run with restart=true to restart now, or restart manually. After restart, run /iris module structure list to see the new keys.");
@@ -1435,15 +1493,74 @@ public final class DatapackIngestService {
}
public static KList<String> collectConfiguredImports() {
LinkedHashSet<String> urls = new LinkedHashSet<>();
LinkedHashSet<String> sources = new LinkedHashSet<>();
try (Stream<IrisData> stream = ServerConfigurator.allPacks()) {
stream.forEach(data -> collectImports(data, urls));
stream.forEach(data -> collectImports(data, sources));
}
sources.addAll(localDatapackImports());
KList<String> result = new KList<>();
result.addAll(urls);
result.addAll(sources);
return result;
}
public static Set<String> configuredImports(IrisDimension dimension) {
Iterable<String> explicit = dimension == null ? List.of() : dimension.getDatapackImports();
return mergeConfiguredImports(explicit, localDatapackImports());
}
static Set<String> mergeConfiguredImports(
Iterable<String> explicit,
Iterable<String> discovered
) {
LinkedHashSet<String> sources = new LinkedHashSet<>();
if (explicit != null) {
addImports(explicit, sources);
}
if (discovered != null) {
addImports(discovered, sources);
}
return sources.isEmpty() ? Set.of() : Set.copyOf(sources);
}
static List<String> discoverLocalDatapackImports(File directory) throws IOException {
Path root = directory.toPath().toAbsolutePath().normalize();
if (Files.notExists(root, LinkOption.NOFOLLOW_LINKS)) {
Files.createDirectories(root);
}
if (Files.isSymbolicLink(root)
|| !Files.isDirectory(root, LinkOption.NOFOLLOW_LINKS)) {
throw new IOException("Local datapack import path is not a safe directory: " + root);
}
try (Stream<Path> stream = Files.list(root)) {
return stream
.filter(path -> !Files.isSymbolicLink(path))
.filter(path -> Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS))
.filter(DatapackIngestService::isLocalDatapackArchive)
.sorted(Comparator.comparing(
(Path path) -> path.getFileName().toString(),
String.CASE_INSENSITIVE_ORDER)
.thenComparing((Path path) -> path.getFileName().toString()))
.map(path -> path.toAbsolutePath().normalize().toUri().toASCIIString())
.toList();
}
}
private static boolean isLocalDatapackArchive(Path path) {
String name = path.getFileName().toString();
return !name.startsWith(".") && name.toLowerCase(Locale.ROOT).endsWith(".zip");
}
private static List<String> localDatapackImports() {
File directory = IrisPlatforms.get().dataFolder("datapacks", LOCAL_IMPORT_DIRECTORY);
try {
return discoverLocalDatapackImports(directory);
} catch (IOException exception) {
IrisLogging.reportError("Could not discover local datapack imports under "
+ directory.getPath() + ".", exception);
return List.of();
}
}
public static List<Entry> installed() {
TRANSACTION_LOCK.lock();
try {
@@ -1884,34 +2001,39 @@ public final class DatapackIngestService {
if (imports == null) {
continue;
}
for (String url : imports) {
if (url != null && !url.isBlank()) {
urls.add(url.trim());
}
addImports(imports, urls);
}
}
private static void addImports(Iterable<String> imports, LinkedHashSet<String> sources) {
for (String source : imports) {
if (source != null && !source.isBlank()) {
sources.add(normalizeConfiguredSource(source));
}
}
}
static String normalizeConfiguredSource(String source) {
String normalized = source.trim();
try {
URI uri = new URI(normalized);
if ("file".equalsIgnoreCase(uri.getScheme())) {
return Path.of(uri).toAbsolutePath().normalize().toUri().toASCIIString();
}
} catch (IllegalArgumentException | URISyntaxException ignored) {
}
return normalized;
}
private static Set<String> configuredImports(IrisData data) {
LinkedHashSet<String> urls = new LinkedHashSet<>();
collectImports(data, urls);
urls.addAll(localDatapackImports());
return urls;
}
private static boolean hasImports(IrisData data) {
if (data.getDimensionLoader() == null) {
return false;
}
for (IrisDimension dimension : data.getDimensionLoader().loadAll(data.getDimensionLoader().getPossibleKeys())) {
if (dimension == null) {
continue;
}
KList<String> imports = dimension.getDatapackImports();
if (imports != null && !imports.isEmpty()) {
return true;
}
}
return false;
return !configuredImports(data).isEmpty();
}
static InstallResult install(File stagedDir, KList<File> worldFolders, Entry entry, boolean stripOverrides) throws IOException {
@@ -3542,11 +3664,12 @@ public final class DatapackIngestService {
}
static DownloadResult download(String url, File dest, String etag, String lastModified) throws IOException {
URI current;
try {
current = new URI(url);
} catch (URISyntaxException e) {
throw new IOException("Invalid datapack URL " + url, e);
URI current = parseSourceUri(url);
if (current == null) {
throw new IOException("Empty datapack URL");
}
if ("file".equalsIgnoreCase(current.getScheme())) {
return copyLocalDatapack(current, dest);
}
for (int attempt = 0; attempt < MAX_REDIRECTS; attempt++) {
if (!"http".equalsIgnoreCase(current.getScheme()) && !"https".equalsIgnoreCase(current.getScheme())) {
@@ -3624,6 +3747,84 @@ public final class DatapackIngestService {
throw new IOException("Too many redirects downloading " + url);
}
private static DownloadResult copyLocalDatapack(URI source, File destination) throws IOException {
Path sourcePath = requireLocalDatapackPath(source);
Path destinationPath = destination.toPath().toAbsolutePath().normalize();
if (Files.exists(destinationPath, LinkOption.NOFOLLOW_LINKS)
&& Files.isSameFile(sourcePath, destinationPath)) {
throw new IOException("Local datapack source and cache destination are the same file: " + sourcePath);
}
Path parent = destinationPath.getParent();
if (parent == null) {
throw new IOException("Local datapack cache destination has no parent: " + destinationPath);
}
ensureScratchDirectory(parent.toFile(), "datapack download cache");
BasicFileAttributes before = Files.readAttributes(
sourcePath,
BasicFileAttributes.class,
LinkOption.NOFOLLOW_LINKS);
Path temporary = Files.createTempFile(parent, destination.getName() + "-", ".part");
try {
long copied = 0;
try (InputStream input = Files.newInputStream(
sourcePath,
StandardOpenOption.READ,
LinkOption.NOFOLLOW_LINKS);
OutputStream output = Files.newOutputStream(temporary)) {
byte[] buffer = new byte[HASH_BUFFER_BYTES];
int length;
while ((length = input.read(buffer)) > 0) {
copied += length;
if (copied > MAX_DOWNLOAD_BYTES) {
throw new IOException("Local datapack exceeds " + MAX_DOWNLOAD_BYTES + " bytes: " + sourcePath);
}
output.write(buffer, 0, length);
}
}
BasicFileAttributes after = Files.readAttributes(
sourcePath,
BasicFileAttributes.class,
LinkOption.NOFOLLOW_LINKS);
if (!after.isRegularFile()
|| before.size() != after.size()
|| !before.lastModifiedTime().equals(after.lastModifiedTime())
|| !Objects.equals(before.fileKey(), after.fileKey())
|| copied != after.size()) {
throw new IOException("Local datapack changed while Iris was copying it: " + sourcePath);
}
move(temporary, destinationPath);
return new DownloadResult(false, null, null);
} finally {
Files.deleteIfExists(temporary);
}
}
private static Path requireLocalDatapackPath(URI source) throws IOException {
if (source == null
|| !"file".equalsIgnoreCase(source.getScheme())
|| source.isOpaque()
|| source.getRawAuthority() != null
|| source.getRawQuery() != null
|| source.getRawFragment() != null) {
throw new IOException("Datapack file URL must be an absolute local file URI without authority, query, or fragment: " + source);
}
Path path;
try {
path = Path.of(source).toAbsolutePath().normalize();
} catch (IllegalArgumentException exception) {
throw new IOException("Invalid local datapack file URL: " + source, exception);
}
if (Files.isSymbolicLink(path)
|| !Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) {
throw new IOException("Local datapack is not a regular non-symbolic-link file: " + path);
}
long size = Files.size(path);
if (size > MAX_DOWNLOAD_BYTES) {
throw new IOException("Local datapack exceeds " + MAX_DOWNLOAD_BYTES + " bytes: " + path);
}
return path;
}
private static String headerOrFallback(HttpURLConnection connection, String name, String fallback) {
String value = connection.getHeaderField(name);
return value == null || value.isBlank() ? fallback : value;
@@ -32,6 +32,7 @@ import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
@@ -42,6 +43,7 @@ public final class ModrinthResolver {
private static final String API = "https://api.modrinth.com/v2";
private static final String USER_AGENT = "VolmitSoftware/Iris (datapack-ingest)";
private static final String DATAPACK_LOADER = "datapack";
private static final String DEFAULT_DIRECT_FILENAME = "datapack.zip";
private static final int MAX_API_RESPONSE_CHARS = 8 * 1024 * 1024;
private ModrinthResolver() {
@@ -228,22 +230,33 @@ public final class ModrinthResolver {
}
private static ResolvedDatapack directResolve(String url) {
String filename = url;
int slash = filename.lastIndexOf('/');
if (slash >= 0) {
filename = filename.substring(slash + 1);
}
int query = filename.indexOf('?');
if (query >= 0) {
filename = filename.substring(0, query);
}
if (filename.isBlank()) {
filename = "datapack.zip";
}
String filename = directFilename(url);
String identity = directIdentity(url);
return new ResolvedDatapack(url, filename, null, "direct-" + identity, "direct", null, true);
}
private static String directFilename(String url) {
try {
URI uri = new URI(url);
if ("file".equalsIgnoreCase(uri.getScheme())) {
Path fileName = Path.of(uri).getFileName();
return fileName == null || fileName.toString().isBlank()
? DEFAULT_DIRECT_FILENAME
: fileName.toString();
}
String path = uri.getPath();
if (path != null && !path.isBlank()) {
int slash = path.lastIndexOf('/');
String fileName = slash >= 0 ? path.substring(slash + 1) : path;
if (!fileName.isBlank()) {
return fileName;
}
}
} catch (IllegalArgumentException | URISyntaxException ignored) {
}
return DEFAULT_DIRECT_FILENAME;
}
static String directIdentity(String url) {
String normalized = url;
try {
@@ -44,7 +44,8 @@ public final class ModuleObjectPlacement {
}
/**
* @param requestedY the height to place at, or a negative value for the placement to sample it
* Places the object at {@code requestedY}, which may be below zero in a dimension that reaches down there.
*
* @param listener hears each of the object's own blocks once the placement is written; null for none
* @param cave the cave the object is placed in, or null outside caves
*/
@@ -52,21 +53,42 @@ public final class ModuleObjectPlacement {
ObjectPlacement config, RNG rng,
BiConsumer<art.arcane.volmlib.util.math.BlockPosition, PlatformBlockState> listener,
CarveResult cave, IrisData data) {
ObjectRun run = cave == null
? ObjectRun.of(object, config, x, requestedY, z)
: ObjectRun.inCave(object, config, x, requestedY, z, caveOf(cave));
return place(run, placer, config, rng, listener, data);
}
/** As {@link #place}, at the height the placement samples from the terrain, or from {@code cave}. */
public static ObjectPlacementResult placeAutomatic(IrisObject object, int x, int z, IObjectPlacer placer,
ObjectPlacement config, RNG rng,
BiConsumer<art.arcane.volmlib.util.math.BlockPosition, PlatformBlockState> listener,
CarveResult cave, IrisData data) {
ObjectRun run = cave == null
? ObjectRun.automatic(object, config, x, z)
: ObjectRun.automaticInCave(object, config, x, z, caveOf(cave));
return place(run, placer, config, rng, listener, data);
}
private static ObjectRun.Cave caveOf(CarveResult cave) {
return new ObjectRun.Cave(cave.getSurface(), cave.getHeight());
}
private static ObjectPlacementResult place(ObjectRun run, IObjectPlacer placer, ObjectPlacement config, RNG rng,
BiConsumer<art.arcane.volmlib.util.math.BlockPosition, PlatformBlockState> listener,
IrisData data) {
Objects.requireNonNull(placer, "Object placer is required.");
Objects.requireNonNull(config, "Object placement config is required.");
Objects.requireNonNull(rng, "Object placement RNG is required.");
Objects.requireNonNull(data, "Object placement data is required.");
PlacerTerrain terrain = listener == null ? PlacerTerrain.of(placer, data) : PlacerTerrain.rememberingWrites(placer, data);
ObjectRun run = cave == null
? ObjectRun.of(object, config, x, requestedY, z)
: ObjectRun.inCave(object, config, x, requestedY, z, new ObjectRun.Cave(cave.getSurface(), cave.getHeight()));
PlacementOutcome outcome = placeIn(run, terrain, placer.getEngine(), rng, data);
if (!outcome.isPlaced()) {
return ObjectPlacementResult.rejected(outcome.rejection().orElseThrow());
}
reportObjectBlocks(run, terrain, listener);
int anchorY = run.anchorY().orElseThrow(() -> new IllegalStateException(
"The placement graph placed " + object.name() + " without anchoring it"));
"The placement graph placed " + run.object().name() + " without anchoring it"));
return ObjectPlacementResult.placed(anchorY);
}
@@ -0,0 +1,114 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.engine.mantle;
import art.arcane.iris.core.link.Identifier;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.util.project.matter.TileWrapper;
import art.arcane.volmlib.util.mantle.runtime.Mantle;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.matter.Matter;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
/**
* Drops the deferred custom-block and tile records that a native structure write has overwritten, so the
* chunk's later materialization pass does not replay them onto the structure's blocks.
*/
public final class DeferredPlacementRecords {
private DeferredPlacementRecords() {
}
public static void clearWritten(Engine engine, WrittenBlocks written) {
if (written.isEmpty()) {
return;
}
Mantle<Matter> mantle = engine.getMantle().getMantle();
int minHeight = engine.getMinHeight();
Long2ObjectOpenHashMap<MantleChunk<Matter>> acquired = new Long2ObjectOpenHashMap<>();
try {
for (int index = 0; index < written.size(); index++) {
int x = written.x(index);
int z = written.z(index);
MantleChunk<Matter> chunk = acquired.computeIfAbsent(chunkKey(x >> 4, z >> 4),
key -> mantle.getChunk(x >> 4, z >> 4).use());
synchronized (chunk) {
clearRecords(chunk, x & 15, written.y(index) - minHeight, z & 15);
}
}
} finally {
acquired.values().forEach(MantleChunk::release);
}
}
private static long chunkKey(int chunkX, int chunkZ) {
return ((long) chunkX << 32) | (chunkZ & 0xFFFFFFFFL);
}
private static void clearRecords(MantleChunk<Matter> chunk, int x, int y, int z) {
if (y < 0 || (y >> 4) >= chunk.sectionCount() || !chunk.exists(y >> 4)) {
return;
}
Matter section = chunk.get(y >> 4);
if (section == null) {
return;
}
clearRecord(section, Identifier.class, x, y & 15, z);
clearRecord(section, TileWrapper.class, x, y & 15, z);
}
private static void clearRecord(Matter section, Class<?> type, int x, int y, int z) {
if (section.hasSlice(type)) {
section.getSlice(type).set(x, y, z, null);
}
}
/** World positions a native structure wrote, in write order, duplicates allowed. */
public static final class WrittenBlocks {
private final IntArrayList xs = new IntArrayList();
private final IntArrayList ys = new IntArrayList();
private final IntArrayList zs = new IntArrayList();
public void add(int x, int y, int z) {
xs.add(x);
ys.add(y);
zs.add(z);
}
public boolean isEmpty() {
return xs.isEmpty();
}
int size() {
return xs.size();
}
int x(int index) {
return xs.getInt(index);
}
int y(int index) {
return ys.getInt(index);
}
int z(int index) {
return zs.getInt(index);
}
}
}
@@ -25,6 +25,7 @@ import art.arcane.iris.builtin.objects.ObjectPlacement;
import art.arcane.iris.builtin.prepare.ObjectRotation;
import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.core.modules.ModuleObjectPlacement;
import art.arcane.iris.core.modules.ObjectPlacementResult;
import art.arcane.iris.engine.object.prefab.ObjectTurn;
import art.arcane.volmlib.util.cache.CacheKey;
import art.arcane.iris.engine.framework.IrisStructureLocator;
@@ -60,6 +61,7 @@ import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.MatterCavern;
import art.arcane.volmlib.util.matter.MatterStructurePOI;
import art.arcane.volmlib.util.math.BlockPosition;
import art.arcane.volmlib.util.math.RNG;
import it.unimi.dsi.fastutil.longs.Long2IntMap;
import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
@@ -68,6 +70,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
/**
* Places the Iris structures of the dimension, its regions and biomes into the mantle for
@@ -149,26 +152,26 @@ public class StructurePlacing {
ObjectPlaceMode undergroundMode = mode.placeMode().has(PlaceTrait.CAVE_ANCHORED)
? mode : ObjectPlaceMode.STRUCTURE_PIECE;
for (PlacedStructurePiece p : pieces) {
if (placeObject(writer, structure, p, undergroundMode, p.getY(), rng,
if (placeObject(writer, structure, p, undergroundMode, false, rng,
foundationColumns, supportNonOccluding) == -1) {
failedPieces++;
}
}
} else if (mode.placeMode().has(PlaceTrait.FREE_HEIGHT)) {
for (PlacedStructurePiece p : pieces) {
if (placeObject(writer, structure, p, ObjectPlaceMode.STRUCTURE_PIECE, p.getY(), rng,
if (placeObject(writer, structure, p, ObjectPlaceMode.STRUCTURE_PIECE, false, rng,
foundationColumns, supportNonOccluding) == -1) {
failedPieces++;
}
}
} else if (pieces.size() == 1) {
if (placeObject(writer, structure, pieces.getFirst(), mode, -1, rng,
if (placeObject(writer, structure, pieces.getFirst(), mode, true, rng,
foundationColumns, supportNonOccluding) == -1) {
failedPieces++;
}
} else {
for (PlacedStructurePiece p : pieces) {
if (placeObject(writer, structure, p, ObjectPlaceMode.STRUCTURE_PIECE, p.getY(), rng,
if (placeObject(writer, structure, p, ObjectPlaceMode.STRUCTURE_PIECE, false, rng,
foundationColumns, supportNonOccluding) == -1) {
failedPieces++;
}
@@ -561,7 +564,7 @@ public class StructurePlacing {
}
private int placeObject(MantleWriter writer, IrisStructure structure, PlacedStructurePiece p,
ObjectPlaceMode mode, int y, RNG rng, Long2IntOpenHashMap foundationColumns,
ObjectPlaceMode mode, boolean sampledHeight, RNG rng, Long2IntOpenHashMap foundationColumns,
boolean supportNonOccluding) {
IrisObject object = p.getObject();
String objectKey = object.getLoadKey();
@@ -573,16 +576,20 @@ public class StructurePlacing {
builder.forcePlace(true);
}
ObjectPlacement config = builder.build();
int placeY = (y == -1) ? -1 : y - engine.getMinHeight();
String marker = structurePlacementMarker(structure, p, objectKey);
return ModuleObjectPlacement.place(object, p.getX(), placeY, p.getZ(), writer, config, rng, (position, state) -> {
BiConsumer<BlockPosition, PlatformBlockState> listener = (position, state) -> {
StructureFoundationPlanner.recordBaseCell(
foundationColumns, position.getX(), position.getY(), position.getZ(), state,
supportNonOccluding);
if (marker != null && shouldWriteStructureMarker(state)) {
writer.setData(position.getX(), position.getY(), position.getZ(), marker);
}
}, null, engine.getData()).heightOrRejected();
};
ObjectPlacementResult result = sampledHeight
? ModuleObjectPlacement.placeAutomatic(object, p.getX(), p.getZ(), writer, config, rng, listener, null, engine.getData())
: ModuleObjectPlacement.place(object, p.getX(), p.getY() - engine.getMinHeight(), p.getZ(), writer, config, rng,
listener, null, engine.getData());
return result.heightOrRejected();
}
/** The placement rotation that turns a placed piece the way {@code turn} does. */
@@ -135,17 +135,22 @@ public class IrisObject extends IrisRegistrant implements PlaceableObject {
return aabb.aquire(() -> getAABBFor(new IrisBlockVector(w, h, d)));
}
public synchronized IrisObject copy() {
IrisObject o = new IrisObject(w, h, d);
o.setLoadKey(getLoadKey());
o.setLoader(getLoader());
o.setLoadFile(getLoadFile());
o.setCenter(getCenter().clone());
public IrisObject copy() {
readLock.lock();
try {
IrisObject o = new IrisObject(w, h, d);
o.setLoadKey(getLoadKey());
o.setLoader(getLoader());
o.setLoadFile(getLoadFile());
o.setCenter(getCenter().clone());
blocks.forEach((i, v) -> o.blocks.put(i.clone(), v));
states.forEach((i, v) -> o.states.put(i.clone(), v.clone()));
blocks.forEach((i, v) -> o.blocks.put(i.clone(), v));
states.forEach((i, v) -> o.states.put(i.clone(), v.clone()));
return o;
return o;
} finally {
readLock.unlock();
}
}
public void readLegacy(InputStream in) throws IOException {
@@ -30,7 +30,9 @@ import art.arcane.iris.util.project.interpolation.Interpolation3D;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Geometric transforms for {@link IrisObject}: rotation, scaling and the interpolated upscalers.
@@ -50,14 +52,23 @@ final class IrisObjectTransforms {
try {
VectorMap<PlatformBlockState> d = new VectorMap<>();
Set<IrisBlockVector> omitted = new HashSet<>();
for (var entry : self.blocks) {
d.put(turn.rotate(entry.getKey()), BlockStateRotation.rotate(turn, entry.getValue()));
PlatformBlockState rotated = BlockStateRotation.rotate(turn, entry.getValue());
if (rotated == null) {
omitted.add(entry.getKey());
continue;
}
d.put(turn.rotate(entry.getKey()), rotated);
}
VectorMap<TileData> dx = new VectorMap<>();
for (var entry : self.states) {
dx.put(turn.rotate(entry.getKey()), entry.getValue());
if (!omitted.contains(entry.getKey())) {
dx.put(turn.rotate(entry.getKey()), entry.getValue());
}
}
self.blocks = d;
@@ -79,28 +90,27 @@ final class IrisObjectTransforms {
scale = scale - 0.0001;
}
IrisPosition l1 = self.getAABB().max();
IrisPosition l2 = self.getAABB().min();
VectorMap<PlatformBlockState> placeBlock = new VectorMap<>();
IrisVector center = new IrisVector(self.getCenter().getX(), self.getCenter().getY(), self.getCenter().getZ());
if (self.getH() == 2) {
center = center.setY(center.getBlockY() + 0.5);
}
if (self.getW() == 2) {
center = center.setX(center.getBlockX() + 0.5);
}
if (self.getD() == 2) {
center = center.setZ(center.getBlockZ() + 0.5);
}
IrisObject oo = new IrisObject((int) Math.ceil((self.w * scale) + (scale * 2)), (int) Math.ceil((self.h * scale) + (scale * 2)), (int) Math.ceil((self.d * scale) + (scale * 2)));
oo.setLoadKey(self.getLoadKey());
oo.setLoader(self.getLoader());
oo.setLoadFile(self.getLoadFile());
IrisVector center;
IrisObject oo;
self.readLock.lock();
try {
center = new IrisVector(self.getCenter().getX(), self.getCenter().getY(), self.getCenter().getZ());
if (self.getH() == 2) {
center = center.setY(center.getBlockY() + 0.5);
}
if (self.getW() == 2) {
center = center.setX(center.getBlockX() + 0.5);
}
if (self.getD() == 2) {
center = center.setZ(center.getBlockZ() + 0.5);
}
oo = new IrisObject((int) Math.ceil((self.w * scale) + (scale * 2)), (int) Math.ceil((self.h * scale) + (scale * 2)), (int) Math.ceil((self.d * scale) + (scale * 2)));
oo.setLoadKey(self.getLoadKey());
oo.setLoader(self.getLoader());
oo.setLoadFile(self.getLoadFile());
for (var entry : self.blocks) {
PlatformBlockState bd = entry.getValue();
placeBlock.put(entry.getKey().clone().add(IrisObject.HALF).subtract(center)
@@ -209,7 +209,7 @@ public class IrisDimension extends IrisRegistrant {
@Desc("Overlay additional noise on top of the interoplated terrain.")
private KList<IrisShapedGeneratorStyle> overlayNoise = new KList<>();
@ArrayType(type = String.class, min = 1)
@Desc("External datapack sources owned by this dimension. Bukkit registers their resources server-wide, but Iris excludes their structure sets and definitions from generation and locate state in vanilla worlds and Iris dimensions that do not declare the same source. Editable auto-import is limited to resources supplied by the URLs declared by each Iris pack. Any registered datapack structure can be placed directly through nativeStructures without conversion. Replacing native generation requires a dimension-level structure placement with nativeSuppression set to REPLACE_SOURCE; provenance alone never disables native structures.")
@Desc("External Modrinth, HTTP(S) or file URL datapack sources owned by this dimension. Bukkit registers their resources server-wide, but Iris excludes their structure sets and definitions from generation and locate state in vanilla worlds and Iris dimensions that do not declare the same source. Local ZIPs under Iris/datapacks/imports are discovered automatically and enabled for every Iris dimension. Editable auto-import is limited to resources supplied by configured or discovered sources. Any registered datapack structure can be placed directly through nativeStructures without conversion. Replacing native generation requires a dimension-level structure placement with nativeSuppression set to REPLACE_SOURCE; provenance alone never disables native structures.")
private KList<String> datapackImports = new KList<>();
@RegistryListFunction(ComponentFlagFunction.class)
@ArrayType(type = String.class)
@@ -33,6 +33,7 @@ import art.arcane.iris.engine.framework.WrongEngineBroException;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.engine.object.prefab.TileData;
import art.arcane.iris.util.common.data.IrisCustomData;
import art.arcane.iris.platform.bukkit.BukkitBlockResolution;
import art.arcane.iris.platform.bukkit.BukkitBlockState;
import art.arcane.iris.spi.IrisLogging;
@@ -80,7 +81,9 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.loot.Lootable;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CancellationException;
@@ -194,12 +197,16 @@ public final class EngineBukkitOps {
}
static void materializeTiles(Engine engine, Chunk chunk, MantleChunk<Matter> mantleChunk) {
StaleRecords stale = new StaleRecords();
mantleChunk.iterate(TileWrapper.class, (x, y, z, value) -> {
int worldY = y + engine.getWorld().minHeight();
if (worldY < chunk.getWorld().getMinHeight() || worldY >= chunk.getWorld().getMaxHeight()) {
return;
}
Block block = chunk.getBlock(x & 15, worldY, z & 15);
if (stale.tileReplaced(block, value.getData())) {
return;
}
if (!TileData.setTileState(block, value.getData())) {
NamespacedKey blockTypeKey = KeyedType.getKey(block.getType());
String blockType = blockTypeKey == null ? block.getType().name() : blockTypeKey.toString();
@@ -208,21 +215,25 @@ public final class EngineBukkitOps {
}
});
mantleChunk.deleteSlices(TileWrapper.class);
stale.report("tile", chunk);
}
static void materializeCustomBlocks(Engine engine, Chunk chunk, MantleChunk<Matter> mantleChunk) {
StaleRecords stale = new StaleRecords();
mantleChunk.iterate(Identifier.class, (x, y, z, value) -> {
int worldY = y + engine.getWorld().minHeight();
if (worldY < chunk.getWorld().getMinHeight() || worldY >= chunk.getWorld().getMaxHeight()) {
return;
}
IrisServices.get(ExternalDataSVC.class).processUpdate(
engine,
chunk.getBlock(x & 15, worldY, z & 15),
value
);
ExternalDataSVC service = IrisServices.get(ExternalDataSVC.class);
Block block = chunk.getBlock(x & 15, worldY, z & 15);
if (stale.carrierReplaced(service, block, value)) {
return;
}
service.processUpdate(engine, block, value);
});
mantleChunk.deleteSlices(Identifier.class);
stale.report("custom block", chunk);
}
static void runMaterializationPasses(
@@ -693,4 +704,44 @@ public final class EngineBukkitOps {
record LootMutationTask(World world, int chunkX, int chunkZ, Runnable mutation) {
}
private static final class StaleRecords {
private final Map<Identifier, Material> carriers = new HashMap<>();
private int skipped;
private boolean carrierReplaced(ExternalDataSVC service, Block block, Identifier record) {
Material carrier = carriers.computeIfAbsent(record, key -> carrierType(service, key));
if (carrier == Material.AIR || block.getType() == carrier) {
return false;
}
skipped++;
return true;
}
private boolean tileReplaced(Block block, TileData tile) {
if (tile.resolveMaterial() == null || tile.isApplicable(block.getBlockData())) {
return false;
}
skipped++;
return true;
}
private void report(String records, Chunk chunk) {
if (skipped == 0) {
return;
}
IrisLogging.debug("Skipped %d stale %s records at chunk %d,%d in %s",
skipped, records, chunk.getX(), chunk.getZ(), chunk.getWorld().getName());
}
private static Material carrierType(ExternalDataSVC service, Identifier record) {
Optional<BlockData> resolved = service.getBlockData(record);
if (resolved.isEmpty()) {
return Material.AIR;
}
BlockData data = resolved.get();
Material type = (data instanceof IrisCustomData custom ? custom.getBase() : data).getMaterial();
return type == Material.CAVE_AIR || type == Material.VOID_AIR ? Material.AIR : type;
}
}
}
@@ -357,6 +357,111 @@ public class DatapackIngestServiceTest {
}
}
@Test
public void downloadCopiesLocalFileUrl() throws Exception {
Path source = temporaryFolder.newFile("local source.zip").toPath();
Files.writeString(source, "local-archive", StandardCharsets.UTF_8);
File destination = new File(temporaryFolder.newFolder("local-download"), "pack.zip");
DatapackIngestService.DownloadResult result = DatapackIngestService.download(
source.toUri().toASCIIString(),
destination,
null,
null
);
assertFalse(result.notModified());
assertEquals("local-archive", Files.readString(destination.toPath(), StandardCharsets.UTF_8));
}
@Test
public void failedLocalDownloadPreservesExistingDestination() throws Exception {
Path missing = temporaryFolder.getRoot().toPath().resolve("missing.zip");
File destination = new File(temporaryFolder.newFolder("local-download-existing"), "pack.zip");
Files.writeString(destination.toPath(), "existing", StandardCharsets.UTF_8);
try {
DatapackIngestService.download(
missing.toUri().toASCIIString(),
destination,
null,
null
);
fail("Expected missing local source rejection");
} catch (IOException expected) {
assertTrue(expected.getMessage().contains("regular non-symbolic-link file"));
}
assertEquals("existing", Files.readString(destination.toPath(), StandardCharsets.UTF_8));
}
@Test
public void localDropFolderDiscoversOnlyTopLevelZipFilesInStableOrder() throws Exception {
File imports = temporaryFolder.newFolder("local-imports");
Path first = new File(imports, "Alpha Pack.ZIP").toPath();
Path second = new File(imports, "bravo.zip").toPath();
Files.writeString(first, "alpha", StandardCharsets.UTF_8);
Files.writeString(second, "bravo", StandardCharsets.UTF_8);
Files.writeString(new File(imports, "ignored.txt").toPath(), "ignored", StandardCharsets.UTF_8);
Path nested = new File(imports, "nested/hidden.zip").toPath();
Files.createDirectories(nested.getParent());
Files.writeString(nested, "nested", StandardCharsets.UTF_8);
List<String> discovered = DatapackIngestService.discoverLocalDatapackImports(imports);
assertEquals(List.of(
first.toAbsolutePath().normalize().toUri().toASCIIString(),
second.toAbsolutePath().normalize().toUri().toASCIIString()
), discovered);
}
@Test
public void localDropFolderSkipsSymbolicLinkArchives() throws Exception {
File imports = temporaryFolder.newFolder("local-imports-links");
Path real = temporaryFolder.newFile("linked-target.zip").toPath();
Path link = new File(imports, "linked.zip").toPath();
try {
Files.createSymbolicLink(link, real);
} catch (UnsupportedOperationException | IOException unsupported) {
return;
}
assertTrue(DatapackIngestService.discoverLocalDatapackImports(imports).isEmpty());
}
@Test
public void configuredFileSourceNormalizesToTheDiscoveredArchiveUri() throws Exception {
Path source = temporaryFolder.newFile("normalized-local.zip").toPath();
String discovered = source.toAbsolutePath().normalize().toUri().toASCIIString();
String alternate = discovered.replace("file:///", "file:/");
assertEquals(discovered, DatapackIngestService.normalizeConfiguredSource(alternate));
assertEquals(
Set.of("https://example.test/dimension.zip", discovered),
DatapackIngestService.mergeConfiguredImports(
List.of("https://example.test/dimension.zip", alternate),
List.of(discovered)));
}
@Test
public void startupValidationFingerprintChangesWithLocalSourceBytes() throws Exception {
File root = temporaryFolder.newFolder("startup-local-source-fingerprint");
Path source = temporaryFolder.newFile("startup-local.zip").toPath();
KList<File> worldFolders = new KList<>();
String sourceUrl = source.toUri().toASCIIString();
Files.writeString(source, "alpha", StandardCharsets.UTF_8);
String before = DatapackIngestService.startupValidationFingerprint(
root, worldFolders, List.of(sourceUrl));
FileTime originalTime = Files.getLastModifiedTime(source);
Files.writeString(source, "bravo", StandardCharsets.UTF_8);
Files.setLastModifiedTime(source, originalTime);
String after = DatapackIngestService.startupValidationFingerprint(
root, worldFolders, List.of(sourceUrl));
assertFalse(before.equals(after));
}
@Test
public void removalRequiresMatchingIrisOwnership() throws Exception {
File unmanaged = datapackDirectory("unmanaged");
@@ -8,6 +8,9 @@ import org.junit.Test;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
@@ -104,6 +107,25 @@ public class ModrinthResolverTest {
assertFalse(resolved.getVersionId().isBlank());
}
@Test
public void fileUrlResolvesAsDirectArchiveWithDecodedFilename() throws Exception {
Path directory = Files.createTempDirectory("iris-local-resolver");
Path archive = directory.resolve("local pack.zip");
try {
Files.writeString(archive, "archive", StandardCharsets.UTF_8);
ModrinthResolver.ResolvedDatapack resolved = ModrinthResolver.resolve(
archive.toUri().toASCIIString(), "26.2");
assertTrue(resolved.isDirect());
assertEquals("local pack.zip", resolved.getFileName());
assertFalse(resolved.getVersionId().isBlank());
} finally {
Files.deleteIfExists(archive);
Files.deleteIfExists(directory);
}
}
@Test
public void boundedApiReaderAcceptsTheExactCharacterLimit() throws Exception {
String response = "1234\n5678";
@@ -0,0 +1,137 @@
package art.arcane.iris.engine.mantle;
import art.arcane.iris.core.link.Identifier;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.mantle.DeferredPlacementRecords.WrittenBlocks;
import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.spi.PlatformRegistries;
import art.arcane.iris.util.project.matter.TileWrapper;
import art.arcane.volmlib.util.mantle.runtime.Mantle;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.MatterSlice;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
public class DeferredPlacementRecordsTest {
private static final int MIN_HEIGHT = -64;
private static final int SECTION_COUNT = 24;
private Engine engine;
private Mantle<Matter> mantle;
private MantleChunk<Matter> chunk;
private Matter section;
private MatterSlice<Identifier> identifiers;
private MatterSlice<TileWrapper> tiles;
@After
public void tearDown() {
IrisPlatforms.unbind();
}
@Before
@SuppressWarnings("unchecked")
public void setUp() {
IrisPlatforms.unbind();
PlatformRegistries registries = mock(PlatformRegistries.class);
IrisPlatform platform = mock(IrisPlatform.class);
when(registries.block(anyString())).thenReturn(mock(PlatformBlockState.class));
when(platform.registries()).thenReturn(registries);
IrisPlatforms.bind(platform);
engine = mock(Engine.class);
EngineMantle engineMantle = mock(EngineMantle.class);
mantle = mock(Mantle.class);
chunk = mock(MantleChunk.class);
section = mock(Matter.class);
identifiers = mock(MatterSlice.class);
tiles = mock(MatterSlice.class);
when(engine.getMantle()).thenReturn(engineMantle);
when(engine.getMinHeight()).thenReturn(MIN_HEIGHT);
when(engineMantle.getMantle()).thenReturn(mantle);
when(mantle.getChunk(anyInt(), anyInt())).thenReturn(chunk);
when(chunk.use()).thenReturn(chunk);
when(chunk.sectionCount()).thenReturn(SECTION_COUNT);
when(chunk.exists(anyInt())).thenReturn(true);
when(chunk.get(anyInt())).thenReturn(section);
when(section.hasSlice(Identifier.class)).thenReturn(true);
when(section.hasSlice(TileWrapper.class)).thenReturn(true);
when(section.getSlice(Identifier.class)).thenReturn(identifiers);
when(section.getSlice(TileWrapper.class)).thenReturn(tiles);
}
@Test
public void writtenPositionsLoseTheirCustomAndTileRecords() {
WrittenBlocks written = new WrittenBlocks();
written.add(19, 70, 5);
DeferredPlacementRecords.clearWritten(engine, written);
int mantleY = 70 - MIN_HEIGHT;
verify(chunk).get(mantleY >> 4);
verify(identifiers).set(3, mantleY & 15, 5, null);
verify(tiles).set(3, mantleY & 15, 5, null);
verify(mantle).getChunk(1, 0);
verify(chunk).release();
}
@Test
public void eachTouchedChunkIsAcquiredOnceAndReleasedOnce() {
WrittenBlocks written = new WrittenBlocks();
written.add(1, 70, 1);
written.add(2, 71, 2);
written.add(-1, 70, 1);
DeferredPlacementRecords.clearWritten(engine, written);
verify(mantle).getChunk(0, 0);
verify(mantle).getChunk(-1, 0);
verify(chunk, times(2)).release();
}
@Test
public void positionsBelowTheWorldOrInMissingSectionsAreIgnored() {
when(chunk.exists(anyInt())).thenReturn(false);
WrittenBlocks written = new WrittenBlocks();
written.add(1, MIN_HEIGHT - 1, 1);
written.add(1, 70, 1);
DeferredPlacementRecords.clearWritten(engine, written);
verify(identifiers, never()).set(anyInt(), anyInt(), anyInt(), any());
verify(tiles, never()).set(anyInt(), anyInt(), anyInt(), any());
}
@Test
public void slicesThatWereNeverCreatedAreNotCreatedByClearing() {
when(section.hasSlice(Identifier.class)).thenReturn(false);
WrittenBlocks written = new WrittenBlocks();
written.add(1, 70, 1);
DeferredPlacementRecords.clearWritten(engine, written);
verify(section, never()).getSlice(Identifier.class);
verify(tiles).set(1, (70 - MIN_HEIGHT) & 15, 1, null);
}
@Test
public void noWritesLeaveTheMantleUntouched() {
DeferredPlacementRecords.clearWritten(engine, new WrittenBlocks());
verifyNoInteractions(mantle);
}
}
@@ -60,6 +60,18 @@ public class PlacementReachTest {
assertEquals(53, PlacementReach.of(new ObjectSize(5, 48, 7), placement));
}
@Test
public void slopeTiltReachesAsFarAsAVerticalRotationEvenWhenTheRotationIsDisabled() {
String disabledRotation = "\"rotation\":{\"enabled\":false}";
ObjectPlacement flat = TestSettings.of(ObjectPlacement.class, "{" + disabledRotation + ",\"translate\":{\"x\":3,\"y\":4}}");
ObjectPlacement tilted = TestSettings.of(ObjectPlacement.class,
"{" + disabledRotation + ",\"rotateTowardsSlope\":true,\"translate\":{\"x\":3,\"y\":4}}");
ObjectSize tallObject = new ObjectSize(5, 48, 7);
assertEquals(10, PlacementReach.of(tallObject, flat));
assertEquals(53, PlacementReach.of(tallObject, tilted));
}
@Test
public void scaleWarpAndVacuumExpandPlacementReach() {
ObjectPlacement placement = TestSettings.of(ObjectPlacement.class,
@@ -1,5 +1,6 @@
package art.arcane.iris.engine.object.placement;
import com.volmit.block.BlockState;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
@@ -18,6 +19,16 @@ public class IrisObjectStructurePieceAirTest {
assertTrue(BlocksModule.shouldPlaceObjectBlock(false, false, false));
}
@Test
public void aBlockTurnedIntoAirHadNoValidOrientationAndIsDropped() {
BlockState torch = new BlockState("minecraft:wall_torch");
BlockState air = new BlockState("minecraft:air");
assertTrue(BlocksModule.isDroppedByRotation(torch, air));
assertFalse(BlocksModule.isDroppedByRotation(torch, torch));
assertFalse(BlocksModule.isDroppedByRotation(air, air));
}
@Test
public void vineReplacementRemainsRejectedForEveryPlacementMode() {
assertFalse(BlocksModule.shouldPlaceObjectBlock(false, false, true));
@@ -110,7 +110,7 @@ public class IrisObjectSurfaceSupportPlacementTest {
placer.carve(0, SURFACE_Y, 0);
assertEquals("mode " + mode + " must skip over a carved column",
-1, place(placer, placement(mode), -1));
-1, placeAutomatic(placer, placement(mode)));
assertTrue("mode " + mode + " must not write blocks", placer.written().isEmpty());
}
}
@@ -120,7 +120,7 @@ public class IrisObjectSurfaceSupportPlacementTest {
SurfacePlacer placer = new SurfacePlacer();
placer.carve(2, SURFACE_Y, 0);
assertEquals(-1, place(placer, placement(ObjectPlaceMode.CENTER_HEIGHT), -1));
assertEquals(-1, placeAutomatic(placer, placement(ObjectPlaceMode.CENTER_HEIGHT)));
}
@Test
@@ -128,14 +128,14 @@ public class IrisObjectSurfaceSupportPlacementTest {
SurfacePlacer placer = new SurfacePlacer();
placer.carve(6, SURFACE_Y, 0);
assertTrue(place(placer, placement(ObjectPlaceMode.CENTER_HEIGHT), -1) >= 0);
assertTrue(placeAutomatic(placer, placement(ObjectPlaceMode.CENTER_HEIGHT)) >= 0);
}
@Test
public void solidGroundStillPlaces() {
SurfacePlacer placer = new SurfacePlacer();
assertTrue(place(placer, placement(ObjectPlaceMode.CENTER_HEIGHT), -1) >= 0);
assertTrue(placeAutomatic(placer, placement(ObjectPlaceMode.CENTER_HEIGHT)) >= 0);
}
@Test
@@ -153,7 +153,7 @@ public class IrisObjectSurfaceSupportPlacementTest {
ObjectPlacement.Builder placement = placement(ObjectPlaceMode.CENTER_HEIGHT);
placement.forcePlace(true);
assertTrue(place(placer, placement, -1) >= 0);
assertTrue(placeAutomatic(placer, placement) >= 0);
}
@Test
@@ -163,7 +163,7 @@ public class IrisObjectSurfaceSupportPlacementTest {
ObjectPlacement.Builder placement = placement(ObjectPlaceMode.CENTER_HEIGHT);
placement.requireSurfaceSupport(false);
assertTrue(place(placer, placement, -1) >= 0);
assertTrue(placeAutomatic(placer, placement) >= 0);
}
@Test
@@ -248,7 +248,11 @@ public class IrisObjectSurfaceSupportPlacementTest {
ObjectPlacement.Builder placement = placement(ObjectPlaceMode.FLOATING);
placement.translate(ObjectTranslate.of(0, SURFACE_Y + 40, 0, 0));
assertTrue(place(placer, placement, -1) >= 0);
assertTrue(placeAutomatic(placer, placement) >= 0);
}
private int placeAutomatic(SurfacePlacer placer, ObjectPlacement.Builder placement) {
return ModuleObjectPlacement.placeAutomatic(object(), 0, 0, placer, placement.build(), new RNG(1234L), null, null, data).heightOrRejected();
}
private int place(SurfacePlacer placer, ObjectPlacement.Builder placement, int anchorY) {
@@ -33,6 +33,7 @@ import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.OptionalInt;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.anyString;
@@ -108,9 +109,14 @@ public class ObjectPlaceModePinTest {
.translate(ObjectTranslate.of(0, mode == ObjectPlaceMode.FLOATING ? 140 : 2, 0, 0))
.build();
CarveResult cave = isCaveMode(mode) ? new CarveResult(CAVE_FLOOR_Y, CEILING_Y) : null;
int requestedY = requestedY(mode);
ModuleObjectPlacement.place(pinnedObject(), OBJECT_X, requestedY, OBJECT_Z, placer, config,
new RNG(PLACEMENT_SEED), null, cave, data);
OptionalInt requestedY = requestedY(mode);
if (requestedY.isPresent()) {
ModuleObjectPlacement.place(pinnedObject(), OBJECT_X, requestedY.getAsInt(), OBJECT_Z, placer, config,
new RNG(PLACEMENT_SEED), null, cave, data);
} else {
ModuleObjectPlacement.placeAutomatic(pinnedObject(), OBJECT_X, OBJECT_Z, placer, config,
new RNG(PLACEMENT_SEED), null, cave, data);
}
return placer.writes();
}
@@ -119,12 +125,12 @@ public class ObjectPlaceModePinTest {
}
/** Cave modes and structure pieces are placed at a height, the way their callers place them; the rest sample. */
private static int requestedY(ObjectPlaceMode mode) {
private static OptionalInt requestedY(ObjectPlaceMode mode) {
return switch (mode) {
case CEILING_HANG -> CEILING_Y - 9;
case ORGANIC_STILT -> CAVE_FLOOR_Y + 12;
case STRUCTURE_PIECE -> 90;
default -> -1;
case CEILING_HANG -> OptionalInt.of(CEILING_Y - 9);
case ORGANIC_STILT -> OptionalInt.of(CAVE_FLOOR_Y + 12);
case STRUCTURE_PIECE -> OptionalInt.of(90);
default -> OptionalInt.empty();
};
}
@@ -37,6 +37,7 @@ import art.arcane.iris.spi.PlatformRegistries;
import art.arcane.iris.util.project.stream.ProceduralStream;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.math.Vector3i;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
@@ -203,7 +204,7 @@ public class ObjectPlacementRegressionTest {
placement.mode(ObjectPlaceMode.MAX_HEIGHT);
placement.rotation(ObjectRotation.of(0, 45, 0));
placed(boxObject(5, 1, 3), 0, -1, 0, placer, placement.build(), new RNG(2L), data);
placedAutomatic(boxObject(5, 1, 3), 0, 0, placer, placement.build(), new RNG(2L), data);
assertTrue(placer.sampledColumns().contains("-2:-2"));
assertTrue(placer.sampledColumns().contains("2:2"));
@@ -334,7 +335,7 @@ public class ObjectPlacementRegressionTest {
RecordingPlacer placer = new RecordingPlacer(null);
ObjectPlacement.Builder config = placement();
config.mode(ObjectPlaceMode.ERODE_STILT);
assertEquals(ANCHOR_Y, placed(lineObject(1), 0, -1, 0, placer, config.build(), new RNG(2L), data));
assertEquals(ANCHOR_Y, placedAutomatic(lineObject(1), 0, 0, placer, config.build(), new RNG(2L), data));
assertFalse(placer.writes().isEmpty());
}
@@ -527,12 +528,36 @@ public class ObjectPlacementRegressionTest {
assertNull(storage.value(MARKS, TEXT, 1, ANCHOR_Y, 0));
}
@Test
public void explicitHeightBelowZeroIsPlacedWhereAsked() {
for (int requestedY : new int[]{-1, -3}) {
RecordingPlacer placer = new RecordingPlacer(null);
ObjectPlacementResult result = ModuleObjectPlacement.place(lineObject(1), 0, requestedY, 0, placer,
placement().build(), new RNG(2L), null, null, data);
assertTrue(result.isPlaced());
assertEquals(requestedY, result.height());
assertFalse(placer.writes().isEmpty());
assertTrue(placer.writes().stream().allMatch(write -> write.y() == requestedY));
assertTrue(placer.sampledColumns().isEmpty());
}
}
@Test
public void automaticHeightSamplesTheTerrain() {
RecordingPlacer placer = new RecordingPlacer(null);
ObjectPlacementResult result = ModuleObjectPlacement.placeAutomatic(lineObject(1), 0, 0, placer,
placement().build(), new RNG(2L), null, null, data);
assertTrue(result.isPlaced());
assertEquals(ANCHOR_Y, result.height());
assertFalse(placer.sampledColumns().isEmpty());
}
@Test
public void fromBottomKeepsItsAnchorWithoutSamplingTerrain() {
RecordingPlacer placer = new RecordingPlacer(null);
ObjectPlacement.Builder config = placement();
config.fromBottom(true);
assertEquals(2, placed(lineObject(1), 0, -1, 0, placer, config.build(), new RNG(2L), data));
assertEquals(2, placedAutomatic(lineObject(1), 0, 0, placer, config.build(), new RNG(2L), data));
assertTrue(placer.sampledColumns().isEmpty());
}
@@ -542,7 +567,7 @@ public class ObjectPlacementRegressionTest {
RecordingPlacer placer = new RecordingPlacer(null);
ObjectPlacement.Builder config = placement().bore(true).snow(0.1);
CarveResult cave = null;
int anchor = ANCHOR_Y;
boolean automatic = false;
switch (reason) {
case "carving-anchor" -> {
placer.carved = true;
@@ -550,7 +575,7 @@ public class ObjectPlacementRegressionTest {
}
case "underwater-anchor" -> {
placer.underwater = true;
anchor = -1;
automatic = true;
}
case "cave-clearance" -> cave = new CarveResult(ANCHOR_Y, ANCHOR_Y + 1);
case "fluid-height" -> {
@@ -559,13 +584,13 @@ public class ObjectPlacementRegressionTest {
}
case "height-clamp" -> config.clamp(TestSettings.of(ObjectLimit.class, "{\"maximumHeight\":" + (ANCHOR_Y - 1) + "}"));
}
ObjectPlacementResult result = place(config, anchor, placer, cave);
ObjectPlacementResult result = place(config, automatic, placer, cave);
assertEquals(Optional.of(reason), result.rejection());
assertEquals(-1, result.heightOrRejected());
assertTrue(reason, placer.writes().isEmpty());
config.forcePlace(true);
assertTrue(reason, place(config, anchor, placer, cave).isPlaced());
assertTrue(reason, place(config, automatic, placer, cave).isPlaced());
assertFalse(reason, placer.writes().isEmpty());
}
}
@@ -585,6 +610,41 @@ public class ObjectPlacementRegressionTest {
assertFalse(placer.writes().isEmpty());
}
@Test
public void obliqueRotationRejectsNativePiecesBeyondTheUnrotatedRadius() {
int reach = 14;
when(engine.getNativeStructureVolumes(anyInt(), anyInt(), anyInt(), anyInt())).thenReturn(new KList<>(
NativeStructureVolume.of("minecraft:village", reach, ANCHOR_Y, 0, reach, ANCHOR_Y, 0),
NativeStructureVolume.of("minecraft:village", -reach, ANCHOR_Y, 0, -reach, ANCHOR_Y, 0),
NativeStructureVolume.of("minecraft:village", 0, ANCHOR_Y, reach, 0, ANCHOR_Y, reach),
NativeStructureVolume.of("minecraft:village", 0, ANCHOR_Y, -reach, 0, ANCHOR_Y, -reach)));
IrisObject object = new IrisObject(21, 1, 21);
object.setUnsigned(20, 0, 20, solid);
RecordingPlacer placer = new RecordingPlacer(engine);
ObjectPlacementResult result = ModuleObjectPlacement.place(object, 0, ANCHOR_Y, 0, placer,
placement().rotation(ObjectRotation.of(0, 45, 0)).build(), new RNG(2L), null, null, data);
assertEquals(Optional.of("native-structure"), result.rejection());
assertTrue(placer.writes().isEmpty());
}
@Test
public void offCenterOriginRejectsNativePiecesAtTheFarEdge() {
when(engine.getNativeStructureVolumes(anyInt(), anyInt(), anyInt(), anyInt())).thenReturn(
new KList<>(NativeStructureVolume.of("minecraft:village", 8, ANCHOR_Y, 0, 8, ANCHOR_Y, 0)));
IrisObject object = new IrisObject(9, 1, 1);
object.setCenter(new Vector3i(0, 0, 0));
object.setUnsigned(8, 0, 0, solid);
RecordingPlacer placer = new RecordingPlacer(engine);
ObjectPlacementResult result = ModuleObjectPlacement.place(object, 0, ANCHOR_Y, 0, placer,
placement().rotation(ObjectRotation.of(0, 0, 0)).build(), new RNG(2L), null, null, data);
assertEquals(Optional.of("native-structure"), result.rejection());
assertTrue(placer.writes().isEmpty());
}
@Test
public void collisionRejectionPrecedesBoreAndAllowedObjectsOverrideForbiddenOnes() {
PlacedObject forbidden = new PlacedObject(object("forbidden"), 1, 0, 0);
@@ -675,10 +735,21 @@ public class ObjectPlacementRegressionTest {
}
/** The height {@code object} was placed at, or -1 when the placement rejected it. */
private static int placedAutomatic(IrisObject object, int x, int z, IObjectPlacer placer, ObjectPlacement config, RNG rng, IrisData data) {
return ModuleObjectPlacement.placeAutomatic(object, x, z, placer, config, rng, null, null, data).heightOrRejected();
}
private static int placed(IrisObject object, int x, int y, int z, IObjectPlacer placer, ObjectPlacement config, RNG rng, IrisData data) {
return ModuleObjectPlacement.place(object, x, y, z, placer, config, rng, null, null, data).heightOrRejected();
}
private ObjectPlacementResult place(ObjectPlacement.Builder config, boolean automatic, RecordingPlacer placer, CarveResult cave) {
if (automatic) {
return ModuleObjectPlacement.placeAutomatic(lineObject(1), 0, 0, placer, config.build(), new RNG(2L), null, cave, data);
}
return place(config, ANCHOR_Y, placer, cave);
}
private ObjectPlacementResult place(ObjectPlacement.Builder config, int y, RecordingPlacer placer, CarveResult cave) {
return ModuleObjectPlacement.place(lineObject(1), 0, y, 0, placer, config.build(), new RNG(2L), null, cave, data);
}
@@ -0,0 +1,80 @@
package art.arcane.iris.engine.object.prefab;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.volmlib.util.collection.KMap;
import art.arcane.volmlib.util.math.IrisBlockVector;
import art.arcane.volmlib.util.math.Vector3i;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
public class IrisObjectCopyTest {
private static final long WAIT_SECONDS = 5;
private static final long BLOCKED_PROBE_MILLIS = 150;
@Test
public void copyWaitsForVolumeMutationToComplete() throws Exception {
IrisObject source = new IrisObject(1, 1, 1);
PlatformBlockState block = mock(PlatformBlockState.class);
CountDownLatch started = new CountDownLatch(1);
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
source.writeLock.lock();
Future<IrisObject> result;
try {
result = executor.submit(() -> {
started.countDown();
return source.copy();
});
assertTrue(started.await(WAIT_SECONDS, TimeUnit.SECONDS));
assertThrows(TimeoutException.class, () -> result.get(BLOCKED_PROBE_MILLIS, TimeUnit.MILLISECONDS));
source.setW(3);
source.setCenter(new Vector3i(1, 0, 0));
source.setUnsigned(2, 0, 0, block);
} finally {
source.writeLock.unlock();
}
IrisObject copy = result.get(WAIT_SECONDS, TimeUnit.SECONDS);
assertEquals(3, copy.getW());
assertEquals(new Vector3i(1, 0, 0), copy.getCenter());
assertSame(block, copy.getBlocks().get(new IrisBlockVector(1, 0, 0)));
} finally {
executor.shutdownNow();
}
}
@Test
public void copyOwnsItsCenterAndTiles() {
IrisObject source = new IrisObject(1, 1, 1);
PlatformBlockState block = mock(PlatformBlockState.class);
TileData tile = new TileData("minecraft:chest", new KMap<>());
tile.getProperties().put("name", "source");
source.setUnsigned(0, 0, 0, block);
source.setUnsignedTile(0, 0, 0, tile);
IrisObject copy = source.copy();
IrisBlockVector position = new IrisBlockVector(0, 0, 0);
TileData copiedTile = copy.getStates().get(position);
assertNotSame(source.getCenter(), copy.getCenter());
assertNotSame(tile, copiedTile);
assertNotSame(tile.getProperties(), copiedTile.getProperties());
copiedTile.getProperties().put("name", "copy");
copy.getBlocks().remove(position);
assertEquals("source", tile.getProperties().get("name"));
assertSame(block, source.getBlocks().get(position));
}
}
@@ -0,0 +1,130 @@
package art.arcane.iris.engine.object.prefab;
import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.spi.PlatformRegistries;
import art.arcane.volmlib.util.collection.KMap;
import art.arcane.volmlib.util.math.Vector3i;
import com.volmit.object.ScaleMethod;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** Rotation drops blocks with no valid orientation and their tiles; scaling reads one snapshot of the object. */
public class IrisObjectTransformsStabilityTest {
private static final long WAIT_SECONDS = 5;
private static final long PARK_MILLIS = 1;
private static final int QUARTER_TURN_DEGREES = 90;
private static final double SCALE = 2;
@Before
public void bindPlatform() {
IrisPlatforms.unbind();
PlatformRegistries registries = mock(PlatformRegistries.class);
when(registries.block(anyString())).thenAnswer(call -> state(call.getArgument(0)));
IrisPlatform platform = mock(IrisPlatform.class);
when(platform.registries()).thenReturn(registries);
IrisPlatforms.bind(platform);
}
@After
public void unbindPlatform() {
IrisPlatforms.unbind();
}
@Test
public void rotationOmitsUnsupportedBlocksAndTheirTiles() {
IrisObject source = new IrisObject(3, 1, 1);
PlatformBlockState unsupported = state("minecraft:wall_torch");
PlatformBlockState chest = state("minecraft:chest");
source.setUnsigned(0, 0, 0, unsupported);
source.setUnsignedTile(0, 0, 0, tile("minecraft:wall_torch", "omitted"));
source.setUnsigned(1, 0, 0, chest);
source.setUnsignedTile(1, 0, 0, tile("minecraft:chest", "kept"));
source.setUnsigned(2, 0, 0, state("minecraft:stone"));
BlockStateRotation.StateRotator previous = BlockStateRotation.bindPlatformRotator(
(turn, block) -> block == unsupported ? null : block);
IrisObject rotated;
try {
rotated = source.rotateCopy(ObjectTurn.of(0, QUARTER_TURN_DEGREES, 0));
} finally {
BlockStateRotation.restorePlatformRotator(previous);
}
assertEquals(2, rotated.getBlocks().size());
assertEquals(1, rotated.getStates().size());
rotated.getStates().forEach(entry -> {
assertEquals(chest, rotated.getBlocks().get(entry.getKey()));
assertEquals("kept", entry.getValue().getProperties().get("name"));
});
assertEquals(3, source.getBlocks().size());
assertEquals(2, source.getStates().size());
}
@Test
public void scalingWaitsForMatchingGeometryAndVolume() throws Exception {
IrisObject source = new IrisObject(9, 5, 3);
source.setUnsigned(0, 0, 0, state("minecraft:stone"));
FutureTask<IrisObject> scaling = new FutureTask<>(() -> source.scaled(SCALE, ScaleMethod.NONE));
Thread worker = new Thread(scaling, "object-scaling-snapshot");
source.writeLock.lock();
try {
worker.start();
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(WAIT_SECONDS);
while (worker.getState() != Thread.State.WAITING && System.nanoTime() < deadline) {
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(PARK_MILLIS));
}
assertEquals(Thread.State.WAITING, worker.getState());
source.setW(2);
source.setH(2);
source.setD(2);
source.setCenter(new Vector3i(1, 1, 1));
source.getBlocks().clear();
source.setUnsigned(0, 0, 0, state("minecraft:chest"));
} finally {
source.writeLock.unlock();
}
try {
IrisObject actual = scaling.get(WAIT_SECONDS, TimeUnit.SECONDS);
IrisObject expected = source.scaled(SCALE, ScaleMethod.NONE);
assertEquals(expected.getW(), actual.getW());
assertEquals(expected.getH(), actual.getH());
assertEquals(expected.getD(), actual.getD());
assertEquals(expected.getBlocks().size(), actual.getBlocks().size());
expected.getBlocks().forEach(entry -> {
assertNotNull(actual.getBlocks().get(entry.getKey()));
assertEquals(entry.getValue(), actual.getBlocks().get(entry.getKey()));
});
} finally {
worker.interrupt();
worker.join(TimeUnit.SECONDS.toMillis(WAIT_SECONDS));
}
}
private static PlatformBlockState state(String key) {
PlatformBlockState state = mock(PlatformBlockState.class);
when(state.key()).thenReturn(key);
when(state.materialKey()).thenReturn(key);
when(state.isAir()).thenReturn(false);
when(state.isSolid()).thenReturn(true);
return state;
}
private static TileData tile(String id, String name) {
TileData tile = new TileData(id, new KMap<>());
tile.getProperties().put("name", name);
return tile;
}
}
@@ -190,7 +190,7 @@ public class NativeStructureObjectVetoTest {
volumes(volume(-64, -64, -64, 64, 320, 64));
ObjectPlacement placement = placement().toBuilder().forcePlace(true).build();
assertEquals(-1, placed(0, -1, placer, placement));
assertEquals(-1, placedAutomatic(0, placer, placement));
assertTrue(placer.written().isEmpty());
}
@@ -229,7 +229,11 @@ public class NativeStructureObjectVetoTest {
}
private int place(RecordingPlacer placer) {
return placed(0, -1, placer, placement());
return placedAutomatic(0, placer, placement());
}
private int placedAutomatic(int x, RecordingPlacer placer, ObjectPlacement config) {
return ModuleObjectPlacement.placeAutomatic(tree(), x, 0, placer, config, new RNG(1234L), null, null, data).heightOrRejected();
}
private int placed(int x, int y, RecordingPlacer placer, ObjectPlacement config) {
@@ -0,0 +1,281 @@
package art.arcane.iris.engine.platform;
import art.arcane.iris.core.link.Identifier;
import art.arcane.iris.core.service.ExternalDataSVC;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.object.prefab.TileData;
import art.arcane.iris.engine.object.world.IrisWorld;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.IrisServices;
import art.arcane.iris.spi.PlatformBlockState;
import art.arcane.iris.spi.PlatformRegistries;
import art.arcane.iris.util.common.data.IrisCustomData;
import art.arcane.iris.util.project.matter.TileWrapper;
import art.arcane.volmlib.util.collection.KMap;
import art.arcane.volmlib.util.function.Consumer4;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.matter.Matter;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.TileState;
import org.bukkit.block.data.BlockData;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockedStatic;
import org.mockito.invocation.InvocationOnMock;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class EngineBukkitOpsStaleRecordTest {
private static final Identifier ORE = Identifier.fromString("itemsadder:forest/amber_ore");
private static final Identifier CHAIR = Identifier.fromString("craftengine:test/chair[variant=alpha]");
@Before
public void bindPlatform() {
IrisPlatforms.unbind();
PlatformRegistries registries = mock(PlatformRegistries.class);
IrisPlatform platform = mock(IrisPlatform.class);
when(registries.block(anyString())).thenReturn(mock(PlatformBlockState.class));
when(platform.registries()).thenReturn(registries);
IrisPlatforms.bind(platform);
}
@After
public void unbindPlatform() {
IrisPlatforms.unbind();
}
@Test
public void customRecordOverFlattenedAirIsNotPlaced() {
Fixture fixture = new Fixture();
fixture.carrier(ORE, Material.NOTE_BLOCK);
Block flattened = fixture.block(1, 10, 1, Material.AIR);
MantleChunk<Matter> records = customRecords(new Placed<>(1, 10, 1, ORE));
fixture.materializeCustomBlocks(records);
verify(fixture.service, never()).processUpdate(any(), eq(flattened), any());
verify(records).deleteSlices(Identifier.class);
}
@Test
public void customRecordOverReplacedBlockIsNotPlaced() {
Fixture fixture = new Fixture();
fixture.carrier(ORE, Material.NOTE_BLOCK);
Block wall = fixture.block(2, 10, 2, Material.COBBLESTONE);
MantleChunk<Matter> records = customRecords(new Placed<>(2, 10, 2, ORE));
fixture.materializeCustomBlocks(records);
verify(fixture.service, never()).processUpdate(any(), eq(wall), any());
verify(records).deleteSlices(Identifier.class);
}
@Test
public void customRecordOverIntactCarrierIsPlaced() {
Fixture fixture = new Fixture();
fixture.carrier(ORE, Material.NOTE_BLOCK);
Block intact = fixture.block(3, 10, 3, Material.NOTE_BLOCK);
fixture.materializeCustomBlocks(customRecords(new Placed<>(3, 10, 3, ORE)));
verify(fixture.service).processUpdate(fixture.engine, intact, ORE);
}
@Test
public void airCarrierFurnitureRecordIsPlacedWhateverTheLiveBlock() {
Fixture fixture = new Fixture();
fixture.carrier(CHAIR, Material.AIR);
Block open = fixture.block(4, 10, 4, Material.AIR);
Block covered = fixture.block(5, 10, 5, Material.COBBLESTONE);
fixture.materializeCustomBlocks(customRecords(
new Placed<>(4, 10, 4, CHAIR),
new Placed<>(5, 10, 5, CHAIR)));
verify(fixture.service).processUpdate(fixture.engine, open, CHAIR);
verify(fixture.service).processUpdate(fixture.engine, covered, CHAIR);
}
@Test
public void unresolvableCarrierLeavesPlacementToTheProvider() {
Fixture fixture = new Fixture();
when(fixture.service.getBlockData(ORE)).thenReturn(Optional.empty());
Block block = fixture.block(6, 10, 6, Material.STONE);
fixture.materializeCustomBlocks(customRecords(new Placed<>(6, 10, 6, ORE)));
verify(fixture.service).processUpdate(fixture.engine, block, ORE);
}
@Test
public void carrierResolvesOncePerIdentifierAndStaleRecordsLogOncePerChunk() {
Fixture fixture = new Fixture();
fixture.carrier(ORE, Material.NOTE_BLOCK);
fixture.block(1, 10, 1, Material.AIR);
fixture.block(2, 10, 2, Material.COBBLESTONE);
Block intact = fixture.block(3, 10, 3, Material.NOTE_BLOCK);
MantleChunk<Matter> records = customRecords(
new Placed<>(1, 10, 1, ORE),
new Placed<>(2, 10, 2, ORE),
new Placed<>(3, 10, 3, ORE));
List<String> debug = fixture.materializeCustomBlocksCapturingDebug(records);
verify(fixture.service, times(1)).getBlockData(ORE);
verify(fixture.service, times(1)).processUpdate(any(), any(), any());
verify(fixture.service).processUpdate(fixture.engine, intact, ORE);
assertEquals(1, debug.size());
assertTrue(debug.getFirst(), debug.getFirst().contains("2 stale"));
}
@Test
public void staleTileRecordIsSkippedWithoutWarning() {
Fixture fixture = new Fixture();
TileData chest = chestTile();
Block replaced = fixture.block(7, 10, 7, Material.STONE);
BlockData stone = blockData(Material.STONE);
when(replaced.getBlockData()).thenReturn(stone);
try (MockedStatic<IrisLogging> logging = mockStatic(IrisLogging.class)) {
EngineBukkitOps.materializeTiles(fixture.engine, fixture.chunk, tileRecords(new Placed<>(7, 10, 7, chest)));
logging.verify(() -> IrisLogging.warn(anyString(), any(Object[].class)), never());
logging.verify(() -> IrisLogging.debug(anyString(), any(Object[].class)), times(1));
}
verify(chest, never()).toBukkitTry(any());
}
@Test
public void intactTileRecordIsApplied() {
Fixture fixture = new Fixture();
TileData chest = chestTile();
Block intact = fixture.block(8, 10, 8, Material.CHEST);
BlockData chestData = blockData(Material.CHEST);
when(intact.getBlockData()).thenReturn(chestData);
when(intact.getState()).thenReturn(mock(TileState.class));
doReturn(true).when(chest).toBukkitTry(intact);
try (MockedStatic<IrisLogging> logging = mockStatic(IrisLogging.class)) {
EngineBukkitOps.materializeTiles(fixture.engine, fixture.chunk, tileRecords(new Placed<>(8, 10, 8, chest)));
logging.verify(() -> IrisLogging.warn(anyString(), any(Object[].class)), never());
}
verify(chest).toBukkitTry(intact);
}
private static TileData chestTile() {
TileData tile = spy(new TileData("minecraft:chest", new KMap<>()));
doReturn(Material.CHEST).when(tile).resolveMaterial();
return tile;
}
private static BlockData blockData(Material material) {
BlockData data = mock(BlockData.class);
when(data.getMaterial()).thenReturn(material);
return data;
}
@SafeVarargs
private static MantleChunk<Matter> customRecords(Placed<Identifier>... records) {
return records(Identifier.class, records);
}
@SafeVarargs
private static MantleChunk<Matter> tileRecords(Placed<TileData>... records) {
List<Placed<TileWrapper>> wrapped = new ArrayList<>(records.length);
for (Placed<TileData> record : records) {
wrapped.add(new Placed<>(record.x(), record.y(), record.z(), new TileWrapper(record.value())));
}
return records(TileWrapper.class, wrapped.toArray(Placed[]::new));
}
@SuppressWarnings("unchecked")
private static <T> MantleChunk<Matter> records(Class<T> type, Placed<T>[] records) {
MantleChunk<Matter> chunk = mock(MantleChunk.class);
doAnswer((InvocationOnMock invocation) -> {
Consumer4<Integer, Integer, Integer, T> iterator = invocation.getArgument(1);
for (Placed<T> record : records) {
iterator.accept(record.x(), record.y(), record.z(), record.value());
}
return null;
}).when(chunk).iterate(eq(type), any());
return chunk;
}
private record Placed<T>(int x, int y, int z, T value) {
}
private static final class Fixture {
private final Engine engine = mock(Engine.class);
private final Chunk chunk = mock(Chunk.class);
private final ExternalDataSVC service = mock(ExternalDataSVC.class);
private Fixture() {
IrisWorld irisWorld = mock(IrisWorld.class);
when(engine.getWorld()).thenReturn(irisWorld);
World world = mock(World.class);
when(world.getMinHeight()).thenReturn(0);
when(world.getMaxHeight()).thenReturn(256);
when(world.getName()).thenReturn("example");
when(chunk.getWorld()).thenReturn(world);
}
private void carrier(Identifier identifier, Material material) {
BlockData carrier = IrisCustomData.of(blockData(material), identifier);
when(service.getBlockData(identifier)).thenReturn(Optional.of(carrier));
}
private Block block(int x, int y, int z, Material type) {
Block block = mock(Block.class);
when(block.getType()).thenReturn(type);
when(chunk.getBlock(x, y, z)).thenReturn(block);
return block;
}
private void materializeCustomBlocks(MantleChunk<Matter> records) {
try (MockedStatic<IrisServices> services = mockStatic(IrisServices.class)) {
services.when(() -> IrisServices.get(ExternalDataSVC.class)).thenReturn(service);
EngineBukkitOps.materializeCustomBlocks(engine, chunk, records);
}
}
private List<String> materializeCustomBlocksCapturingDebug(MantleChunk<Matter> records) {
List<String> messages = new ArrayList<>();
try (MockedStatic<IrisServices> services = mockStatic(IrisServices.class);
MockedStatic<IrisLogging> logging = mockStatic(IrisLogging.class)) {
services.when(() -> IrisServices.get(ExternalDataSVC.class)).thenReturn(service);
logging.when(() -> IrisLogging.debug(anyString(), any(Object[].class))).thenAnswer((InvocationOnMock invocation) -> {
Object[] arguments = invocation.getArguments();
messages.add(String.format((String) arguments[0], Arrays.copyOfRange(arguments, 1, arguments.length)));
return null;
});
EngineBukkitOps.materializeCustomBlocks(engine, chunk, records);
}
return messages;
}
}
}
@@ -45,6 +45,7 @@ import java.util.OptionalInt;
*/
public final class ObjectRun {
private static final int NOT_ANCHORED = Integer.MIN_VALUE;
private static final int AUTOMATIC_Y = -1;
private static final int NEIGHBOR_READ_BLOCKS = 1;
private static final long X_MULTIPLIER = 0x9E3779B97F4A7C15L;
private static final long Z_MULTIPLIER = 0xC2B2AE3D27D4EB4FL;
@@ -56,28 +57,41 @@ public final class ObjectRun {
private final ObjectPlacement settings;
private final int x;
private final int requestedY;
private final boolean automaticHeight;
private final int z;
private final Cave cave;
private final List<BlockPosition> objectBlocks = new ArrayList<>();
private int anchorY = NOT_ANCHORED;
private ObjectRun(PlaceableObject object, ObjectPlacement settings, int x, int requestedY, int z, Cave cave) {
private ObjectRun(PlaceableObject object, ObjectPlacement settings, int x, int requestedY, boolean automaticHeight, int z,
Cave cave) {
this.object = Objects.requireNonNull(object, "object");
this.settings = Objects.requireNonNull(settings, "settings");
this.x = x;
this.requestedY = requestedY;
this.automaticHeight = automaticHeight;
this.z = z;
this.cave = cave;
}
/** @param requestedY the height to place at, or a negative value for the stages to sample it */
/** @param requestedY the height to place at, which may be below zero in a dimension that reaches down there */
public static ObjectRun of(PlaceableObject object, ObjectPlacement settings, int x, int requestedY, int z) {
return new ObjectRun(object, settings, x, requestedY, z, null);
return new ObjectRun(object, settings, x, requestedY, false, z, null);
}
/** A placement inside {@code cave}, which the stages anchor in and keep the object's height within. */
/** A placement at the height the stages sample from the terrain. */
public static ObjectRun automatic(PlaceableObject object, ObjectPlacement settings, int x, int z) {
return new ObjectRun(object, settings, x, AUTOMATIC_Y, true, z, null);
}
/** A placement at {@code requestedY} inside {@code cave}, which the stages anchor in and keep the object's height within. */
public static ObjectRun inCave(PlaceableObject object, ObjectPlacement settings, int x, int requestedY, int z, Cave cave) {
return new ObjectRun(object, settings, x, requestedY, z, Objects.requireNonNull(cave, "cave"));
return new ObjectRun(object, settings, x, requestedY, false, z, Objects.requireNonNull(cave, "cave"));
}
/** A placement inside {@code cave} at the height the stages sample from it. */
public static ObjectRun automaticInCave(PlaceableObject object, ObjectPlacement settings, int x, int z, Cave cave) {
return new ObjectRun(object, settings, x, AUTOMATIC_Y, true, z, Objects.requireNonNull(cave, "cave"));
}
/**
@@ -127,11 +141,16 @@ public final class ObjectRun {
return x;
}
/** The height the caller asked for, negative when the stages sample it. */
/** The height the caller asked for; meaningless when {@link #automaticHeight()}. */
public int requestedY() {
return requestedY;
}
/** Whether the stages sample the height from the terrain instead of placing at {@link #requestedY()}. */
public boolean automaticHeight() {
return automaticHeight;
}
public int z() {
return z;
}
@@ -54,7 +54,6 @@ import java.util.Set;
*/
final class FloatingPlacer {
private static final ObjectRotation NO_ROTATION = ObjectRotation.of(0, 0, 0);
private static final int SAMPLED_HEIGHT = -1;
private static final Set<String> AIR_MATERIALS = Set.of("minecraft:air", "minecraft:cave_air");
private final PackWorld world;
@@ -111,7 +110,7 @@ final class FloatingPlacer {
ObjectPlacement floating = placement.toBuilder().place(List.of(object.name())).build();
int id = random.i(0, Integer.MAX_VALUE);
try {
place(ObjectRun.of(object, floating, worldX, SAMPLED_HEIGHT, worldZ), context.placementTerrain(), object, id);
place(ObjectRun.automatic(object, floating, worldX, worldZ), context.placementTerrain(), object, id);
} catch (Throwable failure) {
GenerationFailures.skipPlacement(log, failure, "floating object", object.name(), "at " + worldX + "," + worldZ);
}
@@ -48,7 +48,6 @@ import com.volmit.world.PackWorld;
*/
final class ObjectChunk {
private static final int REJECTED = -1;
private static final int SAMPLED_HEIGHT = -1;
private final PackWorld world;
private final PlacementTerrain terrain;
@@ -85,7 +84,7 @@ final class ObjectChunk {
int placeOnSurface(PlaceableObject object, int x, int z, ObjectPlacement placement, PlacementChanges changes,
PlacementTags tags, String goldenTag) {
PlacementTerrain placer = proceduralTerrain(terrain, object, goldenTag);
return place(ObjectRun.of(object, EffectiveSettings.withChanges(placement, changes), x, SAMPLED_HEIGHT, z), placer, tags);
return place(ObjectRun.automatic(object, EffectiveSettings.withChanges(placement, changes), x, z), placer, tags);
}
/**
@@ -113,21 +113,22 @@ final class PlacementReach {
}
static int of(ObjectSize size, ObjectPlacement placement) {
return of(size, placement.mode().placeMode(), placement.scale().maxScale(), placement.rotation(), placement.translate(),
placement.warp() == null || placement.warp().isFlat() ? 0 : placement.warp().multiplier(),
return of(size, placement.mode().placeMode(), placement.scale().maxScale(), placement.rotation(), placement.rotateTowardsSlope(),
placement.translate(), placement.warp() == null || placement.warp().isFlat() ? 0 : placement.warp().multiplier(),
placement.vacuumSettings().orElse(null));
}
private static int of(ObjectSize size, PlaceMode mode, Double maxScale, ObjectRotation rotation, ObjectTranslate translate,
Double warpMultiplier, VacuumSettings vacuum) {
private static int of(ObjectSize size, PlaceMode mode, Double maxScale, ObjectRotation rotation, boolean rotatesTowardsSlope,
ObjectTranslate translate, Double warpMultiplier, VacuumSettings vacuum) {
double scale = maxScale == null ? 1D : Math.max(1D, maxScale);
int width = scaledDimension(size.width(), scale);
int height = scaledDimension(size.height(), scale);
int depth = scaledDimension(size.depth(), scale);
boolean rotateX = rotation != null && rotation.enabled() && rotation.xAxis() != null && rotation.xAxis().enabled();
boolean rotateZ = rotation != null && rotation.enabled() && rotation.zAxis() != null && rotation.zAxis().enabled();
int footprint = rotateX || rotateZ ? Math.max(width, Math.max(height, depth)) : Math.max(width, depth);
int translation = translationReach(translate, rotation, rotateX || rotateZ);
boolean tiltsVertically = rotatesTowardsSlope || rotateX || rotateZ;
int footprint = tiltsVertically ? Math.max(width, Math.max(height, depth)) : Math.max(width, depth);
int translation = translationReach(translate, rotation, tiltsVertically);
int warp = warpMultiplier == null ? 0 : (int) Math.ceil(Math.abs(warpMultiplier) / 2D);
int vacuumReach = mode.bendsTerrain() ? 2 * vacuumRadius(mode, vacuum) : 0;
long reach = (long) footprint + translation + warp + vacuumReach;
@@ -66,7 +66,7 @@ public final class AnchorModule implements IrisModule {
PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS);
PlacementSettings settings = prepared.settings();
boolean structurePiece = prepared.mode().has(PlaceTrait.RAW_STAMP);
if (!settings.fromBottom() && placement.requestedY() < 0) {
if (!settings.fromBottom() && placement.automaticHeight()) {
return new AnchorHeight(sampled(context, placement, prepared));
}
ObjectShape object = placement.object();
@@ -75,7 +75,7 @@ public final class AnchorModule implements IrisModule {
context.reject(CARVING_ANCHOR);
return null;
}
if (placement.requestedY() < 0 || !settings.bottom() || structurePiece) {
if (placement.automaticHeight() || !settings.bottom() || structurePiece) {
return new AnchorHeight(y);
}
y += Math.floorDiv(object.height(), 2);
@@ -107,7 +107,11 @@ public final class BlocksModule implements IrisModule {
data = edited.data();
blockEntity = edited.blockEntity();
}
data = prepared.rotate(data);
BlockState rotated = prepared.rotate(data);
if (isDroppedByRotation(data, rotated)) {
return;
}
data = rotated;
int x = placement.x() + offset.x();
int y = anchorY + offset.y();
int z = placement.z() + offset.z();
@@ -123,7 +127,7 @@ public final class BlocksModule implements IrisModule {
if (settings.meld() && !structurePiece && !world.isSolid(x, y, z)) {
return;
}
if (data.properties().containsKey(WATERLOGGED) && shouldWaterlog(world, settings, placement.requestedY(), x, y, z)) {
if (data.properties().containsKey(WATERLOGGED) && shouldWaterlog(world, settings, placement.automaticHeight(), x, y, z)) {
data = data.withProperty(WATERLOGGED, TRUE);
}
if (world.has(data, BlockTrait.VINE)) {
@@ -152,6 +156,11 @@ public final class BlocksModule implements IrisModule {
return data;
}
/** A block that turned into air had no valid orientation: it is left out with its block entity, even for structure pieces that write air. */
static boolean isDroppedByRotation(BlockState source, BlockState rotated) {
return !AIR_MATERIALS.contains(source.material().toString()) && AIR_MATERIALS.contains(rotated.material().toString());
}
private static boolean shouldWrite(PlacementWorld world, BlockState data, int x, int y, int z, boolean structurePiece) {
if (world.has(data, BlockTrait.CUSTOM)) {
return true;
@@ -176,11 +185,11 @@ public final class BlocksModule implements IrisModule {
}
/** Whether a waterloggable block lands in water a waterloggable or underwater placement keeps. */
static boolean shouldWaterlog(PlacementWorld world, PlacementSettings settings, int requestedY, int x, int y, int z) {
static boolean shouldWaterlog(PlacementWorld world, PlacementSettings settings, boolean automaticHeight, int x, int y, int z) {
if (!(settings.waterloggable() || settings.underwater())) {
return false;
}
if (requestedY >= 0 && settings.carvingSupport() == CarvingMode.CARVING_ONLY) {
if (!automaticHeight && settings.carvingSupport() == CarvingMode.CARVING_ONLY) {
return false;
}
BlockState existing = world.get(x, y, z);
@@ -195,7 +195,7 @@ public final class StiltModule implements IrisModule {
int top = layerY + anchorY;
int highest = prepared.terrain().highest(x, z, true);
if (state.properties().containsKey(BlocksModule.WATERLOGGED)
&& BlocksModule.shouldWaterlog(world, config, placement.requestedY(), x, highest, z)) {
&& BlocksModule.shouldWaterlog(world, config, placement.automaticHeight(), x, highest, z)) {
state = state.withProperty(BlocksModule.WATERLOGGED, BlocksModule.TRUE);
}
int lowerBound = highest - 1;
@@ -22,7 +22,7 @@ import art.arcane.iris.builtin.anchor.PlaceTrait;
import art.arcane.iris.builtin.carve.CarvingMode;
import art.arcane.iris.builtin.objects.ObjectRun;
import art.arcane.iris.builtin.terrain.BedrockSettings;
import art.arcane.iris.modules.placement.ObjectShape;
import art.arcane.iris.builtin.prepare.TransformedBounds;
import art.arcane.iris.modules.placement.PlacementSettings;
import art.arcane.iris.modules.placement.PlacementStages;
import art.arcane.iris.modules.placement.PreparedPlacement;
@@ -84,7 +84,7 @@ public final class ValidateModule implements IrisModule {
return;
}
int y = context.output(PlacementStages.Anchor.HEIGHT).y();
boolean sampled = placement.requestedY() < 0;
boolean sampled = placement.automaticHeight();
if (sampled && settings.carvingSupport().supportsSurface() && isOnBedrock(context, prepared, y)) {
warnImplausibleBedrockPlacement(placement, settings, y, context.log());
context.reject("bedrock-anchor");
@@ -124,7 +124,7 @@ public final class ValidateModule implements IrisModule {
int rotated = prepared.rotatedCenterY();
int translated = prepared.translatedCenterY();
Optional<ObjectRun.Cave> cave = placement.cave();
if (placement.requestedY() < 0 && !prepared.mode().has(PlaceTrait.FREE_HEIGHT) && !settings.underwater()
if (placement.automaticHeight() && !prepared.mode().has(PlaceTrait.FREE_HEIGHT) && !settings.underwater()
&& !settings.onwater() && prepared.terrain().isUnderwater(placement.x(), placement.z())) {
context.reject("underwater-anchor");
} else if (cave.isPresent()
@@ -156,15 +156,19 @@ public final class ValidateModule implements IrisModule {
}
int x = placement.x();
int z = placement.z();
int margin = nativeStructureMargin(placement.object(), prepared);
StructureVolumes volumes = terrain.structureVolumes(x - margin, z - margin, x + margin, z + margin);
TransformedBounds bounds = prepared.bounds();
int minX = x + bounds.minX();
int maxX = x + bounds.maxX();
int minZ = z + bounds.minZ();
int maxZ = z + bounds.maxZ();
StructureVolumes volumes = terrain.structureVolumes(minX, minZ, maxX, maxZ);
if (volumes.isEmpty()) {
return false;
}
boolean painted = WorldVolume.isPainted(placement, prepared);
int envelopeMinY = painted ? Integer.MIN_VALUE : y - margin;
int envelopeMaxY = painted ? Integer.MAX_VALUE : y + margin;
if (!volumes.intersects(x - margin, envelopeMinY, z - margin, x + margin, envelopeMaxY, z + margin)) {
int envelopeMinY = painted ? Integer.MIN_VALUE : y + bounds.minY() - prepared.warpMargin();
int envelopeMaxY = painted ? Integer.MAX_VALUE : y + bounds.maxY() + prepared.warpMargin();
if (!volumes.intersects(minX, envelopeMinY, minZ, maxX, envelopeMaxY, maxZ)) {
return false;
}
for (ObjectBlock block : context.request().object().blocks()) {
@@ -185,16 +189,6 @@ public final class ValidateModule implements IrisModule {
return false;
}
/** How far around the anchor any block of the transformed object can reach. */
private static int nativeStructureMargin(ObjectShape object, PreparedPlacement prepared) {
int margin = (Math.max(object.width(), Math.max(object.height(), object.depth())) / 2) + 1 + prepared.warpMargin();
if (prepared.translation() == null) {
return margin;
}
return margin + Math.max(Math.abs(prepared.translation().getBlockX()),
Math.max(Math.abs(prepared.translation().getBlockY()), Math.abs(prepared.translation().getBlockZ())));
}
private static boolean isAir(BlockState state) {
return AIR_MATERIALS.contains(state.material().toString());
}
@@ -53,6 +53,6 @@ record WorldVolume(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) {
/** Whether each block of the placement follows the surface of its own column. */
static boolean isPainted(RunningPlacement placement, PreparedPlacement prepared) {
return placement.requestedY() < 0 && prepared.mode().anchor() == AnchorSampling.SURFACE;
return placement.automaticHeight() && prepared.mode().anchor() == AnchorSampling.SURFACE;
}
}
@@ -79,11 +79,16 @@ public final class RunningPlacement {
return run.x();
}
/** The height the caller asked for, negative when the placement samples it. */
/** The height the caller asked for; meaningless when {@link #automaticHeight()}. */
public int requestedY() {
return run.requestedY();
}
/** Whether the placement samples its height from the terrain instead of placing at {@link #requestedY()}. */
public boolean automaticHeight() {
return run.automaticHeight();
}
public int z() {
return run.z();
}