From 67c913041e0d185b5e70dc1dc2f9cec4250af9a5 Mon Sep 17 00:00:00 2001 From: ostermine Date: Thu, 5 Nov 2026 13:46:49 +0300 Subject: [PATCH] fix headless tick rate: schedule ticks by deadlines ServerMainloop slept the rest of the tick and then restarted counting from the moment it woke up, so every sleep overshoot made the tick longer. With a coarse timer (a VirtualBox guest of a Windows host) --tps 20 gave 12-17 ticks per second. Ticks now follow absolute deadlines on steady_clock; after falling more than 5 ticks behind the schedule is reset instead of running a burst of ticks. The time of a tick is its scheduled time, so delta is exactly 1 / tps while the loop keeps up, as in test mode. With the wake-up time deltas jitter around 1 / tps, and the world tick clock, which calls on_world_tick at most once per update, skipped every few ticks. --- src/engine/ServerMainloop.cpp | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/src/engine/ServerMainloop.cpp b/src/engine/ServerMainloop.cpp index 9790723a9..6a0342c0f 100644 --- a/src/engine/ServerMainloop.cpp +++ b/src/engine/ServerMainloop.cpp @@ -35,16 +35,16 @@ void ServerMainloop::run() { double targetDelta = 1.0 / static_cast(coreParams.tps); double delta = targetDelta; - auto begin = system_clock::now(); - auto startupTime = begin; + const auto tickDuration = + duration_cast(duration(targetDelta)); + auto startupTime = steady_clock::now(); + auto nextTick = startupTime; while (!engine.isQuitSignal() && !engine.getAppScripts().isFinished()) { if (coreParams.testMode) { time.step(delta); } else { - auto now = system_clock::now(); - time.update( - duration_cast(now - startupTime).count() / 1e6); + time.update(duration(nextTick - startupTime).count()); delta = time.getDelta(); } if (controller) { @@ -55,13 +55,15 @@ void ServerMainloop::run() { engine.postUpdate(); if (!coreParams.testMode) { - auto end = system_clock::now(); - int64_t millis = targetDelta * 1000 - - duration_cast(end - begin).count() / 1000; - if (millis > 0) { - platform::sleep(millis); + nextTick += tickDuration; + auto now = steady_clock::now(); + if (nextTick > now) { + platform::sleep( + duration_cast(nextTick - now).count() + ); + } else if (now - nextTick > tickDuration * 5) { + nextTick = now; } - begin = system_clock::now(); } } logger.info() << "script finished";