Merged stale placement guard

- Combine the carrier check with native write invalidation
This commit is contained in:
Brian Neumann-Fopiano committed 2026-10-16 19:37:15 -04:00
commit ed5483d75a
6 files changed
+765 -7

No files matched your search

@@ -0,0 +1,179 @@
package art.arcane.iris.platform.generation;
import art.arcane.iris.generation.block.IrisCustomData;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.SeedManager;
import art.arcane.iris.integration.ExternalDataProvider;
import art.arcane.iris.integration.ExternalDataSVC;
import art.arcane.iris.integration.Identifier;
import art.arcane.iris.integration.data.CraftEngineDataProvider;
import art.arcane.iris.platform.bukkit.BukkitBlockResolution;
import art.arcane.iris.platform.registry.RegistryUtil;
import art.arcane.iris.spi.IrisServices;
import art.arcane.iris.testsupport.BukkitTestServer;
import art.arcane.iris.world.IrisWorld;
import art.arcane.volmlib.util.function.Consumer4;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.matter.Matter;
import net.momirealms.craftengine.bukkit.api.CraftEngineBlocks;
import net.momirealms.craftengine.bukkit.api.CraftEngineFurniture;
import net.momirealms.craftengine.bukkit.api.CraftEngineItems;
import net.momirealms.craftengine.bukkit.api.event.CraftEngineReloadEvent;
import net.momirealms.craftengine.bukkit.entity.furniture.BukkitFurniture;
import net.momirealms.craftengine.bukkit.plugin.BukkitCraftEngine;
import net.momirealms.craftengine.core.block.BlockDefinition;
import net.momirealms.craftengine.core.block.ImmutableBlockState;
import net.momirealms.craftengine.core.entity.furniture.FurnitureDefinition;
import net.momirealms.craftengine.core.entity.furniture.FurnitureVariant;
import net.momirealms.craftengine.core.registry.Holder;
import net.momirealms.craftengine.core.util.Key;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.data.BlockData;
import org.junit.Test;
import org.mockito.MockedStatic;
import org.mockito.invocation.InvocationOnMock;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class CraftEngineStaleRecordTest {
@Test
public void stalePlacementRecordsAreSkippedAndIntactOnesPlaced() throws Exception {
BukkitTestServer.install();
BlockDefinition lampDefinition = mock(BlockDefinition.class);
ImmutableBlockState lamp = mock(ImmutableBlockState.class);
when(lamp.owner()).thenReturn(Holder.direct(lampDefinition));
when(lamp.toString()).thenReturn("test:lamp");
when(lampDefinition.defaultState()).thenReturn(lamp);
FurnitureDefinition chairDefinition = mock(FurnitureDefinition.class);
when(chairDefinition.id()).thenReturn(Key.of("test:chair"));
when(chairDefinition.variants()).thenReturn(Map.of("alpha", mock(FurnitureVariant.class)));
BlockData noteBlock = blockData(Material.NOTE_BLOCK);
BlockData air = blockData(Material.AIR);
CraftEngineDataProvider provider = new CraftEngineDataProvider();
ExternalDataSVC service = new ExternalDataSVC();
activate(service, provider);
Engine engine = mock(Engine.class);
when(engine.getWorld()).thenReturn(mock(IrisWorld.class));
SeedManager seeds = mock(SeedManager.class);
when(engine.getSeedManager()).thenReturn(seeds);
World world = mock(World.class);
when(world.getMinHeight()).thenReturn(0);
when(world.getMaxHeight()).thenReturn(256);
Chunk chunk = mock(Chunk.class);
when(chunk.getWorld()).thenReturn(world);
block(chunk, 1, Material.NOTE_BLOCK);
block(chunk, 2, Material.AIR);
block(chunk, 3, Material.COBBLESTONE);
block(chunk, 4, Material.COBBLESTONE);
try (MockedStatic<BukkitCraftEngine> craftEngine = mockStatic(BukkitCraftEngine.class);
MockedStatic<CraftEngineBlocks> blocks = mockStatic(CraftEngineBlocks.class);
MockedStatic<CraftEngineFurniture> furniture = mockStatic(CraftEngineFurniture.class);
MockedStatic<CraftEngineItems> items = mockStatic(CraftEngineItems.class);
MockedStatic<RegistryUtil> registry = materialRegistry();
MockedStatic<BukkitBlockResolution> resolution = mockStatic(BukkitBlockResolution.class);
MockedStatic<IrisServices> services = mockStatic(IrisServices.class)) {
resolution.when(BukkitBlockResolution::getAir).thenReturn(air);
services.when(() -> IrisServices.get(ExternalDataSVC.class)).thenReturn(service);
blocks.when(CraftEngineBlocks::loadedBlocks).thenReturn(Map.of(Key.of("test:lamp"), lampDefinition));
furniture.when(CraftEngineFurniture::loadedFurniture).thenReturn(Map.of(Key.of("test:chair"), chairDefinition));
items.when(CraftEngineItems::loadedItems).thenReturn(Map.of());
blocks.when(() -> CraftEngineBlocks.byId(Key.of("test:lamp"))).thenReturn(lampDefinition);
blocks.when(() -> CraftEngineBlocks.getBukkitBlockData(lamp)).thenReturn(noteBlock);
blocks.when(() -> CraftEngineBlocks.place(any(Location.class), eq(lamp), eq(false))).thenReturn(true);
furniture.when(() -> CraftEngineFurniture.byId(Key.of("test:chair"))).thenReturn(chairDefinition);
furniture.when(() -> CraftEngineFurniture.place(any(Location.class), eq(chairDefinition), eq("alpha"), eq(false)))
.thenReturn(mock(BukkitFurniture.class));
provider.onReload(mock(CraftEngineReloadEvent.class));
Identifier lampRecord = generatedRecord(service, "test:lamp");
Identifier chairRecord = generatedRecord(service, "test:chair");
assertEquals("craftengine:test/lamp", lampRecord.toString());
assertEquals("craftengine:test/chair[variant=alpha]", chairRecord.toString());
EngineBukkitOps.materializeCustomBlocks(engine, chunk, records(
new Placed(1, lampRecord),
new Placed(2, lampRecord),
new Placed(3, lampRecord),
new Placed(4, chairRecord)));
blocks.verify(() -> CraftEngineBlocks.place(any(Location.class), eq(lamp), eq(false)), times(1));
blocks.verify(() -> CraftEngineBlocks.place(location(1), lamp, false));
blocks.verify(() -> CraftEngineBlocks.place(location(2), lamp, false), never());
blocks.verify(() -> CraftEngineBlocks.place(location(3), lamp, false), never());
furniture.verify(() -> CraftEngineFurniture.place(location(4), chairDefinition, "alpha", false));
}
}
private static MockedStatic<RegistryUtil> materialRegistry() {
MockedStatic<RegistryUtil> registry = mockStatic(RegistryUtil.class);
registry.when(() -> RegistryUtil.find(Material.class, "grass", "short_grass")).thenReturn(Material.SHORT_GRASS);
return registry;
}
private static Identifier generatedRecord(ExternalDataSVC service, String key) {
BlockData resolved = service.getBlockData(Identifier.fromString(key)).orElseThrow();
return ((IrisCustomData) resolved).getCustom();
}
private static BlockData blockData(Material material) {
BlockData data = mock(BlockData.class);
when(data.getMaterial()).thenReturn(material);
return data;
}
private static Block block(Chunk chunk, int offset, Material type) {
Block block = mock(Block.class);
when(block.getType()).thenReturn(type);
when(block.getX()).thenReturn(offset);
when(block.getY()).thenReturn(10);
when(block.getZ()).thenReturn(offset);
when(block.getLocation()).thenAnswer((InvocationOnMock invocation) -> location(offset));
when(chunk.getBlock(offset, 10, offset)).thenReturn(block);
return block;
}
private static Location location(int offset) {
return new Location(null, offset, 10, offset);
}
@SuppressWarnings("unchecked")
private static MantleChunk<Matter> records(Placed... records) {
MantleChunk<Matter> chunk = mock(MantleChunk.class);
doAnswer((InvocationOnMock invocation) -> {
Consumer4<Integer, Integer, Integer, Identifier> iterator = invocation.getArgument(1);
for (Placed record : records) {
iterator.accept(record.offset(), 10, record.offset(), record.identifier());
}
return null;
}).when(chunk).iterate(eq(Identifier.class), any());
return chunk;
}
@SuppressWarnings("unchecked")
private static void activate(ExternalDataSVC service, ExternalDataProvider provider) throws Exception {
Field field = ExternalDataSVC.class.getDeclaredField("activeProviders");
field.setAccessible(true);
((List<ExternalDataProvider>) field.get(service)).add(provider);
}
private record Placed(int offset, Identifier identifier) {
}
}
@@ -36,6 +36,7 @@ import art.arcane.iris.world.loot.InventorySlotType;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.world.loot.IrisLootTable;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.generation.block.IrisCustomData;
import art.arcane.iris.generation.block.TileData;
import art.arcane.iris.platform.bukkit.BukkitBlockResolution;
import art.arcane.iris.platform.bukkit.BukkitBlockState;
@@ -83,7 +84,10 @@ import org.bukkit.loot.Lootable;
import java.lang.reflect.Method;
import java.util.ArrayList;
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;
import java.util.concurrent.CompletableFuture;
@@ -146,12 +150,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();
@@ -160,21 +168,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 materializeUpdates(Engine engine, Chunk chunk, MantleChunk<Matter> mantleChunk) {
@@ -855,4 +867,47 @@ public final class EngineBukkitOps {
}
}
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.get(record);
if (carrier == null) {
carrier = carrierType(service, record);
carriers.put(record, carrier);
}
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;
}
}
}
@@ -0,0 +1,265 @@
package art.arcane.iris.platform.generation;
import art.arcane.iris.generation.block.IrisCustomData;
import art.arcane.iris.generation.block.TileData;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.integration.ExternalDataSVC;
import art.arcane.iris.integration.Identifier;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.IrisServices;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import art.arcane.iris.world.IrisWorld;
import art.arcane.iris.world.storage.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.ClassRule;
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 {
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
private static final Identifier ORE = Identifier.fromString("itemsadder:forest/amber_ore");
private static final Identifier CHAIR = Identifier.fromString("craftengine:test/chair[variant=alpha]");
@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;
}
}
}