Add InventoryChangedEvent (#282)

This commit is contained in:
Caedis authored and GitHub committed 2026-06-30 14:09:25 -05:00
1 parent e821861847
commit b04aa5287f
18 files changed
+615

No files matched your search

+12
View File
@@ -6,6 +6,18 @@ GTNHLib
Shared code library for GTNH mods
## Events
GTNHLib fires `InventoryChangedEvent` on the Forge event bus when a player's net item holdings change, on both client (local player only) and server. Subscribe to the concrete subclasses:
- `InventoryChangedEvent.ItemAdded` - net gain of an item
- `InventoryChangedEvent.ItemRemoved` - net loss of an item
Each event exposes the representative `ItemStack item`, `getCount()` (absolute amount changed), and `getDelta()` (signed: positive added, negative removed). Items are matched by type and subtype metadata, ignoring NBT, so rearranging or sorting an inventory fires nothing; only crossing an inventory boundary (pickup, drop, chest transfer, crafting) does. Scanned scope: main inventory, armor, the held cursor stack, the 2x2 crafting grid, and Baubles slots when Baubles is installed.
Inventories are scanned every `inventoryScanInterval` ticks (default 5, configurable 1-200 in the GTNHLib config).
Known limitations: items moved into an external crafting-table grid or other open container slots are out of scope, so placing items there reads as a removal and retrieving them reads as an addition. On joining a world the inventory arrives over a few ticks, so a brief burst of add events is possible before the baseline settles.
## Credits
+3
View File
@@ -37,6 +37,9 @@ dependencies {
runtimeOnlyNonPublishable("com.github.GTNewHorizons:NotEnoughItems:2.8.102-GTNH:dev") { transitive = false }
runtimeOnlyNonPublishable("com.github.GTNewHorizons:CodeChickenCore:1.4.15:dev") { transitive = false }
runtimeOnlyNonPublishable("com.github.GTNewHorizons:Applied-Energistics-2-Unofficial:rv3-beta-994-GTNH") {
exclude module:"GTNHLib"
}
// Annotation things
compileOnly("com.github.GTNewHorizons:Angelica:2.1.36:dev") { transitive = false }
@@ -6,6 +6,7 @@ import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.IChatComponent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.FakePlayer;
import com.gtnewhorizon.gtnhlib.blockstate.command.BlockStateCommand;
@@ -23,6 +24,7 @@ import com.gtnewhorizon.gtnhlib.config.ConfigurationManager;
import com.gtnewhorizon.gtnhlib.eventbus.AutoEventBus;
import com.gtnewhorizon.gtnhlib.eventbus.EventBusSubscriber;
import com.gtnewhorizon.gtnhlib.eventbus.Phase;
import com.gtnewhorizon.gtnhlib.eventhandlers.InventoryEventDebugHandler;
import com.gtnewhorizon.gtnhlib.keybind.SyncedKeybind;
import com.gtnewhorizon.gtnhlib.network.NetworkHandler;
import com.gtnewhorizon.gtnhlib.network.PacketMessageAboveHotbar;
@@ -105,6 +107,10 @@ public class CommonProxy {
SyncedKeybind.createConfigurable("gtnhlib.test_keybind", "debug", 0).registerGlobalListener(
(p, l, keyDown) -> { GTNHLib.LOG.info("GTNHLib test keybind down: {}", keyDown); });
}
if (GTNHLibConfig.debugInventoryEvents) {
MinecraftForge.EVENT_BUS.register(new InventoryEventDebugHandler());
}
}
public void postInit(FMLPostInitializationEvent event) {}
@@ -108,4 +108,14 @@ public class GTNHLibConfig {
@Config.DefaultInt(0)
@Config.RangeInt(min = -1000, max = 1000)
public static int titleOffsetY;
@Config.Comment("How often (in ticks) to scan player inventories for the InventoryChangedEvent item add/remove "
+ "events. Higher = less CPU but coarser timing. 1 = every tick.")
@Config.DefaultInt(5)
@Config.RangeInt(min = 1, max = 200)
public static int inventoryScanInterval;
@Config.Comment("Dev only: log every player inventory add/remove event to the console.")
@Config.DefaultBoolean(false)
public static boolean debugInventoryEvents;
}
@@ -0,0 +1,18 @@
package com.gtnewhorizon.gtnhlib.client;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
/** Isolates the client-only {@link Minecraft} reference so it never loads on a dedicated server. */
@SideOnly(Side.CLIENT)
public final class PlayerInventoryClientHelper {
private PlayerInventoryClientHelper() {}
public static boolean isLocalPlayer(EntityPlayer player) {
return player == Minecraft.getMinecraft().thePlayer;
}
}
@@ -0,0 +1,39 @@
package com.gtnewhorizon.gtnhlib.compat;
import java.lang.reflect.Method;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
/**
* Reflection-based access to Baubles inventory (no hard dependency). Lazy-init with double-checked locking.
*/
public final class BaublesCompat {
private static Method getBaublesMethod;
private static volatile boolean resolved;
private BaublesCompat() {}
public static IInventory getBaubles(EntityPlayer player) {
if (!resolved) resolve();
if (getBaublesMethod == null) return null;
try {
return (IInventory) getBaublesMethod.invoke(null, player);
} catch (Throwable t) {
return null;
}
}
// classload attempt is fine since its only done once
private static synchronized void resolve() {
if (resolved) return;
try {
final Class<?> api = Class.forName("baubles.api.BaublesApi");
getBaublesMethod = api.getMethod("getBaubles", EntityPlayer.class);
} catch (Throwable t) {
getBaublesMethod = null;
}
resolved = true;
}
}
@@ -7,4 +7,7 @@ public class Mods {
public static final boolean FALSETWEAKS = Loader.isModLoaded("falsetweaks");
public static final boolean NEI = Loader.isModLoaded("NotEnoughItems");
public static final boolean ANGELICA = Loader.isModLoaded("angelica");
// Covers both Baubles and Baubles-Expanded.
public static final boolean BAUBLES = Loader.isModLoaded("Baubles");
}
@@ -0,0 +1,55 @@
package com.gtnewhorizon.gtnhlib.event;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.entity.player.PlayerEvent;
/**
* Fired when a player's inventory changes (both client and server). Not cancelable. Subscribe to concrete
* {@link ItemAdded} / {@link ItemRemoved} subclasses (1.7.10 Forge cannot register against abstract base without no-arg
* constructor).
*/
public abstract class InventoryChangedEvent extends PlayerEvent {
/** The changed item (representative; identity ignores NBT). Shared across listeners - copy before mutating. */
public final ItemStack item;
protected InventoryChangedEvent(EntityPlayer player, ItemStack item) {
super(player);
this.item = item;
}
/** Absolute amount of the change (always positive). */
public int getCount() {
return item.stackSize;
}
/** Signed change: positive when added, negative when removed. */
public abstract int getDelta();
/** Player gained {@link #item}. */
public static class ItemAdded extends InventoryChangedEvent {
public ItemAdded(EntityPlayer player, ItemStack item) {
super(player, item);
}
@Override
public int getDelta() {
return item.stackSize;
}
}
/** Player lost {@link #item}. */
public static class ItemRemoved extends InventoryChangedEvent {
public ItemRemoved(EntityPlayer player, ItemStack item) {
super(player, item);
}
@Override
public int getDelta() {
return -item.stackSize;
}
}
}
@@ -0,0 +1,43 @@
package com.gtnewhorizon.gtnhlib.eventhandlers;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ChatComponentText;
import com.gtnewhorizon.gtnhlib.GTNHLib;
import com.gtnewhorizon.gtnhlib.event.InventoryChangedEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
/** Dev-only listener that logs inventory change events. Registered with debugInventoryEvents=true. */
public final class InventoryEventDebugHandler {
@SubscribeEvent
public void onItemAdded(InventoryChangedEvent.ItemAdded event) {
log(event);
}
@SubscribeEvent
public void onItemRemoved(InventoryChangedEvent.ItemRemoved event) {
log(event);
}
private static void log(InventoryChangedEvent event) {
final EntityPlayer player = event.entityPlayer;
final String side = player.worldObj.isRemote ? "CLIENT" : "SERVER";
final String verb = event.getDelta() > 0 ? "ADDED" : "REMOVED";
GTNHLib.LOG.info(
"[InvEvent/{}] {} (delta {}) {} x{} for {}",
side,
verb,
event.getDelta(),
event.item.getDisplayName(),
event.getCount(),
player.getCommandSenderName());
if (player.worldObj.isRemote) {
player.addChatMessage(
new ChatComponentText(
"[InvEvent] " + verb + " " + event.item.getDisplayName() + " x" + event.getCount()));
}
}
}
@@ -0,0 +1,69 @@
package com.gtnewhorizon.gtnhlib.eventhandlers;
import java.util.UUID;
import net.minecraft.entity.player.EntityPlayer;
import com.gtnewhorizon.gtnhlib.GTNHLibConfig;
import com.gtnewhorizon.gtnhlib.client.PlayerInventoryClientHelper;
import com.gtnewhorizon.gtnhlib.eventbus.EventBusSubscriber;
import com.gtnewhorizon.gtnhlib.inventory.InventoryEventListeners;
import com.gtnewhorizon.gtnhlib.inventory.InventoryEventPoster;
import com.gtnewhorizon.gtnhlib.inventory.PlayerInvState;
import com.gtnewhorizon.gtnhlib.inventory.PlayerInventoryScanner;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedOutEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.common.network.FMLNetworkEvent;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
@EventBusSubscriber
public final class PlayerInventoryEventHandler {
private static final Object2ObjectOpenHashMap<UUID, PlayerInvState> SERVER_STATES = new Object2ObjectOpenHashMap<>();
private static final Object2ObjectOpenHashMap<UUID, PlayerInvState> CLIENT_STATES = new Object2ObjectOpenHashMap<>();
private static final InventoryEventPoster SERVER_POSTER = new InventoryEventPoster();
private static final InventoryEventPoster CLIENT_POSTER = new InventoryEventPoster();
@SubscribeEvent
public static void onPlayerTick(TickEvent.PlayerTickEvent event) {
if (event.phase != TickEvent.Phase.END) return;
final EntityPlayer player = event.player;
if (player == null || player.inventory == null || player.worldObj == null) return;
final boolean client = player.worldObj.isRemote;
// eval client first so the server never attempts to classload the client Minecraft class
if (client && !PlayerInventoryClientHelper.isLocalPlayer(player)) return;
final Object2ObjectOpenHashMap<UUID, PlayerInvState> states = client ? CLIENT_STATES : SERVER_STATES;
// Skip all scanning when nothing listens. Drop baselines so we re-seed (no backlog burst) once a listener
// returns.
if (!InventoryEventListeners.anySubscribed()) {
if (!states.isEmpty()) states.clear();
return;
}
final UUID id = player.getUniqueID();
PlayerInvState state = states.get(id);
if (state == null) {
state = new PlayerInvState();
// Stagger first scan by a per-player offset so many players' scans don't all land on the same tick.
state.ticksSinceScan = Math.floorMod(id.hashCode(), Math.max(1, GTNHLibConfig.inventoryScanInterval));
states.put(id, state);
}
PlayerInventoryScanner.process(player, state, client ? CLIENT_POSTER : SERVER_POSTER);
}
@SubscribeEvent
public static void onPlayerLogout(PlayerLoggedOutEvent event) {
if (event.player != null) SERVER_STATES.remove(event.player.getUniqueID());
}
@SubscribeEvent
public static void onClientDisconnect(FMLNetworkEvent.ClientDisconnectionFromServerEvent event) {
CLIENT_STATES.clear();
}
}
@@ -0,0 +1,41 @@
package com.gtnewhorizon.gtnhlib.inventory;
import it.unimi.dsi.fastutil.longs.Long2IntMap;
import it.unimi.dsi.fastutil.longs.Long2IntMaps;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
/**
* Diff between two item-count snapshots. Maps must use default-return-0 for absent keys.
*/
public final class InventoryDiffer {
@FunctionalInterface
public interface DeltaConsumer {
/** @param delta positive = added, negative = removed. */
void accept(long key, int delta);
}
private InventoryDiffer() {}
/**
* @param previous prior snapshot; MUST use default-return-0 for absent keys.
* @param current current snapshot; same default-return-0 requirement.
* @param consumer receives one signed delta per identity whose count changed.
*/
public static void diff(Long2IntMap previous, Long2IntMap current, DeltaConsumer consumer) {
final ObjectIterator<Long2IntMap.Entry> ci = Long2IntMaps.fastIterator(current);
while (ci.hasNext()) {
final Long2IntMap.Entry e = ci.next();
final long key = e.getLongKey();
final int delta = e.getIntValue() - previous.get(key);
if (delta != 0) consumer.accept(key, delta);
}
final ObjectIterator<Long2IntMap.Entry> pi = Long2IntMaps.fastIterator(previous);
while (pi.hasNext()) {
final Long2IntMap.Entry e = pi.next();
final long key = e.getLongKey();
if (!current.containsKey(key)) consumer.accept(key, -e.getIntValue());
}
}
}
@@ -0,0 +1,36 @@
package com.gtnewhorizon.gtnhlib.inventory;
import net.minecraftforge.common.MinecraftForge;
import com.gtnewhorizon.gtnhlib.event.InventoryChangedEvent;
import com.gtnewhorizon.gtnhlib.mixins.early.fml.EventBusAccessor;
import cpw.mods.fml.common.eventhandler.ListenerList;
/**
* Cheap "is anyone listening" check so the per-player scan can be skipped entirely when no mod subscribes to the
* inventory change events.
*/
public final class InventoryEventListeners {
private static ListenerList added;
private static ListenerList removed;
private static int forgeBusId;
private static volatile boolean ready;
private InventoryEventListeners() {}
public static boolean anySubscribed() {
if (!ready) init();
return added.getListeners(forgeBusId).length > 0 || removed.getListeners(forgeBusId).length > 0;
}
private static synchronized void init() {
if (ready) return;
forgeBusId = ((EventBusAccessor) (Object) MinecraftForge.EVENT_BUS).getBusID();
// The throwaway instances exist only to reach the per-class ListenerList; their fields are never read.
added = new InventoryChangedEvent.ItemAdded(null, null).getListenerList();
removed = new InventoryChangedEvent.ItemRemoved(null, null).getListenerList();
ready = true;
}
}
@@ -0,0 +1,31 @@
package com.gtnewhorizon.gtnhlib.inventory;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import com.gtnewhorizon.gtnhlib.event.InventoryChangedEvent;
/**
* Reusable {@link InventoryDiffer.DeltaConsumer} that turns a packed-key delta into a posted event.
*/
public final class InventoryEventPoster implements InventoryDiffer.DeltaConsumer {
public EntityPlayer player;
@Override
public void accept(long key, int delta) {
if (delta == 0) return;
final Item item = Item.getItemById(ItemIdentity.unpackId(key));
if (item == null) return;
final int meta = ItemIdentity.unpackMeta(key);
if (delta > 0) {
MinecraftForge.EVENT_BUS
.post(new InventoryChangedEvent.ItemAdded(player, new ItemStack(item, delta, meta)));
} else {
MinecraftForge.EVENT_BUS
.post(new InventoryChangedEvent.ItemRemoved(player, new ItemStack(item, -delta, meta)));
}
}
}
@@ -0,0 +1,23 @@
package com.gtnewhorizon.gtnhlib.inventory;
/**
* Packs item identity (id + metadata) into a single {@code long}. Id in high 32 bits, meta in low 32 bits: Meta is
* zeroed for non-subtype/damageable items. NBT excluded.
*/
public final class ItemIdentity {
private ItemIdentity() {}
public static long pack(int itemId, int meta, boolean hasSubtypes) {
final int significantMeta = hasSubtypes ? meta : 0;
return ((long) itemId << 32) | (significantMeta & 0xFFFFFFFFL);
}
public static int unpackId(long key) {
return (int) (key >>> 32);
}
public static int unpackMeta(long key) {
return (int) (key & 0xFFFFFFFFL);
}
}
@@ -0,0 +1,23 @@
package com.gtnewhorizon.gtnhlib.inventory;
import it.unimi.dsi.fastutil.longs.Long2IntMap;
import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
/** Per-player scan state. {@link #current} is cleared before each fill. */
public final class PlayerInvState {
// Pre-sized so the first fills do not rehash.
private static final int INITIAL_CAPACITY = 64;
public Long2IntMap current = new Long2IntOpenHashMap(INITIAL_CAPACITY);
public Long2IntMap previous = new Long2IntOpenHashMap(INITIAL_CAPACITY);
public boolean seeded = false;
public int ticksSinceScan = 0;
/** After a diff, this scan's {@link #current} becomes {@link #previous} for next time. Does not clear. */
public void swap() {
final Long2IntMap tmp = current;
current = previous;
previous = tmp;
}
}
@@ -0,0 +1,69 @@
package com.gtnewhorizon.gtnhlib.inventory;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.ContainerPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import com.gtnewhorizon.gtnhlib.GTNHLibConfig;
import com.gtnewhorizon.gtnhlib.compat.BaublesCompat;
import com.gtnewhorizon.gtnhlib.compat.Mods;
import it.unimi.dsi.fastutil.longs.Long2IntMap;
/** Builds the per-tick inventory snapshot and diffs it. */
public final class PlayerInventoryScanner {
private PlayerInventoryScanner() {}
/** @param poster a reusable per-side consumer; its {@code player} is set here before diffing. */
public static void process(EntityPlayer player, PlayerInvState state, InventoryEventPoster poster) {
if (++state.ticksSinceScan < GTNHLibConfig.inventoryScanInterval) return;
state.ticksSinceScan = 0;
final Long2IntMap current = state.current;
current.clear();
scan(player, current);
if (!state.seeded) {
state.seeded = true;
state.swap();
return;
}
poster.player = player;
InventoryDiffer.diff(state.previous, current, poster);
state.swap();
}
private static void scan(EntityPlayer player, Long2IntMap out) {
accumulateArray(player.inventory.mainInventory, out);
accumulateArray(player.inventory.armorInventory, out);
accumulate(player.inventory.getItemStack(), out); // cursor / held stack
if (player.inventoryContainer instanceof ContainerPlayer) {
accumulateInventory(((ContainerPlayer) player.inventoryContainer).craftMatrix, out);
}
if (Mods.BAUBLES) {
accumulateInventory(BaublesCompat.getBaubles(player), out);
}
}
private static void accumulateArray(ItemStack[] stacks, Long2IntMap out) {
if (stacks == null) return;
for (ItemStack s : stacks) accumulate(s, out);
}
private static void accumulateInventory(IInventory inv, Long2IntMap out) {
if (inv == null) return;
final int size = inv.getSizeInventory();
for (int i = 0; i < size; i++) accumulate(inv.getStackInSlot(i), out);
}
private static void accumulate(ItemStack stack, Long2IntMap out) {
if (stack == null || stack.getItem() == null || stack.stackSize <= 0) return;
final Item item = stack.getItem();
final long key = ItemIdentity.pack(Item.getIdFromItem(item), stack.getItemDamage(), item.getHasSubtypes());
out.put(key, out.get(key) + stack.stackSize);
}
}
@@ -0,0 +1,77 @@
package com.gtnewhorizon.gtnhlib.inventory;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
class InventoryDifferTest {
private static Long2IntOpenHashMap map(long... kv) {
Long2IntOpenHashMap m = new Long2IntOpenHashMap();
for (int i = 0; i < kv.length; i += 2) m.put(kv[i], (int) kv[i + 1]);
return m;
}
/** Returns key -> delta, order-independent. */
private static Long2IntOpenHashMap deltas(Long2IntOpenHashMap prev, Long2IntOpenHashMap cur) {
Long2IntOpenHashMap out = new Long2IntOpenHashMap();
InventoryDiffer.diff(prev, cur, out::put);
return out;
}
@Test
void sortingFiresNothing() {
// identical totals (items just moved between slots) -> no deltas
assertEquals(0, deltas(map(1, 64, 2, 10), map(1, 64, 2, 10)).size());
}
@Test
void partialAdd() {
Long2IntOpenHashMap d = deltas(map(1, 10), map(1, 15));
assertEquals(1, d.size());
assertEquals(5, d.get(1L));
}
@Test
void partialRemove() {
Long2IntOpenHashMap d = deltas(map(1, 15), map(1, 10));
assertEquals(1, d.size());
assertEquals(-5, d.get(1L));
}
@Test
void fullRemove() {
Long2IntOpenHashMap d = deltas(map(1, 10), map());
assertEquals(1, d.size());
assertEquals(-10, d.get(1L));
}
@Test
void newItem() {
Long2IntOpenHashMap d = deltas(map(), map(1, 10));
assertEquals(1, d.size());
assertEquals(10, d.get(1L));
}
@Test
void typeChangeRemovesOldAddsNew() {
Long2IntOpenHashMap d = deltas(map(1, 5), map(2, 5));
assertEquals(2, d.size());
assertEquals(-5, d.get(1L));
assertEquals(5, d.get(2L));
}
@Test
void gregtechSubtypesDiffIndependently() {
// Same GT meta-item id, three subtypes by metadata. Gain one subtype, lose another, leave the third alone.
final long matA = ItemIdentity.pack(4096, 1000, true);
final long matB = ItemIdentity.pack(4096, 1001, true);
final long matC = ItemIdentity.pack(4096, 1002, true);
Long2IntOpenHashMap d = deltas(map(matA, 4, matB, 8, matC, 2), map(matA, 4, matB, 5, matC, 9));
assertEquals(2, d.size()); // matA unchanged -> no entry
assertEquals(-3, d.get(matB)); // lost 3 of subtype B
assertEquals(7, d.get(matC)); // gained 7 of subtype C
}
}
@@ -0,0 +1,57 @@
package com.gtnewhorizon.gtnhlib.inventory;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import org.junit.jupiter.api.Test;
class ItemIdentityTest {
// A GregTech meta-item: one item id, many subtypes by metadata.
private static final int GT_META_ITEM_ID = 4096;
@Test
void distinctGregtechSubtypesGetDistinctKeys() {
// e.g. two different GT materials/parts on the same meta-item id
long a = ItemIdentity.pack(GT_META_ITEM_ID, 1000, true);
long b = ItemIdentity.pack(GT_META_ITEM_ID, 1001, true);
assertNotEquals(a, b);
}
@Test
void highMetaRoundTrips() {
// a real ItemStack metadata is stored as a short; 32767 is its max
long key = ItemIdentity.pack(GT_META_ITEM_ID, 32767, true);
assertEquals(GT_META_ITEM_ID, ItemIdentity.unpackId(key));
assertEquals(32767, ItemIdentity.unpackMeta(key));
}
@Test
void idAndMetaDoNotCollide() {
// a high id with meta 0 must never equal a low id with a high meta
assertNotEquals(ItemIdentity.pack(GT_META_ITEM_ID, 0, true), ItemIdentity.pack(0, GT_META_ITEM_ID, true));
}
@Test
void damageableItemCollapsesMeta() {
// hasSubtypes == false (a tool): durability/damage must NOT split identity
long fresh = ItemIdentity.pack(7, 0, false);
long worn = ItemIdentity.pack(7, 561, false);
assertEquals(fresh, worn);
assertEquals(0, ItemIdentity.unpackMeta(fresh));
}
@Test
void subtypeItemKeepsMeta() {
long key = ItemIdentity.pack(35, 14, true); // e.g. red wool
assertEquals(14, ItemIdentity.unpackMeta(key));
}
@Test
void metaBeyond16BitsRoundTrips() {
// Pins id in high 32 bits, meta in low 32 (16-bit packing would truncate).
long key = ItemIdentity.pack(1, 100000, true);
assertEquals(1, ItemIdentity.unpackId(key));
assertEquals(100000, ItemIdentity.unpackMeta(key));
}
}