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

66 lines
1.6 KiB
Kotlin

package net.shadowfacts.phycon.network
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Direction
import net.minecraft.world.World
import net.shadowfacts.phycon.api.NetworkCable
import net.shadowfacts.phycon.api.PacketSink
import net.shadowfacts.phycon.api.PhyAttributes
import java.util.*
/**
* @author shadowfacts
*/
object NetworkUtil {
fun findDestinations(world: World, startPos: BlockPos, direction: Direction? = null): List<PacketSink> {
val results = LinkedList<PacketSink>()
val visited = hashSetOf(startPos)
val queue = LinkedList<BlockPos>()
if (direction != null) {
queue.add(startPos.offset(direction))
} else {
addAdjacent(queue, visited, startPos)
}
while (queue.isNotEmpty()) {
val pos = queue.pop()
val sink = PhyAttributes.PACKET_SINK.getFirstOrNull(world, pos)
if (sink != null) {
results.add(sink)
}
findEdges(queue, visited, world, pos)
visited.add(pos)
}
return results
}
private fun findEdges(queue: MutableList<BlockPos>, visited: Set<BlockPos>, world: World, pos: BlockPos) {
val state = world.getBlockState(pos)
val block = state.block
if (block is NetworkCable) {
val connections = block.getNetworkConnectedSides(state, world, pos)
for (side in connections) {
val newPos = pos.offset(side)
if (newPos !in visited) {
queue.add(newPos)
}
}
}
}
private fun addAdjacent(queue: MutableList<BlockPos>, visited: Set<BlockPos>, pos: BlockPos) {
for (dir in Direction.values()) {
val newPos = pos.offset(dir)
if (newPos !in visited) {
queue.add(newPos)
}
}
}
}