add deprecated

This commit is contained in:
2022-03-13 08:16:35 +08:00
parent 2e9d684622
commit 660dd4f029
18 changed files with 231 additions and 42 deletions
+16
View File
@@ -0,0 +1,16 @@
package cc.maxmc.servux
import cc.maxmc.servux.network.packet.StructureDataPacketHandler
import org.bukkit.Bukkit
import taboolib.common.platform.Plugin
import taboolib.platform.BukkitPlugin
object ServuxServer: Plugin() {
override fun onEnable() {
Bukkit.getMessenger().registerOutgoingPluginChannel(BukkitPlugin.getInstance(), StructureDataPacketHandler.CHANNEL)
Bukkit.getMessenger().registerIncomingPluginChannel(BukkitPlugin.getInstance(), StructureDataPacketHandler.CHANNEL) { string, player, byte ->
}
}
}
@@ -0,0 +1,16 @@
package cc.maxmc.servux.dataproviders
import kotlin.math.max
abstract class DataProviderBase protected constructor(
override val name: String,
override val networkChannel: String,
override val protocolVersion: Int,
override val description: String,
) : IDataProvider {
override var isEnabled = false
override var tickRate = 40
protected set(tickRate) {
field = max(tickRate, 1)
}
}
+78
View File
@@ -0,0 +1,78 @@
package cc.maxmc.servux.dataproviders
interface IDataProvider {
/**
* Returns the simple name for this data provider.
* This should preferably be a lower case alphanumeric string with no
* other special characters than '-' and '_'.
* This name will be used in the enable/disable commands as the argument
* and also as the config file key/identifier.
*
* @return
*/
val name: String
/**
* Returns the description of this data provider.
* Used in the command to list the available providers and to check the status
* of a given provider.
*
* @return
*/
val description: String
/**
* Returns the network channel name used by this data provider to listen
* for incoming data requests and to respond and send the requested data.
*
* @return
*/
val networkChannel: String
/**
* Returns the current protocol version this provider supports
*
* @return
*/
val protocolVersion: Int
/**
* Returns true if this data provider is currently enabled.
*
* @return
*/
/**
* Enables or disables this data provider
*
* @param enabled
*/
var isEnabled: Boolean
/**
* Returns whether or not this data provider should get ticked to periodically send some data,
* or if it's only listening for incoming requests and responds to them directly.
*
* @return
*/
fun shouldTick(): Boolean {
return false
}
/**
* Returns the interval in game ticks that this data provider should be ticked at
*
* @return
*/
val tickRate: Int
/**
* Called at the given tick rate
*
* @param tickCounter The current server tick (since last server start)
*/
fun tick(tickCounter: Int) {}
/**
* Returns the network packet handler used for this data provider.
* @return
*/
// IPluginChannelHandler getPacketHandler();
}
@@ -0,0 +1,280 @@
package cc.maxmc.servux.dataproviders
// native NBT
// World Structure
import cc.maxmc.servux.network.packet.StructureDataPacketHandler
import cc.maxmc.servux.util.*
import io.netty.buffer.Unpooled
import it.unimi.dsi.fastutil.longs.LongOpenHashSet
import it.unimi.dsi.fastutil.longs.LongSet
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.nbt.NBTTagList
import net.minecraft.world.level.ChunkCoordIntPair
import net.minecraft.world.level.levelgen.feature.StructureGenerator
import net.minecraft.world.level.levelgen.structure.StructureStart
import net.minecraft.world.level.levelgen.structure.pieces.StructurePieceSerializationContext
import org.bukkit.Bukkit
import org.bukkit.Chunk
import org.bukkit.World
import org.bukkit.entity.Player
import taboolib.platform.BukkitPlugin
import java.util.*
import kotlin.math.abs
class StructureDataProvider : DataProviderBase("structure_bounding_boxes",
StructureDataPacketHandler.CHANNEL,
StructureDataPacketHandler.PROTOCOL_VERSION,
"Structure Bounding Boxes data for structures such as Witch Huts, Ocean Monuments, Nether Fortresses etc.") {
companion object {
private const val timeout = 30 * 20
private const val updateInterval = 40
}
private val registeredPlayers = HashMap<UUID, PlayerDimensionPosition>()
private val timeouts = HashMap<UUID, MutableMap<ChunkPos, Timeout>>()
val metadata: NBTTagCompound = NBTTagCompound()
init {
metadata.putString("id", StructureDataPacketHandler.CHANNEL)
metadata.putInt("timeout", timeout)
metadata.putInt("version", StructureDataPacketHandler.PROTOCOL_VERSION)
}
private var retainDistance = 0
override fun shouldTick(): Boolean = true
override fun tick(tickCounter: Int) {
if (tickCounter % updateInterval == 0) {
if (registeredPlayers.isNotEmpty()) {
// System.out.printf("=======================\n");
// System.out.printf("tick: %d - %s\n", tickCounter, this.isEnabled());
retainDistance = Bukkit.getViewDistance() + 2
val uuidIter = registeredPlayers.keys.iterator()
while (uuidIter.hasNext()) {
val uuid = uuidIter.next()
val player: Player = Bukkit.getPlayer(uuid) ?: return run {
timeouts.remove(uuid)
uuidIter.remove()
}
this.checkForDimensionChange(player)
this.refreshTrackedChunks(player, tickCounter)
}
}
}
}
private fun checkForDimensionChange(player: Player) {
val uuid: UUID = player.uniqueId
val playerPos: PlayerDimensionPosition? = registeredPlayers[uuid]
if (playerPos == null || playerPos.dimensionChanged(player)) {
timeouts.remove(uuid)
registeredPlayers.computeIfAbsent(uuid) {
PlayerDimensionPosition(player)
}.setPosition(player)
}
}
private fun refreshTrackedChunks(player: Player, tickCounter: Int) {
val uuid: UUID = player.uniqueId
val map: MutableMap<ChunkPos, Timeout>? = timeouts[uuid]
if (map != null) {
// System.out.printf("refreshTrackedChunks: timeouts: %d\n", map.size());
this.sendAndRefreshExpiredStructures(player, map, tickCounter)
}
}
private fun sendAndRefreshExpiredStructures(
player: Player,
map: MutableMap<ChunkPos, Timeout>,
tickCounter: Int,
) {
val positionsToUpdate: MutableSet<ChunkPos> = HashSet()
map.forEach { (key, timeout) ->
if (timeout.needsUpdate(tickCounter, Companion.timeout)) {
positionsToUpdate.add(key)
}
}
if (positionsToUpdate.isNotEmpty()) {
val world = player.world
val center = player.location.chunk
val references: MutableMap<StructureGenerator<*>, LongSet> = HashMap()
for (pos in positionsToUpdate) {
if (this.isOutOfRange(pos, center)) {
map.remove(pos)
} else {
this.getStructureReferencesFromChunk(pos.x, pos.z, world, references)
val timeout = map[pos]
timeout?.lastSync = tickCounter
}
}
// System.out.printf("sendAndRefreshExpiredStructures: positionsToUpdate: %d -> references: %d, to: %d\n", positionsToUpdate.size(), references.size(), this.timeout);
if (references.isNotEmpty()) {
this.sendStructures(player, references, tickCounter)
}
}
}
private fun isOutOfRange(pos: ChunkPos, center: Chunk): Boolean {
val chunkRadius = retainDistance
return abs(pos.x - center.x) > chunkRadius ||
abs(pos.z - center.z) > chunkRadius
}
private fun getStructureReferencesFromChunk(
chunkX: Int,
chunkZ: Int,
world: World,
references: MutableMap<StructureGenerator<*>, LongSet>,
) {
if (!world.isChunkLoaded(chunkX, chunkZ)) {
return
}
val nmsWorld = NMS.INSTANCE.getMinecraftServer().allLevels.findLast { it.serverLevelData.levelName == world.name }!!
val chunk = nmsWorld.getChunk(chunkX, chunkZ)
chunk.allReferences.forEach { (feature, startChunks) ->
if (!startChunks.isEmpty() && feature != StructureGenerator.MINESHAFT) {
references.merge(feature, startChunks) { oldSet, entrySet ->
val newSet = LongOpenHashSet(oldSet)
newSet.addAll(entrySet)
return@merge newSet
}
}
}
}
private fun sendStructures(
player: Player,
references: Map<StructureGenerator<*>, LongSet>,
tickCounter: Int,
) {
val world: World = player.world
val starts: Map<ChunkPos, StructureStart<*>> = this.getStructureStartsFromReferences(world, references)
if (starts.isNotEmpty()) {
this.addOrRefreshTimeouts(player.uniqueId, references, tickCounter)
val structureList: NBTTagList = getStructureList(starts, world)
// System.out.printf("sendStructures: starts: %d -> structureList: %d. refs: %s\n", starts.size(), structureList.size(), references.keySet());
val tag = NBTTagCompound()
tag.put("Structures", structureList)
sendPacketTypeAndCompound(StructureDataPacketHandler.CHANNEL,
StructureDataPacketHandler.PACKET_S2C_STRUCTURE_DATA,
tag,
player)
}
}
private fun getStructureStartsFromReferences(
world: World,
references: Map<StructureGenerator<*>, LongSet>,
): Map<ChunkPos, StructureStart<*>> {
val starts = HashMap<ChunkPos, StructureStart<*>>()
references.forEach { (feature, startChunks) ->
val iter = startChunks.iterator()
while (iter.hasNext()) {
val pos = ChunkPos(iter.nextLong())
if (!world.isChunkLoaded(pos.x, pos.z)) {
continue
}
val nmsWorld = NMS.INSTANCE.getMinecraftServer().allLevels.findLast { it.serverLevelData.levelName == world.name }!!
val chunk = nmsWorld.getChunk(pos.x, pos.z)
val start: StructureStart<*> = chunk.getStartForFeature(feature) ?: return@forEach
starts[pos] = start
}
}
// System.out.printf("getStructureStartsFromReferences: references: %d -> starts: %d\n", references.size(), starts.size());
return starts
}
private fun addOrRefreshTimeouts(uuid: UUID, references: Map<StructureGenerator<*>, LongSet>, tickCounter: Int) {
// System.out.printf("addOrRefreshTimeouts: references: %d\n", references.size());
val map: MutableMap<ChunkPos, Timeout> = timeouts.computeIfAbsent(uuid
) { HashMap() }
for (chunks: LongSet in references.values) {
for (chunkPosLong in chunks) {
val pos = ChunkPos(chunkPosLong)
map.computeIfAbsent(pos) {
Timeout(tickCounter)
}.lastSync = tickCounter
}
}
}
private fun getStructureList(structures: Map<ChunkPos, StructureStart<*>>, world: World): NBTTagList {
val list = NBTTagList()
structures.forEach { (pos, value) ->
list.add(value.createTag(StructurePieceSerializationContext.fromLevel(NMS.INSTANCE.getMinecraftServer().allLevels.findLast { it.serverLevelData.levelName == world.name }!!),
ChunkCoordIntPair(pos.x, pos.z)))
}
return list
}
fun register(player: Player): Boolean {
// System.out.printf("register\n");
var registered = false
val uuid: UUID = player.uniqueId
if (!registeredPlayers.containsKey(uuid)) {
val bytebuf = Unpooled.buffer()
sendPacketTypeAndCompound(StructureDataPacketHandler.CHANNEL,
StructureDataPacketHandler.PACKET_S2C_METADATA,
metadata,
player)
registeredPlayers[uuid] = PlayerDimensionPosition(player)
val tickCounter: Int = Bukkit.getServer().ticksPerAmbientSpawns
this.initialSyncStructuresToPlayerWithinRange(player,
Bukkit.getViewDistance(),
tickCounter)
registered = true
}
return registered
}
private fun initialSyncStructuresToPlayerWithinRange(
player: Player,
chunkRadius: Int,
tickCounter: Int,
) {
val uuid: UUID = player.uniqueId
val center = ChunkPos(player.location.chunk)
val references: Map<StructureGenerator<*>, LongSet> =
this.getStructureReferencesWithinRange(player.world, center, chunkRadius)
timeouts.remove(uuid)
registeredPlayers.computeIfAbsent(uuid) { u: UUID? ->
PlayerDimensionPosition(player)
}.setPosition(player)
// System.out.printf("initialSyncStructuresToPlayerWithinRange: references: %d\n", references.size());
sendStructures(player, references, tickCounter)
}
private fun getStructureReferencesWithinRange(
world: World,
center: ChunkPos,
chunkRadius: Int,
): Map<StructureGenerator<*>, LongSet> {
val references = HashMap<StructureGenerator<*>, LongSet>()
for (cx in center.x - chunkRadius..center.x + chunkRadius) {
for (cz in center.z - chunkRadius..center.z + chunkRadius) {
getStructureReferencesFromChunk(cx, cz, world, references)
}
}
// System.out.printf("getStructureReferencesWithinRange: references: %d\n", references.size());
return references
}
private fun sendPacketTypeAndCompound(
channel: String,
packetType: Int,
data: NBTTagCompound,
player: Player,
) {
val buf = Unpooled.buffer()
buf.writeVarInt(packetType)
buf.writeNBT(data)
buf.readBytes(ByteArray(buf.capacity()))
player.sendPluginMessage(BukkitPlugin.getInstance(), channel, buf.array())
}
}
@@ -0,0 +1,29 @@
package cc.maxmc.servux.network.packet;
import cc.maxmc.servux.dataproviders.StructureDataProvider;
import org.bukkit.entity.Player;
public class StructureDataPacketHandler {
public static final String CHANNEL = "servux:structures";
public static final StructureDataPacketHandler INSTANCE = new StructureDataPacketHandler();
public static final int PROTOCOL_VERSION = 1;
public static final int PACKET_S2C_METADATA = 1;
public static final int PACKET_S2C_STRUCTURE_DATA = 2;
public String getChannel() {
return CHANNEL;
}
public boolean isSubscribable() {
return true;
}
public boolean subscribe(Player player) {
return StructureDataProvider.register(player);
}
public boolean unsubscribe(Player player) {
return StructureDataProvider.unregister(netHandler.player);
}
}
+8
View File
@@ -0,0 +1,8 @@
package cc.maxmc.servux.util
import org.bukkit.Chunk
data class ChunkPos(var x: Int, var z: Int) {
constructor(pos: Long) : this(pos.toInt(), (pos shr 32).toInt())
constructor(chunk: Chunk) : this(chunk.x, chunk.z)
}
+330
View File
@@ -0,0 +1,330 @@
package cc.maxmc.servux.util
import com.google.gson.*
import org.bukkit.util.Vector
import taboolib.common.platform.function.info
import taboolib.common.platform.function.warning
import taboolib.platform.BukkitPlugin
import java.io.File
import java.io.FileReader
import java.io.FileWriter
import java.io.IOException
object JsonUtils {
val GSON = GsonBuilder().setPrettyPrinting().create()
fun getNestedObject(parent: JsonObject, key: String?, create: Boolean): JsonObject? {
return if (!parent.has(key) || !parent[key].isJsonObject) {
if (!create) {
return null
}
val obj = JsonObject()
parent.add(key, obj)
obj
} else {
parent[key].asJsonObject
}
}
fun hasBoolean(obj: JsonObject, name: String?): Boolean {
val el = obj[name]
if (el != null && el.isJsonPrimitive) {
try {
el.asBoolean
return true
} catch (_: Exception) { }
}
return false
}
fun hasInteger(obj: JsonObject, name: String?): Boolean {
val el = obj[name]
if (el != null && el.isJsonPrimitive) {
try {
el.asInt
return true
} catch (e: Exception) {
}
}
return false
}
fun hasLong(obj: JsonObject, name: String?): Boolean {
val el = obj[name]
if (el != null && el.isJsonPrimitive) {
try {
el.asLong
return true
} catch (_: Exception) {
}
}
return false
}
fun hasFloat(obj: JsonObject, name: String?): Boolean {
val el = obj[name]
if (el != null && el.isJsonPrimitive) {
try {
el.asFloat
return true
} catch (_: Exception) {
}
}
return false
}
fun hasDouble(obj: JsonObject, name: String?): Boolean {
val el = obj[name]
if (el != null && el.isJsonPrimitive) {
try {
el.asDouble
return true
} catch (_: Exception) { }
}
return false
}
fun hasString(obj: JsonObject, name: String?): Boolean {
val el = obj[name]
if (el != null && el.isJsonPrimitive) {
try {
el.asString
return true
} catch (_: Exception) { }
}
return false
}
fun hasObject(obj: JsonObject, name: String?): Boolean {
val el = obj[name]
return el != null && el.isJsonObject
}
fun hasArray(obj: JsonObject, name: String?): Boolean {
val el = obj[name]
return el != null && el.isJsonArray
}
fun getBooleanOrDefault(obj: JsonObject, name: String?, defaultValue: Boolean): Boolean {
if (obj.has(name) && obj[name].isJsonPrimitive) {
try {
return obj[name].asBoolean
} catch (e: Exception) {
}
}
return defaultValue
}
fun getIntegerOrDefault(obj: JsonObject, name: String?, defaultValue: Int): Int {
if (obj.has(name) && obj[name].isJsonPrimitive) {
try {
return obj[name].asInt
} catch (e: Exception) {
}
}
return defaultValue
}
fun getLongOrDefault(obj: JsonObject, name: String?, defaultValue: Long): Long {
if (obj.has(name) && obj[name].isJsonPrimitive) {
try {
return obj[name].asLong
} catch (e: Exception) {
}
}
return defaultValue
}
fun getFloatOrDefault(obj: JsonObject, name: String?, defaultValue: Float): Float {
if (obj.has(name) && obj[name].isJsonPrimitive) {
try {
return obj[name].asFloat
} catch (e: Exception) {
}
}
return defaultValue
}
fun getDoubleOrDefault(obj: JsonObject, name: String?, defaultValue: Double): Double {
if (obj.has(name) && obj[name].isJsonPrimitive) {
try {
return obj[name].asDouble
} catch (e: Exception) {
}
}
return defaultValue
}
fun getStringOrDefault(obj: JsonObject, name: String?, defaultValue: String?): String? {
if (obj.has(name) && obj[name].isJsonPrimitive) {
try {
return obj[name].asString
} catch (e: Exception) {
}
}
return defaultValue
}
fun getBoolean(obj: JsonObject, name: String?): Boolean {
return getBooleanOrDefault(obj, name, false)
}
fun getInteger(obj: JsonObject, name: String?): Int {
return getIntegerOrDefault(obj, name, 0)
}
fun getLong(obj: JsonObject, name: String?): Long {
return getLongOrDefault(obj, name, 0)
}
fun getFloat(obj: JsonObject, name: String?): Float {
return getFloatOrDefault(obj, name, 0f)
}
fun getDouble(obj: JsonObject, name: String?): Double {
return getDoubleOrDefault(obj, name, 0.0)
}
fun getString(obj: JsonObject, name: String?): String? {
return getStringOrDefault(obj, name, null)
}
fun hasBlockPos(obj: JsonObject, name: String?): Boolean {
return blockPosFromJson(obj, name) != null
}
fun blockPosToJson(pos: Vector): JsonArray {
val arr = JsonArray()
arr.add(pos.x)
arr.add(pos.y)
arr.add(pos.z)
return arr
}
fun blockPosFromJson(obj: JsonObject, name: String?): Vector? {
if (hasArray(obj, name)) {
val arr = obj.getAsJsonArray(name)
if (arr.size() == 3) {
try {
return Vector(arr[0].asInt, arr[1].asInt, arr[2].asInt)
} catch (ignored: Exception) {
}
}
}
return null
}
fun hasVec3d(obj: JsonObject, name: String?): Boolean {
return vec3dFromJson(obj, name) != null
}
fun vec3dToJson(vec: Vector): JsonArray {
val arr = JsonArray()
arr.add(vec.x)
arr.add(vec.y)
arr.add(vec.z)
return arr
}
fun vec3dFromJson(obj: JsonObject, name: String?): Vector? {
if (hasArray(obj, name)) {
val arr = obj.getAsJsonArray(name)
if (arr.size() == 3) {
try {
return Vector(arr[0].asDouble, arr[1].asDouble, arr[2].asDouble)
} catch (e: Exception) {
}
}
}
return null
}
// https://stackoverflow.com/questions/29786197/gson-jsonobject-copy-value-affected-others-jsonobject-instance
fun deepCopy(jsonObject: JsonObject): JsonObject {
val result = JsonObject()
for ((key, value) in jsonObject.entrySet()) {
result.add(key, deepCopy(value))
}
return result
}
fun deepCopy(jsonArray: JsonArray): JsonArray {
val result = JsonArray()
for (e in jsonArray) {
result.add(deepCopy(e))
}
return result
}
fun deepCopy(jsonElement: JsonElement): JsonElement {
return if (jsonElement.isJsonPrimitive || jsonElement.isJsonNull) {
jsonElement // these are immutable anyway
} else if (jsonElement.isJsonObject) {
deepCopy(jsonElement.asJsonObject)
} else if (jsonElement.isJsonArray) {
deepCopy(jsonElement.asJsonArray)
} else {
throw UnsupportedOperationException("Unsupported element: $jsonElement")
}
}
fun parseJsonFromString(str: String?): JsonElement? {
try {
val parser = JsonParser()
return parser.parse(str)
} catch (e: Exception) {
}
return null
}
fun parseJsonFile(file: File?): JsonElement? {
if (file != null && file.exists() && file.isFile && file.canRead()) {
val fileName = file.absolutePath
try {
val parser = JsonParser()
val reader = FileReader(file)
val element = parser.parse(reader)
reader.close()
return element
} catch (e: Exception) {
warning("Failed to parse the JSON file '" + fileName + "'" + e.message)
}
}
return null
}
/**
* Converts the given JsonElement tree into its string representation.
* If **compact** is true, then it's written in one line without spaces or line breaks.
*
* @param element
* @param compact
* @return
*/
fun jsonToString(element: JsonElement?, compact: Boolean): String {
val gson = if (compact) Gson() else GSON
return gson.toJson(element)
}
fun writeJsonToFile(root: JsonElement?, file: File): Boolean {
return writeJsonToFile(GSON, root, file)
}
fun writeJsonToFile(gson: Gson, root: JsonElement?, file: File): Boolean {
var writer: FileWriter? = null
try {
writer = FileWriter(file)
writer.write(gson.toJson(root))
writer.close()
return true
} catch (e: IOException) {
warning("Failed to write JSON data to file '" + file.absolutePath + "'" + e.message)
} finally {
try {
writer?.close()
} catch (e: Exception) {
warning("Failed to close JSON file" + e.message)
}
}
return false
}
}
+12
View File
@@ -0,0 +1,12 @@
package cc.maxmc.servux.util
import net.minecraft.server.MinecraftServer
import taboolib.module.nms.nmsProxy
abstract class NMS {
abstract fun getMinecraftServer(): MinecraftServer
companion object {
val INSTANCE = nmsProxy<NMS>()
}
}
+13
View File
@@ -0,0 +1,13 @@
package cc.maxmc.servux.util
import net.minecraft.server.MinecraftServer
import org.bukkit.Bukkit
import org.bukkit.craftbukkit.v1_18_R1.CraftServer
class NMSImpl: NMS() {
override fun getMinecraftServer(): MinecraftServer {
val cServer = Bukkit.getServer() as CraftServer
return cServer.server
}
}
+12
View File
@@ -0,0 +1,12 @@
package cc.maxmc.servux.util
import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket
import taboolib.common.platform.event.SubscribeEvent
import taboolib.module.nms.PacketSendEvent
class PacketListener {
@SubscribeEvent
fun onPacket(e: PacketSendEvent) {
if(e.packet.source is ClientboundLevelChunkWithLightPacket)
}
}
+31
View File
@@ -0,0 +1,31 @@
package cc.maxmc.servux.util
import io.netty.buffer.ByteBuf
import io.netty.buffer.ByteBufOutputStream
import io.netty.handler.codec.EncoderException
import net.minecraft.nbt.NBTCompressedStreamTools
import net.minecraft.nbt.NBTTagCompound
import java.io.IOException
fun ByteBuf.writeVarInt(value: Int): ByteBuf {
var value = value
while (value and -128 != 0) {
this.writeByte(value and 127 or 128)
value = value ushr 7
}
this.writeByte(value)
return this
}
fun ByteBuf.writeNBT(compound: NBTTagCompound?): ByteBuf {
if (compound == null) {
this.writeByte(0)
} else {
try {
NBTCompressedStreamTools.write(compound, ByteBufOutputStream(this))
} catch (var3: IOException) {
throw EncoderException(var3)
}
}
return this
}
@@ -0,0 +1,34 @@
package cc.maxmc.servux.util
import org.bukkit.World
import org.bukkit.entity.Player
import org.bukkit.util.BlockVector
import org.bukkit.util.Vector
import kotlin.math.abs
class PlayerDimensionPosition(player: Player) {
lateinit var world: World
lateinit var pos: BlockVector
init {
setPosition(player)
}
fun dimensionChanged(player: Player): Boolean {
return world != player.world
}
fun needsUpdate(player: Player, distanceThreshold: Int): Boolean {
if (player.world != world) {
return true
}
val pos: Vector = player.location.toVector().toBlockVector()
return abs(pos.x - this.pos.x) > distanceThreshold || abs(pos.y - this.pos.y) > distanceThreshold || abs(
pos.z - this.pos.z) > distanceThreshold
}
fun setPosition(player: Player) {
world = player.world
pos = player.location.toVector().toBlockVector()
}
}
+9
View File
@@ -0,0 +1,9 @@
package cc.maxmc.servux.util
class Timeout(var lastSync: Int) {
fun needsUpdate(currentTick: Int, timeout: Int): Boolean {
return currentTick - lastSync >= timeout
}
}