1#![no_std]
29
30#[derive(Copy, Clone, Debug, PartialEq, Eq)]
32pub struct TickRate(u16);
33
34impl TickRate {
35 pub const HZ60: TickRate = TickRate(1);
37 pub const HZ30: TickRate = TickRate(2);
39 pub const HZ20: TickRate = TickRate(3);
41
42 #[must_use]
44 pub const fn every_vblanks(vblanks: u16) -> TickRate {
45 TickRate(if vblanks == 0 { 1 } else { vblanks })
46 }
47
48 pub const fn vblanks(self) -> u16 {
50 self.0
51 }
52}
53
54#[derive(Copy, Clone, Debug, PartialEq, Eq)]
56pub enum CatchUp {
57 Unbounded,
59 Interleave(u16),
63 Cap(u16),
67}
68
69#[derive(Copy, Clone, Debug, PartialEq, Eq)]
71pub struct TickConfig {
72 pub rate: TickRate,
74 pub catch_up: CatchUp,
76}
77
78impl TickConfig {
79 pub const fn new(rate: TickRate) -> TickConfig {
81 TickConfig {
82 rate,
83 catch_up: CatchUp::Unbounded,
84 }
85 }
86
87 pub const fn with_interleave(self, max_ticks: u16) -> TickConfig {
89 TickConfig {
90 rate: self.rate,
91 catch_up: CatchUp::Interleave(if max_ticks == 0 { 1 } else { max_ticks }),
92 }
93 }
94
95 pub const fn with_cap(self, max_ticks: u16) -> TickConfig {
97 TickConfig {
98 rate: self.rate,
99 catch_up: CatchUp::Cap(if max_ticks == 0 { 1 } else { max_ticks }),
100 }
101 }
102}
103
104#[derive(Copy, Clone, Debug, PartialEq, Eq)]
118pub struct PresentCap(u8);
119
120impl PresentCap {
121 pub const HZ30: PresentCap = PresentCap(2);
123 pub const UNCAPPED: PresentCap = PresentCap(1);
126
127 pub const fn every_vblanks(vblanks: u8) -> PresentCap {
129 PresentCap(if vblanks == 0 { 1 } else { vblanks })
130 }
131
132 #[must_use]
134 pub const fn min_vblanks(self) -> u8 {
135 self.0
136 }
137}
138
139impl Default for PresentCap {
140 fn default() -> PresentCap {
142 PresentCap::HZ30
143 }
144}
145
146pub const FLIP_HISTOGRAM_BUCKETS: usize = 8;
149
150#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
157pub struct FlipHistogram {
158 buckets: [u32; FLIP_HISTOGRAM_BUCKETS],
159}
160
161impl FlipHistogram {
162 #[must_use]
166 pub const fn buckets(&self) -> &[u32; FLIP_HISTOGRAM_BUCKETS] {
167 &self.buckets
168 }
169
170 #[must_use]
172 pub const fn from_buckets(buckets: [u32; FLIP_HISTOGRAM_BUCKETS]) -> FlipHistogram {
173 FlipHistogram { buckets }
174 }
175
176 #[must_use]
179 pub fn below(&self, min_vblanks: u8) -> u32 {
180 let end = usize::from(min_vblanks).min(FLIP_HISTOGRAM_BUCKETS);
181 self.buckets[..end].iter().sum()
182 }
183
184 #[must_use]
186 pub fn total(&self) -> u32 {
187 self.buckets.iter().sum()
188 }
189
190 fn record(&mut self, interval: u32) {
191 let k = (interval as usize).min(FLIP_HISTOGRAM_BUCKETS - 1);
192 self.buckets[k] = self.buckets[k].saturating_add(1);
193 }
194}
195
196#[derive(Copy, Clone, Debug, PartialEq, Eq)]
208pub struct FlipGate {
209 min: u32,
210 hold: u32,
211 age: u32,
212 histogram: FlipHistogram,
213}
214
215impl FlipGate {
216 #[must_use]
218 pub const fn new(cap: PresentCap) -> FlipGate {
219 FlipGate {
220 min: cap.min_vblanks() as u32,
221 hold: 0,
222 age: FLIP_HISTOGRAM_BUCKETS as u32 - 1,
223 histogram: FlipHistogram {
224 buckets: [0; FLIP_HISTOGRAM_BUCKETS],
225 },
226 }
227 }
228
229 pub fn edge(&mut self, flip_wanted: bool) -> bool {
233 let flipped = flip_wanted && self.hold == 0;
234 if flipped {
235 self.histogram.record(self.age);
236 self.age = 0;
237 self.hold = self.min;
238 }
239 self.hold = self.hold.saturating_sub(1);
240 self.age = self.age.saturating_add(1);
241 flipped
242 }
243
244 #[must_use]
246 pub const fn histogram(&self) -> FlipHistogram {
247 self.histogram
248 }
249}
250
251pub const TICK_HISTOGRAM_BUCKETS: usize = 9;
254
255#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
257pub struct TickStats {
258 pub frames: u32,
260 pub ticks: u32,
262 pub dropped: u32,
264 pub max_frame_ticks: u16,
266 pub ticks_per_frame: [u32; TICK_HISTOGRAM_BUCKETS],
269}
270
271#[derive(Copy, Clone, Debug, PartialEq, Eq)]
273pub struct FixedClock {
274 rate: u16,
275 cap: u16,
276 drop_excess: bool,
277 next_due: u32,
278 tick: u32,
279 frame_ticks: u16,
280 stats: TickStats,
281}
282
283#[inline(always)]
284fn reached(now: u32, target: u32) -> bool {
285 now.wrapping_sub(target) < 0x8000_0000
286}
287
288impl FixedClock {
289 pub const fn new(config: TickConfig, first_due: u32) -> FixedClock {
291 FixedClock {
292 rate: config.rate.vblanks(),
293 cap: match config.catch_up {
294 CatchUp::Unbounded => 0,
295 CatchUp::Interleave(n) | CatchUp::Cap(n) => n,
296 },
297 drop_excess: matches!(config.catch_up, CatchUp::Cap(_)),
298 next_due: first_due,
299 tick: 0,
300 frame_ticks: 0,
301 stats: TickStats {
302 frames: 0,
303 ticks: 0,
304 dropped: 0,
305 max_frame_ticks: 0,
306 ticks_per_frame: [0; TICK_HISTOGRAM_BUCKETS],
307 },
308 }
309 }
310
311 pub fn realign(&mut self, first_due: u32) {
315 self.next_due = first_due;
316 }
317
318 pub fn due(&mut self, now: u32) -> bool {
324 if !reached(now, self.next_due) {
325 return false;
326 }
327 if self.cap != 0 && self.frame_ticks >= self.cap {
328 if !self.drop_excess {
329 return false;
330 }
331 let behind = now.wrapping_sub(self.next_due) / u32::from(self.rate) + 1;
332 self.stats.dropped = self.stats.dropped.saturating_add(behind);
333 self.next_due = self
334 .next_due
335 .wrapping_add(behind.wrapping_mul(u32::from(self.rate)));
336 return false;
337 }
338 self.consume();
339 true
340 }
341
342 pub fn is_due(&self, now: u32) -> bool {
347 reached(now, self.next_due)
348 }
349
350 pub fn consume(&mut self) {
353 self.next_due = self.next_due.wrapping_add(u32::from(self.rate));
354 self.tick = self.tick.wrapping_add(1);
355 self.frame_ticks = self.frame_ticks.saturating_add(1);
356 self.stats.ticks = self.stats.ticks.saturating_add(1);
357 }
358
359 pub fn end_frame(&mut self) {
362 let k = usize::from(self.frame_ticks).min(TICK_HISTOGRAM_BUCKETS - 1);
363 self.stats.ticks_per_frame[k] = self.stats.ticks_per_frame[k].saturating_add(1);
364 self.stats.frames = self.stats.frames.saturating_add(1);
365 self.stats.max_frame_ticks = self.stats.max_frame_ticks.max(self.frame_ticks);
366 self.frame_ticks = 0;
367 }
368
369 pub const fn tick(&self) -> u32 {
371 self.tick
372 }
373
374 pub const fn frame_ticks(&self) -> u16 {
376 self.frame_ticks
377 }
378
379 pub const fn rate(&self) -> TickRate {
381 TickRate(self.rate)
382 }
383
384 pub const fn next_due(&self) -> u32 {
386 self.next_due
387 }
388
389 pub fn phase_q12(&self, now: u32) -> u16 {
396 let ahead = self.next_due.wrapping_sub(now) as i32;
397 let rate = i32::from(self.rate);
398 if ahead <= 0 {
399 4096
400 } else {
401 (((rate - ahead.min(rate)) << 12) / rate) as u16
402 }
403 }
404
405 pub const fn stats(&self) -> TickStats {
407 self.stats
408 }
409
410 pub fn reset_stats(&mut self) {
412 self.stats = TickStats::default();
413 }
414}
415
416#[cfg(test)]
417mod tests {
418 use super::*;
419
420 fn run(clock: &mut FixedClock, now: u32) -> u32 {
421 let mut n = 0;
422 while clock.due(now) {
423 n += 1;
424 }
425 clock.end_frame();
426 n
427 }
428
429 #[test]
430 fn sixty_hz_runs_one_tick_per_vblank_and_catches_up_a_slow_frame() {
431 let mut c = FixedClock::new(TickConfig::new(TickRate::HZ60), 10);
432 assert_eq!(run(&mut c, 9), 0);
433 assert_eq!(run(&mut c, 10), 1);
434 assert_eq!(run(&mut c, 11), 1);
435 assert_eq!(run(&mut c, 15), 4);
436 assert_eq!(c.tick(), 6);
437 assert_eq!(c.stats().ticks_per_frame[..5], [1, 2, 0, 0, 1]);
438 assert_eq!(c.stats().max_frame_ticks, 4);
439 assert_eq!(c.stats().dropped, 0);
440 }
441
442 #[test]
443 fn twenty_hz_ticks_every_third_vblank() {
444 let mut c = FixedClock::new(TickConfig::new(TickRate::HZ20), 3);
445 let ticks: u32 = (0..=30).map(|now| run(&mut c, now)).sum();
446 assert_eq!(ticks, 10); assert_eq!(c.next_due(), 33);
448 }
449
450 #[test]
451 fn logic_time_matches_real_time_whatever_the_frame_lengths() {
452 let mut c = FixedClock::new(TickConfig::new(TickRate::HZ30), 0);
455 let mut now = 0u32;
456 let mut k = 0u32;
457 while now < 1000 {
458 run(&mut c, now);
459 now += 1 + (k % 7);
460 k += 1;
461 }
462 run(&mut c, 1000);
463 assert_eq!(c.tick(), 501); assert_eq!(c.stats().dropped, 0);
465 }
466
467 #[test]
468 fn cap_drops_the_excess_and_counts_it() {
469 let mut c = FixedClock::new(TickConfig::new(TickRate::HZ60).with_cap(4), 0);
470 assert_eq!(run(&mut c, 0), 1);
471 assert_eq!(run(&mut c, 10), 4);
473 assert_eq!(c.stats().dropped, 6);
474 assert_eq!(c.next_due(), 11);
475 assert_eq!(run(&mut c, 11), 1);
476 }
477
478 #[test]
479 fn interleave_renders_between_bursts_and_loses_no_time() {
480 let mut c = FixedClock::new(TickConfig::new(TickRate::HZ60).with_interleave(4), 0);
481 assert_eq!(run(&mut c, 0), 1);
482 assert_eq!(run(&mut c, 10), 4); assert_eq!(run(&mut c, 10), 4); assert_eq!(run(&mut c, 11), 3); assert_eq!(c.tick(), 12);
486 assert_eq!(c.stats().dropped, 0);
487 }
488
489 #[test]
490 fn is_due_and_consume_split_the_decision_from_the_commit() {
491 let mut c = FixedClock::new(TickConfig::new(TickRate::HZ60), 5);
492 assert!(!c.is_due(4));
493 assert!(c.is_due(5));
494 assert!(c.is_due(5)); c.consume();
496 assert!(!c.is_due(5));
497 assert_eq!((c.tick(), c.frame_ticks(), c.next_due()), (1, 1, 6));
498 }
499
500 #[test]
501 fn realign_forgets_debt_without_counting_it_dropped() {
502 let mut c = FixedClock::new(TickConfig::new(TickRate::HZ60), 0);
503 run(&mut c, 0);
504 c.realign(501); assert_eq!(run(&mut c, 501), 1);
506 assert_eq!(c.stats().dropped, 0);
507 }
508
509 #[test]
510 fn phase_sweeps_from_last_tick_to_next() {
511 let mut c = FixedClock::new(TickConfig::new(TickRate::HZ20), 0);
512 run(&mut c, 0); assert_eq!(c.phase_q12(0), 0);
514 assert_eq!(c.phase_q12(1), 1365);
515 assert_eq!(c.phase_q12(2), 2730);
516 assert_eq!(c.phase_q12(3), 4096);
517 let mut s = FixedClock::new(TickConfig::new(TickRate::HZ60), 0);
518 run(&mut s, 0);
519 assert_eq!(s.phase_q12(0), 0);
520 assert_eq!(s.phase_q12(1), 4096);
521 }
522
523 #[test]
524 fn the_default_cap_never_flips_twice_in_two_vblanks_whatever_is_asked() {
525 let mut gate = FlipGate::new(PresentCap::default());
526 let mut last = None;
527 for edge in 0..1000u32 {
528 let wanted = edge % 5 != 3;
530 if gate.edge(wanted) {
531 if let Some(prev) = last {
532 assert!(edge - prev >= 2, "flips at {prev} and {edge}");
533 }
534 last = Some(edge);
535 }
536 }
537 assert_eq!(gate.histogram().below(2), 0);
538 assert!(gate.histogram().total() > 400);
539 }
540
541 #[test]
542 fn a_slower_game_is_not_delayed_and_uncapped_flips_every_edge() {
543 let mut gate = FlipGate::new(PresentCap::HZ30);
545 let granted: u32 = (0..30).map(|e| u32::from(gate.edge(e % 3 == 0))).sum();
546 assert_eq!(granted, 10);
547 assert_eq!(gate.histogram().buckets()[3], 9);
548 let mut free = FlipGate::new(PresentCap::UNCAPPED);
549 assert!((0..10).all(|_| free.edge(true)));
550 assert_eq!(free.histogram().buckets()[1], 9);
551 assert_eq!(free.histogram().below(2), 9);
552 }
553
554 #[test]
555 fn caps_below_one_vblank_are_one_and_slower_caps_hold_longer() {
556 assert_eq!(PresentCap::every_vblanks(0), PresentCap::UNCAPPED);
557 let mut gate = FlipGate::new(PresentCap::every_vblanks(3));
558 let mut granted = [false; 7];
559 for slot in &mut granted {
560 *slot = gate.edge(true);
561 }
562 assert_eq!(granted, [true, false, false, true, false, false, true]);
563 }
564
565 #[test]
566 fn survives_vblank_counter_wraparound() {
567 let start = u32::MAX - 2;
568 let mut c = FixedClock::new(TickConfig::new(TickRate::HZ60), start);
569 assert_eq!(run(&mut c, start.wrapping_add(5)), 6);
570 assert_eq!(c.next_due(), start.wrapping_add(6));
571 }
572}