walkmc.PResource.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of resources-addon Show documentation
Show all versions of resources-addon Show documentation
A resources API/Addon with compatibility with others plugins
The newest version!
package walkmc
import com.sk89q.worldguard.protection.regions.*
import org.bukkit.*
import org.bukkit.entity.*
import org.bukkit.event.player.*
import walkmc.event.*
import walkmc.extensions.*
import walkmc.graphical.*
import java.util.*
/**
* The main class of the service plugin.
*/
object PResource : Plugin() {
/**
* All cached regions of a player.
*/
private val regionCache = cacheOf>()
/**
* Setups start feature of the resources' plugin.
*/
override fun onEnable() {
loadInterfaceService()
events()
}
/**
* Register all events of the resources' plugin.
*/
private fun events() {
subscribe {
updateRegion(player, player.location, Movement.CONNECT)
}
subscribe {
updateRegion(player, respawnLocation, Movement.SPAWN)
}
subscribe {
isCancelled = updateRegion(player, to, Movement.TELEPORT)
}
subscribe {
isCancelled = updateRegion(player, to, Movement.MOVE)
}
subscribe {
runCatching {
regionCache -= player.uuid
for (region in player.location.regions())
RegionLeaveEvent(player, region, Movement.DISCONNECT).call()
}
}
subscribe {
runCatching {
regionCache -= player.uuid
for (region in player.location.regions())
RegionLeaveEvent(player, region, Movement.DISCONNECT).call()
}
}
}
/**
* Updates player data of a region.
*/
private fun updateRegion(player: Player, location: Location, movement: Movement): Boolean {
return runCatching {
val manager = location.world.regionManager()
val cachedRegions = regionCache[player.uuid] ?: hashSetOf()
val applicableRegions = manager.getApplicableRegions(location)
val oldRegions = HashSet(cachedRegions)
// enter
for (region in applicableRegions) {
if (region !in cachedRegions) {
val event = RegionEnterEvent(player, region, movement).call()
if (event.isCancelled) {
cachedRegions.clear()
cachedRegions += oldRegions
return true
}
cachedRegions += region
}
}
// leave
for (region in cachedRegions) {
if (region !in applicableRegions) {
if (manager.getRegion(region.id) != region) {
cachedRegions -= region
continue
}
val event = RegionLeaveEvent(player, region, movement).call()
if (event.isCancelled) {
cachedRegions.clear()
cachedRegions += oldRegions
return true
}
cachedRegions -= region
}
}
regionCache[player.uuid] = cachedRegions
false
}.getOrDefault(false)
}
}