Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 27 additions & 4 deletions crates/ui-egui/src/headless.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ const CLEAR: Color32 = Color32::from_rgb(12, 12, 12);
/// Simulated frame interval (deterministic animation time).
const FRAME_DT: f64 = 1.0 / 60.0;

/// The longest [`Headless::wait_for_work`] waits between two frames for pending work. Shorter
/// than a frame of the simulated clock ([`FRAME_DT`]), so a busy app still runs ahead of real time.
const BUSY_PAUSE: Duration = Duration::from_millis(10);

/// Validate the scaled screenshot dimensions before layout or pixel allocation.
pub fn viewport_pixels(size: [f32; 2], pixels_per_point: f32) -> Result<[usize; 2], String> {
if size.iter().any(|edge| *edge < 1.0) {
Expand Down Expand Up @@ -408,15 +412,16 @@ impl Headless {
}

/// Run frames until nothing is pending (renders finished, input consumed) for a few frames in
/// a row, or `timeout` passes. Returns whether it settled.
/// a row, or `timeout` passes. Returns whether it settled. While something is pending, frames
/// are paced by [`Self::wait_for_work`].
pub fn settle(&mut self, timeout: Duration) -> bool {
let t0 = Instant::now();
let mut quiet = 0;
loop {
self.step();
if self.busy() {
quiet = 0;
std::thread::sleep(Duration::from_millis(1));
self.wait_for_work();
} else {
quiet += 1;
}
Expand All @@ -432,18 +437,36 @@ impl Headless {

/// Run frames until `done` holds or `timeout` passes (a render that finishes on a busy machine
/// after a quiet spell, where [`Self::settle`] alone would stop too early). Returns `done`.
/// While [`Self::busy`], frames are paced by [`Self::wait_for_work`].
pub fn step_until(&mut self, timeout: Duration, done: impl Fn(&Self) -> bool) -> bool {
let t0 = Instant::now();
while !done(self) {
if t0.elapsed() > timeout {
return false;
}
self.step();
std::thread::sleep(Duration::from_millis(1));
if self.busy() {
self.wait_for_work();
} else {
std::thread::sleep(Duration::from_millis(1));
}
}
true
}

/// Between two frames while the app is [`Self::busy`]: leave the CPU to the work being waited
/// for until a render finishes or [`BUSY_PAUSE`] passes, rather than draw the next frame at
/// once. Every frame lays out the whole UI; drawn back to back, the frames of the tests that were
/// waiting took about half the CPU of ui-egui's test binary on a loaded machine, away from the
/// very renders they waited for, and the waits ran past their limits (#3981).
fn wait_for_work(&mut self) {
let t0 = Instant::now();
// (no render on the workers to wait for: a merge, file checks, input, an offload)
if !self.app.renderer.wait_for_worker(BUSY_PAUSE) {
std::thread::sleep(BUSY_PAUSE.saturating_sub(t0.elapsed()));
}
}

/// Rasterize the last frame (with the photo textures).
pub fn paint(&self) -> ColorImage {
self.view.paint(&HashMap::new())
Expand Down Expand Up @@ -492,7 +515,7 @@ impl Headless {
return json!({"ok": false, "error": "timeout"});
}
if self.busy() {
std::thread::sleep(Duration::from_millis(1));
self.wait_for_work();
}
};
// let injected input (clicks, keys, drags) play out before the next request
Expand Down
21 changes: 21 additions & 0 deletions crates/ui-egui/src/headless/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,27 @@ fn the_headless_host_has_a_clipboard() {
assert!(!seen.iter().any(|e| matches!(e, egui::Event::Paste(_))), "{seen:?}");
}

/// Waiting on a render gives it the CPU: `settle` and `step_until` draw a frame each time a render
/// finishes or [`BUSY_PAUSE`] passes, not one frame after another (#3981).
#[test]
fn waits_pace_their_frames_while_a_render_is_out() {
let app = LightcraftApp::new(lightcraft_engine::Session::new(), crate::Services { png: None, ..Default::default() });
let mut h = Headless::new(app, [800.0, 600.0], 1.0);
// a render that never finishes
h.app.renderer.force_in_flight_for_test(1);
let limit = Duration::from_millis(300);
for wait in ["settle", "step_until"] {
assert!(h.busy(), "{wait}: the render is still out");
let (frames, t0) = (h.frames(), Instant::now());
let done = if wait == "settle" { h.settle(limit) } else { h.step_until(limit, |_| false) };
let (ran, took) = (h.frames() - frames, t0.elapsed());
assert!(!done, "{wait}: nothing finished");
// one frame per pause at most, and one more for the frame that found the limit passed
let paced = (took.as_millis() / BUSY_PAUSE.as_millis()) as u64 + 2;
assert!(ran <= paced, "{wait}: {ran} frames in {took:?}, at most {paced} paced ones");
}
}

#[test]
fn screenshot_dimensions_are_checked_before_layout() {
assert_eq!(viewport_pixels([1600.0, 1000.0], 2.0).unwrap(), [3200, 2000]);
Expand Down
Loading