Terminal: Merge stacks into buffer where possible

This commit is contained in:
Shadowfacts 2019-10-30 14:27:18 -04:00
parent 2ec294d427
commit 37692aac7d
Signed by: shadowfacts
GPG Key ID: 94A5AB95422746E5
2 changed files with 35 additions and 9 deletions

View File

@ -21,6 +21,7 @@ import net.shadowfacts.phycon.network.DeviceBlockEntity
import net.shadowfacts.phycon.network.block.netinterface.InterfaceBlockEntity
import net.shadowfacts.phycon.network.packet.*
import net.shadowfacts.phycon.util.fromTag
import net.shadowfacts.phycon.util.insert
import net.shadowfacts.phycon.util.toTag
import java.util.*
import kotlin.math.min
@ -83,16 +84,12 @@ class TerminalBlockEntity: DeviceBlockEntity(PhyBlockEntities.TERMINAL), Invento
}
private fun handleItemStack(packet: ItemStackPacket) {
// todo: handle merging stacks into the buffer better?
for (i in 0 until internalBuffer.invSize) {
if (internalBuffer.getInvStack(i).isEmpty) {
internalBuffer.setInvStack(i, packet.stack)
return
}
val remaining = internalBuffer.insert(packet.stack)
if (!remaining.isEmpty) {
// todo: calculate entity spawn point by finding non-obstructed location
val entity = ItemEntity(world!!, pos.x.toDouble(), pos.y + 1.0, pos.z.toDouble(), remaining)
world!!.spawnEntity(entity)
}
// todo: calculate entity spawn point by finding non-obstructed location
val entity = ItemEntity(world!!, pos.x.toDouble(), pos.y + 1.0, pos.z.toDouble(), packet.stack)
world!!.spawnEntity(entity)
}
private fun updateNetItems() {

View File

@ -1,10 +1,12 @@
package net.shadowfacts.phycon.util
import alexiil.mc.lib.attributes.item.ItemStackUtil
import net.minecraft.inventory.BasicInventory
import net.minecraft.item.ItemStack
import net.minecraft.nbt.CompoundTag
import net.minecraft.nbt.ListTag
import java.lang.RuntimeException
import kotlin.math.min
/**
* @author shadowfacts
@ -32,3 +34,30 @@ fun BasicInventory.fromTag(list: ListTag) {
setInvStack(slot, stack)
}
}
fun BasicInventory.insert(stack: ItemStack, slot: Int): ItemStack {
@Suppress("NAME_SHADOWING") val stack = stack.copy()
val current = getInvStack(slot)
if (current.isEmpty) {
setInvStack(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 BasicInventory.insert(stack: ItemStack): ItemStack {
var remaining = stack
for (slot in 0 until invSize) {
remaining = insert(stack, slot)
if (remaining.isEmpty) {
break
}
}
return remaining
}