@@ -10,6 +10,8 @@ SPDX-License-Identifier: GPL-2.0-or-later
1010#include < cstring>
1111
1212#include < algorithm>
13+ #include < chrono>
14+ #include < thread>
1315
1416#include " gfxv.h"
1517#include " id_ca.h"
@@ -1469,57 +1471,39 @@ void DrawPlayerWeapon()
14691471
14701472void CalcTics ()
14711473{
1472- std::int32_t newtime;
1473-
1474- //
1475- // calculate tics since last refresh for adaptive timing
1476- //
1477- if (lasttimecount > TimeCount)
1478- {
1479- TimeCount = lasttimecount; // if the game was paused a LONG time
1480-
1481-
1482- }
1483-
1484- {
1485- //
1486- // non demo, so report actual time
1487- //
1488- do
1489- {
1490- newtime = TimeCount;
1491- auto diff = newtime - lasttimecount;
1492- if (diff <= 0 )
1493- {
1494- tics = 0 ;
1495- }
1496- else
1497- {
1498- tics = static_cast <std::uint16_t >(diff);
1499- }
1500- } while (tics == 0 ); // make sure at least one tic passes
1501-
1502- lasttimecount = newtime;
1503- framecount++;
1504-
1474+ constexpr long long one_second_ns = 1'000'000'000 ;
1475+ using Clock = std::chrono::steady_clock;
1476+ using TimePoint = Clock::time_point;
1477+ static long long period_counter = 0 ;
1478+ static TimePoint last_time_point{};
1479+ const TimePoint time_point = Clock::now ();
1480+ const long long diff_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(time_point - last_time_point).count ();
1481+ last_time_point = time_point;
1482+ period_counter += diff_ns * TickBase;
1483+ const long long elapsed_periods = period_counter / one_second_ns;
1484+ period_counter %= one_second_ns;
1485+ const std::chrono::nanoseconds delay{(one_second_ns - period_counter) / TickBase};
1486+ std::this_thread::sleep_for (delay);
1487+ constexpr long long min_tics = 1 ;
1488+ constexpr long long max_tics = UINT16_MAX;
1489+ tics = static_cast <std::uint16_t >(bstone::clamp (elapsed_periods, min_tics, max_tics));
1490+ lasttimecount = TimeCount;
1491+ framecount++;
15051492#ifdef FILEPROFILE
1506- strcpy (scratch, " \t Tics:" );
1507- itoa (tics, str, 10 );
1508- strcat (scratch, str);
1509- strcat (scratch, " \n " );
1510- write (profilehandle, scratch, strlen (scratch));
1493+ strcpy (scratch, " \t Tics:" );
1494+ itoa (tics, str, 10 );
1495+ strcat (scratch, str);
1496+ strcat (scratch, " \n " );
1497+ write (profilehandle, scratch, strlen (scratch));
15111498#endif
1512-
15131499#ifdef DEBUGTICS
1514- VW_SetAtrReg (ATR_OVERSCAN, tics);
1500+ VW_SetAtrReg (ATR_OVERSCAN, tics);
15151501#endif
1516-
1517- realtics = tics;
1518- if (tics > MAXTICS)
1519- {
1520- TimeCount -= (tics - MAXTICS);
1521- tics = MAXTICS;
1522- }
1502+ realtics = tics;
1503+ if (tics > MAXTICS)
1504+ {
1505+ TimeCount = std::max (TimeCount - (tics - MAXTICS), 0 );
1506+ tics = MAXTICS;
15231507 }
15241508}
15251509
0 commit comments