Skip to content
0.2.0-dev Download ZIP
543 lines ·19.0 KB Raw
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
31#include "main_timer_sync.h"
32
33#include "core/os/os.h"
34#include "servers/display/display_server.h"
35
36// Uncomment this define to get more debugging logs for the delta smoothing.
37// #define GODOT_DEBUG_DELTA_SMOOTHER
38#ifdef GODOT_DEBUG_DELTA_SMOOTHER
39#include "core/string/print_string.h"
40#include "core/string/string.h"
41#endif
42
43void MainFrameTime::clamp_process_step(double min_process_step, double max_process_step) {
44 if (process_step < min_process_step) {
45 process_step = min_process_step;
46 } else if (process_step > max_process_step) {
47 process_step = max_process_step;
48 }
49}
50
51/////////////////////////////////
52
53void MainTimerSync::DeltaSmoother::made_new_estimate() {
54 _hits_above_estimated = 0;
55 _hits_at_estimated = 0;
56 _hits_below_estimated = 0;
57 _hits_one_above_estimated = 0;
58 _hits_one_below_estimated = 0;
59
60 _estimate_complete = false;
61
62#ifdef GODOT_DEBUG_DELTA_SMOOTHER
63 print_line("estimated fps " + itos(_estimated_fps));
64#endif
65}
66
67void MainTimerSync::DeltaSmoother::update_refresh_rate_estimator(int64_t p_delta) {
68 // the calling code should prevent 0 or negative values of delta
69 // (preventing divide by zero)
70
71 // note that if the estimate gets locked, and something external changes this
72 // (e.g. user changes to non-vsync in the OS), then the results may be less than ideal,
73 // but usually it will detect this via the FPS measurement and not attempt smoothing.
74 // This should be a rare occurrence anyway, and will be cured next time user restarts game.
75 if (_estimate_locked) {
76 return;
77 }
78
79 // First average the delta over NUM_READINGS
80 _estimator_total_delta += p_delta;
81 _estimator_delta_readings++;
82
83 const int NUM_READINGS = 60;
84
85 if (_estimator_delta_readings < NUM_READINGS) {
86 return;
87 }
88
89 // use average
90 p_delta = _estimator_total_delta / NUM_READINGS;
91
92 // reset the averager for next time
93 _estimator_delta_readings = 0;
94 _estimator_total_delta = 0;
95
96 ///////////////////////////////
97
98 int fps = Math::round(1000000.0 / p_delta);
99
100 // initial estimation, to speed up converging, special case we will estimate the refresh rate
101 // from the first average FPS reading
102 if (_estimated_fps == 0) {
103 // below 50 might be chugging loading stuff, or else
104 // dropping loads of frames, so the estimate will be inaccurate
105 if (fps >= 50) {
106 _estimated_fps = fps;
107#ifdef GODOT_DEBUG_DELTA_SMOOTHER
108 print_line("initial guess (average measured) refresh rate: " + itos(fps));
109#endif
110 } else {
111 // can't get started until above 50
112 return;
113 }
114 }
115
116 // we hit our exact estimated refresh rate.
117 // increase our confidence in the estimate.
118 if (fps == _estimated_fps) {
119 // note that each hit is an average of NUM_READINGS frames
120 _hits_at_estimated++;
121
122 if (_estimate_complete && _hits_at_estimated == 20) {
123 _estimate_locked = true;
124#ifdef GODOT_DEBUG_DELTA_SMOOTHER
125 print_line("estimate LOCKED at " + itos(_estimated_fps) + " fps");
126#endif
127 return;
128 }
129
130 // if we are getting pretty confident in this estimate, decide it is complete
131 // (it can still be increased later, and possibly lowered but only for a short time)
132 if ((!_estimate_complete) && (_hits_at_estimated > 2)) {
133 // when the estimate is complete we turn on smoothing
134 if (_estimated_fps) {
135 _estimate_complete = true;
136 _vsync_delta = 1000000 / _estimated_fps;
137
138#ifdef GODOT_DEBUG_DELTA_SMOOTHER
139 print_line("estimate complete. vsync_delta " + itos(_vsync_delta) + ", fps " + itos(_estimated_fps));
140#endif
141 }
142 }
143
144#ifdef GODOT_DEBUG_DELTA_SMOOTHER
145 if ((_hits_at_estimated % (400 / NUM_READINGS)) == 0) {
146 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) + " )";
147
148 print_line(sz);
149 }
150#endif
151
152 return;
153 }
154
155 const int SIGNIFICANCE_UP = 1;
156 const int SIGNIFICANCE_DOWN = 2;
157
158 // we are not usually interested in slowing the estimate
159 // but we may have overshot, so make it possible to reduce
160 if (fps < _estimated_fps) {
161 // micro changes
162 if (fps == (_estimated_fps - 1)) {
163 _hits_one_below_estimated++;
164
165 if ((_hits_one_below_estimated > _hits_at_estimated) && (_hits_one_below_estimated > SIGNIFICANCE_DOWN)) {
166 _estimated_fps--;
167 made_new_estimate();
168 }
169
170 return;
171 } else {
172 _hits_below_estimated++;
173
174 // don't allow large lowering if we are established at a refresh rate, as it will probably be dropped frames
175 bool established = _estimate_complete && (_hits_at_estimated > 10);
176
177 // macro changes
178 // note there is a large barrier to macro lowering. That is because it is more likely to be dropped frames
179 // than mis-estimation of the refresh rate.
180 if (!established) {
181 if (((_hits_below_estimated / 8) > _hits_at_estimated) && (_hits_below_estimated > SIGNIFICANCE_DOWN)) {
182 // decrease the estimate
183 _estimated_fps--;
184 made_new_estimate();
185 }
186 }
187
188 return;
189 }
190 }
191
192 // Changes increasing the estimate.
193 // micro changes
194 if (fps == (_estimated_fps + 1)) {
195 _hits_one_above_estimated++;
196
197 if ((_hits_one_above_estimated > _hits_at_estimated) && (_hits_one_above_estimated > SIGNIFICANCE_UP)) {
198 _estimated_fps++;
199 made_new_estimate();
200 }
201 return;
202 } else {
203 _hits_above_estimated++;
204
205 // macro changes
206 if ((_hits_above_estimated > _hits_at_estimated) && (_hits_above_estimated > SIGNIFICANCE_UP)) {
207 // increase the estimate
208 int change = fps - _estimated_fps;
209 change /= 2;
210 change = MAX(1, change);
211
212 _estimated_fps += change;
213 made_new_estimate();
214 }
215 return;
216 }
217}
218
219bool MainTimerSync::DeltaSmoother::fps_allows_smoothing(int64_t p_delta) {
220 _measurement_time += p_delta;
221 _measurement_frame_count++;
222
223 if (_measurement_frame_count == _measurement_end_frame) {
224 // only switch on or off if the estimate is complete
225 if (_estimate_complete) {
226 int64_t time_passed = _measurement_time - _measurement_start_time;
227
228 // average delta
229 time_passed /= MEASURE_FPS_OVER_NUM_FRAMES;
230
231 // estimate fps
232 if (time_passed) {
233 double fps = 1000000.0 / time_passed;
234 double ratio = fps / (double)_estimated_fps;
235
236 if ((ratio > 0.95) && (ratio < 1.05)) {
237 _measurement_allows_smoothing = true;
238 } else {
239 _measurement_allows_smoothing = false;
240 }
241 }
242 } // estimate complete
243
244 // new start time for next iteration
245 _measurement_start_time = _measurement_time;
246 _measurement_end_frame += MEASURE_FPS_OVER_NUM_FRAMES;
247 }
248
249 return _measurement_allows_smoothing;
250}
251
252int64_t MainTimerSync::DeltaSmoother::smooth_delta(int64_t p_delta) {
253 // Conditions to disable smoothing.
254 // Note that vsync is a request, it cannot be relied on, the OS may override this.
255 // If the OS turns vsync on without vsync in the app, smoothing will not be enabled.
256 // If the OS turns vsync off with sync enabled in the app, the smoothing must detect this
257 // via the error metric and switch off.
258 // Also only try smoothing if vsync is enabled (classical vsync, not new types) ..
259 // This condition is currently checked before calling smooth_delta().
260 if (!OS::get_singleton()->is_delta_smoothing_enabled() || Engine::get_singleton()->is_editor_hint()) {
261 return p_delta;
262 }
263
264 // only attempt smoothing if vsync is selected
265 DisplayServerEnums::VSyncMode vsync_mode = DisplayServer::get_singleton()->window_get_vsync_mode(DisplayServerEnums::MAIN_WINDOW_ID);
266 if (vsync_mode != DisplayServerEnums::VSYNC_ENABLED) {
267 return p_delta;
268 }
269
270 // Very important, ignore long deltas and pass them back unmodified.
271 // This is to deal with resuming after suspend for long periods.
272 if (p_delta > 1000000) {
273 return p_delta;
274 }
275
276 // keep a running guesstimate of the FPS, and turn off smoothing if
277 // conditions not close to the estimated FPS
278 if (!fps_allows_smoothing(p_delta)) {
279 return p_delta;
280 }
281
282 // we can't cope with negative deltas .. OS bug on some hardware
283 // and also very small deltas caused by vsync being off.
284 // This could possibly be part of a hiccup, this value isn't fixed in stone...
285 if (p_delta < 1000) {
286 return p_delta;
287 }
288
289 // note still some vsync off will still get through to this point...
290 // and we need to cope with it by not converging the estimator / and / or not smoothing
291 update_refresh_rate_estimator(p_delta);
292
293 // no smoothing until we know what the refresh rate is
294 if (!_estimate_complete) {
295 return p_delta;
296 }
297
298 // accumulate the time we have available to use
299 _leftover_time += p_delta;
300
301 // how many vsyncs units can we fit?
302 int64_t units = _leftover_time / _vsync_delta;
303
304 // a delta must include minimum 1 vsync
305 // (if it is less than that, it is either random error or we are no longer running at the vsync rate,
306 // in which case we should switch off delta smoothing, or re-estimate the refresh rate)
307 units = MAX(units, 1);
308
309 _leftover_time -= units * _vsync_delta;
310
311 return units * _vsync_delta;
312}
313
314/////////////////////////////////////
315
316// returns the fraction of p_physics_step required for the timer to overshoot
317// before advance_core considers changing the physics_steps return from
318// the typical values as defined by typical_physics_steps
319double MainTimerSync::get_physics_jitter_fix() {
320 return Engine::get_singleton()->get_physics_jitter_fix();
321}
322
323// gets our best bet for the average number of physics steps per render frame
324// return value: number of frames back this data is consistent
325int MainTimerSync::get_average_physics_steps(double &p_min, double &p_max) {
326 p_min = typical_physics_steps[0];
327 p_max = p_min + 1;
328
329 for (int i = 1; i < CONTROL_STEPS; ++i) {
330 const double typical_lower = typical_physics_steps[i];
331 const double current_min = typical_lower / (i + 1);
332 if (current_min > p_max) {
333 return i; // bail out if further restrictions would void the interval
334 } else if (current_min > p_min) {
335 p_min = current_min;
336 }
337 const double current_max = (typical_lower + 1) / (i + 1);
338 if (current_max < p_min) {
339 return i;
340 } else if (current_max < p_max) {
341 p_max = current_max;
342 }
343 }
344
345 return CONTROL_STEPS;
346}
347
348// advance physics clock by p_process_step, return appropriate number of steps to simulate
349MainFrameTime MainTimerSync::advance_core(double p_physics_step, int p_physics_ticks_per_second, double p_process_step) {
350 MainFrameTime ret;
351
352 ret.process_step = p_process_step;
353
354 // simple determination of number of physics iteration
355 time_accum += ret.process_step;
356 ret.physics_steps = std::floor(time_accum * p_physics_ticks_per_second);
357
358 int min_typical_steps = typical_physics_steps[0];
359 int max_typical_steps = min_typical_steps + 1;
360
361 // given the past recorded steps and typical steps to match, calculate bounds for this
362 // step to be typical
363 bool update_typical = false;
364
365 for (int i = 0; i < CONTROL_STEPS - 1; ++i) {
366 int steps_left_to_match_typical = typical_physics_steps[i + 1] - accumulated_physics_steps[i];
367 if (steps_left_to_match_typical > max_typical_steps ||
368 steps_left_to_match_typical + 1 < min_typical_steps) {
369 update_typical = true;
370 break;
371 }
372
373 if (steps_left_to_match_typical > min_typical_steps) {
374 min_typical_steps = steps_left_to_match_typical;
375 }
376 if (steps_left_to_match_typical + 1 < max_typical_steps) {
377 max_typical_steps = steps_left_to_match_typical + 1;
378 }
379 }
380
381#ifdef DEBUG_ENABLED
382 if (max_typical_steps < 0) {
383 WARN_PRINT_ONCE("`max_typical_steps` is negative. This could hint at an engine bug or system timer misconfiguration.");
384 }
385#endif
386
387 // try to keep it consistent with previous iterations
388 if (ret.physics_steps < min_typical_steps) {
389 const int max_possible_steps = std::floor((time_accum)*p_physics_ticks_per_second + get_physics_jitter_fix());
390 if (max_possible_steps < min_typical_steps) {
391 ret.physics_steps = max_possible_steps;
392 update_typical = true;
393 } else {
394 ret.physics_steps = min_typical_steps;
395 }
396 } else if (ret.physics_steps > max_typical_steps) {
397 const int min_possible_steps = std::floor((time_accum)*p_physics_ticks_per_second - get_physics_jitter_fix());
398 if (min_possible_steps > max_typical_steps) {
399 ret.physics_steps = min_possible_steps;
400 update_typical = true;
401 } else {
402 ret.physics_steps = max_typical_steps;
403 }
404 }
405
406 if (ret.physics_steps < 0) {
407 ret.physics_steps = 0;
408 }
409
410 time_accum -= ret.physics_steps * p_physics_step;
411
412 // keep track of accumulated step counts
413 for (int i = CONTROL_STEPS - 2; i >= 0; --i) {
414 accumulated_physics_steps[i + 1] = accumulated_physics_steps[i] + ret.physics_steps;
415 }
416 accumulated_physics_steps[0] = ret.physics_steps;
417
418 if (update_typical) {
419 for (int i = CONTROL_STEPS - 1; i >= 0; --i) {
420 if (typical_physics_steps[i] > accumulated_physics_steps[i]) {
421 typical_physics_steps[i] = accumulated_physics_steps[i];
422 } else if (typical_physics_steps[i] < accumulated_physics_steps[i] - 1) {
423 typical_physics_steps[i] = accumulated_physics_steps[i] - 1;
424 }
425 }
426 }
427
428 return ret;
429}
430
431// calls advance_core, keeps track of deficit it adds to animaption_step, make sure the deficit sum stays close to zero
432MainFrameTime MainTimerSync::advance_checked(double p_physics_step, int p_physics_ticks_per_second, double p_process_step) {
433 if (fixed_fps != -1) {
434 p_process_step = 1.0 / fixed_fps;
435 }
436
437 float min_output_step = p_process_step / 8;
438 min_output_step = MAX(min_output_step, 1E-6);
439
440 // compensate for last deficit
441 p_process_step += time_deficit;
442
443 MainFrameTime ret = advance_core(p_physics_step, p_physics_ticks_per_second, p_process_step);
444
445 // we will do some clamping on ret.process_step and need to sync those changes to time_accum,
446 // that's easiest if we just remember their fixed difference now
447 const double process_minus_accum = ret.process_step - time_accum;
448
449 // first, least important clamping: keep ret.process_step consistent with typical_physics_steps.
450 // this smoothes out the process steps and culls small but quick variations.
451 {
452 double min_average_physics_steps, max_average_physics_steps;
453 int consistent_steps = get_average_physics_steps(min_average_physics_steps, max_average_physics_steps);
454 if (consistent_steps > 3) {
455 ret.clamp_process_step(min_average_physics_steps * p_physics_step, max_average_physics_steps * p_physics_step);
456 }
457 }
458
459 // second clamping: keep abs(time_deficit) < jitter_fix * frame_slise
460 double max_clock_deviation = get_physics_jitter_fix() * p_physics_step;
461 ret.clamp_process_step(p_process_step - max_clock_deviation, p_process_step + max_clock_deviation);
462
463 // last clamping: make sure time_accum is between 0 and p_physics_step for consistency between physics and process
464 ret.clamp_process_step(process_minus_accum, process_minus_accum + p_physics_step);
465
466 // all the operations above may have turned ret.p_process_step negative or zero, keep a minimal value
467 if (ret.process_step < min_output_step) {
468 ret.process_step = min_output_step;
469 }
470
471 // restore time_accum
472 time_accum = ret.process_step - process_minus_accum;
473
474 // forcing ret.process_step to be positive may trigger a violation of the
475 // promise that time_accum is between 0 and p_physics_step
476#ifdef DEBUG_ENABLED
477 if (time_accum < -1E-7) {
478 WARN_PRINT_ONCE("Intermediate value of `time_accum` is negative. This could hint at an engine bug or system timer misconfiguration.");
479 }
480#endif
481
482 if (time_accum > p_physics_step) {
483 const int extra_physics_steps = std::floor(time_accum * p_physics_ticks_per_second);
484 time_accum -= extra_physics_steps * p_physics_step;
485 ret.physics_steps += extra_physics_steps;
486 }
487
488#ifdef DEBUG_ENABLED
489 if (time_accum < -1E-7) {
490 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.");
491 }
492 if (time_accum > p_physics_step + 1E-7) {
493 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.");
494 }
495#endif
496
497 // track deficit
498 time_deficit = p_process_step - ret.process_step;
499
500 // p_physics_step is 1.0 / iterations_per_sec
501 // i.e. the time in seconds taken by a physics tick
502 ret.interpolation_fraction = time_accum / p_physics_step;
503
504 return ret;
505}
506
507// determine wall clock step since last iteration
508double MainTimerSync::get_cpu_process_step() {
509 uint64_t cpu_ticks_elapsed = current_cpu_ticks_usec - last_cpu_ticks_usec;
510 last_cpu_ticks_usec = current_cpu_ticks_usec;
511
512 cpu_ticks_elapsed = _delta_smoother.smooth_delta(cpu_ticks_elapsed);
513
514 return cpu_ticks_elapsed / 1000000.0;
515}
516
517MainTimerSync::MainTimerSync() {
518 for (int i = CONTROL_STEPS - 1; i >= 0; --i) {
519 typical_physics_steps[i] = i;
520 accumulated_physics_steps[i] = i;
521 }
522}
523
524// start the clock
525void MainTimerSync::init(uint64_t p_cpu_ticks_usec) {
526 current_cpu_ticks_usec = last_cpu_ticks_usec = p_cpu_ticks_usec;
527}
528
529// set measured wall clock time
530void MainTimerSync::set_cpu_ticks_usec(uint64_t p_cpu_ticks_usec) {
531 current_cpu_ticks_usec = p_cpu_ticks_usec;
532}
533
534void MainTimerSync::set_fixed_fps(int p_fixed_fps) {
535 fixed_fps = p_fixed_fps;
536}
537
538// advance one physics frame, return timesteps to take
539MainFrameTime MainTimerSync::advance(double p_physics_step, int p_physics_ticks_per_second) {
540 double cpu_process_step = get_cpu_process_step();
541
542 return advance_checked(p_physics_step, p_physics_ticks_per_second, cpu_process_step);
543}