PhysicalConnectivity/src/main/kotlin/net/shadowfacts/phycon/network/DeviceBlockEntity.kt

87 lines
2.2 KiB
Kotlin

package net.shadowfacts.phycon.network
import net.minecraft.block.BlockState
import net.minecraft.block.entity.BlockEntity
import net.minecraft.block.entity.BlockEntityType
import net.minecraft.nbt.CompoundTag
import net.minecraft.util.Tickable
import net.shadowfacts.phycon.api.PacketSink
import net.shadowfacts.phycon.api.packet.Packet
import net.shadowfacts.phycon.api.util.MACAddress
import net.shadowfacts.phycon.network.packet.DeviceRemovedPacket
import java.lang.ref.WeakReference
import java.util.*
/**
* @author shadowfacts
*/
abstract class DeviceBlockEntity(type: BlockEntityType<*>): BlockEntity(type), PacketSink {
var macAddress = MACAddress.random()
protected set
override fun getMACAddress(): MACAddress {
return macAddress
}
override fun handle(packet: Packet) {
if (acceptsPacket(packet)) {
handlePacket(packet)
}
}
protected abstract fun handlePacket(packet: Packet)
protected open fun acceptsPacket(packet: Packet): Boolean {
return when (packet.destination.type) {
MACAddress.Type.BROADCAST -> true
MACAddress.Type.UNICAST -> macAddress == packet.destination
MACAddress.Type.MULTICAST -> acceptsMulticastPacket(packet)
}
}
open fun acceptsMulticastPacket(packet: Packet): Boolean {
return false
}
fun send(packet: Packet, destination: PacketSink) {
destination.handle(packet)
}
// todo: better name for this
fun sendToSingle(packet: Packet) {
val destinations = NetworkUtil.findDestinations(world!!, pos)
if (destinations.size != 1) {
// todo: handle this better
println("Can't send packet, multiple destinations available: $destinations")
return
}
send(packet, destinations.first())
}
fun sendToAll(packet: Packet) {
sendToAll(packet, NetworkUtil.findDestinations(world!!, pos))
}
fun sendToAll(packet: Packet, destinations: Iterable<PacketSink>) {
destinations.forEach {
it.handle(packet)
}
}
override fun toTag(tag: CompoundTag): CompoundTag {
tag.putLong("MACAddress", macAddress.address)
return super.toTag(tag)
}
override fun fromTag(state: BlockState, tag: CompoundTag) {
super.fromTag(state, tag)
macAddress = MACAddress(tag.getLong("MACAddress"))
}
fun onBreak() {
sendToAll(DeviceRemovedPacket(this))
}
}