main_timer_sync.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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. // Turn off jitter fix when using fixed timestep interpolation.
  249. // Note this shouldn't be on UNTIL 3d interpolation is implemented,
  250. // otherwise we will get people making 3d games with the physics_interpolation
  251. // set to on getting jitter fix disabled unexpectedly.
  252. #if 0
  253. if (Engine::get_singleton()->is_physics_interpolation_enabled()) {
  254. // Would be better to write a simple bypass for jitter fix but this will do to get started.
  255. return 0.0;
  256. }
  257. #endif
  258. return Engine::get_singleton()->get_physics_jitter_fix();
  259. }
  260. // gets our best bet for the average number of physics steps per render frame
  261. // return value: number of frames back this data is consistent
  262. int MainTimerSync::get_average_physics_steps(double &p_min, double &p_max) {
  263. p_min = typical_physics_steps[0];
  264. p_max = p_min + 1;
  265. for (int i = 1; i < CONTROL_STEPS; ++i) {
  266. const double typical_lower = typical_physics_steps[i];
  267. const double current_min = typical_lower / (i + 1);
  268. if (current_min > p_max) {
  269. return i; // bail out if further restrictions would void the interval
  270. } else if (current_min > p_min) {
  271. p_min = current_min;
  272. }
  273. const double current_max = (typical_lower + 1) / (i + 1);
  274. if (current_max < p_min) {
  275. return i;
  276. } else if (current_max < p_max) {
  277. p_max = current_max;
  278. }
  279. }
  280. return CONTROL_STEPS;
  281. }
  282. // advance physics clock by p_process_step, return appropriate number of steps to simulate
  283. MainFrameTime MainTimerSync::advance_core(double p_physics_step, int p_physics_ticks_per_second, double p_process_step) {
  284. MainFrameTime ret;
  285. ret.process_step = p_process_step;
  286. // simple determination of number of physics iteration
  287. time_accum += ret.process_step;
  288. ret.physics_steps = floor(time_accum * p_physics_ticks_per_second);
  289. int min_typical_steps = typical_physics_steps[0];
  290. int max_typical_steps = min_typical_steps + 1;
  291. // given the past recorded steps and typical steps to match, calculate bounds for this
  292. // step to be typical
  293. bool update_typical = false;
  294. for (int i = 0; i < CONTROL_STEPS - 1; ++i) {
  295. int steps_left_to_match_typical = typical_physics_steps[i + 1] - accumulated_physics_steps[i];
  296. if (steps_left_to_match_typical > max_typical_steps ||
  297. steps_left_to_match_typical + 1 < min_typical_steps) {
  298. update_typical = true;
  299. break;
  300. }
  301. if (steps_left_to_match_typical > min_typical_steps) {
  302. min_typical_steps = steps_left_to_match_typical;
  303. }
  304. if (steps_left_to_match_typical + 1 < max_typical_steps) {
  305. max_typical_steps = steps_left_to_match_typical + 1;
  306. }
  307. }
  308. #ifdef DEBUG_ENABLED
  309. if (max_typical_steps < 0) {
  310. WARN_PRINT_ONCE("`max_typical_steps` is negative. This could hint at an engine bug or system timer misconfiguration.");
  311. }
  312. #endif
  313. // try to keep it consistent with previous iterations
  314. if (ret.physics_steps < min_typical_steps) {
  315. const int max_possible_steps = floor((time_accum)*p_physics_ticks_per_second + get_physics_jitter_fix());
  316. if (max_possible_steps < min_typical_steps) {
  317. ret.physics_steps = max_possible_steps;
  318. update_typical = true;
  319. } else {
  320. ret.physics_steps = min_typical_steps;
  321. }
  322. } else if (ret.physics_steps > max_typical_steps) {
  323. const int min_possible_steps = floor((time_accum)*p_physics_ticks_per_second - get_physics_jitter_fix());
  324. if (min_possible_steps > max_typical_steps) {
  325. ret.physics_steps = min_possible_steps;
  326. update_typical = true;
  327. } else {
  328. ret.physics_steps = max_typical_steps;
  329. }
  330. }
  331. if (ret.physics_steps < 0) {
  332. ret.physics_steps = 0;
  333. }
  334. time_accum -= ret.physics_steps * p_physics_step;
  335. // keep track of accumulated step counts
  336. for (int i = CONTROL_STEPS - 2; i >= 0; --i) {
  337. accumulated_physics_steps[i + 1] = accumulated_physics_steps[i] + ret.physics_steps;
  338. }
  339. accumulated_physics_steps[0] = ret.physics_steps;
  340. if (update_typical) {
  341. for (int i = CONTROL_STEPS - 1; i >= 0; --i) {
  342. if (typical_physics_steps[i] > accumulated_physics_steps[i]) {
  343. typical_physics_steps[i] = accumulated_physics_steps[i];
  344. } else if (typical_physics_steps[i] < accumulated_physics_steps[i] - 1) {
  345. typical_physics_steps[i] = accumulated_physics_steps[i] - 1;
  346. }
  347. }
  348. }
  349. return ret;
  350. }
  351. // calls advance_core, keeps track of deficit it adds to animaption_step, make sure the deficit sum stays close to zero
  352. MainFrameTime MainTimerSync::advance_checked(double p_physics_step, int p_physics_ticks_per_second, double p_process_step) {
  353. if (fixed_fps != -1) {
  354. p_process_step = 1.0 / fixed_fps;
  355. }
  356. float min_output_step = p_process_step / 8;
  357. min_output_step = MAX(min_output_step, 1E-6);
  358. // compensate for last deficit
  359. p_process_step += time_deficit;
  360. MainFrameTime ret = advance_core(p_physics_step, p_physics_ticks_per_second, p_process_step);
  361. // we will do some clamping on ret.process_step and need to sync those changes to time_accum,
  362. // that's easiest if we just remember their fixed difference now
  363. const double process_minus_accum = ret.process_step - time_accum;
  364. // first, least important clamping: keep ret.process_step consistent with typical_physics_steps.
  365. // this smoothes out the process steps and culls small but quick variations.
  366. {
  367. double min_average_physics_steps, max_average_physics_steps;
  368. int consistent_steps = get_average_physics_steps(min_average_physics_steps, max_average_physics_steps);
  369. if (consistent_steps > 3) {
  370. ret.clamp_process_step(min_average_physics_steps * p_physics_step, max_average_physics_steps * p_physics_step);
  371. }
  372. }
  373. // second clamping: keep abs(time_deficit) < jitter_fix * frame_slise
  374. double max_clock_deviation = get_physics_jitter_fix() * p_physics_step;
  375. ret.clamp_process_step(p_process_step - max_clock_deviation, p_process_step + max_clock_deviation);
  376. // last clamping: make sure time_accum is between 0 and p_physics_step for consistency between physics and process
  377. ret.clamp_process_step(process_minus_accum, process_minus_accum + p_physics_step);
  378. // all the operations above may have turned ret.p_process_step negative or zero, keep a minimal value
  379. if (ret.process_step < min_output_step) {
  380. ret.process_step = min_output_step;
  381. }
  382. // restore time_accum
  383. time_accum = ret.process_step - process_minus_accum;
  384. // forcing ret.process_step to be positive may trigger a violation of the
  385. // promise that time_accum is between 0 and p_physics_step
  386. #ifdef DEBUG_ENABLED
  387. if (time_accum < -1E-7) {
  388. WARN_PRINT_ONCE("Intermediate value of `time_accum` is negative. This could hint at an engine bug or system timer misconfiguration.");
  389. }
  390. #endif
  391. if (time_accum > p_physics_step) {
  392. const int extra_physics_steps = floor(time_accum * p_physics_ticks_per_second);
  393. time_accum -= extra_physics_steps * p_physics_step;
  394. ret.physics_steps += extra_physics_steps;
  395. }
  396. #ifdef DEBUG_ENABLED
  397. if (time_accum < -1E-7) {
  398. 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.");
  399. }
  400. if (time_accum > p_physics_step + 1E-7) {
  401. 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.");
  402. }
  403. #endif
  404. // track deficit
  405. time_deficit = p_process_step - ret.process_step;
  406. // p_physics_step is 1.0 / iterations_per_sec
  407. // i.e. the time in seconds taken by a physics tick
  408. ret.interpolation_fraction = time_accum / p_physics_step;
  409. return ret;
  410. }
  411. // determine wall clock step since last iteration
  412. double MainTimerSync::get_cpu_process_step() {
  413. uint64_t cpu_ticks_elapsed = current_cpu_ticks_usec - last_cpu_ticks_usec;
  414. last_cpu_ticks_usec = current_cpu_ticks_usec;
  415. cpu_ticks_elapsed = _delta_smoother.smooth_delta(cpu_ticks_elapsed);
  416. return cpu_ticks_elapsed / 1000000.0;
  417. }
  418. MainTimerSync::MainTimerSync() {
  419. for (int i = CONTROL_STEPS - 1; i >= 0; --i) {
  420. typical_physics_steps[i] = i;
  421. accumulated_physics_steps[i] = i;
  422. }
  423. }
  424. // start the clock
  425. void MainTimerSync::init(uint64_t p_cpu_ticks_usec) {
  426. current_cpu_ticks_usec = last_cpu_ticks_usec = p_cpu_ticks_usec;
  427. }
  428. // set measured wall clock time
  429. void MainTimerSync::set_cpu_ticks_usec(uint64_t p_cpu_ticks_usec) {
  430. current_cpu_ticks_usec = p_cpu_ticks_usec;
  431. }
  432. void MainTimerSync::set_fixed_fps(int p_fixed_fps) {
  433. fixed_fps = p_fixed_fps;
  434. }
  435. // advance one physics frame, return timesteps to take
  436. MainFrameTime MainTimerSync::advance(double p_physics_step, int p_physics_ticks_per_second) {
  437. double cpu_process_step = get_cpu_process_step();
  438. return advance_checked(p_physics_step, p_physics_ticks_per_second, cpu_process_step);
  439. }