|
| 1 | +package dev.kitteh.cardboardbox.v1_21_3; |
| 2 | + |
| 3 | +import com.google.common.base.Preconditions; |
| 4 | +import com.mojang.serialization.Dynamic; |
| 5 | +import net.minecraft.nbt.CompoundTag; |
| 6 | +import net.minecraft.nbt.NbtOps; |
| 7 | +import net.minecraft.server.MinecraftServer; |
| 8 | +import net.minecraft.util.datafix.fixes.References; |
| 9 | +import org.bukkit.craftbukkit.inventory.CraftItemStack; |
| 10 | +import org.bukkit.craftbukkit.util.CraftMagicNumbers; |
| 11 | +import org.bukkit.inventory.ItemStack; |
| 12 | + |
| 13 | +import java.io.IOException; |
| 14 | + |
| 15 | +public class Box implements dev.kitteh.cardboardbox.api.Box { |
| 16 | + public boolean check(ItemStack itemStack) { |
| 17 | + return itemStack.equals(deserializeItem(serializeItem(itemStack))); |
| 18 | + } |
| 19 | + |
| 20 | + private static final int DATA_VERSION = CraftMagicNumbers.INSTANCE.getDataVersion(); |
| 21 | + |
| 22 | + @Override |
| 23 | + public byte[] serializeItem(ItemStack item) { |
| 24 | + CompoundTag compound = (net.minecraft.nbt.CompoundTag) CraftItemStack.asNMSCopy(item).save(MinecraftServer.getServer().registryAccess()); |
| 25 | + compound.putInt("DataVersion", DATA_VERSION); |
| 26 | + java.io.ByteArrayOutputStream outputStream = new java.io.ByteArrayOutputStream(); |
| 27 | + try { |
| 28 | + net.minecraft.nbt.NbtIo.writeCompressed( |
| 29 | + compound, |
| 30 | + outputStream |
| 31 | + ); |
| 32 | + } catch (IOException ex) { |
| 33 | + throw new RuntimeException(ex); |
| 34 | + } |
| 35 | + return outputStream.toByteArray(); |
| 36 | + } |
| 37 | + |
| 38 | + @Override |
| 39 | + public ItemStack deserializeItem(byte[] data) { |
| 40 | + net.minecraft.nbt.CompoundTag compound; |
| 41 | + try { |
| 42 | + compound = net.minecraft.nbt.NbtIo.readCompressed( |
| 43 | + new java.io.ByteArrayInputStream(data), net.minecraft.nbt.NbtAccounter.unlimitedHeap() |
| 44 | + ); |
| 45 | + } catch (IOException ex) { |
| 46 | + throw new RuntimeException(ex); |
| 47 | + } |
| 48 | + final int dataVersion = compound.getInt("DataVersion"); |
| 49 | + Preconditions.checkArgument(dataVersion <= DATA_VERSION, "Newer version! Server downgrades are not supported!"); |
| 50 | + compound = (net.minecraft.nbt.CompoundTag) MinecraftServer.getServer().fixerUpper.update(References.ITEM_STACK, new Dynamic<>(NbtOps.INSTANCE, compound), dataVersion, dataVersion).getValue(); |
| 51 | + return CraftItemStack.asCraftMirror(net.minecraft.world.item.ItemStack.parse(MinecraftServer.getServer().registryAccess(), compound).orElseThrow()); |
| 52 | + } |
| 53 | +} |
0 commit comments