main_timer_sync.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. /**************************************************************************/
  2. /* main_timer_sync.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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/os/os.h"
  32. #include "servers/display_server.h"
  33. void MainFrameTime::clamp_process_step(double min_process_step, double max_process_step) {
  34. if (process_step < min_process_step) {
  35. process_step = min_process_step;
  36. } else if (process_step > max_process_step) {
  37. process_step = max_process_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. // Also only try smoothing if vsync is enabled (classical vsync, not new types) ..
  199. // This condition is currently checked before calling smooth_delta().
  200. if (!OS::get_singleton()->is_delta_smoothing_enabled() || Engine::get_singleton()->is_editor_hint()) {
  201. return p_delta;
  202. }
  203. // only attempt smoothing if vsync is selected
  204. DisplayServer::VSyncMode vsync_mode = DisplayServer::get_singleton()->window_get_vsync_mode(DisplayServer::MAIN_WINDOW_ID);
  205. if (vsync_mode != DisplayServer::VSYNC_ENABLED) {
  206. return p_delta;
  207. }
  208. // Very important, ignore long deltas and pass them back unmodified.
  209. // This is to deal with resuming after suspend for long periods.
  210. if (p_delta > 1000000) {
  211. return p_delta;
  212. }
  213. // keep a running guesstimate of the FPS, and turn off smoothing if
  214. // conditions not close to the estimated FPS
  215. if (!fps_allows_smoothing(p_delta)) {
  216. return p_delta;
  217. }
  218. // we can't cope with negative deltas .. OS bug on some hardware
  219. // and also very small deltas caused by vsync being off.
  220. // This could possibly be part of a hiccup, this value isn't fixed in stone...
  221. if (p_delta < 1000) {
  222. return p_delta;
  223. }
  224. // note still some vsync off will still get through to this point...
  225. // and we need to cope with it by not converging the estimator / and / or not smoothing
  226. update_refresh_rate_estimator(p_delta);
  227. // no smoothing until we know what the refresh rate is
  228. if (!_estimate_complete) {
  229. return p_delta;
  230. }
  231. // accumulate the time we have available to use
  232. _leftover_time += p_delta;
  233. // how many vsyncs units can we fit?
  234. int64_t units = _leftover_time / _vsync_delta;
  235. // a delta must include minimum 1 vsync
  236. // (if it is less than that, it is either random error or we are no longer running at the vsync rate,
  237. // in which case we should switch off delta smoothing, or re-estimate the refresh rate)
  238. units = MAX(units, 1);
  239. _leftover_time -= units * _vsync_delta;
  240. // print_line("units " + itos(units) + ", leftover " + itos(_leftover_time/1000) + " ms");
  241. return units * _vsync_delta;
  242. }
  243. /////////////////////////////////////
  244. // returns the fraction of p_physics_step required for the timer to overshoot
  245. // before advance_core considers changing the physics_steps return from
  246. // the typical values as defined by typical_physics_steps
  247. double MainTimerSync::get_physics_jitter_fix() {
  248. return Engine::get_singleton()->get_physics_jitter_fix();
  249. }
  250. // gets our best bet for the average number of physics steps per render frame
  251. // return value: number of frames back this data is consistent
  252. int MainTimerSync::get_average_physics_steps(double &p_min, double &p_max) {
  253. p_min = typical_physics_steps[0];
  254. p_max = p_min + 1;
  255. for (int i = 1; i < CONTROL_STEPS; ++i) {
  256. const double typical_lower = typical_physics_steps[i];
  257. const double current_min = typical_lower / (i + 1);
  258. if (current_min > p_max) {
  259. return i; // bail out if further restrictions would void the interval
  260. } else if (current_min > p_min) {
  261. p_min = current_min;
  262. }
  263. const double current_max = (typical_lower + 1) / (i + 1);
  264. if (current_max < p_min) {
  265. return i;
  266. } else if (current_max < p_max) {
  267. p_max = current_max;
  268. }
  269. }
  270. return CONTROL_STEPS;
  271. }
  272. // advance physics clock by p_process_step, return appropriate number of steps to simulate
  273. MainFrameTime MainTimerSync::advance_core(double p_physics_step, int p_physics_ticks_per_second, double p_process_step) {
  274. MainFrameTime ret;
  275. ret.process_step = p_process_step;
  276. // simple determination of number of physics iteration
  277. time_accum += ret.process_step;
  278. ret.physics_steps = floor(time_accum * p_physics_ticks_per_second);
  279. int min_typical_steps = typical_physics_steps[0];
  280. int max_typical_steps = min_typical_steps + 1;
  281. // given the past recorded steps and typical steps to match, calculate bounds for this
  282. // step to be typical
  283. bool update_typical = false;
  284. for (int i = 0; i < CONTROL_STEPS - 1; ++i) {
  285. int steps_left_to_match_typical = typical_physics_steps[i + 1] - accumulated_physics_steps[i];
  286. if (steps_left_to_match_typical > max_typical_steps ||
  287. steps_left_to_match_typical + 1 < min_typical_steps) {
  288. update_typical = true;
  289. break;
  290. }
  291. if (steps_left_to_match_typical > min_typical_steps) {
  292. min_typical_steps = steps_left_to_match_typical;
  293. }
  294. if (steps_left_to_match_typical + 1 < max_typical_steps) {
  295. max_typical_steps = steps_left_to_match_typical + 1;
  296. }
  297. }
  298. #ifdef DEBUG_ENABLED
  299. if (max_typical_steps < 0) {
  300. WARN_PRINT_ONCE("`max_typical_steps` is negative. This could hint at an engine bug or system timer misconfiguration.");
  301. }
  302. #endif
  303. // try to keep it consistent with previous iterations
  304. if (ret.physics_steps < min_typical_steps) {
  305. const int max_possible_steps = floor((time_accum)*p_physics_ticks_per_second + get_physics_jitter_fix());
  306. if (max_possible_steps < min_typical_steps) {
  307. ret.physics_steps = max_possible_steps;
  308. update_typical = true;
  309. } else {
  310. ret.physics_steps = min_typical_steps;
  311. }
  312. } else if (ret.physics_steps > max_typical_steps) {
  313. const int min_possible_steps = floor((time_accum)*p_physics_ticks_per_second - get_physics_jitter_fix());
  314. if (min_possible_steps > max_typical_steps) {
  315. ret.physics_steps = min_possible_steps;
  316. update_typical = true;
  317. } else {
  318. ret.physics_steps = max_typical_steps;
  319. }
  320. }
  321. if (ret.physics_steps < 0) {
  322. ret.physics_steps = 0;
  323. }
  324. time_accum -= ret.physics_steps * p_physics_step;
  325. // keep track of accumulated step counts
  326. for (int i = CONTROL_STEPS - 2; i >= 0; --i) {
  327. accumulated_physics_steps[i + 1] = accumulated_physics_steps[i] + ret.physics_steps;
  328. }
  329. accumulated_physics_steps[0] = ret.physics_steps;
  330. if (update_typical) {
  331. for (int i = CONTROL_STEPS - 1; i >= 0; --i) {
  332. if (typical_physics_steps[i] > accumulated_physics_steps[i]) {
  333. typical_physics_steps[i] = accumulated_physics_steps[i];
  334. } else if (typical_physics_steps[i] < accumulated_physics_steps[i] - 1) {
  335. typical_physics_steps[i] = accumulated_physics_steps[i] - 1;
  336. }
  337. }
  338. }
  339. return ret;
  340. }
  341. // calls advance_core, keeps track of deficit it adds to animaption_step, make sure the deficit sum stays close to zero
  342. MainFrameTime MainTimerSync::advance_checked(double p_physics_step, int p_physics_ticks_per_second, double p_process_step) {
  343. if (fixed_fps != -1) {
  344. p_process_step = 1.0 / fixed_fps;
  345. }
  346. float min_output_step = p_process_step / 8;
  347. min_output_step = MAX(min_output_step, 1E-6);
  348. // compensate for last deficit
  349. p_process_step += time_deficit;
  350. MainFrameTime ret = advance_core(p_physics_step, p_physics_ticks_per_second, p_process_step);
  351. // we will do some clamping on ret.process_step and need to sync those changes to time_accum,
  352. // that's easiest if we just remember their fixed difference now
  353. const double process_minus_accum = ret.process_step - time_accum;
  354. // first, least important clamping: keep ret.process_step consistent with typical_physics_steps.
  355. // this smoothes out the process steps and culls small but quick variations.
  356. {
  357. double min_average_physics_steps, max_average_physics_steps;
  358. int consistent_steps = get_average_physics_steps(min_average_physics_steps, max_average_physics_steps);
  359. if (consistent_steps > 3) {
  360. ret.clamp_process_step(min_average_physics_steps * p_physics_step, max_average_physics_steps * p_physics_step);
  361. }
  362. }
  363. // second clamping: keep abs(time_deficit) < jitter_fix * frame_slise
  364. double max_clock_deviation = get_physics_jitter_fix() * p_physics_step;
  365. ret.clamp_process_step(p_process_step - max_clock_deviation, p_process_step + max_clock_deviation);
  366. // last clamping: make sure time_accum is between 0 and p_physics_step for consistency between physics and process
  367. ret.clamp_process_step(process_minus_accum, process_minus_accum + p_physics_step);
  368. // all the operations above may have turned ret.p_process_step negative or zero, keep a minimal value
  369. if (ret.process_step < min_output_step) {
  370. ret.process_step = min_output_step;
  371. }
  372. // restore time_accum
  373. time_accum = ret.process_step - process_minus_accum;
  374. // forcing ret.process_step to be positive may trigger a violation of the
  375. // promise that time_accum is between 0 and p_physics_step
  376. #ifdef DEBUG_ENABLED
  377. if (time_accum < -1E-7) {
  378. WARN_PRINT_ONCE("Intermediate value of `time_accum` is negative. This could hint at an engine bug or system timer misconfiguration.");
  379. }
  380. #endif
  381. if (time_accum > p_physics_step) {
  382. const int extra_physics_steps = floor(time_accum * p_physics_ticks_per_second);
  383. time_accum -= extra_physics_steps * p_physics_step;
  384. ret.physics_steps += extra_physics_steps;
  385. }
  386. #ifdef DEBUG_ENABLED
  387. if (time_accum < -1E-7) {
  388. 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.");
  389. }
  390. if (time_accum > p_physics_step + 1E-7) {
  391. WARN_PRINT_ONCE("Final value of `time_accum` is larger than `p_physics_step`. It should always be between 0 and `p_physics_step`. This hints at an engine bug.");
  392. }
  393. #endif
  394. // track deficit
  395. time_deficit = p_process_step - ret.process_step;
  396. // p_physics_step is 1.0 / iterations_per_sec
  397. // i.e. the time in seconds taken by a physics tick
  398. ret.interpolation_fraction = time_accum / p_physics_step;
  399. return ret;
  400. }
  401. // determine wall clock step since last iteration
  402. double MainTimerSync::get_cpu_process_step() {
  403. uint64_t cpu_ticks_elapsed = current_cpu_ticks_usec - last_cpu_ticks_usec;
  404. last_cpu_ticks_usec = current_cpu_ticks_usec;
  405. cpu_ticks_elapsed = _delta_smoother.smooth_delta(cpu_ticks_elapsed);
  406. return cpu_ticks_elapsed / 1000000.0;
  407. }
  408. MainTimerSync::MainTimerSync() {
  409. for (int i = CONTROL_STEPS - 1; i >= 0; --i) {
  410. typical_physics_steps[i] = i;
  411. accumulated_physics_steps[i] = i;
  412. }
  413. }
  414. // start the clock
  415. void MainTimerSync::init(uint64_t p_cpu_ticks_usec) {
  416. current_cpu_ticks_usec = last_cpu_ticks_usec = p_cpu_ticks_usec;
  417. }
  418. // set measured wall clock time
  419. void MainTimerSync::set_cpu_ticks_usec(uint64_t p_cpu_ticks_usec) {
  420. current_cpu_ticks_usec = p_cpu_ticks_usec;
  421. }
  422. void MainTimerSync::set_fixed_fps(int p_fixed_fps) {
  423. fixed_fps = p_fixed_fps;
  424. }
  425. // advance one physics frame, return timesteps to take
  426. MainFrameTime MainTimerSync::advance(double p_physics_step, int p_physics_ticks_per_second) {
  427. double cpu_process_step = get_cpu_process_step();
  428. return advance_checked(p_physics_step, p_physics_ticks_per_second, cpu_process_step);
  429. }