19#ifndef HEADER_NETWORK_TIMER_SYNCHRONIZER_HPP
20#define HEADER_NETWORK_TIMER_SYNCHRONIZER_HPP
23#include "utils/log.hpp"
24#include "utils/time.hpp"
36 std::deque<std::tuple<uint32_t, uint64_t, uint64_t> > m_times;
38 std::atomic_bool m_synchronised, m_force_set_timer;
43 m_synchronised.store(
false);
44 m_force_set_timer.store(
false);
47 bool isSynchronised()
const {
return m_synchronised.load(); }
49 void enableForceSetTimer()
51 if (m_synchronised.load() ==
true)
53 m_force_set_timer.store(
true);
56 void resynchroniseTimer() { m_synchronised.store(
false); }
58 void addAndSetTime(uint32_t ping, uint64_t server_time)
60 if (m_synchronised.load() ==
true)
63 if (m_force_set_timer.load() ==
true)
65 m_force_set_timer.store(
false);
66 m_synchronised.store(
true);
67 STKHost::get()->setNetworkTimer(server_time + (uint64_t)(ping / 2));
75 const uint64_t frequency = (uint64_t)((1.0f / 10.0f) * 1000.0f) / 2;
76 if (!m_times.empty() &&
77 cur_time - std::get<2>(m_times.back()) < frequency)
83 if (m_times.size() >= 20)
85 uint64_t sum = std::accumulate(m_times.begin(), m_times.end(),
86 (uint64_t)0, [cur_time](
const uint64_t previous,
87 const std::tuple<uint32_t, uint64_t, uint64_t>& b)->uint64_t
89 return previous + (uint64_t)(std::get<0>(b) / 2) +
90 std::get<1>(b) + cur_time - std::get<2>(b);
92 const int64_t averaged_time = sum / 20;
93 const int64_t server_time_now = server_time + (uint64_t)(ping / 2);
94 int difference = (int)std::abs(averaged_time - server_time_now);
95 if (std::abs(averaged_time - server_time_now) <
96 UserConfigParams::m_timer_sync_difference_tolerance)
100 m_force_set_timer.store(
false);
101 m_synchronised.store(
true);
102 Log::info(
"NetworkTimerSynchronizer",
"Network "
103 "timer synchronized, difference: %dms", difference);
106 m_times.erase(m_times.begin(), m_times.begin() + 10);
108 m_times.emplace_back(ping, server_time, cur_time);
Definition: network_timer_synchronizer.hpp:34
static STKHost * get()
Returns the instance of STKHost.
Definition: stk_host.hpp:185
static uint64_t getMonoTimeMs()
Returns a time based since the starting of stk (monotonic clock).
Definition: time.hpp:106
Defines an interface to use network low-level functions easily.
Declares the general types that are used by the network.