46 lines
1.5 KiB
Kotlin
46 lines
1.5 KiB
Kotlin
package net.shadowfacts.phycon.network.block.netinterface
|
|
|
|
import alexiil.mc.lib.attributes.SearchOptions
|
|
import alexiil.mc.lib.attributes.item.GroupedItemInv
|
|
import alexiil.mc.lib.attributes.item.ItemAttributes
|
|
import net.minecraft.util.math.Direction
|
|
import net.shadowfacts.phycon.api.packet.Packet
|
|
import net.shadowfacts.phycon.init.PhyBlockEntities
|
|
import net.shadowfacts.phycon.network.DeviceBlockEntity
|
|
import net.shadowfacts.phycon.network.packet.ReadInventoryPacket
|
|
import net.shadowfacts.phycon.network.packet.RequestInventoryPacket
|
|
|
|
/**
|
|
* @author shadowfacts
|
|
*/
|
|
class InterfaceBlockEntity: DeviceBlockEntity(PhyBlockEntities.INTERFACE) {
|
|
|
|
private val facing: Direction
|
|
get() = world!!.getBlockState(pos)[InterfaceBlock.FACING]
|
|
|
|
// todo: should this be a weak ref?
|
|
private var inventory: GroupedItemInv? = null
|
|
|
|
fun updateInventory() {
|
|
val offsetPos = pos.offset(facing)
|
|
val option = SearchOptions.inDirection(facing)
|
|
inventory = ItemAttributes.GROUPED_INV.getFirstOrNull(world, offsetPos, option)
|
|
}
|
|
|
|
override fun handlePacket(packet: Packet) {
|
|
when (packet) {
|
|
is RequestInventoryPacket -> handleRequestInventory(packet)
|
|
}
|
|
}
|
|
|
|
private fun handleRequestInventory(packet: RequestInventoryPacket) {
|
|
// if we don't have an inventory, try to get one
|
|
// this happens when readAll is called before a neighbor state changes, such as immediately after world load
|
|
if (inventory == null) updateInventory()
|
|
inventory?.also {
|
|
enqueueToSingle(ReadInventoryPacket(it, macAddress, packet.source))
|
|
}
|
|
}
|
|
|
|
}
|