2019-10-29 19:15:27 +00:00
|
|
|
package net.shadowfacts.phycon.util
|
|
|
|
|
2019-10-30 18:27:18 +00:00
|
|
|
import alexiil.mc.lib.attributes.item.ItemStackUtil
|
2021-02-10 23:55:49 +00:00
|
|
|
import net.minecraft.inventory.SimpleInventory
|
2019-10-29 19:15:27 +00:00
|
|
|
import net.minecraft.item.ItemStack
|
|
|
|
import net.minecraft.nbt.CompoundTag
|
|
|
|
import net.minecraft.nbt.ListTag
|
|
|
|
import java.lang.RuntimeException
|
2019-10-30 18:27:18 +00:00
|
|
|
import kotlin.math.min
|
2019-10-29 19:15:27 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @author shadowfacts
|
|
|
|
*/
|
2021-02-10 23:55:49 +00:00
|
|
|
fun SimpleInventory.toTag(): ListTag {
|
2019-10-29 19:15:27 +00:00
|
|
|
val list = ListTag()
|
2021-02-10 23:55:49 +00:00
|
|
|
for (slot in 0 until size()) {
|
|
|
|
val stack = getStack(slot)
|
2019-10-29 19:15:27 +00:00
|
|
|
if (!stack.isEmpty) {
|
|
|
|
val stackTag = stack.toTag(CompoundTag())
|
|
|
|
stackTag.putInt("Slot", slot)
|
|
|
|
list.add(stackTag)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return list
|
|
|
|
}
|
|
|
|
|
2021-02-10 23:55:49 +00:00
|
|
|
fun SimpleInventory.fromTag(list: ListTag) {
|
|
|
|
if (list.elementType != 10.toByte()) throw RuntimeException("Can't decode BasicInventory from list tag that does not contain compound tags")
|
2019-10-29 19:15:27 +00:00
|
|
|
this.clear()
|
|
|
|
for (tag in list) {
|
|
|
|
val compound = tag as CompoundTag
|
|
|
|
val stack = ItemStack.fromTag(compound)
|
|
|
|
val slot = compound.getInt("Slot")
|
2021-02-10 23:55:49 +00:00
|
|
|
setStack(slot, stack)
|
2019-10-29 19:15:27 +00:00
|
|
|
}
|
|
|
|
}
|
2019-10-30 18:27:18 +00:00
|
|
|
|
2021-02-10 23:55:49 +00:00
|
|
|
fun SimpleInventory.insert(stack: ItemStack, slot: Int): ItemStack {
|
2019-10-30 18:27:18 +00:00
|
|
|
@Suppress("NAME_SHADOWING") val stack = stack.copy()
|
2021-02-10 23:55:49 +00:00
|
|
|
val current = getStack(slot)
|
2019-10-30 18:27:18 +00:00
|
|
|
if (current.isEmpty) {
|
2021-02-10 23:55:49 +00:00
|
|
|
setStack(slot, stack)
|
2019-10-30 18:27:18 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-10 23:55:49 +00:00
|
|
|
fun SimpleInventory.insert(stack: ItemStack): ItemStack {
|
2019-10-30 18:27:18 +00:00
|
|
|
var remaining = stack
|
2021-02-10 23:55:49 +00:00
|
|
|
for (slot in 0 until size()) {
|
2019-10-30 18:27:18 +00:00
|
|
|
remaining = insert(stack, slot)
|
|
|
|
if (remaining.isEmpty) {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return remaining
|
|
|
|
}
|