💿🐜 Antkeeper source code https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.2 KiB

  1. /*
  2. * Copyright (C) 2020 Christopher J. Howard
  3. *
  4. * This file is part of Antkeeper source code.
  5. *
  6. * Antkeeper source code is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Antkeeper source code is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with Antkeeper source code. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include "frame-scheduler.hpp"
  20. #include <algorithm>
  21. frame_scheduler::frame_scheduler():
  22. update_callback(nullptr),
  23. render_callback(nullptr),
  24. update_rate(60.0),
  25. update_timestep(1.0 / update_rate),
  26. max_frame_duration(update_timestep)
  27. {
  28. reset();
  29. }
  30. void frame_scheduler::set_update_callback(std::function<void(double, double)> callback)
  31. {
  32. update_callback = callback;
  33. }
  34. void frame_scheduler::set_render_callback(std::function<void(double)> callback)
  35. {
  36. render_callback = callback;
  37. }
  38. void frame_scheduler::set_update_rate(double frequency)
  39. {
  40. update_rate = frequency;
  41. update_timestep = 1.0 / frequency;
  42. }
  43. void frame_scheduler::set_max_frame_duration(double duration)
  44. {
  45. max_frame_duration = duration;
  46. }
  47. double frame_scheduler::get_frame_duration() const
  48. {
  49. return frame_duration;
  50. }
  51. void frame_scheduler::reset()
  52. {
  53. elapsed_time = 0.0;
  54. accumulator = 0.0;
  55. frame_start = std::chrono::high_resolution_clock::now();
  56. frame_end = frame_start;
  57. frame_duration = 0.0;
  58. }
  59. void frame_scheduler::tick()
  60. {
  61. accumulator += std::min<double>(max_frame_duration, frame_duration);
  62. while (accumulator >= update_timestep)
  63. {
  64. update_callback(elapsed_time, update_timestep);
  65. elapsed_time += update_timestep;
  66. accumulator -= update_timestep;
  67. }
  68. render_callback(accumulator * update_rate);
  69. frame_end = std::chrono::high_resolution_clock::now();
  70. frame_duration = static_cast<double>(std::chrono::duration_cast<std::chrono::microseconds>(frame_end - frame_start).count()) / 1000000.0;
  71. frame_start = frame_end;
  72. }