main_timer_sync.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. /*************************************************************************/
  2. /* main_timer_sync.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "main_timer_sync.h"
  31. #include "core/math/math_funcs.h"
  32. #include "core/os/os.h"
  33. void MainFrameTime::clamp_idle(float min_idle_step, float max_idle_step) {
  34. if (idle_step < min_idle_step) {
  35. idle_step = min_idle_step;
  36. } else if (idle_step > max_idle_step) {
  37. idle_step = max_idle_step;
  38. }
  39. }
  40. /////////////////////////////////
  41. void MainTimerSync::DeltaSmoother::update_refresh_rate_estimator(int64_t p_delta) {
  42. // the calling code should prevent 0 or negative values of delta
  43. // (preventing divide by zero)
  44. // note that if the estimate gets locked, and something external changes this
  45. // (e.g. user changes to non-vsync in the OS), then the results may be less than ideal,
  46. // but usually it will detect this via the FPS measurement and not attempt smoothing.
  47. // This should be a rare occurrence anyway, and will be cured next time user restarts game.
  48. if (_estimate_locked) {
  49. return;
  50. }
  51. // First average the delta over NUM_READINGS
  52. _estimator_total_delta += p_delta;
  53. _estimator_delta_readings++;
  54. const int NUM_READINGS = 60;
  55. if (_estimator_delta_readings < NUM_READINGS) {
  56. return;
  57. }
  58. // use average
  59. p_delta = _estimator_total_delta / NUM_READINGS;
  60. // reset the averager for next time
  61. _estimator_delta_readings = 0;
  62. _estimator_total_delta = 0;
  63. ///////////////////////////////
  64. int fps = Math::round(1000000.0 / p_delta);
  65. // initial estimation, to speed up converging, special case we will estimate the refresh rate
  66. // from the first average FPS reading
  67. if (_estimated_fps == 0) {
  68. // below 50 might be chugging loading stuff, or else
  69. // dropping loads of frames, so the estimate will be inaccurate
  70. if (fps >= 50) {
  71. _estimated_fps = fps;
  72. #ifdef GODOT_DEBUG_DELTA_SMOOTHER
  73. print_line("initial guess (average measured) refresh rate: " + itos(fps));
  74. #endif
  75. } else {
  76. // can't get started until above 50
  77. return;
  78. }
  79. }
  80. // we hit our exact estimated refresh rate.
  81. // increase our confidence in the estimate.
  82. if (fps == _estimated_fps) {
  83. // note that each hit is an average of NUM_READINGS frames
  84. _hits_at_estimated++;
  85. if (_estimate_complete && _hits_at_estimated == 20) {
  86. _estimate_locked = true;
  87. #ifdef GODOT_DEBUG_DELTA_SMOOTHER
  88. print_line("estimate LOCKED at " + itos(_estimated_fps) + " fps");
  89. #endif
  90. return;
  91. }
  92. // if we are getting pretty confident in this estimate, decide it is complete
  93. // (it can still be increased later, and possibly lowered but only for a short time)
  94. if ((!_estimate_complete) && (_hits_at_estimated > 2)) {
  95. // when the estimate is complete we turn on smoothing
  96. if (_estimated_fps) {
  97. _estimate_complete = true;
  98. _vsync_delta = 1000000 / _estimated_fps;
  99. #ifdef GODOT_DEBUG_DELTA_SMOOTHER
  100. print_line("estimate complete. vsync_delta " + itos(_vsync_delta) + ", fps " + itos(_estimated_fps));
  101. #endif
  102. }
  103. }
  104. #ifdef GODOT_DEBUG_DELTA_SMOOTHER
  105. if ((_hits_at_estimated % (400 / NUM_READINGS)) == 0) {
  106. String sz = "hits at estimated : " + itos(_hits_at_estimated) + ", above : " + itos(_hits_above_estimated) + "( " + itos(_hits_one_above_estimated) + " ), below : " + itos(_hits_below_estimated) + " (" + itos(_hits_one_below_estimated) + " )";
  107. print_line(sz);
  108. }
  109. #endif
  110. return;
  111. }
  112. const int SIGNIFICANCE_UP = 1;
  113. const int SIGNIFICANCE_DOWN = 2;
  114. // we are not usually interested in slowing the estimate
  115. // but we may have overshot, so make it possible to reduce
  116. if (fps < _estimated_fps) {
  117. // micro changes
  118. if (fps == (_estimated_fps - 1)) {
  119. _hits_one_below_estimated++;
  120. if ((_hits_one_below_estimated > _hits_at_estimated) && (_hits_one_below_estimated > SIGNIFICANCE_DOWN)) {
  121. _estimated_fps--;
  122. made_new_estimate();
  123. }
  124. return;
  125. } else {
  126. _hits_below_estimated++;
  127. // don't allow large lowering if we are established at a refresh rate, as it will probably be dropped frames
  128. bool established = _estimate_complete && (_hits_at_estimated > 10);
  129. // macro changes
  130. // note there is a large barrier to macro lowering. That is because it is more likely to be dropped frames
  131. // than mis-estimation of the refresh rate.
  132. if (!established) {
  133. if (((_hits_below_estimated / 8) > _hits_at_estimated) && (_hits_below_estimated > SIGNIFICANCE_DOWN)) {
  134. // decrease the estimate
  135. _estimated_fps--;
  136. made_new_estimate();
  137. }
  138. }
  139. return;
  140. }
  141. }
  142. // Changes increasing the estimate.
  143. // micro changes
  144. if (fps == (_estimated_fps + 1)) {
  145. _hits_one_above_estimated++;
  146. if ((_hits_one_above_estimated > _hits_at_estimated) && (_hits_one_above_estimated > SIGNIFICANCE_UP)) {
  147. _estimated_fps++;
  148. made_new_estimate();
  149. }
  150. return;
  151. } else {
  152. _hits_above_estimated++;
  153. // macro changes
  154. if ((_hits_above_estimated > _hits_at_estimated) && (_hits_above_estimated > SIGNIFICANCE_UP)) {
  155. // increase the estimate
  156. int change = fps - _estimated_fps;
  157. change /= 2;
  158. change = MAX(1, change);
  159. _estimated_fps += change;
  160. made_new_estimate();
  161. }
  162. return;
  163. }
  164. }
  165. bool MainTimerSync::DeltaSmoother::fps_allows_smoothing(int64_t p_delta) {
  166. _measurement_time += p_delta;
  167. _measurement_frame_count++;
  168. if (_measurement_frame_count == _measurement_end_frame) {
  169. // only switch on or off if the estimate is complete
  170. if (_estimate_complete) {
  171. int64_t time_passed = _measurement_time - _measurement_start_time;
  172. // average delta
  173. time_passed /= MEASURE_FPS_OVER_NUM_FRAMES;
  174. // estimate fps
  175. if (time_passed) {
  176. double fps = 1000000.0 / time_passed;
  177. double ratio = fps / (double)_estimated_fps;
  178. //print_line("ratio : " + String(Variant(ratio)));
  179. if ((ratio > 0.95) && (ratio < 1.05)) {
  180. _measurement_allows_smoothing = true;
  181. } else {
  182. _measurement_allows_smoothing = false;
  183. }
  184. }
  185. } // estimate complete
  186. // new start time for next iteration
  187. _measurement_start_time = _measurement_time;
  188. _measurement_end_frame += MEASURE_FPS_OVER_NUM_FRAMES;
  189. }
  190. return _measurement_allows_smoothing;
  191. }
  192. int64_t MainTimerSync::DeltaSmoother::smooth_delta(int64_t p_delta) {
  193. // Conditions to disable smoothing.
  194. // Note that vsync is a request, it cannot be relied on, the OS may override this.
  195. // If the OS turns vsync on without vsync in the app, smoothing will not be enabled.
  196. // If the OS turns vsync off with sync enabled in the app, the smoothing must detect this
  197. // via the error metric and switch off.
  198. if (!OS::get_singleton()->is_delta_smoothing_enabled() || !OS::get_singleton()->is_vsync_enabled() || Engine::get_singleton()->is_editor_hint()) {
  199. return p_delta;
  200. }
  201. // Very important, ignore long deltas and pass them back unmodified.
  202. // This is to deal with resuming after suspend for long periods.
  203. if (p_delta > 1000000) {
  204. return p_delta;
  205. }
  206. // keep a running guesstimate of the FPS, and turn off smoothing if
  207. // conditions not close to the estimated FPS
  208. if (!fps_allows_smoothing(p_delta)) {
  209. return p_delta;
  210. }
  211. // we can't cope with negative deltas .. OS bug on some hardware
  212. // and also very small deltas caused by vsync being off.
  213. // This could possibly be part of a hiccup, this value isn't fixed in stone...
  214. if (p_delta < 1000) {
  215. return p_delta;
  216. }
  217. // note still some vsync off will still get through to this point...
  218. // and we need to cope with it by not converging the estimator / and / or not smoothing
  219. update_refresh_rate_estimator(p_delta);
  220. // no smoothing until we know what the refresh rate is
  221. if (!_estimate_complete) {
  222. return p_delta;
  223. }
  224. // accumulate the time we have available to use
  225. _leftover_time += p_delta;
  226. // how many vsyncs units can we fit?
  227. int64_t units = _leftover_time / _vsync_delta;
  228. // a delta must include minimum 1 vsync
  229. // (if it is less than that, it is either random error or we are no longer running at the vsync rate,
  230. // in which case we should switch off delta smoothing, or re-estimate the refresh rate)
  231. units = MAX(units, 1);
  232. _leftover_time -= units * _vsync_delta;
  233. // print_line("units " + itos(units) + ", leftover " + itos(_leftover_time/1000) + " ms");
  234. return units * _vsync_delta;
  235. }
  236. /////////////////////////////////////
  237. // returns the fraction of p_frame_slice required for the timer to overshoot
  238. // before advance_core considers changing the physics_steps return from
  239. // the typical values as defined by typical_physics_steps
  240. float MainTimerSync::get_physics_jitter_fix() {
  241. return Engine::get_singleton()->get_physics_jitter_fix();
  242. }
  243. // gets our best bet for the average number of physics steps per render frame
  244. // return value: number of frames back this data is consistent
  245. int MainTimerSync::get_average_physics_steps(float &p_min, float &p_max) {
  246. p_min = typical_physics_steps[0];
  247. p_max = p_min + 1;
  248. for (int i = 1; i < CONTROL_STEPS; ++i) {
  249. const float typical_lower = typical_physics_steps[i];
  250. const float current_min = typical_lower / (i + 1);
  251. if (current_min > p_max) {
  252. return i; // bail out if further restrictions would void the interval
  253. } else if (current_min > p_min) {
  254. p_min = current_min;
  255. }
  256. const float current_max = (typical_lower + 1) / (i + 1);
  257. if (current_max < p_min) {
  258. return i;
  259. } else if (current_max < p_max) {
  260. p_max = current_max;
  261. }
  262. }
  263. return CONTROL_STEPS;
  264. }
  265. // advance physics clock by p_idle_step, return appropriate number of steps to simulate
  266. MainFrameTime MainTimerSync::advance_core(float p_frame_slice, int p_iterations_per_second, float p_idle_step) {
  267. MainFrameTime ret;
  268. ret.idle_step = p_idle_step;
  269. // simple determination of number of physics iteration
  270. time_accum += ret.idle_step;
  271. ret.physics_steps = floor(time_accum * p_iterations_per_second);
  272. int min_typical_steps = typical_physics_steps[0];
  273. int max_typical_steps = min_typical_steps + 1;
  274. // given the past recorded steps and typical steps to match, calculate bounds for this
  275. // step to be typical
  276. bool update_typical = false;
  277. for (int i = 0; i < CONTROL_STEPS - 1; ++i) {
  278. int steps_left_to_match_typical = typical_physics_steps[i + 1] - accumulated_physics_steps[i];
  279. if (steps_left_to_match_typical > max_typical_steps ||
  280. steps_left_to_match_typical + 1 < min_typical_steps) {
  281. update_typical = true;
  282. break;
  283. }
  284. if (steps_left_to_match_typical > min_typical_steps) {
  285. min_typical_steps = steps_left_to_match_typical;
  286. }
  287. if (steps_left_to_match_typical + 1 < max_typical_steps) {
  288. max_typical_steps = steps_left_to_match_typical + 1;
  289. }
  290. }
  291. #ifdef DEBUG_ENABLED
  292. if (max_typical_steps < 0) {
  293. WARN_PRINT_ONCE("`max_typical_steps` is negative. This could hint at an engine bug or system timer misconfiguration.");
  294. }
  295. #endif
  296. // try to keep it consistent with previous iterations
  297. if (ret.physics_steps < min_typical_steps) {
  298. const int max_possible_steps = floor((time_accum)*p_iterations_per_second + get_physics_jitter_fix());
  299. if (max_possible_steps < min_typical_steps) {
  300. ret.physics_steps = max_possible_steps;
  301. update_typical = true;
  302. } else {
  303. ret.physics_steps = min_typical_steps;
  304. }
  305. } else if (ret.physics_steps > max_typical_steps) {
  306. const int min_possible_steps = floor((time_accum)*p_iterations_per_second - get_physics_jitter_fix());
  307. if (min_possible_steps > max_typical_steps) {
  308. ret.physics_steps = min_possible_steps;
  309. update_typical = true;
  310. } else {
  311. ret.physics_steps = max_typical_steps;
  312. }
  313. }
  314. if (ret.physics_steps < 0) {
  315. ret.physics_steps = 0;
  316. }
  317. time_accum -= ret.physics_steps * p_frame_slice;
  318. // keep track of accumulated step counts
  319. for (int i = CONTROL_STEPS - 2; i >= 0; --i) {
  320. accumulated_physics_steps[i + 1] = accumulated_physics_steps[i] + ret.physics_steps;
  321. }
  322. accumulated_physics_steps[0] = ret.physics_steps;
  323. if (update_typical) {
  324. for (int i = CONTROL_STEPS - 1; i >= 0; --i) {
  325. if (typical_physics_steps[i] > accumulated_physics_steps[i]) {
  326. typical_physics_steps[i] = accumulated_physics_steps[i];
  327. } else if (typical_physics_steps[i] < accumulated_physics_steps[i] - 1) {
  328. typical_physics_steps[i] = accumulated_physics_steps[i] - 1;
  329. }
  330. }
  331. }
  332. return ret;
  333. }
  334. // calls advance_core, keeps track of deficit it adds to animaption_step, make sure the deficit sum stays close to zero
  335. MainFrameTime MainTimerSync::advance_checked(float p_frame_slice, int p_iterations_per_second, float p_idle_step) {
  336. if (fixed_fps != -1) {
  337. p_idle_step = 1.0 / fixed_fps;
  338. }
  339. float min_output_step = p_idle_step / 8;
  340. min_output_step = MAX(min_output_step, 1E-6);
  341. // compensate for last deficit
  342. p_idle_step += time_deficit;
  343. MainFrameTime ret = advance_core(p_frame_slice, p_iterations_per_second, p_idle_step);
  344. // we will do some clamping on ret.idle_step and need to sync those changes to time_accum,
  345. // that's easiest if we just remember their fixed difference now
  346. const double idle_minus_accum = ret.idle_step - time_accum;
  347. // first, least important clamping: keep ret.idle_step consistent with typical_physics_steps.
  348. // this smoothes out the idle steps and culls small but quick variations.
  349. {
  350. float min_average_physics_steps, max_average_physics_steps;
  351. int consistent_steps = get_average_physics_steps(min_average_physics_steps, max_average_physics_steps);
  352. if (consistent_steps > 3) {
  353. ret.clamp_idle(min_average_physics_steps * p_frame_slice, max_average_physics_steps * p_frame_slice);
  354. }
  355. }
  356. // second clamping: keep abs(time_deficit) < jitter_fix * frame_slise
  357. float max_clock_deviation = get_physics_jitter_fix() * p_frame_slice;
  358. ret.clamp_idle(p_idle_step - max_clock_deviation, p_idle_step + max_clock_deviation);
  359. // last clamping: make sure time_accum is between 0 and p_frame_slice for consistency between physics and idle
  360. ret.clamp_idle(idle_minus_accum, idle_minus_accum + p_frame_slice);
  361. // all the operations above may have turned ret.idle_step negative or zero, keep a minimal value
  362. if (ret.idle_step < min_output_step) {
  363. ret.idle_step = min_output_step;
  364. }
  365. // restore time_accum
  366. time_accum = ret.idle_step - idle_minus_accum;
  367. // forcing ret.idle_step to be positive may trigger a violation of the
  368. // promise that time_accum is between 0 and p_frame_slice
  369. #ifdef DEBUG_ENABLED
  370. if (time_accum < -1E-7) {
  371. WARN_PRINT_ONCE("Intermediate value of `time_accum` is negative. This could hint at an engine bug or system timer misconfiguration.");
  372. }
  373. #endif
  374. if (time_accum > p_frame_slice) {
  375. const int extra_physics_steps = floor(time_accum * p_iterations_per_second);
  376. time_accum -= extra_physics_steps * p_frame_slice;
  377. ret.physics_steps += extra_physics_steps;
  378. }
  379. #ifdef DEBUG_ENABLED
  380. if (time_accum < -1E-7) {
  381. WARN_PRINT_ONCE("Final value of `time_accum` is negative. It should always be between 0 and `p_physics_step`. This hints at an engine bug.");
  382. }
  383. if (time_accum > p_frame_slice + 1E-7) {
  384. WARN_PRINT_ONCE("Final value of `time_accum` is larger than `p_frame_slice`. It should always be between 0 and `p_frame_slice`. This hints at an engine bug.");
  385. }
  386. #endif
  387. // track deficit
  388. time_deficit = p_idle_step - ret.idle_step;
  389. // p_frame_slice is 1.0 / iterations_per_sec
  390. // i.e. the time in seconds taken by a physics tick
  391. ret.interpolation_fraction = time_accum / p_frame_slice;
  392. return ret;
  393. }
  394. // determine wall clock step since last iteration
  395. float MainTimerSync::get_cpu_idle_step() {
  396. uint64_t cpu_ticks_elapsed = current_cpu_ticks_usec - last_cpu_ticks_usec;
  397. last_cpu_ticks_usec = current_cpu_ticks_usec;
  398. cpu_ticks_elapsed = _delta_smoother.smooth_delta(cpu_ticks_elapsed);
  399. return cpu_ticks_elapsed / 1000000.0;
  400. }
  401. MainTimerSync::MainTimerSync() :
  402. last_cpu_ticks_usec(0),
  403. current_cpu_ticks_usec(0),
  404. time_accum(0),
  405. time_deficit(0),
  406. fixed_fps(0) {
  407. for (int i = CONTROL_STEPS - 1; i >= 0; --i) {
  408. typical_physics_steps[i] = i;
  409. accumulated_physics_steps[i] = i;
  410. }
  411. }
  412. // start the clock
  413. void MainTimerSync::init(uint64_t p_cpu_ticks_usec) {
  414. current_cpu_ticks_usec = last_cpu_ticks_usec = p_cpu_ticks_usec;
  415. }
  416. // set measured wall clock time
  417. void MainTimerSync::set_cpu_ticks_usec(uint64_t p_cpu_ticks_usec) {
  418. current_cpu_ticks_usec = p_cpu_ticks_usec;
  419. }
  420. void MainTimerSync::set_fixed_fps(int p_fixed_fps) {
  421. fixed_fps = p_fixed_fps;
  422. }
  423. // advance one frame, return timesteps to take
  424. MainFrameTime MainTimerSync::advance(float p_frame_slice, int p_iterations_per_second) {
  425. float cpu_idle_step = get_cpu_idle_step();
  426. return advance_checked(p_frame_slice, p_iterations_per_second, cpu_idle_step);
  427. }