diff --git a/src/main/java/baubles/api/BaublesApi.java b/src/main/java/baubles/api/BaublesApi.java index 3c12674..339afa9 100644 --- a/src/main/java/baubles/api/BaublesApi.java +++ b/src/main/java/baubles/api/BaublesApi.java @@ -1,41 +1,50 @@ package baubles.api; -import java.lang.reflect.Method; - +import baubles.api.expanded.IBaubleSlotInventory; import cpw.mods.fml.common.FMLLog; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; +import java.lang.reflect.Method; + /** * @author Azanor */ -public class BaublesApi +public class BaublesApi { static Method getBaubles; - + + /** + * Returns dynamic slot support from the player's current baubles inventory. + */ + public static IBaubleSlotInventory getBaubleSlots(EntityPlayer player) { + IInventory inventory = getBaubles(player); + return inventory instanceof IBaubleSlotInventory ? (IBaubleSlotInventory) inventory : null; + } + /** * Retrieves the baubles inventory for the supplied player */ public static IInventory getBaubles(EntityPlayer player) { IInventory ot = null; - + try { - if(getBaubles == null) + if(getBaubles == null) { Class fake = Class.forName("baubles.common.lib.PlayerHandler"); getBaubles = fake.getMethod("getPlayerBaubles", EntityPlayer.class); } - + ot = (IInventory) getBaubles.invoke(null, player); - } - catch(Exception ex) - { + } + catch(Exception ex) + { FMLLog.warning("[Baubles API] Could not invoke baubles.common.lib.PlayerHandler method getPlayerBaubles"); } - + return ot; } - + } diff --git a/src/main/java/baubles/api/expanded/BaubleItemHelper.java b/src/main/java/baubles/api/expanded/BaubleItemHelper.java index ba3d8f2..69b59c7 100644 --- a/src/main/java/baubles/api/expanded/BaubleItemHelper.java +++ b/src/main/java/baubles/api/expanded/BaubleItemHelper.java @@ -49,6 +49,7 @@ public class BaubleItemHelper { * @return The item stack. */ public static ItemStack onBaubleRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer player) { + if (itemStackIn == null || itemStackIn.stackSize <= 0) return itemStackIn; IInventory baubles = BaublesApi.getBaubles(player); if(baubles == null) { return itemStackIn; @@ -56,13 +57,16 @@ public class BaubleItemHelper { for(int slotIndex = 0; slotIndex < baubles.getSizeInventory(); slotIndex++) { if(baubles.getStackInSlot(slotIndex) == null && baubles.isItemValidForSlot(slotIndex, itemStackIn)) { if(!worldIn.isRemote) { - baubles.setInventorySlotContents(slotIndex, itemStackIn.copy()); - if(!player.capabilities.isCreativeMode) { - itemStackIn.stackSize = 0; - //Work around the event being fired twice in single player before the return stack is set. - player.inventory.setInventorySlotContents(player.inventory.currentItem, itemStackIn); + ItemStack equipped = itemStackIn.copy(); + equipped.stackSize = 1; + if (!player.capabilities.isCreativeMode) { + itemStackIn.stackSize--; + } + baubles.setInventorySlotContents(slotIndex, equipped); + if (!player.capabilities.isCreativeMode && itemStackIn.stackSize <= 0 + && player.inventory.getCurrentItem() == itemStackIn) { + player.inventory.setInventorySlotContents(player.inventory.currentItem, null); } - ((IBaubleExpanded)itemStackIn.getItem()).onEquipped(itemStackIn, player); return itemStackIn; } } diff --git a/src/main/java/baubles/api/expanded/IBaubleSlotInventory.java b/src/main/java/baubles/api/expanded/IBaubleSlotInventory.java new file mode 100644 index 0000000..b6ed917 --- /dev/null +++ b/src/main/java/baubles/api/expanded/IBaubleSlotInventory.java @@ -0,0 +1,43 @@ +package baubles.api.expanded; + +import java.util.Map; + +import net.minecraft.inventory.IInventory; + +/** + * Optional dynamic slot support. Obtain it through BaublesApi.getBaubleSlots(player). + * Mutations must run on the server game thread. Modifiers persist with the player. + * Use a unique source such as "examplemod:equipment" to keep contributions independent. + * Requests made inside equipment callbacks are applied on the next player tick, after item movement completes. + */ +public interface IBaubleSlotInventory extends IInventory { + + String getSlotType(int slot); + + /** + * Returns a copy of the effective layout, including inactive reserved indices. + */ + String[] getSlotAssignments(); + + int getSlotCount(String type); + + /** + * Returns an immutable snapshot of source identifiers and their additive amounts. + */ + Map getSlotModifiers(String type); + + /** + * Replaces one source's contribution; zero removes that contribution. + */ + void setSlotModifier(String type, String source, int amount); + + /** + * Adjusts one source so that the effective count equals amount at the time of the call. + */ + void setSlotCount(String type, String source, int amount); + + /** + * Removes only the named source, across all types. + */ + void resetSlotModifiers(String source); +} diff --git a/src/main/java/baubles/client/gui/GuiEvents.java b/src/main/java/baubles/client/gui/GuiEvents.java index a7e6f0d..29326ff 100644 --- a/src/main/java/baubles/client/gui/GuiEvents.java +++ b/src/main/java/baubles/client/gui/GuiEvents.java @@ -56,13 +56,14 @@ public class GuiEvents { if (event.gui instanceof GuiPlayerExpanded) { if (event.button.id == 55) { GuiPlayerExpanded expandedInventory = (GuiPlayerExpanded) event.gui; + PacketOpenNormalInventory close = new PacketOpenNormalInventory(event.gui.mc.thePlayer); GuiInventory inventory = new GuiInventory(event.gui.mc.thePlayer); GuiInventoryReflectionHelper.setMousePosition( inventory, expandedInventory.getMouseX(), expandedInventory.getMouseY()); event.gui.mc.displayGuiScreen(inventory); - PacketHandler.INSTANCE.sendToServer(new PacketOpenNormalInventory(event.gui.mc.thePlayer)); + PacketHandler.INSTANCE.sendToServer(close); } } } diff --git a/src/main/java/baubles/client/gui/GuiPlayerExpanded.java b/src/main/java/baubles/client/gui/GuiPlayerExpanded.java index a9eccdf..2ab8e15 100644 --- a/src/main/java/baubles/client/gui/GuiPlayerExpanded.java +++ b/src/main/java/baubles/client/gui/GuiPlayerExpanded.java @@ -1,7 +1,11 @@ package baubles.client.gui; import baubles.api.IBauble; +import baubles.api.expanded.BaubleExpandedSlots; import baubles.api.expanded.IBaubleExpanded; +import baubles.common.Baubles; +import baubles.common.BaublesConfig; +import baubles.common.container.ContainerPlayerExpanded; import baubles.common.container.SlotBauble; import codechicken.lib.vec.Rectangle4i; import codechicken.nei.NEIClientConfig; @@ -10,38 +14,31 @@ import codechicken.nei.api.INEIGuiHandler; import codechicken.nei.api.TaggedInventoryArea; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Optional; - import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.achievement.GuiAchievements; +import net.minecraft.client.gui.achievement.GuiStats; import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.client.gui.inventory.GuiContainerCreative; import net.minecraft.client.gui.inventory.GuiInventory; import net.minecraft.client.resources.I18n; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.util.MathHelper; - +import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; -import baubles.api.expanded.BaubleExpandedSlots; -import baubles.common.Baubles; -import baubles.common.BaublesConfig; -import baubles.common.container.ContainerPlayerExpanded; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.achievement.GuiAchievements; -import net.minecraft.client.gui.achievement.GuiStats; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.util.ResourceLocation; - import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; -import static baubles.common.BaublesConfig.useOldGuiRendering; import static net.minecraft.client.gui.inventory.GuiInventory.func_147046_a; @Optional.Interface(iface = "codechicken.nei.api.INEIGuiHandler", modid = "NotEnoughItems") @@ -70,11 +67,18 @@ public class GuiPlayerExpanded extends GuiContainer implements INEIGuiHandler { public boolean showActivePotionEffects; - /** Amount scrolled in inventory (0 = top, 1 = bottom) */ + /** + * Amount scrolled in inventory (0 = top, 1 = bottom). + */ private float currentScroll; - /** True if the scrollbar is being dragged */ + private final boolean useOldGuiRendering; + /** + * True if the scrollbar is being dragged. + */ private boolean isScrolling; - /** True if the left mouse button was held down last time drawScreen was called. */ + /** + * True if the left mouse button was held down last time drawScreen was called. + */ private boolean wasClicking; private int tooltipIndexCache = -1; @@ -82,6 +86,7 @@ public class GuiPlayerExpanded extends GuiContainer implements INEIGuiHandler { public GuiPlayerExpanded(EntityPlayer player) { super(new ContainerPlayerExpanded(player.inventory, !player.worldObj.isRemote, player)); + useOldGuiRendering = ((ContainerPlayerExpanded) inventorySlots).usesOldGuiRendering(); allowUserInput = true; } @@ -124,11 +129,11 @@ public class GuiPlayerExpanded extends GuiContainer implements INEIGuiHandler { handleScrollbar(mouseX, mouseY); } - float getMouseX() { + public float getMouseX() { return xSizeFloat; } - float getMouseY() { + public float getMouseY() { return ySizeFloat; } @@ -160,7 +165,7 @@ public class GuiPlayerExpanded extends GuiContainer implements INEIGuiHandler { private void drawBaubleSlots() { drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize); int columns = getColumns(); - int upperHeight = 7 + ((BaubleExpandedSlots.slotsCurrentlyUsed() + columns - 1) / columns) * 18; + int upperHeight = 7 + ((getBaubleSlotCount() + columns - 1) / columns) * 18; if (!useOldGuiRendering) { this.mc.getTextureManager().bindTexture(gui_background); } @@ -196,8 +201,8 @@ public class GuiPlayerExpanded extends GuiContainer implements INEIGuiHandler { // Bauble slot backgrounds this.mc.getTextureManager().bindTexture(useOldGuiRendering ? background : gui_background); - for (int slotIndex = 0; slotIndex < BaubleExpandedSlots.slotsCurrentlyUsed(); slotIndex++) { - String slotType = BaubleExpandedSlots.getSlotType(slotIndex); + for (int slotIndex = 0; slotIndex < getBaubleSlotCount(); slotIndex++) { + String slotType = ((ContainerPlayerExpanded) inventorySlots).getBaubleSlot(slotIndex).getSlotType(); if (!BaublesConfig.showUnusedSlots && slotType.equals(BaubleExpandedSlots.unknownType)) { continue; } @@ -231,7 +236,7 @@ public class GuiPlayerExpanded extends GuiContainer implements INEIGuiHandler { } if (!useOldGuiRendering) { - int activeSlots = BaubleExpandedSlots.slotsCurrentlyUsed(); + int activeSlots = getBaubleSlotCount(); int totalRows = (activeSlots + columns - 1) / columns; int renderedCells = totalRows * columns; int slotRowOffset = 0; @@ -318,7 +323,7 @@ public class GuiPlayerExpanded extends GuiContainer implements INEIGuiHandler { // Cursor inside slot rect if (this.func_146978_c(slot.xDisplayPosition, slot.yDisplayPosition, 16, 16, mouseX, mouseY)) { - ItemStack stack = expandedInventory.baubles.getStackInSlot(tooltipIndexCache); + ItemStack stack = slot.getStack(); if(stack == null || stack.stackSize == 0) { // drawHoveringText with default font func_146283_a(tooltipCache, mouseX, mouseY); @@ -331,24 +336,23 @@ public class GuiPlayerExpanded extends GuiContainer implements INEIGuiHandler { for (int slotIndex = 0; slotIndex < expandedInventory.getBaubleSlotCount(); slotIndex++) { if(slotIndex == tooltipIndexCache) continue; - Slot slot = expandedInventory.getBaubleSlot(slotIndex); + SlotBauble slot = expandedInventory.getBaubleSlot(slotIndex); // Cursor inside slot rect if (!this.func_146978_c(slot.xDisplayPosition, slot.yDisplayPosition, 16, 16, mouseX, mouseY)) continue; - ItemStack stack = expandedInventory.baubles.getStackInSlot(slotIndex); + ItemStack stack = slot.getStack(); if(stack != null && stack.stackSize > 0) continue; // Only show tooltip on empty slots tooltipIndexCache = slotIndex; - String slotType = slot instanceof SlotBauble ? ((SlotBauble) slot).getSlotType() : BaubleExpandedSlots.unknownType; + String slotType = slot.getSlotType(); tooltipCache.clear(); // Strip formatting codes String strippedType = StatCollector.translateToLocal("slot." + slotType).replaceAll("ยง[0-9a-fklmnor]", ""); tooltipCache.add(strippedType); - ItemStack heldItem = mc.thePlayer.inventory.getItemStack(); if (heldItem != null && heldItem.stackSize > 0) { @@ -382,6 +386,10 @@ public class GuiPlayerExpanded extends GuiContainer implements INEIGuiHandler { tooltipIndexCache = -1; } + private int getBaubleSlotCount() { + return ((ContainerPlayerExpanded) inventorySlots).getBaubleSlotCount(); + } + private boolean needsScrollBars() { return ((ContainerPlayerExpanded) this.inventorySlots).canScroll(); } @@ -438,7 +446,7 @@ public class GuiPlayerExpanded extends GuiContainer implements INEIGuiHandler { wheel = -(int) Math.addExact(Math.addExact(-wheel, 120), -1) / 120; } } - int i = BaubleExpandedSlots.slotsCurrentlyUsed(); + int i = getBaubleSlotCount(); this.currentScroll = (float) ((double) this.currentScroll - wheel / (double) i); this.currentScroll = MathHelper.clamp_float(this.currentScroll, 0.0F, 1.0F); ((ContainerPlayerExpanded) this.inventorySlots).scrollTo(this.currentScroll); @@ -577,7 +585,7 @@ public class GuiPlayerExpanded extends GuiContainer implements INEIGuiHandler { slotIndent += 16; } - int upperHeight = 7 + ((BaubleExpandedSlots.slotsCurrentlyUsed() + columns - 1) / columns) * 18; + int upperHeight = 7 + ((getBaubleSlotCount() + columns - 1) / columns) * 18; Rectangle4i baubleSlots = new Rectangle4i(guiLeft - slotIndent, guiTop + 4, totalWidth, upperHeight + 4); diff --git a/src/main/java/baubles/common/container/BaubleSlotState.java b/src/main/java/baubles/common/container/BaubleSlotState.java new file mode 100644 index 0000000..4d85c21 --- /dev/null +++ b/src/main/java/baubles/common/container/BaubleSlotState.java @@ -0,0 +1,140 @@ +package baubles.common.container; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import baubles.api.expanded.BaubleExpandedSlots; + +public class BaubleSlotState { + + public static final int MAX_SLOTS = Short.MAX_VALUE - 45; + + private final String[] assignments; + private final Map> modifiers; + + public BaubleSlotState(String[] assignments, Map> modifiers) { + if (assignments.length > MAX_SLOTS) { + throw new IllegalArgumentException("Too many bauble slots: " + assignments.length); + } + this.assignments = assignments.clone(); + this.modifiers = new LinkedHashMap<>(); + for (Map.Entry> entry : modifiers.entrySet()) { + this.modifiers.put(entry.getKey(), Collections.unmodifiableMap(new LinkedHashMap<>(entry.getValue()))); + } + } + + public String[] getAssignments() { + return assignments.clone(); + } + + public String getType(int slot) { + return slot >= 0 && slot < assignments.length ? assignments[slot] : BaubleExpandedSlots.unknownType; + } + + public int getCount(String type) { + int count = 0; + for (String assignment : assignments) { + if (assignment.equals(type)) count++; + } + return count; + } + + public Map> getModifiers() { + return Collections.unmodifiableMap(modifiers); + } + + public Map getModifiers(String type) { + return modifiers.getOrDefault(type, Collections.emptyMap()); + } + + public BaubleSlotState withModifier(String type, String source, int amount) { + validateType(type); + validateSource(source); + Map> updated = new LinkedHashMap<>(modifiers); + Map values = new LinkedHashMap<>(getModifiers(type)); + if (amount == 0) values.remove(source); + else values.put(source, amount); + if (values.isEmpty()) updated.remove(type); + else updated.put(type, values); + return resolve(BaubleExpandedSlots.getCurrentSlotAssignments(), assignments, updated); + } + + public BaubleSlotState withoutSource(String source) { + validateSource(source); + Map> updated = new LinkedHashMap<>(); + for (Map.Entry> entry : modifiers.entrySet()) { + Map values = new LinkedHashMap<>(entry.getValue()); + values.remove(source); + if (!values.isEmpty()) updated.put(entry.getKey(), values); + } + return resolve(BaubleExpandedSlots.getCurrentSlotAssignments(), assignments, updated); + } + + public static void validateType(String type) { + if (!BaubleExpandedSlots.isTypeRegistered(type) || BaubleExpandedSlots.unknownType.equals(type)) { + throw new IllegalArgumentException("Unknown bauble slot type: " + type); + } + } + + public static void validateSource(String source) { + if (source == null || source.trim().isEmpty() || source.length() > 256) { + throw new IllegalArgumentException("A modifier source must contain 1 to 256 characters"); + } + } + + public static BaubleSlotState resolve(String[] base, String[] previous, + Map> modifiers) { + Map remaining = new LinkedHashMap<>(); + for (String type : base) { + if (!BaubleExpandedSlots.unknownType.equals(type)) { + remaining.put(type, remaining.getOrDefault(type, 0L) + 1); + } + } + for (Map.Entry> entry : modifiers.entrySet()) { + if (!BaubleExpandedSlots.isTypeRegistered(entry.getKey()) + || BaubleExpandedSlots.unknownType.equals(entry.getKey())) continue; + long count = remaining.getOrDefault(entry.getKey(), 0L); + for (int amount : entry.getValue().values()) count += amount; + remaining.put(entry.getKey(), Math.max(0L, count)); + } + long total = 0; + for (long count : remaining.values()) total += count; + if (total > MAX_SLOTS || base.length > MAX_SLOTS) { + throw new IllegalArgumentException("Bauble slot capacity exceeds " + MAX_SLOTS); + } + + List layout = new ArrayList<>(Arrays.asList(base)); + for (int slot = 0; slot < base.length; slot++) { + if (!consume(remaining, base[slot])) layout.set(slot, BaubleExpandedSlots.unknownType); + } + for (int slot = base.length; slot < previous.length; slot++) { + String type = previous[slot]; + layout.add(consume(remaining, type) ? type : BaubleExpandedSlots.unknownType); + } + int free = base.length; + for (Map.Entry entry : remaining.entrySet()) { + for (long count = entry.getValue(); count > 0; count--) { + while (free < layout.size() && !BaubleExpandedSlots.unknownType.equals(layout.get(free))) free++; + if (free < layout.size()) layout.set(free, entry.getKey()); + else layout.add(entry.getKey()); + free++; + } + } + while (layout.size() > base.length + && BaubleExpandedSlots.unknownType.equals(layout.get(layout.size() - 1))) { + layout.remove(layout.size() - 1); + } + return new BaubleSlotState(layout.toArray(new String[0]), modifiers); + } + + private static boolean consume(Map counts, String type) { + long count = counts.getOrDefault(type, 0L); + if (count <= 0) return false; + counts.put(type, count - 1); + return true; + } +} diff --git a/src/main/java/baubles/common/container/BaubleSlotStorage.java b/src/main/java/baubles/common/container/BaubleSlotStorage.java new file mode 100644 index 0000000..4f89d5d --- /dev/null +++ b/src/main/java/baubles/common/container/BaubleSlotStorage.java @@ -0,0 +1,51 @@ +package baubles.common.container; + +import java.util.LinkedHashMap; +import java.util.Map; + +import baubles.api.expanded.BaubleExpandedSlots; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.nbt.NBTTagString; + +public class BaubleSlotStorage { + + public static void write(NBTTagCompound tags, BaubleSlotState state) { + NBTTagList layout = new NBTTagList(); + for (String type : state.getAssignments()) layout.appendTag(new NBTTagString(type)); + tags.setTag("Baubles.Slots", layout); + NBTTagList modifiers = new NBTTagList(); + for (Map.Entry> type : state.getModifiers().entrySet()) { + for (Map.Entry source : type.getValue().entrySet()) { + NBTTagCompound entry = new NBTTagCompound(); + entry.setString("Type", type.getKey()); + entry.setString("Source", source.getKey()); + entry.setInteger("Amount", source.getValue()); + modifiers.appendTag(entry); + } + } + tags.setTag("Baubles.SlotModifiers", modifiers); + } + + public static BaubleSlotState read(NBTTagCompound tags) { + String[] assignments = BaubleExpandedSlots.getCurrentSlotAssignments(); + if (tags.hasKey("Baubles.Slots", 9)) { + NBTTagList layout = tags.getTagList("Baubles.Slots", 8); + if (layout.tagCount() > BaubleSlotState.MAX_SLOTS) { + throw new IllegalArgumentException("Saved bauble layout is too large"); + } + assignments = new String[layout.tagCount()]; + for (int i = 0; i < assignments.length; i++) assignments[i] = layout.getStringTagAt(i); + } + Map> modifiers = new LinkedHashMap<>(); + NBTTagList entries = tags.getTagList("Baubles.SlotModifiers", 10); + for (int i = 0; i < entries.tagCount(); i++) { + NBTTagCompound entry = entries.getCompoundTagAt(i); + String source = entry.getString("Source"); + BaubleSlotState.validateSource(source); + modifiers.computeIfAbsent(entry.getString("Type"), key -> new LinkedHashMap<>()) + .put(source, entry.getInteger("Amount")); + } + return new BaubleSlotState(assignments, modifiers); + } +} diff --git a/src/main/java/baubles/common/container/ContainerPlayerExpanded.java b/src/main/java/baubles/common/container/ContainerPlayerExpanded.java index 48246bb..afe1f63 100644 --- a/src/main/java/baubles/common/container/ContainerPlayerExpanded.java +++ b/src/main/java/baubles/common/container/ContainerPlayerExpanded.java @@ -21,8 +21,10 @@ import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.util.IIcon; +import java.util.ArrayList; +import java.util.List; + import static baubles.common.BaublesConfig.maxColumns; -import static baubles.common.BaublesConfig.useOldGuiRendering; public class ContainerPlayerExpanded extends Container { @@ -31,6 +33,9 @@ public class ContainerPlayerExpanded extends Container { public InventoryBaubles baubles; private final EntityPlayer thePlayer; + private final boolean useOldGuiRendering; + private final long layoutRevision; + private final List visibleBaubleSlots = new ArrayList<>(); private int slotsAdded = 0; @@ -40,6 +45,8 @@ public class ContainerPlayerExpanded extends Container { public ContainerPlayerExpanded(InventoryPlayer playerInv, boolean isClient, EntityPlayer player) { this.thePlayer = player; baubles = PlayerHandler.getPlayerBaubles(player); + useOldGuiRendering = baubles.usesOldGuiRendering(); + layoutRevision = baubles.getLayoutRevision(); baubles.setEventHandler(this); int i; @@ -83,15 +90,22 @@ public class ContainerPlayerExpanded extends Container { // Bauble slots baubleFirstSlotIndex = slotsAdded; - String[] currentSlotAssignments = BaubleExpandedSlots.getCurrentSlotAssignments(); - for (String slotType: currentSlotAssignments) { - if (BaublesConfig.showUnusedSlots || !slotType.equals(BaubleExpandedSlots.unknownType)) { - Slot slot = useOldGuiRendering - ? new SlotBauble(baubles, slotType, baubleSlotCount, slotStartX + (slotOffset * (baubleSlotCount / 4)), slotStartY + (slotOffset * (baubleSlotCount % 4))) - : new SlotBauble(baubles, slotType, baubleSlotCount, -18 - (18 * (baubleSlotCount % getColumns())), 12 + (slotOffset * (baubleSlotCount / getColumns()))); - addSlotToContainer(slot); - baubleSlotCount++; - } + String[] currentSlotAssignments = baubles.getSlotAssignments(); + for (String type : currentSlotAssignments) { + if (BaublesConfig.showUnusedSlots || !BaubleExpandedSlots.unknownType.equals(type)) baubleSlotCount++; + } + int visibleIndex = 0; + for (int index = 0; index < currentSlotAssignments.length; index++) { + String type = currentSlotAssignments[index]; + boolean visible = BaublesConfig.showUnusedSlots || !BaubleExpandedSlots.unknownType.equals(type); + int x = useOldGuiRendering ? slotStartX + slotOffset * (visibleIndex / 4) : -18 - 18 * (visibleIndex % getColumns()); + int y = useOldGuiRendering ? slotStartY + slotOffset * (visibleIndex % 4) : 12 + slotOffset * (visibleIndex / getColumns()); + SlotBauble slot = new SlotBauble(baubles, type, index, x, y); + addSlotToContainer(slot); + if (visible) { + visibleBaubleSlots.add(slot); + visibleIndex++; + } else slot.yDisplayPosition = -2000; } // Inventory slots @@ -128,7 +142,10 @@ public class ContainerPlayerExpanded extends Container { @Override public void onContainerClosed(EntityPlayer player) { + ItemStack cursor = player.inventory.getItemStack(); + player.inventory.setItemStack(null); super.onContainerClosed(player); + if (cursor != null && !player.worldObj.isRemote) PlayerHandler.getPlayerBaubles(player).returnItem(cursor); if (baubles != null && baubles.getEventHandler() == this) { baubles.setEventHandler(null); @@ -140,17 +157,10 @@ public class ContainerPlayerExpanded extends Container { for (int i = 0; i < 4; ++i) { ItemStack itemstack = this.craftMatrix.getStackInSlotOnClosing(i); - if (itemstack != null) { - if (!player.inventory.addItemStackToInventory(itemstack)) { - player.dropPlayerItemWithRandomChoice(itemstack, false); - } - } + if (itemstack != null && !player.worldObj.isRemote) PlayerHandler.getPlayerBaubles(player).returnItem(itemstack); } this.craftResult.setInventorySlotContents(0, null); - if (!player.worldObj.isRemote) { - PlayerHandler.setPlayerBaubles(player, baubles); - } } public int getBaubleSlotCount() { @@ -159,12 +169,16 @@ public class ContainerPlayerExpanded extends Container { public SlotBauble getBaubleSlot(int slotIndex) { if(slotIndex < 0 || slotIndex >= baubleSlotCount) return null; - return (SlotBauble) inventorySlots.get(baubleFirstSlotIndex + slotIndex); + return visibleBaubleSlots.get(slotIndex); + } + + public boolean usesOldGuiRendering() { + return useOldGuiRendering; } public void scrollTo(float offset) { if (!canScroll()) return; - final int activeBaubleSlots = BaubleExpandedSlots.slotsCurrentlyUsed(); + final int activeBaubleSlots = baubleSlotCount; final int columns = getColumns(); offset = Math.max(0, Math.min(1, offset)); @@ -177,8 +191,8 @@ public class ContainerPlayerExpanded extends Container { slotRowOffset = 0; } - for (int i = 0; i < activeBaubleSlots && i < BaubleExpandedSlots.slotsCurrentlyUsed(); i++) { - Slot slot = (Slot) this.inventorySlots.get(baubleFirstSlotIndex + i); + for (int i = 0; i < activeBaubleSlots; i++) { + Slot slot = visibleBaubleSlots.get(i); int row = i / columns; int scrolledRow = row - slotRowOffset; slot.yDisplayPosition = 12 + scrolledRow * 18; @@ -189,7 +203,7 @@ public class ContainerPlayerExpanded extends Container { } public int getColumns() { - int activeBaubleSlots = BaubleExpandedSlots.slotsCurrentlyUsed(); + int activeBaubleSlots = baubleSlotCount; for (int cols = 1; cols < maxColumns; cols++) { if ((activeBaubleSlots + cols - 1) / cols <= 8) { return cols; @@ -199,12 +213,22 @@ public class ContainerPlayerExpanded extends Container { } public boolean canScroll() { - return BaubleExpandedSlots.slotsCurrentlyUsed() > maxColumns * 8 && !useOldGuiRendering; + return baubleSlotCount > (long) maxColumns * 8 && !useOldGuiRendering; } @Override public boolean canInteractWith(EntityPlayer player) { - return true; + return player == thePlayer && player.isEntityAlive() && baubles == PlayerHandler.getPlayerBaubles(player) + && layoutRevision == baubles.getLayoutRevision(); + } + + @Override + public ItemStack slotClick(int slot, int button, int mode, EntityPlayer player) { + if (!canInteractWith(player) || slot >= inventorySlots.size() || slot < -1 && slot != -999 + || mode < 0 || mode > 6 || button < 0) return null; + if (mode == 2 ? button > 8 : mode == 3 ? button != 2 + : mode == 5 ? button > 10 || (button & 3) > 2 : button > 1) return null; + return super.slotClick(slot, button, mode, player); } /** @@ -212,15 +236,16 @@ public class ContainerPlayerExpanded extends Container { */ @Override public ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) { + if (!canInteractWith(player) || slotIndex < 0 || slotIndex >= inventorySlots.size()) return null; ItemStack returnStack = null; Slot slot = (Slot) inventorySlots.get(slotIndex); - final int visibleBaubleSlots = BaubleExpandedSlots.slotsCurrentlyUsed(); + final int visibleBaubleSlots = baubles.getSizeInventory(); int craftingActive = 5; if (useOldGuiRendering) { craftingActive = 0; } - if (slot == null || !slot.getHasStack()) { + if (slot == null || !slot.getHasStack() || !slot.canTakeStack(player)) { return returnStack; } ItemStack originalStack = slot.getStack(); @@ -242,9 +267,11 @@ public class ContainerPlayerExpanded extends Container { return null; } } else if (slotIndex >= baubleStart && slotIndex < baubleEnd) { - if (!mergeItemStack(originalStack, baubleEnd, hotbarEnd, false, slot)) { - returnStack = null; - } + ItemStack remaining = originalStack.copy(); + if (!mergeItemStack(remaining, baubleEnd, hotbarEnd, false, slot)) return null; + ItemStack removed = slot.decrStackSize(originalStack.stackSize - remaining.stackSize); + slot.onPickupFromSlot(player, removed); + return returnStack; } else if (item instanceof ItemArmor armor && !((Slot) inventorySlots.get(craftingActive + armor.armorType)).getHasStack()) { int armorSlot = craftingActive + armor.armorType; @@ -255,6 +282,7 @@ public class ContainerPlayerExpanded extends Container { String[] types = item instanceof IBaubleExpanded ? ((IBaubleExpanded) item).getBaubleTypes(returnStack) : new String[] {BaubleExpandedSlots.getTypeFromBaubleType(bauble.getBaubleType(returnStack))}; + if (types == null) return null; // Priority 2: direct slot matches (or universal items) tryMergeIntoBaubleSlotsByPriority(originalStack, baubleStart, baubleEnd, types, 2); @@ -290,16 +318,15 @@ public class ContainerPlayerExpanded extends Container { return returnStack; } - private void unequipBauble(ItemStack stack) { - //if (stack.getItem() instanceof IBauble) { - // ((IBauble)stack.getItem()).onUnequipped(stack, thePlayer); - //} - } - @Override public void putStacksInSlots(ItemStack[] p_75131_1_) { + boolean previous = baubles.blockEvents; baubles.blockEvents = true; - super.putStacksInSlots(p_75131_1_); + try { + super.putStacksInSlots(p_75131_1_); + } finally { + baubles.blockEvents = previous; + } } private void tryMergeIntoBaubleSlotsByPriority(ItemStack sourceStack, int baubleStart, int baubleEnd, String[] itemTypes, int priority) { @@ -350,67 +377,38 @@ public class ContainerPlayerExpanded extends Container { return best; } - protected boolean mergeItemStack(ItemStack sourceStack, int startIndex, int endIndex, boolean reverse, Slot sourceSlot) { + @Override + protected boolean mergeItemStack(ItemStack sourceStack, int startIndex, int endIndex, boolean reverse) { boolean merged = false; - int index = reverse ? endIndex - 1 : startIndex; - - Slot targetSlot; - ItemStack targetStack; - - // First pass: try stacking into existing stacks - if (sourceStack.isStackable()) { - while (sourceStack.stackSize > 0 && (!reverse && index < endIndex || reverse && index >= startIndex)) { - targetSlot = (Slot) inventorySlots.get(index); - targetStack = targetSlot.getStack(); - - if (targetStack != null && targetStack.getItem() == sourceStack.getItem() && - (!sourceStack.getHasSubtypes() || sourceStack.getItemDamage() == targetStack.getItemDamage()) && - ItemStack.areItemStackTagsEqual(sourceStack, targetStack)) { - - int combinedSize = targetStack.stackSize + sourceStack.stackSize; - - if (combinedSize <= sourceStack.getMaxStackSize()) { - if (sourceSlot instanceof SlotBauble) { - unequipBauble(sourceStack); - } - sourceStack.stackSize = 0; - targetStack.stackSize = combinedSize; - targetSlot.onSlotChanged(); - return true; - } else if (targetStack.stackSize < sourceStack.getMaxStackSize()) { - if (sourceSlot instanceof SlotBauble) { - unequipBauble(sourceStack); - } - sourceStack.stackSize -= sourceStack.getMaxStackSize() - targetStack.stackSize; - targetStack.stackSize = sourceStack.getMaxStackSize(); - targetSlot.onSlotChanged(); - merged = true; - } + for (int pass = 0; pass < 2 && sourceStack.stackSize > 0; pass++) { + for (int index = reverse ? endIndex - 1 : startIndex; + sourceStack.stackSize > 0 && index >= startIndex && index < endIndex; + index += reverse ? -1 : 1) { + Slot targetSlot = (Slot) inventorySlots.get(index); + ItemStack targetStack = targetSlot.getStack(); + if ((pass == 0) != (targetStack != null) || !targetSlot.isItemValid(sourceStack)) continue; + int limit = Math.min(sourceStack.getMaxStackSize(), targetSlot.getSlotStackLimit()); + if (targetStack != null) { + if (!sourceStack.isStackable() || !sourceStack.isItemEqual(targetStack) + || !ItemStack.areItemStackTagsEqual(sourceStack, targetStack)) continue; + int moved = Math.min(sourceStack.stackSize, limit - targetStack.stackSize); + if (moved <= 0) continue; + sourceStack.stackSize -= moved; + targetStack.stackSize += moved; + targetSlot.onSlotChanged(); + } else { + int moved = Math.min(sourceStack.stackSize, limit); + if (moved <= 0) continue; + ItemStack inserted = sourceStack.splitStack(moved); + targetSlot.putStack(inserted); } - - index = reverse ? index - 1 : index + 1; + merged = true; } } - - // Second pass: put into empty slots - index = reverse ? endIndex - 1 : startIndex; - while (!reverse && index < endIndex || reverse && index >= startIndex) { - targetSlot = (Slot) inventorySlots.get(index); - targetStack = targetSlot.getStack(); - - if (targetStack == null) { - if (sourceSlot instanceof SlotBauble) { - unequipBauble(sourceStack); - } - targetSlot.putStack(sourceStack.copy()); - targetSlot.onSlotChanged(); - sourceStack.stackSize = 0; - return true; - } - - index = reverse ? index - 1 : index + 1; - } - return merged; } + + protected boolean mergeItemStack(ItemStack sourceStack, int startIndex, int endIndex, boolean reverse, Slot sourceSlot) { + return mergeItemStack(sourceStack, startIndex, endIndex, reverse); + } } diff --git a/src/main/java/baubles/common/container/InventoryBaubles.java b/src/main/java/baubles/common/container/InventoryBaubles.java index 9345307..671fb8c 100644 --- a/src/main/java/baubles/common/container/InventoryBaubles.java +++ b/src/main/java/baubles/common/container/InventoryBaubles.java @@ -1,39 +1,285 @@ package baubles.common.container; -import java.lang.ref.WeakReference; -import java.util.ArrayList; - import baubles.api.BaubleType; import baubles.api.IBauble; import baubles.api.expanded.BaubleExpandedSlots; import baubles.api.expanded.IBaubleExpanded; +import baubles.api.expanded.IBaubleSlotInventory; +import baubles.common.Baubles; import baubles.common.BaublesConfig; import baubles.common.lib.ItemStackHelper; import baubles.common.network.PacketHandler; +import baubles.common.network.PacketSyncAllBauble; import baubles.common.network.PacketSyncBauble; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.Container; -import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.MathHelper; -public class InventoryBaubles implements IInventory { +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.ArrayDeque; +import java.util.Arrays; +import java.util.Collections; +import java.util.Map; + +public class InventoryBaubles implements IBaubleSlotInventory { public ItemStack[] stackList; private Container eventHandler; public WeakReference player; public boolean blockEvents = false; + private BaubleSlotState slotState; + private long layoutRevision; + private boolean changingSlots; + private int callbackDepth; + private boolean returningItems; + private BaubleSlotState pendingSlotState; + private boolean oldGuiRendering = BaublesConfig.useOldGuiRendering; + private WeakReference loadedPlayer = new WeakReference<>(null); + private final ArrayDeque pendingReturns = new ArrayDeque<>(); public InventoryBaubles(EntityPlayer player) { - stackList = new ItemStack[BaubleExpandedSlots.slotsCurrentlyUsed()]; + slotState = new BaubleSlotState(BaubleExpandedSlots.getCurrentSlotAssignments(), Collections.emptyMap()); + stackList = new ItemStack[slotState.getAssignments().length]; this.player = new WeakReference<>(player); } + @Override + public String getSlotType(int slot) { + return slotState.getType(slot); + } + + @Override + public String[] getSlotAssignments() { + return slotState.getAssignments(); + } + + @Override + public int getSlotCount(String type) { + return slotState.getCount(type); + } + + @Override + public Map getSlotModifiers(String type) { + return slotState.getModifiers(type); + } + + public BaubleSlotState getSlotState() { + return slotState; + } + + public long getLayoutRevision() { + return layoutRevision; + } + + public boolean usesOldGuiRendering() { + return oldGuiRendering; + } + + @Override + public void setSlotModifier(String type, String source, int amount) { + requireServerPlayer(); + updateSlots(getPendingSlotState().withModifier(type, source, amount)); + } + + @Override + public void setSlotCount(String type, String source, int amount) { + requireServerPlayer(); + if (amount < 0 || amount > BaubleSlotState.MAX_SLOTS) { + throw new IllegalArgumentException("Slot count must be between 0 and " + BaubleSlotState.MAX_SLOTS); + } + long contribution = amount; + contribution -= BaubleExpandedSlots.totalCurrentlyAssignedSlotsOfType(type); + for (Map.Entry modifier : getPendingSlotState().getModifiers(type).entrySet()) { + if (!modifier.getKey().equals(source)) contribution -= modifier.getValue(); + } + if (contribution < Integer.MIN_VALUE || contribution > Integer.MAX_VALUE) { + throw new IllegalArgumentException("Slot modifier overflow"); + } + setSlotModifier(type, source, (int) contribution); + } + + @Override + public void resetSlotModifiers(String source) { + requireServerPlayer(); + updateSlots(getPendingSlotState().withoutSource(source)); + } + + private BaubleSlotState getPendingSlotState() { + return pendingSlotState == null ? slotState : pendingSlotState; + } + + private EntityPlayer requireServerPlayer() { + EntityPlayer owner = player.get(); + if (owner == null || owner.worldObj.isRemote) { + throw new IllegalStateException("Slot mutations require a server player"); + } + return owner; + } + + private void updateSlots(BaubleSlotState updated) { + EntityPlayer owner = requireServerPlayer(); + if (callbackDepth > 0 || changingSlots || returningItems) { + pendingSlotState = updated; + return; + } + pendingSlotState = null; + String[] assignments = updated.getAssignments(); + if (Arrays.equals(assignments, getSlotAssignments()) + && updated.getModifiers().equals(slotState.getModifiers())) return; + changingSlots = true; + try { + boolean closedBaubles = owner.openContainer instanceof ContainerPlayerExpanded; + if (closedBaubles) owner.closeScreen(); + ItemStack[] previous = stackList; + BaubleSlotState previousState = slotState; + slotState = updated; + stackList = Arrays.copyOf(previous, assignments.length); + layoutRevision++; + for (int slot = 0; slot < previous.length; slot++) { + if (previousState.getType(slot).equals(updated.getType(slot)) && slot < stackList.length) continue; + ItemStack stack = previous[slot]; + if (slot < stackList.length) stackList[slot] = null; + if (stack != null) { + notifyUnequipped(stack, owner); + pendingReturns.add(stack); + } + } + returnOverflowItems(); + markDirty(); + if (owner instanceof EntityPlayerMP serverPlayer) { + // Correct client predictions made before the close packet arrived. + if (closedBaubles) serverPlayer.sendContainerToPlayer(serverPlayer.inventoryContainer); + PacketHandler.sendToTracking(new PacketSyncAllBauble(owner), owner, true); + } + } finally { + changingSlots = false; + } + } + + private void notifyUnequipped(ItemStack stack, EntityPlayer owner) { + if (stack.getItem() instanceof IBauble bauble) { + callbackDepth++; + try { + bauble.onUnequipped(stack, owner); + } catch (Exception e) { + Baubles.log.error("Error unequipping bauble {}", stack, e); + } finally { + callbackDepth--; + } + } + } + + private void notifyEquipped(ItemStack stack, EntityPlayer owner) { + if (owner != null && stack.getItem() instanceof IBauble bauble) { + callbackDepth++; + try { + bauble.onEquipped(stack, owner); + } catch (Exception e) { + Baubles.log.error("Error equipping bauble {}", stack, e); + } finally { + callbackDepth--; + } + } + } + + public void tick() { + EntityPlayer owner = player.get(); + if (owner == null) return; + if (!owner.worldObj.isRemote) { + if (pendingSlotState != null && callbackDepth == 0 && !changingSlots && !returningItems) { + updateSlots(pendingSlotState); + } + if (owner.ticksExisted % 20 == 0) returnOverflowItems(); + } + for (int slot = 0; slot < getSizeInventory(); slot++) { + ItemStack stack = getStackInSlot(slot); + if (stack == null || !(stack.getItem() instanceof IBauble bauble)) continue; + callbackDepth++; + try { + bauble.onWornTick(stack, owner); + } finally { + callbackDepth--; + } + } + } + + public void onSlotContentsChanged(int slot) { + ItemStack stack = getStackInSlot(slot); + EntityPlayer owner = player.get(); + if (!blockEvents && owner != null && stack != null && stack.getItem() instanceof IBaubleExpanded bauble) { + callbackDepth++; + try { + bauble.onSlotContentsChanged(stack, owner); + } catch (Exception e) { + Baubles.log.error("Error updating bauble {}", stack, e); + } finally { + callbackDepth--; + } + } + syncSlotToClients(slot); + } + + public void applySnapshot(BaubleSlotState state, long revision, ItemStack[] stacks, boolean oldGui) { + EntityPlayer owner = player.get(); + if (owner == null || !owner.worldObj.isRemote) return; + if (loadedPlayer.get() == owner && revision < layoutRevision) return; + if (stacks.length != state.getAssignments().length) { + throw new IllegalArgumentException("Snapshot items and layout have different sizes"); + } + ItemStack[] previous = stackList; + boolean loadAll = loadedPlayer.get() != owner; + loadedPlayer = new WeakReference<>(owner); + slotState = state; + stackList = stacks.clone(); + layoutRevision = revision; + oldGuiRendering = oldGui; + for (int slot = 0; slot < Math.max(previous.length, stacks.length); slot++) { + ItemStack before = slot < previous.length ? previous[slot] : null; + ItemStack after = getStackInSlot(slot); + if (!loadAll && ItemStack.areItemStacksEqual(before, after)) continue; + if (before != null && !loadAll) notifyUnequipped(before, owner); + if (after != null && after.getItem() instanceof IBauble bauble) { + try { + bauble.onPlayerLoad(after, owner); + } catch (Exception e) { + Baubles.log.error("Error loading bauble {}", after, e); + } + } + } + } + + public void returnOverflowItems() { + EntityPlayer owner = player.get(); + if (owner == null || owner.worldObj.isRemote || returningItems || pendingReturns.isEmpty()) return; + returningItems = true; + try { + int count = pendingReturns.size(); + while (count-- > 0) { + if (ItemStackHelper.returnToPlayer(owner, pendingReturns.peekFirst())) pendingReturns.removeFirst(); + else pendingReturns.addLast(pendingReturns.removeFirst()); + } + } finally { + returningItems = false; + } + } + + /** + * Returns a detached stack, retaining it for later delivery if a drop is cancelled. + */ + public void returnItem(ItemStack stack) { + requireServerPlayer(); + if (stack == null || stack.stackSize <= 0) return; + pendingReturns.add(stack); + returnOverflowItems(); + } + public Container getEventHandler() { return eventHandler; } @@ -55,7 +301,7 @@ public class InventoryBaubles implements IInventory { */ @Override public ItemStack getStackInSlot(int slot) { - return slot >= getSizeInventory() ? null : stackList[slot]; + return slot < 0 || slot >= getSizeInventory() ? null : stackList[slot]; } /** @@ -81,13 +327,7 @@ public class InventoryBaubles implements IInventory { */ @Override public ItemStack getStackInSlotOnClosing(int slot) { - if(stackList[slot] != null) { - ItemStack itemstack = this.stackList[slot]; - stackList[slot] = null; - return itemstack; - } else { - return null; - } + return decrStackSize(slot, Integer.MAX_VALUE); } /** @@ -96,6 +336,7 @@ public class InventoryBaubles implements IInventory { */ @Override public ItemStack decrStackSize(int slot, int decrementBy) { + if (slot < 0 || slot >= stackList.length || decrementBy <= 0) return null; if(stackList[slot] != null) { ItemStack itemstack; @@ -103,24 +344,19 @@ public class InventoryBaubles implements IInventory { itemstack = stackList[slot]; stackList[slot] = null; - if(itemstack != null && itemstack.getItem() instanceof IBauble) { - ((IBauble) itemstack.getItem()).onUnequipped(itemstack, player.get()); - } } else { itemstack = stackList[slot].splitStack(decrementBy); - if(itemstack != null && itemstack.getItem() instanceof IBauble) { - ((IBauble)itemstack.getItem()).onUnequipped(itemstack, player.get()); - } - if(stackList[slot].stackSize == 0) { stackList[slot] = null; } } + if (!blockEvents) notifyUnequipped(itemstack, player.get()); if(eventHandler != null) eventHandler.onCraftMatrixChanged(this); syncSlotToClients(slot); + markDirty(); return itemstack; } else { return null; @@ -133,19 +369,19 @@ public class InventoryBaubles implements IInventory { */ @Override public void setInventorySlotContents(int slot, ItemStack stack) { - if (!blockEvents && stackList[slot] != null && stackList[slot].getItem() instanceof IBauble bauble) { - bauble.onUnequipped(stackList[slot], player.get()); - } + if (slot < 0 || slot >= stackList.length) return; + ItemStack previous = stackList[slot]; + boolean changed = !ItemStack.areItemStacksEqual(previous, stack); stackList[slot] = stack; - if (!blockEvents && stack != null && stack.getItem() instanceof IBauble bauble) { - if (player.get() != null) { - bauble.onEquipped(stack, player.get()); - } + if (!blockEvents && changed) { + if (previous != null) notifyUnequipped(previous, player.get()); + if (stack != null) notifyEquipped(stack, player.get()); } if (eventHandler != null) { eventHandler.onCraftMatrixChanged(this); } syncSlotToClients(slot); + markDirty(); } /** @@ -191,8 +427,8 @@ public class InventoryBaubles implements IInventory { */ @Override public boolean isItemValidForSlot(int slot, ItemStack stack) { - String slotType = BaubleExpandedSlots.getSlotType(slot); - if (stack == null || slotType == null) { + String slotType = getSlotType(slot); + if (stack == null || slot < 0 || slot >= getSizeInventory() || BaubleExpandedSlots.unknownType.equals(slotType)) { return false; } @@ -209,6 +445,7 @@ public class InventoryBaubles implements IInventory { types = new String[] {BaubleExpandedSlots.getTypeFromBaubleType(legacyType)}; } + if (types == null) return false; for(String type : types) { if (BaublesConfig.canTypeFitSlot(type, slotType)) { return true; @@ -224,17 +461,22 @@ public class InventoryBaubles implements IInventory { } public void saveNBT(NBTTagCompound tags) { + BaubleSlotStorage.write(tags, new BaubleSlotState(slotState.getAssignments(), getPendingSlotState().getModifiers())); NBTTagList tagList = new NBTTagList(); NBTTagCompound invSlot; for (int slot = 0; slot < stackList.length; ++slot) { if (stackList[slot] != null) { invSlot = new NBTTagCompound(); invSlot.setByte("Slot", (byte) slot); + invSlot.setInteger("SlotIndex", slot); stackList[slot].writeToNBT(invSlot); tagList.appendTag(invSlot); } } tags.setTag("Baubles.Inventory", tagList); + NBTTagList overflow = new NBTTagList(); + for (ItemStack stack : pendingReturns) overflow.appendTag(stack.writeToNBT(new NBTTagCompound())); + tags.setTag("Baubles.Overflow", overflow); } public void readNBT(EntityPlayer player) { @@ -243,15 +485,33 @@ public class InventoryBaubles implements IInventory { } public void readNBT(NBTTagCompound tags) { + pendingSlotState = null; + BaubleSlotState saved = BaubleSlotStorage.read(tags); + slotState = BaubleSlotState.resolve(BaubleExpandedSlots.getCurrentSlotAssignments(), + saved.getAssignments(), saved.getModifiers()); + stackList = new ItemStack[slotState.getAssignments().length]; + pendingReturns.clear(); NBTTagList tagList = tags.getTagList("Baubles.Inventory", 10); for (int i = 0; i < tagList.tagCount(); ++i) { - NBTTagCompound nbttagcompound = (NBTTagCompound) tagList.getCompoundTagAt(i); - int slot = nbttagcompound.getByte("Slot") & 255; + NBTTagCompound nbttagcompound = tagList.getCompoundTagAt(i); + int slot = nbttagcompound.hasKey("SlotIndex", 3) + ? nbttagcompound.getInteger("SlotIndex") : nbttagcompound.getByte("Slot") & 255; ItemStack itemstack = ItemStack.loadItemStackFromNBT(nbttagcompound); if (itemstack != null) { - stackList[slot] = itemstack; + if (slot >= 0 && slot < stackList.length && stackList[slot] == null + && !BaubleExpandedSlots.unknownType.equals(getSlotType(slot)) + && saved.getType(slot).equals(getSlotType(slot))) { + stackList[slot] = itemstack; + } else { + pendingReturns.add(itemstack); + } } } + NBTTagList overflow = tags.getTagList("Baubles.Overflow", 10); + for (int i = 0; i < overflow.tagCount(); i++) { + ItemStack stack = ItemStack.loadItemStackFromNBT(overflow.getCompoundTagAt(i)); + if (stack != null) pendingReturns.add(stack); + } } public void dropItems(ArrayList drops) { @@ -294,6 +554,7 @@ public class InventoryBaubles implements IInventory { } public void syncSlotToClients(int slot) { + if (changingSlots) return; try { final EntityPlayer entityPlayer = this.player.get(); if (entityPlayer instanceof EntityPlayerMP playerMP && !entityPlayer.worldObj.isRemote) { diff --git a/src/main/java/baubles/common/container/SlotBauble.java b/src/main/java/baubles/common/container/SlotBauble.java index 8db48bf..233c4e3 100644 --- a/src/main/java/baubles/common/container/SlotBauble.java +++ b/src/main/java/baubles/common/container/SlotBauble.java @@ -45,7 +45,7 @@ public class SlotBauble extends Slot { */ @Override public boolean isItemValid(ItemStack stack) { - if (stack == null) { + if (stack == null || BaubleExpandedSlots.unknownType.equals(slotType)) { return false; } @@ -62,6 +62,7 @@ public class SlotBauble extends Slot { types = new String[] {BaubleExpandedSlots.getTypeFromBaubleType(legacyType)}; } + if (types == null) return false; for(String type : types) { if (BaublesConfig.canTypeFitSlot(type, slotType)) { return true; @@ -75,15 +76,9 @@ public class SlotBauble extends Slot { public void onSlotChanged() { super.onSlotChanged(); - ItemStack stack = getStack(); - if (stack == null || !(stack.getItem() instanceof IBaubleExpanded bauble) - || !(inventory instanceof InventoryBaubles baubleInventory)) { - return; - } - EntityPlayer player = baubleInventory.player.get(); - if (player != null) { - bauble.onSlotContentsChanged(stack, player); - } + if (inventory instanceof InventoryBaubles baubleInventory) { + baubleInventory.onSlotContentsChanged(getSlotIndex()); + } } @Override diff --git a/src/main/java/baubles/common/event/EventHandlerEntity.java b/src/main/java/baubles/common/event/EventHandlerEntity.java index 84e46d2..ff1e81e 100644 --- a/src/main/java/baubles/common/event/EventHandlerEntity.java +++ b/src/main/java/baubles/common/event/EventHandlerEntity.java @@ -5,21 +5,30 @@ import java.io.IOException; import com.google.common.io.Files; -import baubles.api.IBauble; import baubles.common.Baubles; import baubles.common.container.InventoryBaubles; import baubles.common.lib.PlayerHandler; +import baubles.common.lib.PlayerBaublesProperties; import baubles.common.network.PacketHandler; import baubles.common.network.PacketSyncAllBauble; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraftforge.event.entity.player.PlayerDropsEvent; +import net.minecraftforge.event.entity.EntityEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.event.world.WorldEvent; public class EventHandlerEntity { + @SubscribeEvent + public void entityConstructing(EntityEvent.EntityConstructing event) { + if (event.entity instanceof EntityPlayer player + && player.getExtendedProperties(PlayerBaublesProperties.IDENTIFIER) == null) { + player.registerExtendedProperties(PlayerBaublesProperties.IDENTIFIER, new PlayerBaublesProperties()); + } + } + // player directory private File playerDirectory; @@ -29,13 +38,7 @@ public class EventHandlerEntity { // player events if (event.entity instanceof EntityPlayer player) { InventoryBaubles baubles = PlayerHandler.getPlayerBaubles(player); - for (int a = 0; a < baubles.getSizeInventory(); a++) { - if (baubles.getStackInSlot(a) != null - && baubles.getStackInSlot(a).getItem() instanceof IBauble) { - ((IBauble) baubles.getStackInSlot(a).getItem()).onWornTick( - baubles.getStackInSlot(a), player); - } - } + baubles.tick(); } diff --git a/src/main/java/baubles/common/event/EventHandlerNetwork.java b/src/main/java/baubles/common/event/EventHandlerNetwork.java index 4d604f5..3e37f82 100644 --- a/src/main/java/baubles/common/event/EventHandlerNetwork.java +++ b/src/main/java/baubles/common/event/EventHandlerNetwork.java @@ -1,6 +1,7 @@ package baubles.common.event; import baubles.api.IBauble; +import baubles.common.Baubles; import baubles.common.container.InventoryBaubles; import baubles.common.lib.PlayerHandler; import baubles.common.network.PacketHandler; @@ -12,7 +13,6 @@ import cpw.mods.fml.common.network.FMLNetworkEvent; import cpw.mods.fml.relauncher.Side; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; -import baubles.common.network.PacketSyncBauble; import net.minecraft.item.ItemStack; public class EventHandlerNetwork { @@ -23,6 +23,7 @@ public class EventHandlerNetwork { if (side == Side.SERVER) { // Apply all baubles InventoryBaubles baubles = PlayerHandler.getPlayerBaubles(event.player); + baubles.returnOverflowItems(); PacketHandler.INSTANCE.sendTo(new PacketSyncAllBauble(event.player), ((EntityPlayerMP) event.player)); for (int i = 0; i < baubles.getSizeInventory(); i++) { ItemStack stack = baubles.getStackInSlot(i); @@ -47,10 +48,28 @@ public class EventHandlerNetwork { PlayerHandler.clearClientPlayerBaubles(); } + @SubscribeEvent + public void playerRespawned(PlayerEvent.PlayerRespawnEvent event) { + if (event.player instanceof EntityPlayerMP playerMP) { + InventoryBaubles baubles = PlayerHandler.getPlayerBaubles(playerMP); + baubles.returnOverflowItems(); + for (int slot = 0; slot < baubles.getSizeInventory(); slot++) { + ItemStack stack = baubles.getStackInSlot(slot); + if (stack != null && stack.getItem() instanceof IBauble item) { + try { + item.onPlayerLoad(stack, playerMP); + } catch (Exception e) { + Baubles.log.error("Error restoring bauble after respawn {}", stack, e); + } + } + } + PacketHandler.sendToTracking(new PacketSyncAllBauble(playerMP), playerMP, true); + } + } + public static void syncBaubles(EntityPlayer player) { - InventoryBaubles baubles = PlayerHandler.getPlayerBaubles(player); - for (int i = 0; i < baubles.getSizeInventory(); i++) { - baubles.syncSlotToClients(i); + if (player instanceof EntityPlayerMP && !player.worldObj.isRemote) { + PacketHandler.sendToTracking(new PacketSyncAllBauble(player), player, true); } } diff --git a/src/main/java/baubles/common/lib/ItemStackHelper.java b/src/main/java/baubles/common/lib/ItemStackHelper.java index cd6fd09..113aa8f 100644 --- a/src/main/java/baubles/common/lib/ItemStackHelper.java +++ b/src/main/java/baubles/common/lib/ItemStackHelper.java @@ -1,11 +1,67 @@ package baubles.common.lib; import baubles.common.BaublesConfig; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagList; public class ItemStackHelper { + public static boolean returnToPlayer(EntityPlayer player, ItemStack stack) { + if (stack == null || stack.stackSize <= 0) return true; + InventoryPlayer inventory = player.inventory; + for (int pass = 0; pass < 2 && stack.stackSize > 0; pass++) { + for (int slot = 0; slot < inventory.mainInventory.length && stack.stackSize > 0; slot++) { + ItemStack target = inventory.mainInventory[slot]; + if ((pass == 0) != (target != null) || !inventory.isItemValidForSlot(slot, stack)) continue; + int limit = Math.min(stack.getMaxStackSize(), inventory.getInventoryStackLimit()); + if (target != null) { + if (!stack.isStackable() || !stack.isItemEqual(target) + || !ItemStack.areItemStackTagsEqual(stack, target)) continue; + int moved = Math.min(stack.stackSize, limit - target.stackSize); + if (moved <= 0) continue; + target.stackSize += moved; + target.animationsToGo = 5; + stack.stackSize -= moved; + } else { + int moved = Math.min(stack.stackSize, limit); + if (moved <= 0) continue; + ItemStack inserted = stack.splitStack(moved); + inserted.animationsToGo = 5; + inventory.setInventorySlotContents(slot, inserted); + } + inventory.markDirty(); + } + } + if (stack.stackSize <= 0) return true; + ItemStack attempted = stack.copy(); + int before = countMatching(inventory, attempted); + EntityItem dropped = player.dropPlayerItemWithRandomChoice(stack, false); + if (dropped != null && (dropped.addedToChunk || dropped.isDead || player.capturedDrops.contains(dropped))) return true; + int restored = countMatching(inventory, attempted) - before; + if (restored >= attempted.stackSize || stack.stackSize <= 0) return true; + int alreadyConsumed = attempted.stackSize - stack.stackSize; + stack.stackSize -= Math.min(stack.stackSize, Math.max(0, restored - alreadyConsumed)); + return stack.stackSize <= 0; + } + + private static int countMatching(InventoryPlayer inventory, ItemStack expected) { + int count = 0; + for (int slot = 0; slot < inventory.getSizeInventory(); slot++) { + ItemStack stack = inventory.getStackInSlot(slot); + if (stack != null && expected.isItemEqual(stack) && ItemStack.areItemStackTagsEqual(expected, stack)) { + count += stack.stackSize; + } + } + ItemStack cursor = inventory.getItemStack(); + if (cursor != null && expected.isItemEqual(cursor) && ItemStack.areItemStackTagsEqual(expected, cursor)) { + count += cursor.stackSize; + } + return count; + } + public static boolean isSoulBound(ItemStack itemStack) { if(BaublesConfig.soulBoundEnchantments.length >= 0) { NBTTagList enchantments = itemStack.getEnchantmentTagList(); diff --git a/src/main/java/baubles/common/lib/PlayerBaublesProperties.java b/src/main/java/baubles/common/lib/PlayerBaublesProperties.java new file mode 100644 index 0000000..0331f72 --- /dev/null +++ b/src/main/java/baubles/common/lib/PlayerBaublesProperties.java @@ -0,0 +1,46 @@ +package baubles.common.lib; + +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; +import net.minecraftforge.common.IExtendedEntityProperties; + +public class PlayerBaublesProperties implements IExtendedEntityProperties { + + public static final String IDENTIFIER = "Baubles:inventory"; + public static final String NBT_KEY = "Baubles"; + + private EntityPlayer player; + private NBTTagCompound loadedData; + + @Override + public void init(Entity entity, World world) { + player = (EntityPlayer) entity; + } + + @Override + public void saveNBTData(NBTTagCompound tags) { + if (player == null || player.worldObj.isRemote) return; + NBTTagCompound inventory = new NBTTagCompound(); + PlayerHandler.getPlayerBaubles(player).saveNBT(inventory); + tags.setTag(NBT_KEY, inventory); + } + + @Override + public void loadNBTData(NBTTagCompound tags) { + loadedData = tags.hasKey(NBT_KEY, 10) ? (NBTTagCompound) tags.getCompoundTag(NBT_KEY).copy() : null; + } + + /** + * Consumes the snapshot read with the player, before considering older standalone files. + */ + public static NBTTagCompound takeLoadedData(EntityPlayer player) { + if (player.getExtendedProperties(IDENTIFIER) instanceof PlayerBaublesProperties properties) { + NBTTagCompound data = properties.loadedData; + properties.loadedData = null; + return data; + } + return null; + } +} diff --git a/src/main/java/baubles/common/lib/PlayerHandler.java b/src/main/java/baubles/common/lib/PlayerHandler.java index bff378d..5115af2 100644 --- a/src/main/java/baubles/common/lib/PlayerHandler.java +++ b/src/main/java/baubles/common/lib/PlayerHandler.java @@ -1,13 +1,5 @@ package baubles.common.lib; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.lang.ref.WeakReference; -import java.util.HashMap; - -import com.google.common.io.Files; - import baubles.common.Baubles; import baubles.common.container.InventoryBaubles; import net.minecraft.entity.player.EntityPlayer; @@ -16,6 +8,17 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.server.MinecraftServer; import net.minecraft.world.World; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.lang.ref.WeakReference; +import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.HashMap; + public class PlayerHandler { private static final HashMap playerBaublesServer = new HashMap<>(); @@ -83,11 +86,10 @@ public class PlayerHandler { } public static InventoryBaubles getPlayerBaubles(EntityPlayer player) { - if (player.worldObj.isRemote) { - return playerBaublesClient.computeIfAbsent(player.getCommandSenderName(), username -> new InventoryBaubles(player)); - } else { - return playerBaublesServer.computeIfAbsent(player.getCommandSenderName(), username -> new InventoryBaubles(player)); - } + HashMap inventories = player.worldObj.isRemote ? playerBaublesClient : playerBaublesServer; + InventoryBaubles inventory = inventories.computeIfAbsent(player.getCommandSenderName(), name -> new InventoryBaubles(player)); + if (inventory.player.get() != player) inventory.player = new WeakReference<>(player); + return inventory; } public static void setPlayerBaubles(EntityPlayer player, InventoryBaubles inventory) { @@ -101,13 +103,19 @@ public class PlayerHandler { public static void loadPlayerBaubles(EntityPlayer player, File mainFile, File backupFile) { if(player != null && !player.worldObj.isRemote) { try { - NBTTagCompound data = null; + NBTTagCompound data = PlayerBaublesProperties.takeLoadedData(player); + if (data != null) { + InventoryBaubles inventory = new InventoryBaubles(player); + inventory.readNBT(data); + playerBaublesServer.put(player.getCommandSenderName(), inventory); + return; + } boolean save = false; if(mainFile != null && mainFile.exists()) { try { - FileInputStream fileinputstream = new FileInputStream(mainFile); - data = CompressedStreamTools.readCompressed(fileinputstream); - fileinputstream.close(); + try (FileInputStream stream = new FileInputStream(mainFile)) { + data = CompressedStreamTools.readCompressed(stream); + } } catch (Exception loadMainException) { loadMainException.printStackTrace(); } @@ -120,9 +128,9 @@ public class PlayerHandler { ); if(backupFile != null && backupFile.exists()) { try { - FileInputStream fileinputstream = new FileInputStream(backupFile); - data = CompressedStreamTools.readCompressed(fileinputstream); - fileinputstream.close(); + try (FileInputStream stream = new FileInputStream(backupFile)) { + data = CompressedStreamTools.readCompressed(stream); + } save = true; } catch(Exception loadBackupException) { loadBackupException.printStackTrace(); @@ -135,7 +143,7 @@ public class PlayerHandler { inventory.readNBT(data); playerBaublesServer.put(player.getCommandSenderName(), inventory); if(save) { - savePlayerBaubles(player, mainFile, backupFile); + savePlayerBaubles(player, mainFile, backupFile, false); } } } catch(Exception loadException) { @@ -146,41 +154,47 @@ public class PlayerHandler { } public static void savePlayerBaubles(EntityPlayer player, File mainFile, File backupFile) { - if(player != null && !player.worldObj.isRemote) { - try { - if (mainFile != null && mainFile.exists()) { - try { - Files.copy(mainFile, backupFile); - } catch (Exception saveBackupException) { - Baubles.log.error("Could not backup old baubles file for player " + player.getCommandSenderName()); - } - } - - try { - if(mainFile != null) { - InventoryBaubles inventory = getPlayerBaubles(player); - NBTTagCompound data = new NBTTagCompound(); - inventory.saveNBT(data); - - FileOutputStream fileoutputstream = new FileOutputStream(mainFile); - CompressedStreamTools.writeCompressed(data, fileoutputstream); - fileoutputstream.close(); - } - } catch(Exception saveMainException) { - Baubles.log.error("Could not save baubles file for player " + player.getCommandSenderName()); - saveMainException.printStackTrace(); - if (mainFile.exists()) { - try { - mainFile.delete(); - } catch (Exception ignored) { - } - } - } - } catch(Exception saveException) { - Baubles.log.fatal("Error saving baubles inventory"); - saveException.printStackTrace(); - } - } + savePlayerBaubles(player, mainFile, backupFile, true); } + private static void savePlayerBaubles(EntityPlayer player, File mainFile, File backupFile, boolean backupPrevious) { + if (player == null || player.worldObj.isRemote || mainFile == null) return; + Path target = mainFile.toPath(); + Path temporary = target.resolveSibling(mainFile.getName() + ".tmp"); + try { + NBTTagCompound data = new NBTTagCompound(); + getPlayerBaubles(player).saveNBT(data); + try (OutputStream stream = Files.newOutputStream(temporary)) { + CompressedStreamTools.writeCompressed(data, stream); + } + if (backupPrevious && Files.exists(target) && backupFile != null) { + Path backup = backupFile.toPath(); + Path backupTemporary = backup.resolveSibling(backupFile.getName() + ".tmp"); + try { + Files.copy(target, backupTemporary, StandardCopyOption.REPLACE_EXISTING); + replaceFile(backupTemporary, backup); + } finally { + Files.deleteIfExists(backupTemporary); + } + } + replaceFile(temporary, target); + } catch (Exception e) { + Baubles.log.error("Could not save baubles file for player " + player.getCommandSenderName(), e); + } finally { + try { + Files.deleteIfExists(temporary); + } catch (IOException e) { + Baubles.log.warn("Could not remove temporary baubles file " + temporary, e); + } + } + } + + private static void replaceFile(Path source, Path target) throws IOException { + try { + Files.move(source, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } catch (AtomicMoveNotSupportedException e) { + Files.move(source, target, StandardCopyOption.REPLACE_EXISTING); + } + } + } diff --git a/src/main/java/baubles/common/network/BaubleSlotCodec.java b/src/main/java/baubles/common/network/BaubleSlotCodec.java new file mode 100644 index 0000000..046cb44 --- /dev/null +++ b/src/main/java/baubles/common/network/BaubleSlotCodec.java @@ -0,0 +1,53 @@ +package baubles.common.network; + +import java.util.LinkedHashMap; +import java.util.Map; + +import baubles.common.container.BaubleSlotState; +import cpw.mods.fml.common.network.ByteBufUtils; +import io.netty.buffer.ByteBuf; +import io.netty.handler.codec.DecoderException; + +public class BaubleSlotCodec { + + public static void writeState(ByteBuf buffer, BaubleSlotState state) { + String[] assignments = state.getAssignments(); + ByteBufUtils.writeVarInt(buffer, assignments.length, 5); + for (String type : assignments) ByteBufUtils.writeUTF8String(buffer, type); + ByteBufUtils.writeVarInt(buffer, state.getModifiers().size(), 5); + for (Map.Entry> type : state.getModifiers().entrySet()) { + ByteBufUtils.writeUTF8String(buffer, type.getKey()); + ByteBufUtils.writeVarInt(buffer, type.getValue().size(), 5); + for (Map.Entry source : type.getValue().entrySet()) { + ByteBufUtils.writeUTF8String(buffer, source.getKey()); + buffer.writeInt(source.getValue()); + } + } + } + + public static BaubleSlotState readState(ByteBuf buffer) { + int size = readSize(buffer, BaubleSlotState.MAX_SLOTS); + String[] assignments = new String[size]; + for (int i = 0; i < size; i++) assignments[i] = ByteBufUtils.readUTF8String(buffer); + Map> modifiers = new LinkedHashMap<>(); + int types = readSize(buffer, buffer.readableBytes()); + for (int i = 0; i < types; i++) { + String type = ByteBufUtils.readUTF8String(buffer); + int sources = readSize(buffer, buffer.readableBytes()); + Map values = new LinkedHashMap<>(); + for (int j = 0; j < sources; j++) { + String source = ByteBufUtils.readUTF8String(buffer); + BaubleSlotState.validateSource(source); + if (values.put(source, buffer.readInt()) != null) throw new DecoderException("Duplicate slot source"); + } + if (modifiers.put(type, values) != null) throw new DecoderException("Duplicate slot type"); + } + return new BaubleSlotState(assignments, modifiers); + } + + public static int readSize(ByteBuf buffer, int maximum) { + int size = ByteBufUtils.readVarInt(buffer, 5); + if (size < 0 || size > maximum) throw new DecoderException("Invalid bauble size: " + size); + return size; + } +} diff --git a/src/main/java/baubles/common/network/PacketOpenBaublesInventory.java b/src/main/java/baubles/common/network/PacketOpenBaublesInventory.java index b88b9dc..c1bf4a5 100644 --- a/src/main/java/baubles/common/network/PacketOpenBaublesInventory.java +++ b/src/main/java/baubles/common/network/PacketOpenBaublesInventory.java @@ -6,6 +6,7 @@ import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; import io.netty.buffer.ByteBuf; import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; public class PacketOpenBaublesInventory implements IMessage, IMessageHandler { @@ -21,7 +22,10 @@ public class PacketOpenBaublesInventory implements IMessage, IMessageHandler { + private int windowId = -1; + public PacketOpenNormalInventory() {} - public PacketOpenNormalInventory(EntityPlayer player) {} + public PacketOpenNormalInventory(EntityPlayer player) { + windowId = player.openContainer.windowId; + } @Override - public void toBytes(ByteBuf buffer) {} + public void toBytes(ByteBuf buffer) { + buffer.writeInt(windowId); + } @Override - public void fromBytes(ByteBuf buffer) {} + public void fromBytes(ByteBuf buffer) { + windowId = buffer.isReadable() ? buffer.readInt() : -1; + } @Override public IMessage onMessage(PacketOpenNormalInventory message, MessageContext ctx) { - ctx.getServerHandler().playerEntity.openContainer.onContainerClosed(ctx.getServerHandler().playerEntity); - ctx.getServerHandler().playerEntity.openContainer = ctx.getServerHandler().playerEntity.inventoryContainer; + EntityPlayerMP player = ctx.getServerHandler().playerEntity; + if (!(player.openContainer instanceof ContainerPlayerExpanded container) || !container.canInteractWith(player) + || message.windowId >= 0 && container.windowId != message.windowId) return null; + player.closeContainer(); + player.sendContainerToPlayer(player.inventoryContainer); return null; } } diff --git a/src/main/java/baubles/common/network/PacketSyncAllBauble.java b/src/main/java/baubles/common/network/PacketSyncAllBauble.java index 8493ea9..016b2da 100644 --- a/src/main/java/baubles/common/network/PacketSyncAllBauble.java +++ b/src/main/java/baubles/common/network/PacketSyncAllBauble.java @@ -1,17 +1,15 @@ package baubles.common.network; -import baubles.api.IBauble; -import baubles.api.expanded.BaubleExpandedSlots; import baubles.common.Baubles; +import baubles.common.container.BaubleSlotState; import baubles.common.container.InventoryBaubles; import baubles.common.lib.PlayerHandler; import cpw.mods.fml.common.network.ByteBufUtils; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; -import gnu.trove.map.TIntObjectMap; -import gnu.trove.map.hash.TIntObjectHashMap; import io.netty.buffer.ByteBuf; +import io.netty.handler.codec.DecoderException; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -19,64 +17,78 @@ import net.minecraft.world.World; public class PacketSyncAllBauble implements IMessage, IMessageHandler { - private int playerId; - private TIntObjectMap inventory = new TIntObjectHashMap<>(); + private int playerId; + private int dimension; + private long revision; + private boolean oldGui; + private BaubleSlotState state; + private ItemStack[] inventory; - public PacketSyncAllBauble() {} + public PacketSyncAllBauble() {} - public PacketSyncAllBauble(EntityPlayer player) { - this.playerId = player.getEntityId(); + public PacketSyncAllBauble(EntityPlayer player) { + playerId = player.getEntityId(); + dimension = player.dimension; InventoryBaubles inv = PlayerHandler.getPlayerBaubles(player); - for (int i = 0; i < inv.getSizeInventory(); i++) { - ItemStack slotItem = inv.getStackInSlot(i); - if (slotItem == null) continue; - inventory.put(i, slotItem); + revision = inv.getLayoutRevision(); + state = inv.getSlotState(); + oldGui = inv.usesOldGuiRendering(); + inventory = new ItemStack[inv.getSizeInventory()]; + for (int i = 0; i < inventory.length; i++) inventory[i] = ItemStack.copyItemStack(inv.getStackInSlot(i)); + } + + @Override + public void toBytes(ByteBuf buffer) { + buffer.writeInt(playerId); + buffer.writeInt(dimension); + buffer.writeLong(revision); + buffer.writeBoolean(oldGui); + BaubleSlotCodec.writeState(buffer, state); + writeStacks(buffer, inventory); + } + + private static void writeStacks(ByteBuf buffer, ItemStack[] stacks) { + int occupied = 0; + for (ItemStack stack : stacks) if (stack != null) occupied++; + ByteBufUtils.writeVarInt(buffer, occupied, 5); + for (int slot = 0; slot < stacks.length; slot++) { + if (stacks[slot] == null) continue; + ByteBufUtils.writeVarInt(buffer, slot, 5); + ByteBufUtils.writeItemStack(buffer, stacks[slot]); } } - @Override - public void toBytes(ByteBuf buffer) { - buffer.writeInt(playerId); - ByteBufUtils.writeVarInt(buffer, inventory.size(), BaubleExpandedSlots.maxSlotIdBytes); - inventory.forEachEntry((a, b) -> { - ByteBufUtils.writeVarInt(buffer, a, BaubleExpandedSlots.maxSlotIdBytes); - ByteBufUtils.writeItemStack(buffer, b); - return true; - }); - - } - - @Override - public void fromBytes(ByteBuf buffer) { + @Override + public void fromBytes(ByteBuf buffer) { playerId = buffer.readInt(); - int size = ByteBufUtils.readVarInt(buffer, BaubleExpandedSlots.maxSlotIdBytes); - for (int i = 0; i < size; i++) { - int slotId = ByteBufUtils.readVarInt(buffer, BaubleExpandedSlots.maxSlotIdBytes); - ItemStack slotItem = ByteBufUtils.readItemStack(buffer); - inventory.put(slotId, slotItem); - } - } + dimension = buffer.readInt(); + revision = buffer.readLong(); + oldGui = buffer.readBoolean(); + state = BaubleSlotCodec.readState(buffer); + inventory = new ItemStack[state.getAssignments().length]; + readStacks(buffer, inventory); + } - @Override - public IMessage onMessage(PacketSyncAllBauble message, MessageContext ctx) { - World world = Baubles.proxy.getClientWorld(); - if (world == null) return null; - Entity e = world.getEntityByID(message.playerId); - if (e instanceof EntityPlayer player) { - PlayerHandler.clearPlayerBaubles(player); - InventoryBaubles baubles = PlayerHandler.getPlayerBaubles(player); - message.inventory.forEachEntry((a, b) -> { - baubles.stackList[a] = b; - if (b.getItem() instanceof IBauble itemBauble) { - try { - itemBauble.onPlayerLoad(b, player); - } catch (Exception ex) { - Baubles.log.error("Error loading baubles {}", b, ex); - } - } - return true; - }); - } - return null; - } + private static void readStacks(ByteBuf buffer, ItemStack[] stacks) { + int occupied = BaubleSlotCodec.readSize(buffer, stacks.length); + int previous = -1; + for (int i = 0; i < occupied; i++) { + int slot = BaubleSlotCodec.readSize(buffer, stacks.length - 1); + if (slot <= previous) throw new DecoderException("Unordered bauble item indices"); + stacks[slot] = ByteBufUtils.readItemStack(buffer); + previous = slot; + } + } + + @Override + public IMessage onMessage(PacketSyncAllBauble message, MessageContext ctx) { + World world = Baubles.proxy.getClientWorld(); + if (world == null || world.provider.dimensionId != message.dimension) return null; + Entity entity = world.getEntityByID(message.playerId); + if (entity instanceof EntityPlayer player) { + PlayerHandler.getPlayerBaubles(player).applySnapshot( + message.state, message.revision, message.inventory, message.oldGui); + } + return null; + } } diff --git a/src/main/java/baubles/common/network/PacketSyncBauble.java b/src/main/java/baubles/common/network/PacketSyncBauble.java index a57bf3d..f16e954 100644 --- a/src/main/java/baubles/common/network/PacketSyncBauble.java +++ b/src/main/java/baubles/common/network/PacketSyncBauble.java @@ -1,11 +1,10 @@ package baubles.common.network; -import java.io.IOException; - -import baubles.api.IBauble; import baubles.common.Baubles; +import baubles.common.container.BaubleSlotState; import baubles.common.container.InventoryBaubles; import baubles.common.lib.PlayerHandler; +import cpw.mods.fml.common.network.ByteBufUtils; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; @@ -13,47 +12,56 @@ import io.netty.buffer.ByteBuf; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; -import net.minecraft.network.PacketBuffer; import net.minecraft.world.World; public class PacketSyncBauble implements IMessage, IMessageHandler { - int slot; - int playerId; - ItemStack bauble = null; + private int slot; + private int playerId; + private int dimension; + private long revision; + private ItemStack bauble; - public PacketSyncBauble() {} + public PacketSyncBauble() {} - public PacketSyncBauble(EntityPlayer player, int slot) { - this.slot = slot; - this.bauble = PlayerHandler.getPlayerBaubles(player).getStackInSlot(slot); - this.playerId = player.getEntityId(); - } + public PacketSyncBauble(EntityPlayer player, int slot) { + InventoryBaubles inventory = PlayerHandler.getPlayerBaubles(player); + this.slot = slot; + bauble = ItemStack.copyItemStack(inventory.getStackInSlot(slot)); + playerId = player.getEntityId(); + dimension = player.dimension; + revision = inventory.getLayoutRevision(); + } - @Override - public void toBytes(ByteBuf buffer) { - buffer.writeByte(slot); - buffer.writeInt(playerId); - PacketBuffer pb = new PacketBuffer(buffer); - try { pb.writeItemStackToBuffer(bauble); } catch (IOException ignored) {} - } + @Override + public void toBytes(ByteBuf buffer) { + ByteBufUtils.writeVarInt(buffer, slot, 5); + buffer.writeInt(playerId); + buffer.writeInt(dimension); + buffer.writeLong(revision); + ByteBufUtils.writeItemStack(buffer, bauble); + } - @Override - public void fromBytes(ByteBuf buffer) { - slot = buffer.readByte(); - playerId = buffer.readInt(); - PacketBuffer pb = new PacketBuffer(buffer); - try { bauble = pb.readItemStackFromBuffer(); } catch (IOException ignored) {} - } + @Override + public void fromBytes(ByteBuf buffer) { + slot = BaubleSlotCodec.readSize(buffer, BaubleSlotState.MAX_SLOTS - 1); + playerId = buffer.readInt(); + dimension = buffer.readInt(); + revision = buffer.readLong(); + bauble = ByteBufUtils.readItemStack(buffer); + } - @Override - public IMessage onMessage(PacketSyncBauble message, MessageContext ctx) { - World world = Baubles.proxy.getClientWorld(); - if (world == null) return null; - Entity e = world.getEntityByID(message.playerId); - if (e instanceof EntityPlayer player) { - PlayerHandler.getPlayerBaubles(player).setInventorySlotContents(message.slot, message.bauble); - } - return null; - } + @Override + public IMessage onMessage(PacketSyncBauble message, MessageContext ctx) { + World world = Baubles.proxy.getClientWorld(); + if (world == null || world.provider.dimensionId != message.dimension) return null; + Entity entity = world.getEntityByID(message.playerId); + if (entity instanceof EntityPlayer player) { + InventoryBaubles inventory = PlayerHandler.getPlayerBaubles(player); + if (message.revision == inventory.getLayoutRevision() && message.slot < inventory.getSizeInventory()) { + inventory.setInventorySlotContents(message.slot, message.bauble); + } + } + return null; + } }