fix(gpu): submit stage work on the window's device only inside a frame (M8)

The stage renderer shares the window's device and submitted its work from the
render service's threads at any time. A window reconfigures its surface when
it opens and when it is resized, and wgpu fails that when another thread
submits meanwhile: 'Surface::configure: Failed to wait for GPU to come idle
before reconfiguring the Surface'. In 0.2.1 that error was a panic, so
AniCraft closed at start-up or on a resize (#264, #309, and with them the
'won't open' reports #421 #412 #313 #286 #285 #268 #164); since ADR 0092 it
is survived, at the cost of a skipped frame, an autosave and a status line
blaming the graphics driver.

A SubmitGate (crates/gpu) is open while the window's thread runs the app's
frame and closed otherwise, also around windows drawn inside the frame (Test
Movie, floating panels). Work waits for it (asking for a frame), at most
250 ms; the renderer's starting self-test goes through it too.

Measured on Windows 10, RTX 5090, Vulkan, --screenshot starts: the error in
3 of 20 starts before, 0 of 20 after; 2.81 s and 2.80 s per run.
This commit is contained in:
Tanish Manku committed 2026-11-17 16:48:36 -07:00
1 parent b0fecda353
commit c81de6d649
6 files changed
+441 -12

No files matched your search

+2
View File
@@ -3925,6 +3925,8 @@ impl eframe::App for App {
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
// Stage work on the window's device is submitted only while this frame runs (ADR 0105).
let _in_frame = crate::gpu_stage::in_frame(ui.ctx());
self.frame(ui);
// A few frames drawn: the window started (#207).
crate::startup::frame();
+3
View File
@@ -152,6 +152,8 @@ fn own_window(app: &mut App, ctx: &egui::Context, f: &Float, layout: &Layout, ac
}
let builder = crate::platform::secondary_window(builder);
let shortcuts = app.shortcuts.clone();
// The window's surface is set up and drawn inside the call (ADR 0105).
let paused = crate::gpu_stage::paused();
let (close, commands) = ctx.show_viewport_immediate(egui::ViewportId::from_hash_of(("dock_float", f.id)), builder, |ui, class| {
let (close, outer, inner) = ui.input(|i| (i.viewport().close_requested(), i.viewport().outer_rect, i.viewport().inner_rect));
if let (Some(o), Some(i)) = (outer, inner) {
@@ -187,6 +189,7 @@ fn own_window(app: &mut App, ctx: &egui::Context, f: &Float, layout: &Layout, ac
};
(close, commands)
});
drop(paused);
for id in commands {
app.invoke(id);
}
+142 -4
View File
@@ -125,6 +125,94 @@ pub fn wanted(pref: StageRenderer) -> StageRenderer {
}
}
// ----- when stage work may be submitted on the window's device (ADR 0105) ----------------------
/// The gate stage work on the window's device is submitted through: open while the window's
/// thread runs the app's frame, closed while it may be reconfiguring a surface.
#[cfg(gpu_stage)]
static GATE: std::sync::OnceLock<std::sync::Arc<anicraft_gpu::SubmitGate>> = std::sync::OnceLock::new();
/// The window a waiting submission asks for a frame (the window opens again with a new one
/// after its device was lost, ADR 0092).
#[cfg(gpu_stage)]
static WAKE: std::sync::Mutex<Option<egui::Context>> = std::sync::Mutex::new(None);
/// Submissions that went ahead without a frame, as last written to the log.
#[cfg(gpu_stage)]
static GATE_TIMEOUTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
#[cfg(gpu_stage)]
fn gate(ctx: &egui::Context) -> &'static std::sync::Arc<anicraft_gpu::SubmitGate> {
use std::sync::PoisonError;
let mut wake = WAKE.lock().unwrap_or_else(PoisonError::into_inner);
if wake.as_ref() != Some(ctx) {
*wake = Some(ctx.clone());
}
drop(wake);
GATE.get_or_init(|| {
std::sync::Arc::new(anicraft_gpu::SubmitGate::new(|| {
let ctx = WAKE.lock().unwrap_or_else(PoisonError::into_inner).clone();
if let Some(ctx) = ctx {
ctx.request_repaint();
}
}))
})
}
/// The app's frame, for the stage renderer: while this lives the window's thread is inside
/// [`eframe::App::ui`], so it isn't reconfiguring a surface and stage work may be submitted.
#[must_use]
pub struct InFrame(());
/// Call first thing in the frame, on the window's thread; keep the result until the frame ends.
#[cfg_attr(not(gpu_stage), allow(unused_variables))]
pub fn in_frame(ctx: &egui::Context) -> InFrame {
#[cfg(gpu_stage)]
{
let gate = gate(ctx);
gate.open();
// Work that waited for a frame that never came (a window that draws none) went ahead:
// said once per tenfold, it is the old race's way back in.
let timeouts = gate.waited().1;
let said = GATE_TIMEOUTS.load(std::sync::atomic::Ordering::Relaxed);
if timeouts > 0 && (said == 0 || timeouts >= said.saturating_mul(10)) {
GATE_TIMEOUTS.store(timeouts, std::sync::atomic::Ordering::Relaxed);
crate::startup::line(&format!("stage work was submitted without waiting for a frame {timeouts} time(s) (the window drew none for {} ms)", anicraft_gpu::SUBMIT_WAIT.as_millis()));
}
}
InFrame(())
}
impl Drop for InFrame {
fn drop(&mut self) {
#[cfg(gpu_stage)]
if let Some(gate) = GATE.get() {
gate.close();
}
}
}
/// Inside the frame, around a window of its own drawn at once (Test Movie, a floating panel):
/// eframe sets that window's surface up and draws it inside the call, so stage work waits
/// there too.
#[must_use]
pub struct Paused(());
pub fn paused() -> Paused {
#[cfg(gpu_stage)]
if let Some(gate) = GATE.get() {
gate.close();
}
Paused(())
}
impl Drop for Paused {
fn drop(&mut self) {
#[cfg(gpu_stage)]
if let Some(gate) = GATE.get() {
gate.open();
}
}
}
#[derive(Default)]
pub struct GpuStage {
#[cfg(gpu_stage)]
@@ -284,10 +372,17 @@ mod imp {
/// The window's device first (no readback); a device of our own when that can't work.
fn start(window: Option<RenderState>) -> Result<GpuRenderer, String> {
let shared = match &window {
Some(rs) => match GpuRenderer::shared(&rs.adapter, rs.device.clone(), rs.queue.clone()) {
Ok(g) => return Ok(g),
Err(e) => Some(e.to_string()),
},
// Through the gate: the window reconfigures its surface between frames (ADR 0105).
Some(rs) => {
let on_window = match super::GATE.get() {
Some(gate) => GpuRenderer::shared_gated(&rs.adapter, rs.device.clone(), rs.queue.clone(), gate.clone()),
None => GpuRenderer::shared(&rs.adapter, rs.device.clone(), rs.queue.clone()),
};
match on_window {
Ok(g) => return Ok(g),
Err(e) => Some(e.to_string()),
}
}
None => None,
};
GpuRenderer::new().map_err(|e| match shared {
@@ -584,6 +679,49 @@ mod imp {
mod tests {
use super::*;
/// ADR 0105 (#264, #309): stage work on the window's device is submitted while the app's
/// frame runs, and waits (asking for a frame) while the window may be reconfiguring its
/// surface: between frames, and while a window of its own is drawn inside the frame.
#[cfg(gpu_stage)]
#[test]
fn stage_work_is_submitted_only_inside_the_frame() {
use std::time::{Duration, Instant};
let wait = anicraft_gpu::SUBMIT_WAIT;
let ctx = egui::Context::default();
let frame = in_frame(&ctx);
let gate = GATE.get().cloned().unwrap();
let submit = |gate: &std::sync::Arc<anicraft_gpu::SubmitGate>| {
let g = gate.clone();
std::thread::spawn(move || g.run(|| ()))
};
// Inside the frame: at once.
let t = Instant::now();
submit(&gate).join().unwrap();
assert!(t.elapsed() < wait / 2, "{:?}", t.elapsed());
// While a floating window or Test Movie draws inside the frame: it waits for that.
let floating = paused();
let work = submit(&gate);
std::thread::sleep(Duration::from_millis(40));
assert!(!work.is_finished(), "submitted while a window was being set up");
drop(floating);
work.join().unwrap();
drop(frame);
// Between frames: it waits, asks the window for a frame, and runs when the frame comes.
let work = submit(&gate);
std::thread::sleep(Duration::from_millis(40));
assert!(!work.is_finished(), "submitted between frames");
assert!(ctx.has_requested_repaint(), "the waiting work asks for a frame");
let t = Instant::now();
let frame = in_frame(&ctx);
work.join().unwrap();
assert!(t.elapsed() < wait / 2, "{:?}", t.elapsed());
drop(frame);
// The window's own thread never waits (it can't be reconfiguring while it submits).
let t = Instant::now();
gate.run(|| ());
assert!(t.elapsed() < wait / 2);
}
/// The backoff (ADR 0092): growing pauses, a bounded number of tries, a resize bringing a
/// try forward (not too soon), and a long good run starting the count afresh.
#[test]
+2
View File
@@ -341,6 +341,8 @@ fn own_window(app: &mut App, ctx: &egui::Context) -> Asked {
builder = builder.with_position(at);
}
let builder = crate::platform::secondary_window(builder);
// The window's surface is set up and drawn inside the call (ADR 0105).
let _paused = crate::gpu_stage::paused();
ctx.show_viewport_immediate(viewport_id(), builder, |ui, class| {
let mut asked = Asked::default();
let (close_requested, outer) = ui.input(|i| (i.viewport().close_requested(), i.viewport().outer_rect));