Match Auto Crafter ingredients by exact item identity #31

Merged
unimatrix merged 3 commits from feat/dunechest-planets-ingredient-identity into main 2026-11-30 18:09:13 +01:00
8 changed files with 192 additions and 8 deletions

View file

@ -28,7 +28,7 @@ jobs:
shell: bash
run: |
set -euo pipefail
gradle --no-daemon -p DuneChest test jar
gradle --no-daemon -p DuneChest test jar paperValidationJar
python3 tools/test_plugin_fleet_install.py -v
python3 tools/test_plugin_pack_properties.py -v
mkdir chest-artifacts
@ -46,3 +46,8 @@ jobs:
name: DuneRealms-Planet-DuneChest
path: chest-artifacts/
if-no-files-found: error
- uses: actions/upload-artifact@v3
with:
name: DuneChest-Paper-Validation
path: DuneChest/build/libs/DuneChestPaperValidation.jar
if-no-files-found: error

View file

@ -1,6 +1,6 @@
plugins { java }
group = "com.example"
version = "1.0.0"
version = "1.0.1"
repositories {
mavenCentral()
maven("https://repo.papermc.io/repository/maven-public/")
@ -18,3 +18,11 @@ tasks.jar { archiveFileName.set("DuneChest.jar") }
java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) }
tasks.withType<JavaCompile> { options.encoding = "UTF-8" }
tasks.test { useJUnitPlatform() }
val paperValidation by sourceSets.creating {
compileClasspath += sourceSets.main.get().output + configurations.compileClasspath.get()
}
tasks.register<Jar>("paperValidationJar") {
archiveFileName.set("DuneChestPaperValidation.jar")
from(paperValidation.output)
}

View file

@ -334,14 +334,23 @@ public final class StorageModule implements Listener, CommandExecutor {
Inventory src = containerAt(b.getRelative(BlockFace.UP)), dst = containerAt(b.getRelative(BlockFace.DOWN));
if (src == null || dst == null || !StorageRules.transferable(src.getType().name()) || !StorageRules.transferable(dst.getType().name())) return;
Recipe r = Bukkit.getCraftingRecipe(p.recipe.clone(), b.getWorld()); if (r == null) return;
Map<Material, Integer> need = new EnumMap<>(Material.class);
for (ItemStack s : p.recipe) if (s != null) need.merge(s.getType(), 1, Integer::sum);
for (var n : need.entrySet()) if (!src.containsAtLeast(new ItemStack(n.getKey()), n.getValue())) return;
ItemStack result = r.getResult().clone();
ItemStack[] ingredients = src.getStorageContents();
ItemStack[] actualGrid = new ItemStack[p.recipe.length];
int[] consumption = StorageRules.matchIngredients(p.recipe, ingredients, actualGrid);
if (consumption == null) return;
Recipe actual = Bukkit.getCraftingRecipe(actualGrid, b.getWorld());
if (!(r instanceof Keyed expected) || !(actual instanceof Keyed matched)
|| !expected.getKey().equals(matched.getKey())) return;
ItemStack result = actual.getResult().clone();
Inventory probe = Bukkit.createInventory(null, Math.min(54, Math.max(9, (dst.getSize() + 8) / 9 * 9)));
for (int i = 0; i < dst.getSize() && i < probe.getSize(); i++) probe.setItem(i, dst.getItem(i));
if (!probe.addItem(result.clone()).isEmpty()) return;
for (var n : need.entrySet()) src.removeItem(new ItemStack(n.getKey(), n.getValue()));
for (int slot = 0; slot < consumption.length; slot++) {
if (consumption[slot] == 0) continue;
ItemStack stack = ingredients[slot];
int remaining = stack.getAmount() - consumption[slot];
src.setItem(slot, remaining == 0 ? null : stack.asQuantity(remaining));
}
dst.addItem(result); data.dirty = true;
}

View file

