-
Notifications
You must be signed in to change notification settings - Fork 0
/
PhantomManager.kt
57 lines (46 loc) · 1.64 KB
/
PhantomManager.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
* This Code Showcase is that of
* a Packet based entity manager.
*
* The goal is to efficiently combine entity updates
* (which are async safe packets) for each viewer.
* Packet per player get bundled into a single packet to reduce network usage.
*/
class PhantomManager(val owningPlugin: Plugin) {
val phantoms = mutableMapOf<Int, Phantom>()
private var updateCheckTask: BukkitTask? = null
init {
updateCheckTask = owningPlugin.server.scheduler.runTaskTimerAsynchronously(owningPlugin, Runnable {
sendUpdates()
}, 0L, 1L)
}
private fun sendUpdates() {
val playerUpdateMap = mutableMapOf<Player, MutableList<Packet<*>>>()
phantoms.values.forEach { phantom ->
if (phantom.requiresUpdate) {
phantom.viewers.forEach { viewerId ->
Bukkit.getPlayer(viewerId)?.let {
playerUpdateMap.computeIfAbsent(it) { mutableListOf() }.add(
PhantomPacketFactory.createUpdatePhantomPacket(phantom)
)
} ?: phantom.removeFor(viewerId)
}
}
}
playerUpdateMap.forEach { (player, packets) ->
PacketUtil.sendPacket(player, PhantomPacketFactory.createBundlePacket(packets))
}
}
fun addPhantom(phantom:PhantomManager) {
phantoms[phantom.entityId] = phantom
}
fun removePhantom(phantom:PhantomManager) {
phantoms.remove(phantom.entityId)
phantom.remove()
}
fun onDisable() {
updateCheckTask?.cancel()
updateCheckTask = null
phantoms.clear()
}
}