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

87 lines
2.2 KiB
Kotlin
Raw Normal View History

2019-10-27 01:36:31 +00:00
package net.shadowfacts.phycon.network
2021-02-10 23:55:49 +00:00
import net.minecraft.block.BlockState
2019-10-27 01:36:31 +00:00
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
2019-10-27 01:36:31 +00:00
import java.util.*
/**
* @author shadowfacts
*/
abstract class DeviceBlockEntity(type: BlockEntityType<*>): BlockEntity(type), PacketSink {
2019-10-27 01:36:31 +00:00
var macAddress = MACAddress.random()
protected set
2019-10-27 03:13:26 +00:00
override fun getMACAddress(): MACAddress {
return macAddress
}
2019-10-27 01:36:31 +00:00
override fun handle(packet: Packet) {
if (acceptsPacket(packet)) {
handlePacket(packet)
}
}
2019-10-27 03:13:26 +00:00
protected abstract fun handlePacket(packet: Packet)
2019-10-27 01:36:31 +00:00
2019-10-30 18:05:53 +00:00
protected open fun acceptsPacket(packet: Packet): Boolean {
2019-10-27 01:36:31 +00:00
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 {
2019-10-27 01:36:31 +00:00
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())
2019-10-27 03:13:26 +00:00
}
fun sendToAll(packet: Packet) {
sendToAll(packet, NetworkUtil.findDestinations(world!!, pos))
2019-10-27 01:36:31 +00:00
}
fun sendToAll(packet: Packet, destinations: Iterable<PacketSink>) {
destinations.forEach {
it.handle(packet)
2019-10-27 01:36:31 +00:00
}
}
override fun toTag(tag: CompoundTag): CompoundTag {
tag.putLong("MACAddress", macAddress.address)
return super.toTag(tag)
}
2021-02-10 23:55:49 +00:00
override fun fromTag(state: BlockState, tag: CompoundTag) {
super.fromTag(state, tag)
2019-10-27 01:36:31 +00:00
macAddress = MACAddress(tag.getLong("MACAddress"))
}
fun onBreak() {
sendToAll(DeviceRemovedPacket(this))
}
2019-10-27 01:36:31 +00:00
}