CustomInventory.java 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package me.km.networking;
  2. import java.nio.charset.StandardCharsets;
  3. import java.util.function.Supplier;
  4. import me.km.inventory.CustomContainer;
  5. import me.km.inventory.ModInventory;
  6. import net.minecraft.client.Minecraft;
  7. import net.minecraft.network.PacketBuffer;
  8. import net.minecraft.util.text.StringTextComponent;
  9. import net.minecraftforge.api.distmarker.Dist;
  10. import net.minecraftforge.api.distmarker.OnlyIn;
  11. import net.minecraftforge.fml.network.NetworkEvent;
  12. public class CustomInventory {
  13. private int windowId;
  14. private String windowTitle;
  15. private byte slotCount;
  16. private byte allSlots;
  17. private final byte[] data;
  18. public CustomInventory() {
  19. windowId = -1;
  20. windowTitle = "";
  21. slotCount = 9;
  22. allSlots = 9;
  23. data = new byte[14];
  24. }
  25. public CustomInventory(int id, String title, ModInventory inv) {
  26. windowId = id;
  27. windowTitle = title;
  28. slotCount = (byte) inv.getContainerSize();
  29. allSlots = (byte) inv.getAllSlots();
  30. data = inv.getData();
  31. }
  32. public static void writeBytes(CustomInventory ci, PacketBuffer buf) {
  33. buf.writeInt(ci.windowId);
  34. byte[] b = ci.windowTitle.getBytes(StandardCharsets.UTF_8);
  35. buf.writeInt(b.length);
  36. buf.writeBytes(b);
  37. buf.writeByte(ci.slotCount);
  38. buf.writeByte(ci.allSlots);
  39. buf.writeBytes(ci.data);
  40. }
  41. public static CustomInventory fromBytes(PacketBuffer buf) {
  42. CustomInventory ci = new CustomInventory();
  43. ci.windowId = buf.readInt();
  44. int length = buf.readInt();
  45. ci.windowTitle = buf.readBytes(length).toString(StandardCharsets.UTF_8);
  46. ci.slotCount = buf.readByte();
  47. ci.allSlots = buf.readByte();
  48. for(int i = 0; i < 14; i++) {
  49. ci.data[i] = buf.readByte();
  50. }
  51. return ci;
  52. }
  53. public static void handle(CustomInventory ci, Supplier<NetworkEvent.Context> context) {
  54. // prevent error on loading the class on the server
  55. handleIntern(ci, context);
  56. }
  57. @OnlyIn(Dist.CLIENT)
  58. private static void handleIntern(CustomInventory ci, Supplier<NetworkEvent.Context> context) {
  59. context.get().enqueueWork(() -> {
  60. Minecraft mc = Minecraft.getInstance();
  61. CustomContainer cc = new CustomContainer(ci.windowId, mc.player.inventory,
  62. new ModInventory(ci.data, ci.slotCount, ci.allSlots));
  63. mc.player.containerMenu = cc;
  64. mc.setScreen(new CustomInventoryScreen(cc, mc.player.inventory,
  65. new StringTextComponent(ci.windowTitle)));
  66. });
  67. context.get().setPacketHandled(true);
  68. }
  69. }