//! A fixed-step clock: how many steps of `1 / hz` seconds the frame's ticks //! owe. Keep it in State, so it migrates and replays with the rest. const std = @import("std"); const abi = @import("abi"); /// `for (0..s.clock.steps(in)) |_| step(s);` in `update`. /// /// It reads only the `tick` events in `in.events`, never the host's clock, /// so a replay gives the same steps. The steps of each tick are counted on /// their own, so an update with N ticks gives exactly the steps of N /// updates with one tick each (the host feeds one tick per update anyway). /// A tick owes at most `max_steps`: after a stall the simulation slows down /// instead of trying to catch up forever; the rest of that debt is dropped. /// `set clock.hz 30` from the console is slow motion. /// /// Time is counted in integer nanoseconds, from `Event.tickDt`, so it adds /// up the same everywhere. Two allowances keep a clock at the display's /// rate from juddering (0 steps one frame, 2 the next): /// - a tick within `slack` of a whole number of steps counts as exactly /// that many (a 60 Hz frame is 16 666 666 ns, a step at 60 Hz /// 16 666 667 ns: 60 frames are 60 steps, not 59); /// - a step is taken once `owed` is within `slack` of it, so `owed` may /// end a little below zero, and a frame that comes a little early still /// steps. /// `slack` is an eighth of a step (2 ms at 60 Hz), which covers the jitter /// of a live frame clock. pub const Clock = struct { hz: f32 = 60, /// Nanoseconds received and not yet stepped; down to `-slack` after /// an early step. owed: i64 = 0, /// Steps taken since the clock was made: a frame counter for the /// simulation (Processing's `frameCount`). count: u64 = 0, pub const max_steps = 8; /// Steps to take now; adds them to `count`. pub fn steps(c: *Clock, in: *const abi.Input) u32 { var n: u32 = 0; for (in.events) |e| if (e.kind == .tick) { n += c.tick(e.tickDt()); }; return n; } /// The steps one tick of `dt` nanoseconds owes: the per-event form, for /// an update that handles its events in order (`c.tick(e.tickDt())`). pub fn tick(c: *Clock, dt: u64) u32 { const step = c.stepNs(); if (step == 0 or dt == 0) return 0; const slack = @divTrunc(step, 8); var t: i64 = @intCast(@min(dt, std.time.ns_per_hour)); const whole = @divTrunc(t + @divTrunc(step, 2), step) * step; if (whole > 0 and @abs(t - whole) <= slack) t = whole; c.owed = @max(c.owed, -slack) + t; var n: u32 = 0; while (c.owed >= step - slack and n < max_steps) : (n += 1) c.owed -= step; if (n == max_steps and c.owed > 0) c.owed = @rem(c.owed, step); c.count += n; return n; } /// One step in nanoseconds; 0 when `hz` is not a positive rate. pub fn stepNs(c: *const Clock) i64 { if (!(c.hz > 1e-3) or !(c.hz < 1e9)) return 0; return @intFromFloat(@round(std.time.ns_per_s / @as(f64, c.hz))); } }; fn tickEvent(dt_ns: u64) abi.Event { return abi.Event.tick(0, dt_ns); } test "N updates of one tick each step exactly as one update of N ticks" { var events: [600]abi.Event = undefined; var prng: std.Random.Xoshiro256 = .init(1); for (&events) |*e| e.* = tickEvent(prng.random().uintLessThan(u64, 50_000_000)); events[300] = tickEvent(2 * std.time.ns_per_s); // a stall: capped var one: Clock = .{}; var per: [events.len]u32 = undefined; for (&events, &per) |*e, *n| n.* = one.steps(&.{ .events = e[0..1] }); var all: Clock = .{}; const total = all.steps(&.{ .events = &events }); var sum: u32 = 0; for (per) |n| sum += n; try std.testing.expectEqual(sum, total); try std.testing.expectEqual(std.mem.toBytes(one), std.mem.toBytes(all)); try std.testing.expectEqual(@as(u32, Clock.max_steps), per[300]); try std.testing.expectEqual(@as(u64, total), all.count); } test "sixty script frames are sixty steps at 60 Hz, one each" { var c: Clock = .{}; // What the host and scripts send: ns_per_s / 60, through the f32 tick. const events = [_]abi.Event{ .{ .kind = .mouse_move, .x = 5 }, tickEvent(std.time.ns_per_s / 60) }; for (0..6000) |_| try std.testing.expectEqual(@as(u32, 1), c.steps(&.{ .events = &events })); try std.testing.expectEqual(@as(u64, 6000), c.count); c.hz = 0; try std.testing.expectEqual(@as(u32, 0), c.steps(&.{ .events = &events })); } test "a jittery 60 Hz frame clock gives one step a frame; slower rates divide evenly" { var prng: std.Random.Xoshiro256 = .init(7); var c: Clock = .{}; var half: Clock = .{ .hz = 30 }; var halves: u32 = 0; // Frames shown at vsync, each measured up to 1.5 ms late. var last: u64 = 0; for (0..1200) |i| { const shown = (i + 1) * std.time.ns_per_s / 60 + prng.random().uintLessThan(u64, 1_500_000); const dt = shown - last; last = shown; try std.testing.expectEqual(@as(u32, 1), c.tick(dt)); const h = half.tick(dt); try std.testing.expectEqual(@as(u32, @intFromBool(i % 2 == 1)), h); halves += h; } try std.testing.expectEqual(@as(u32, 600), halves); // A dropped frame is two steps. try std.testing.expectEqual(@as(u32, 2), c.tick(33_333_333)); // 144 Hz on a 60 Hz display: 2.4 steps a frame on average, exactly. var fast: Clock = .{ .hz = 144 }; var n: u32 = 0; for (0..600) |_| n += fast.tick(16_666_667); try std.testing.expect(n >= 1439 and n <= 1441); }