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.shadowfacts.phycon.api.PacketSink import net.shadowfacts.phycon.api.PacketSource import net.shadowfacts.phycon.api.packet.Packet import net.shadowfacts.phycon.api.util.MACAddress import net.shadowfacts.phycon.network.packet.DeviceRemovedPacket /** * @author shadowfacts */ abstract class DeviceBlockEntity(type: BlockEntityType<*>): BlockEntity(type), PacketSink, PacketSource { 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) } override 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()) } override fun sendToAll(packet: Packet) { sendToAll(packet, NetworkUtil.findDestinations(world!!, pos)) } override fun sendToAll(packet: Packet, destinations: Iterable) { 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)) } }