All Downloads are FREE. Search and download functionalities are using the official Maven repository.

walkmc.nbt.InventoryAdapter.kt Maven / Gradle / Ivy

package walkmc.nbt

import net.minecraft.server.*
import org.bukkit.*
import org.bukkit.inventory.*
import walkmc.Slot

/**
 * A tag adapter for adapting [Inventory].
 */
object InventoryAdapter : TagAdapter {
   override fun load(key: String, tag: NBTTagCompound): Inventory {
      return Bukkit.createInventory(null, tag.getByte("Size").toInt() * 9, tag.getString("Title")).apply {
         extract(this, tag)
      }
   }
   
   override fun save(key: String, value: Inventory, tag: NBTTagCompound) {
      tag.setString("Title", value.title)
      tag.setByte("Size", (value.size / 9).toByte())
      tag.set("Items", populate(value))
   }
   
   fun extract(inventory: Inventory, tag: NBTTagCompound) {
      for (compound in tag.getList("Items", NBTTagCompound.COMPOUND)) {
         if (compound !is NBTTagCompound) continue
         val slot = compound.getSlot("SlotType")
         inventory.setItem(slot.slot, slot.item)
      }
   }
   
   fun populate(inventory: Inventory): NBTTagList = NBTTagList().apply {
      for (index in 0 until inventory.size) {
         val item = inventory.getItem(index) ?: continue
         add(NBTTagCompound().apply {
            setSlot("SlotType", Slot(index, item))
         })
      }
   }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy