use winit::{event::WindowEvent, window::Window};
use crate::{
app::Tree,
time::{Duration, Instant},
};
const FALLBACK_REFRESH_INTERVAL: Duration = Duration::from_nanos(16_666_667);
const REFRESH_RECHECK: Duration = Duration::from_secs(1);
#[derive(Clone, Copy, Debug)]
pub(super) struct PresentedFrame {
pub(super) started: Instant,
pub(super) presented: Instant,
}
#[derive(Debug, Default)]
pub(super) struct FramePacing {
occluded: bool,
hidden: bool,
refresh: Option<(Duration, Instant)>,
last_frame: Option<PresentedFrame>,
}
impl FramePacing {
pub(super) fn handle_event(&mut self, event: &WindowEvent) {
match event {
WindowEvent::Occluded(occluded) => self.occluded = *occluded,
WindowEvent::Moved(_) | WindowEvent::ScaleFactorChanged { .. } => self.refresh = None,
_ => {}
}
}
pub(super) fn presented(&mut self, frame: PresentedFrame) {
self.last_frame = Some(frame);
}
pub(super) fn request_frame(&mut self, tree: &mut Tree, refresh: impl FnOnce() -> Duration, now: Instant) {
let (hidden, shown) = self.see_window(tree);
if hidden {
tree.drop_scheduled_redraws();
return;
}
if shown {
tree.request_redraw();
return;
}
tree.tick_perf_overlay();
let changes_at = if tree.perf_overlay_enabled()
|| tree.has_continuous_redraw_still()
|| tree.autoscroll_moving()
|| tree.has_moving_canvas()
{
Some(now)
} else {
tree.next_timeline_change()
};
let Some(changes_at) = changes_at else {
return;
};
let refresh = self.refresh_interval(refresh, now);
let next_frame_at = frame_due(changes_at, self.last_frame, refresh);
if now >= next_frame_at {
tree.request_redraw();
} else {
tree.request_redraw_at(next_frame_at);
}
}
pub(super) fn see_window(&mut self, tree: &mut Tree) -> (bool, bool) {
let hidden = self.occluded || tree.window().info().is_minimized;
let shown = self.hidden && !hidden;
self.hidden = hidden;
tree.set_frames_hidden(hidden);
(hidden, shown)
}
pub(super) fn refresh_interval(&mut self, refresh: impl FnOnce() -> Duration, now: Instant) -> Duration {
match self.refresh {
Some((interval, read_at)) if now.duration_since(read_at) < REFRESH_RECHECK => interval,
_ => {
let interval = refresh();
self.refresh = Some((interval, now));
interval
}
}
}
}
pub(super) fn frame_due(changes_at: Instant, last: Option<PresentedFrame>, refresh: Duration) -> Instant {
let Some(last) = last else {
return changes_at;
};
changes_at
.max(last.presented + refresh / 2)
.max(last.started + refresh * 3 / 4)
}
pub(super) fn refresh_interval(window: Option<&Window>) -> Duration {
window
.and_then(Window::current_monitor)
.and_then(|monitor| monitor.refresh_rate_millihertz())
.filter(|rate| *rate > 0)
.map(|rate| Duration::from_nanos((1_000_000_000_000u64 / rate as u64).max(1)))
.unwrap_or(FALLBACK_REFRESH_INTERVAL)
}