@ -3,6 +3,7 @@ package com.example.dunechest;
import java.util.*;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.inventory.ItemStack;
/** Pure rules for the custom storage blocks: hopper tiers, filters, ender-chest colour frequencies and pad geometry. */
public final class StorageRules {
@ -71,6 +72,25 @@ public final class StorageRules {
return best;
}
/** Build a grid of real inputs and reserve their source slots without changing the inventory. */
static int[] matchIngredients(ItemStack[] template, ItemStack[] source, ItemStack[] actualGrid) {
int[] consumption = new int[source.length];
for (int gridSlot = 0; gridSlot < template.length; gridSlot++) {
ItemStack ingredient = template[gridSlot];
if (ingredient == null || ingredient.isEmpty()) continue;
int slot = 0;
while (slot < source.length) {
ItemStack stack = source[slot];
if (stack != null && stack.getAmount() > consumption[slot] && ingredient.isSimilar(stack)) break;
slot++;
}
if (slot == source.length) return null;
consumption[slot]++;
actualGrid[gridSlot] = source[slot].asOne();
}
return consumption;
}
static final Set<String> BLOCKED_TARGETS = Set.of("BREWING", "CRAFTER", "JUKEBOX", "LECTERN", "COMPOSTER", "DECORATED_POT", "CHISELED_BOOKSHELF", "BEACON", "ENCHANTING", "ANVIL", "SMITHING");
public static boolean transferable(String inventoryType) { return !BLOCKED_TARGETS.contains(inventoryType); }
}

View file

@ -1,5 +1,5 @@
name: DuneChest
version: 1.0.0
version: 1.0.1
main: com.example.dunechest.DuneChest
api-version: '1.21.8'
softdepend: [floodgate, DuneMenus, DuneEss]

View file

@ -0,0 +1,108 @@
package com.example.dunechest.validation;
import com.example.dunechest.DuneChest;
import com.example.dunechest.StorageModule;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Chest;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.ServerLoadEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
/** Test-only plugin for an isolated Paper server with a disposable world. */
public final class DuneChestPaperValidation extends JavaPlugin implements Listener {
@Override
public void onEnable() {
if (!Boolean.getBoolean("dunechest.validation.disposable")) {
throw new IllegalStateException("This test requires an explicitly disposable server");
}
Bukkit.getPluginManager().registerEvents(this, this);
}
@EventHandler
public void onServerLoad(ServerLoadEvent event) {
if (event.getType() != ServerLoadEvent.LoadType.STARTUP) return;
Bukkit.getScheduler().runTask(this, () -> {
try {
validateCrafter();
getLogger().info("DUNECHEST_VALIDATION {\"ok\":true,\"cases\":4}");
} catch (Exception | AssertionError failure) {
getLogger().log(java.util.logging.Level.SEVERE, "DUNECHEST_VALIDATION {\"ok\":false}", failure);
} finally {
Bukkit.shutdown();
}
});
}
private void validateCrafter() throws ReflectiveOperationException {
StorageModule module = JavaPlugin.getPlugin(DuneChest.class).storage();
ItemStack mk1 = module.issue("speed_hopper", 1);
ItemStack mk2 = module.issue("speed_hopper", 2);
ItemStack mk3 = module.issue("speed_hopper", 3);
Block table = Bukkit.getWorlds().getFirst().getSpawnLocation().add(0, 12, 0).getBlock();
table.setType(Material.CRAFTING_TABLE);
Inventory input = chest(table.getRelative(BlockFace.UP));
Inventory output = chest(table.getRelative(BlockFace.DOWN));
Class<?> placedType = Class.forName("com.example.dunechest.StorageData$Placed",
true, module.getClass().getClassLoader());
var constructor = placedType.getDeclaredConstructor();
constructor.setAccessible(true);
Object placed = constructor.newInstance();
Field recipe = placedType.getDeclaredField("recipe");
recipe.setAccessible(true);
ItemStack diamond = new ItemStack(Material.DIAMOND);
ItemStack redstone = new ItemStack(Material.REDSTONE_BLOCK);
recipe.set(placed, new ItemStack[]{
diamond, redstone, diamond, redstone, mk1, redstone, diamond, redstone, diamond
});
Method craft = module.getClass().getDeclaredMethod("crafter", Block.class, placedType);
craft.setAccessible(true);
load(input, new ItemStack(Material.HOPPER), 4, redstone);
assertRejected(craft, module, table, placed, input, output);
input.setItem(0, mk3.clone());
assertRejected(craft, module, table, placed, input, output);
load(input, mk1, 3, redstone);
assertRejected(craft, module, table, placed, input, output);
load(input, mk3, 4, redstone);
input.setItem(3, mk1.asQuantity(2));
craft.invoke(module, table, placed);
if (!output.containsAtLeast(mk2, 1) || output.containsAtLeast(mk2, 2)
|| !mk3.equals(input.getItem(0)) || input.getItem(1) != null
|| input.getItem(2) != null || !mk1.equals(input.getItem(3))) {
throw new AssertionError("Valid upgrade did not credit and debit the exact stacks");
}
}
private static Inventory chest(Block block) {
block.setType(Material.CHEST);
return ((Chest) block.getState()).getBlockInventory();
}
private static void load(Inventory inventory, ItemStack hopper, int diamonds, ItemStack redstone) {
inventory.clear();
inventory.setItem(0, hopper.clone());
inventory.setItem(1, new ItemStack(Material.DIAMOND, diamonds));
inventory.setItem(2, redstone.asQuantity(4));
}
private static void assertRejected(Method craft, StorageModule module, Block table, Object placed,
Inventory input, Inventory output) throws ReflectiveOperationException {
ItemStack[] before = Arrays.stream(input.getStorageContents())
.map(stack -> stack == null ? null : stack.clone()).toArray(ItemStack[]::new);
craft.invoke(module, table, placed);
if (!Arrays.equals(before, input.getStorageContents()) || !output.isEmpty()) {
throw new AssertionError("A rejected craft changed an inventory");
}
}
}

