/// @file core/fixed_step.h /// @brief Runs the simulation in steps of one fixed length, whatever the frame /// rate is. /// /// A frame can take 4 ms or 40 ms. If the simulation advanced by the time of /// the frame, the same game would play out differently on a fast and on a slow /// machine, and replays and tests would not repeat. Instead every update of the /// simulation takes the same time step, and the loop runs as many of them per /// frame as the time that passed calls for: /// @code /// kumo::SystemClock clock; /// kumo::FrameTimer timer(clock); /// kumo::FixedStep step(kumo::step_from_hz(60), kumo::milliseconds(250)); /// for (;;) { /// const int updates = step.advance(timer.tick()); /// for (int i = 0; i < updates; ++i) update(step.step()); /// render(step.alpha()); /// } /// @endcode /// The simulation is then the same sequence of equal steps on every machine; /// only how they are grouped into frames differs. #pragma once #include "core/clock.h" #include "core/fixed.h" #include "core/types.h" namespace kumo { /// @brief Turns the time of each frame into a number of fixed steps. class FixedStep { public: /// @brief Creates a stepper. /// /// @param step Length of one step; must be positive. /// @param max_frame The longest frame that is believed. A longer one, such /// as after the window was dragged or the process was /// stopped, counts as this long, so that one slow frame does /// not cause so many updates that the next is slower still. /// At least @p step. FixedStep(Nanoseconds step, Nanoseconds max_frame); /// @brief Adds the time of one frame, and says how many steps to run. /// /// A negative time counts as none, and one beyond the maximum counts as the /// maximum. The part of the time that does not make a whole step is kept for /// the next call. /// /// @param frame_time Time since the previous frame. /// @return The number of steps to run now, possibly 0. int advance(Nanoseconds frame_time); /// @brief The length of one step. Nanoseconds step() const { return step_; } /// @brief How far the time is into the next step, from 0 up to but not /// including 1. Rendering can use it to draw between the last two /// states of the simulation. double alpha() const { return static_cast(left_over_) / static_cast(step_); } /// @brief Same as alpha(), as a Fixed in [0, 1), ready for lerp(). Fixed alpha_fixed() const { return Fixed::ratio(left_over_, step_); } /// @brief The time that was added but is not yet part of a step. Nanoseconds left_over() const { return left_over_; } /// @brief How many steps have been returned in total. uint64_t total_steps() const { return total_steps_; } /// @brief The time the simulation has run for: the steps so far, times the /// length of a step. Nanoseconds simulated_time() const { return static_cast(total_steps_) * step_; } private: Nanoseconds step_; Nanoseconds max_frame_; Nanoseconds left_over_ = 0; uint64_t total_steps_ = 0; }; } // namespace kumo