PhysicalConnectivity/src/main/kotlin/net/shadowfacts/phycon/component/ItemStackPacketHandler.kt

36 lines
1.3 KiB
Kotlin

package net.shadowfacts.phycon.component
import net.minecraft.block.entity.BlockEntity
import net.minecraft.entity.ItemEntity
import net.minecraft.item.ItemStack
import net.shadowfacts.phycon.api.PacketSink
import net.shadowfacts.phycon.api.PacketSource
import net.shadowfacts.phycon.packet.ItemStackPacket
/**
* @author shadowfacts
*/
interface ItemStackPacketHandler: PacketSink, PacketSource {
fun doHandleItemStack(packet: ItemStackPacket): ItemStack
}
fun <Self> Self.handleItemStack(packet: ItemStackPacket) where Self: BlockEntity, Self: ItemStackPacketHandler {
// todo: is 5 a good number?
// the max bounce count should always be odd, so the item is spawned in-world at the
if (packet.bounceCount == 5) {
spawnItemStack(packet.stack)
return
}
val remainder = doHandleItemStack(packet)
// if there are any items remaining, send them back to the source with incremented bounce count
if (!remainder.isEmpty) {
sendPacket(ItemStackPacket(remainder, packet.bounceCount + 1, ipAddress, packet.source))
}
}
fun <Self> Self.spawnItemStack(stack: ItemStack) where Self: BlockEntity, Self: ItemStackPacketHandler {
// todo: calculate entity spawn point by finding non-obstructed location
val entity = ItemEntity(world!!, pos.x.toDouble(), pos.y + 1.0, pos.z.toDouble(), stack)
world!!.spawnEntity(entity)
}