PhysicalConnectivity/src/main/kotlin/net/shadowfacts/phycon/util/BasicInventoryExtensions.kt

68 lines
1.7 KiB
Kotlin

package net.shadowfacts.phycon.util
import alexiil.mc.lib.attributes.item.ItemStackUtil
import net.minecraft.inventory.SimpleInventory
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NbtCompound
import net.minecraft.nbt.NbtList
import java.lang.RuntimeException
import kotlin.math.min
/**
* @author shadowfacts
*/
fun SimpleInventory.toTag(): NbtList {
val list = NbtList()
for (slot in 0 until size()) {
val stack = getStack(slot)
if (!stack.isEmpty) {
val stackTag = stack.writeNbt(NbtCompound())
stackTag.putInt("Slot", slot)
list.add(stackTag)
}
}
return list
}
fun SimpleInventory.fromTag(list: NbtList) {
if (list.isEmpty()) {
this.clear()
return
}
if (list.heldType != 10.toByte()) throw RuntimeException("Can't decode BasicInventory from list tag that does not contain compound tags")
this.clear()
for (tag in list) {
val compound = tag as NbtCompound
val stack = ItemStack.fromNbt(compound)
val slot = compound.getInt("Slot")
setStack(slot, stack)
}
}
fun SimpleInventory.insert(stack: ItemStack, slot: Int): ItemStack {
@Suppress("NAME_SHADOWING") val stack = stack.copy()
val current = getStack(slot)
if (current.isEmpty) {
setStack(slot, stack)
return ItemStack.EMPTY
} else if (ItemStackUtil.areEqualIgnoreAmounts(stack, current)) {
val toTransfer = min(current.maxCount - current.count, stack.count)
current.count += toTransfer
stack.count -= toTransfer
return stack
} else {
return stack
}
}
fun SimpleInventory.insert(stack: ItemStack): ItemStack {
var remaining = stack
for (slot in 0 until size()) {
remaining = insert(stack, slot)
if (remaining.isEmpty) {
break
}
}
return remaining
}