Kumo

A hand-rolled game engine.

git clone https://git.sentomk.me/Kumo.git

loop.h (2069B) · raw


      1 /// @file runtime/loop.h
      2 /// @brief Drives a Game on a fixed simulation step, without owning a window.
      3 #pragma once
      4 
      5 #include "core/clock.h"
      6 #include "core/fixed.h"
      7 #include "core/fixed_step.h"
      8 #include "core/types.h"
      9 #include "runtime/game.h"
     10 
     11 namespace kumo {
     12 
     13 /// @brief Settings for Loop.
     14 struct LoopConfig {
     15   Nanoseconds step = step_from_hz(60);        ///< Fixed update duration.
     16   Nanoseconds max_frame = milliseconds(250);  ///< Longest frame accepted.
     17 };
     18 
     19 /// @brief Outcome of one rendered frame.
     20 struct FrameReport {
     21   int ticks_run = 0;         ///< Fixed updates executed during this frame.
     22   uint64_t total_ticks = 0;  ///< Total fixed updates executed since start.
     23   Fixed alpha;               ///< Interpolation fraction passed to render().
     24 };
     25 
     26 /// @brief Connects a Clock and a FixedStep to a Game.
     27 ///
     28 /// Does not own a Window, so the same code drives both the windowed app
     29 /// (with SystemClock) and headless tests or replays (with ManualClock).
     30 class Loop {
     31  public:
     32   /// @brief Starts a loop reading frame durations from @p clock.
     33   ///
     34   /// @param clock  Time source; must outlive the loop.
     35   /// @param config Step length and frame clamp.
     36   explicit Loop(Clock& clock, LoopConfig config = {});
     37 
     38   /// @brief Measures elapsed time from the clock, runs 0 or more fixed updates,
     39   ///        and renders one frame into @p frame.
     40   FrameReport step_frame(Game& game, FrameBuffer& frame);
     41 
     42   /// @brief Runs exactly @p count fixed updates without consulting the clock
     43   ///        or rendering. Useful for deterministic tests and replays.
     44   void step_ticks(Game& game, uint64_t count);
     45   /// @brief Forgets elapsed time since the last frame (e.g. after loading).
     46   void reset_timer() { timer_.reset(); }
     47   uint64_t total_ticks() const { return next_tick_index_; }
     48   Nanoseconds step() const { return stepper_.step(); }
     49   Nanoseconds simulated_time() const {
     50     return static_cast<Nanoseconds>(next_tick_index_) * stepper_.step();
     51   }
     52 
     53  private:
     54   FrameTimer timer_;
     55   FixedStep stepper_;
     56   uint64_t next_tick_index_ = 0;
     57 };
     58 
     59 }  // namespace kumo