PlayerHead.java 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package me.km.networking;
  2. import java.nio.charset.StandardCharsets;
  3. import java.util.function.Supplier;
  4. import net.minecraft.network.PacketBuffer;
  5. import net.minecraftforge.fml.network.NetworkEvent;
  6. public class PlayerHead {
  7. // 1 - add - index, name, x, y, scale
  8. // 2 - remove - index
  9. // 3 - clear
  10. private byte action;
  11. private byte index;
  12. private String name;
  13. private int x;
  14. private int y;
  15. private byte scale;
  16. public PlayerHead() {
  17. action = -1;
  18. index = -1;
  19. name = "";
  20. x = -1;
  21. y = -1;
  22. scale = -1;
  23. }
  24. public PlayerHead(byte action, byte index, String name, int x, int y, byte scale) {
  25. this.action = action;
  26. this.index = index;
  27. if(name.length() > 16) {
  28. this.name = name.substring(0, 16);
  29. } else {
  30. this.name = name;
  31. }
  32. this.x = x;
  33. this.y = y;
  34. this.scale = scale;
  35. }
  36. public static void writeBytes(PlayerHead ph, PacketBuffer buf) {
  37. buf.writeByte(ph.action);
  38. switch(ph.action) {
  39. case 1:
  40. buf.writeInt(ph.x);
  41. buf.writeInt(ph.y);
  42. buf.writeByte(ph.scale);
  43. buf.writeByte(ph.index);
  44. byte[] b = ph.name.getBytes(StandardCharsets.UTF_8);
  45. buf.writeInt(b.length);
  46. buf.writeBytes(b);
  47. break;
  48. case 2:
  49. buf.writeByte(ph.index);
  50. break;
  51. }
  52. }
  53. public static PlayerHead fromBytes(PacketBuffer buf) {
  54. PlayerHead ph = new PlayerHead();
  55. ph.action = buf.readByte();
  56. switch(ph.action) {
  57. case 1:
  58. ph.x = buf.readInt();
  59. ph.y = buf.readInt();
  60. ph.scale = buf.readByte();
  61. ph.index = buf.readByte();
  62. int length = buf.readInt();
  63. ph.name = buf.readBytes(length).toString(StandardCharsets.UTF_8);
  64. break;
  65. case 2:
  66. ph.index = buf.readByte();
  67. break;
  68. }
  69. return ph;
  70. }
  71. public static void handle(PlayerHead ph, Supplier<NetworkEvent.Context> context) {
  72. context.get().enqueueWork(() -> {
  73. switch(ph.action) {
  74. case 1:
  75. PlayerHeadGui.INSTANCE.add(ph.index, ph.x, ph.y, ph.scale, ph.name);
  76. break;
  77. case 2:
  78. PlayerHeadGui.INSTANCE.remove(ph.index);
  79. break;
  80. case 3:
  81. PlayerHeadGui.INSTANCE.clear();
  82. break;
  83. }
  84. });
  85. context.get().setPacketHandled(true);
  86. }
  87. }