7 releases

0.1.5 Oct 5, 2024
0.1.4 Jan 21, 2024
0.1.3 Nov 19, 2023
0.1.2 Sep 6, 2023
0.0.0 Jan 16, 2023

#389 in Game dev

Download history 89/week @ 2024-07-14 79/week @ 2024-07-21 114/week @ 2024-07-28 150/week @ 2024-08-04 217/week @ 2024-08-11 181/week @ 2024-08-18 141/week @ 2024-08-25 86/week @ 2024-09-01 82/week @ 2024-09-08 93/week @ 2024-09-15 58/week @ 2024-09-22 120/week @ 2024-09-29 168/week @ 2024-10-06 138/week @ 2024-10-13 71/week @ 2024-10-20 41/week @ 2024-10-27

495 downloads per month

AGPL-3.0-only

17KB
92 lines

chron

Crates.io Documentation License

A game loop with a fixed timestep.

Features:

  • A fixed timestep. Updates to the game logic (chron::Tick::Update) are independent from the rendering of new frames (chron::Tick::Render). Updates are emitted at fixed intervals. Renders are emitted in between updates: the frame rate may either be unlocked (the default) or limited (see below).
  • An optional maximum frame rate, to prevent the game from running at unnecessarily high frame rates. When the maximum frame rate is not set, the frame rate is unlocked, i.e. the loop will emit as many chron::Tick::Render events as possible in between two updates. To set the maximum frame rate use the function Clock::max_frame_rate.
  • An optional way to prevent an infinite update loop. When the loop cannot maintain the specified updates per second (e.g. because updates are taking too long) it has to play catch-up by only emitting updates and no renders. This setting limits how many updates are emitted before a render is enforced. It prevents the game from never rendering at all, at the cost of slowing down even more. To set the maximum updates per frame use the function Clock::max_updates_per_frame.

Note: The maximum frame rate feature uses std::thread::sleep. Its accuracy may or may not be good enough, depending on the platform. So far it seems to work fine (on Linux).

Example

use std::num::NonZeroU32;

let updates_per_second = NonZeroU32::new(50).unwrap();
let frames_per_second = NonZeroU32::new(60).unwrap();

let clock = chron::Clock::new(updates_per_second)
    .max_frame_rate(frames_per_second)
    .max_updates_per_frame(10);

for tick in clock {
    match tick {
        chron::Tick::Update => {
            // ...
        }
        chron::Tick::Render { interpolation } => {
            // ...
        }
    }
}

No runtime deps