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

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

package walkmc.nbt

import net.minecraft.server.*
import org.bukkit.craftbukkit.inventory.*
import org.bukkit.inventory.ItemStack
import walkmc.extensions.*
import walkmc.extensions.collections.*

/**
 * A tag adapter for adapting [ItemStack].
 */
object ItemAdapter : TagAdapter {
   override fun load(key: String, tag: NBTTagCompound): ItemStack {
      return extract(tag.getCompound(key))
   }
   
   override fun save(key: String, value: ItemStack, tag: NBTTagCompound) {
      populate(key, value, tag)
   }
   
   fun populate(key: String, item: ItemStack, tag: NBTTagCompound): NBTTagCompound = tag.apply {
      set(key, item.handler.writeToNBT(NBTTagCompound()))
   }
   
   fun extract(tag: NBTTagCompound): ItemStack {
      return CraftItemStack.asBukkitCopy(net.minecraft.server.ItemStack.createStack(tag))
   }
}


/**
 * A tag adapter for adapting a list of [ItemStack].
 */
object ItemListAdapter : TagAdapter> {
   override fun load(key: String, tag: NBTTagCompound): MutableList {
      return extract(tag.getList(key, NBTBase.COMPOUND), newMutableList())
   }
   
   override fun save(key: String, value: MutableList, tag: NBTTagCompound) {
      tag.set(key, populate(NBTTagList(), value))
   }
   
   fun populate(list: NBTTagList, items: List): NBTTagList = list.apply {
      for (item in items) {
         add(ItemAdapter.populate("ItemStack", item, NBTTagCompound()))
      }
   }
   
   fun extract(from: NBTTagList, to: MutableList): MutableList = to.apply {
      for (compound in from) {
         if (compound !is NBTTagCompound)
            continue
         
         add(ItemAdapter.extract(compound))
      }
   }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy