Add global incrementing tick number to scheduler
This commit is contained in:
parent
58dccea7df
commit
8bfe0141bf
4 changed files with 15 additions and 8 deletions
|
@ -4,6 +4,13 @@ import kotlinx.coroutines.NonCancellable
|
|||
import kotlinx.coroutines.withContext
|
||||
|
||||
interface Scheduler {
|
||||
/**
|
||||
* Only safe to access from the scheduler thread.
|
||||
*
|
||||
* Will overflow after about 5 years.
|
||||
*/
|
||||
val currentTickNumber: Int
|
||||
|
||||
/**
|
||||
* Executes [block] after [delay] ticks passed.
|
||||
*
|
||||
|
|
|
@ -21,6 +21,8 @@ class UranosScheduler : Scheduler {
|
|||
|
||||
val logger = Logger("Scheduler", false)
|
||||
|
||||
override var currentTickNumber = Int.MIN_VALUE
|
||||
|
||||
inner class Task<R : Any>(
|
||||
val fn: suspend () -> R,
|
||||
val interval: Long?,
|
||||
|
@ -29,8 +31,6 @@ class UranosScheduler : Scheduler {
|
|||
@Volatile
|
||||
var cancelled: Boolean = false
|
||||
|
||||
val creationStackTrace = Thread.currentThread().stackTrace
|
||||
|
||||
override fun cancel() {
|
||||
tasks.remove(this)
|
||||
cancelled = true
|
||||
|
@ -68,6 +68,8 @@ class UranosScheduler : Scheduler {
|
|||
val duration = System.currentTimeMillis() - startTime
|
||||
if (duration > interval) logger.warn("Last tick took ${duration}ms, but should only take ${interval}ms")
|
||||
}
|
||||
|
||||
currentTickNumber += 1
|
||||
}, 0, interval, TimeUnit.MILLISECONDS)
|
||||
}
|
||||
|
||||
|
|
|
@ -128,15 +128,12 @@ class UranosServer internal constructor() : Server() {
|
|||
}
|
||||
|
||||
private fun startTicking() {
|
||||
var index = 0
|
||||
scheduler.executeRepeating(1, 0) {
|
||||
runInServerThread {
|
||||
players.forEach { it.container.tick() }
|
||||
internalEntities.forEach { it.tick() }
|
||||
sessions.forEach { it.tick(index) }
|
||||
sessions.forEach { it.tick() }
|
||||
}
|
||||
|
||||
index++
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -2,6 +2,7 @@ package space.uranos.net
|
|||
|
||||
import io.netty.buffer.ByteBuf
|
||||
import kotlinx.coroutines.*
|
||||
import space.uranos.Uranos
|
||||
import space.uranos.UranosServer
|
||||
import space.uranos.chat.ChatColor
|
||||
import space.uranos.chat.ChatComponent
|
||||
|
@ -169,8 +170,8 @@ class UranosSession(val channel: io.netty.channel.Channel, val server: UranosSer
|
|||
|
||||
fun sendKeepAlivePacket() = send(OutgoingKeepAlivePacket(System.currentTimeMillis()))
|
||||
|
||||
suspend fun tick(index: Int) {
|
||||
if (earlyPlayer != null && index % KEEP_ALIVE_PACKET_INTERVAL == 0L) sendKeepAlivePacket()
|
||||
suspend fun tick() {
|
||||
if (earlyPlayer != null && Uranos.scheduler.currentTickNumber % KEEP_ALIVE_PACKET_INTERVAL == 0L) sendKeepAlivePacket()
|
||||
|
||||
packetsAdapter.tick()
|
||||
}
|
||||
|
|
Reference in a new issue