View file

@ -0,0 +1,5 @@
name: DuneChestPaperValidation
version: 1.0.0
main: com.example.dunechest.validation.DuneChestPaperValidation
api-version: '1.21.8'
depend: [DuneChest]

View file

@ -53,6 +53,35 @@ class StorageRulesTest {
assertTrue(StorageRules.padCentre(BlockFace.NORTH, 0)[0] > StorageRules.padCentre(BlockFace.NORTH, 2)[0]);
}
@Test void crafterReservesOnlyMatchingHopperTiersAndCountsEachIngredient() {
ItemStack mk1 = new HopperStack(1, 1);
ItemStack mk2 = new HopperStack(2, 2);
ItemStack vanilla = new HopperStack(0, 64);
assertNull(StorageRules.matchIngredients(new ItemStack[]{mk1}, new ItemStack[]{vanilla, mk2}, new ItemStack[1]));
assertNull(StorageRules.matchIngredients(new ItemStack[]{mk1, mk1}, new ItemStack[]{vanilla, mk1}, new ItemStack[2]));
ItemStack[] actualGrid = new ItemStack[3];
assertArrayEquals(new int[]{0, 0, 2}, StorageRules.matchIngredients(
new ItemStack[]{mk2, null, mk2}, new ItemStack[]{vanilla, mk1, mk2}, actualGrid));
assertTrue(mk2.isSimilar(actualGrid[0]));
assertNull(actualGrid[1]);
assertEquals(1, actualGrid[2].getAmount());
assertEquals(2, mk2.getAmount());
}
// Model the Bukkit metadata comparison without booting a Paper server.
private static final class HopperStack extends ItemStack {
private final int tier, amount;
HopperStack(int tier, int amount) { this.tier = tier; this.amount = amount; }
@Override public Material getType() { return Material.HOPPER; }
@Override public boolean isEmpty() { return false; }
@Override public ItemStack asOne() { return new HopperStack(tier, 1); }
@Override public int getAmount() { return amount; }
@Override public boolean isSimilar(ItemStack other) {
return other instanceof HopperStack hopper && tier == hopper.tier;
}
}
@Test void mostCommonItemPicksBiggestTotal() {
var counts = new java.util.LinkedHashMap<Material, Integer>();
counts.put(Material.DIRT, 50); counts.put(Material.STONE, 40);