mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-20 01:22:11 +01:00
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:
1 parent
b0fecda353
commit
c81de6d649
6 files changed
+441
-12
No files matched your search
@@ -0,0 +1,246 @@
|
||||
//! When work may be submitted on a device shared with a window (ADR 0105).
|
||||
//!
|
||||
//! A window reconfigures its surface when it opens and whenever it is resized. wgpu first waits
|
||||
//! for the device's queue to empty, and fails the reconfiguration when another thread submits
|
||||
//! work meanwhile ("Failed to wait for GPU to come idle before reconfiguring the Surface": its
|
||||
//! own comment says it "can only be non-empty if another thread is submitting at the same
|
||||
//! time"). The stage renderer draws on the window's device from the render service's threads,
|
||||
//! so that is what it did: the error behind AniCraft closing at start-up and on resizing
|
||||
//! (#264, #309) before ADR 0092 kept the window up, and a skipped frame and a false "graphics
|
||||
//! driver problem" since.
|
||||
//!
|
||||
//! The window's thread owns a [`SubmitGate`]: open while it runs the app's frame (it can't be
|
||||
//! reconfiguring a surface then), closed the rest of the time. A renderer given the gate
|
||||
//! ([`crate::GpuRenderer::with_gate`]) submits through [`SubmitGate::run`], which waits for the
|
||||
//! gate to open and asks the owner for a frame. Nothing waits for ever: a submission goes ahead
|
||||
//! after [`SUBMIT_WAIT`] (a window that draws no frames, minimised say), and closing waits at
|
||||
//! most [`CLOSE_WAIT`] for submissions under way; then the old race is possible again, and
|
||||
//! survived as before.
|
||||
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Condvar, Mutex, PoisonError};
|
||||
use std::thread::ThreadId;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Longest a submission waits for the gate to open.
|
||||
pub const SUBMIT_WAIT: Duration = Duration::from_millis(250);
|
||||
/// Longest closing the gate waits for submissions under way (each takes well under a
|
||||
/// millisecond).
|
||||
pub const CLOSE_WAIT: Duration = Duration::from_millis(100);
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
open: bool,
|
||||
/// Submissions under way.
|
||||
running: u32,
|
||||
}
|
||||
|
||||
/// See the module.
|
||||
pub struct SubmitGate {
|
||||
state: Mutex<State>,
|
||||
changed: Condvar,
|
||||
/// The thread that opens and closes the gate, and reconfigures the surface: its own
|
||||
/// submissions never wait (it can't be doing both).
|
||||
owner: ThreadId,
|
||||
/// Asks the owner for a frame (a frame opens the gate).
|
||||
wake: Box<dyn Fn() + Send + Sync>,
|
||||
waits: AtomicU64,
|
||||
timeouts: AtomicU64,
|
||||
}
|
||||
|
||||
/// One submission under way: counted out when it ends, however it ends.
|
||||
struct Running<'a>(&'a SubmitGate);
|
||||
|
||||
impl Drop for Running<'_> {
|
||||
fn drop(&mut self) {
|
||||
let mut s = self.0.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
s.running = s.running.saturating_sub(1);
|
||||
drop(s);
|
||||
self.0.changed.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
impl SubmitGate {
|
||||
/// A closed gate owned by the calling thread; `wake` asks that thread for a frame.
|
||||
pub fn new(wake: impl Fn() + Send + Sync + 'static) -> SubmitGate {
|
||||
SubmitGate { state: Mutex::new(State::default()), changed: Condvar::new(), owner: std::thread::current().id(), wake: Box::new(wake), waits: AtomicU64::new(0), timeouts: AtomicU64::new(0) }
|
||||
}
|
||||
|
||||
/// The owner's frame begins: submissions may run.
|
||||
pub fn open(&self) {
|
||||
self.state.lock().unwrap_or_else(PoisonError::into_inner).open = true;
|
||||
self.changed.notify_all();
|
||||
}
|
||||
|
||||
/// The owner's frame ends: no submission starts from now on, and those under way are waited
|
||||
/// for (at most [`CLOSE_WAIT`]). Whether the queue is now left alone.
|
||||
pub fn close(&self) -> bool {
|
||||
let mut s = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
s.open = false;
|
||||
let until = Instant::now() + CLOSE_WAIT;
|
||||
while s.running > 0 {
|
||||
let Some(left) = until.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()) else { return false };
|
||||
s = self.changed.wait_timeout(s, left).unwrap_or_else(PoisonError::into_inner).0;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Runs `submit` while the gate is open, waiting for it to open if need be (at most
|
||||
/// [`SUBMIT_WAIT`]; the owner is asked for a frame). On the owner's thread it runs at once.
|
||||
pub fn run<R>(&self, submit: impl FnOnce() -> R) -> R {
|
||||
let _running = self.enter();
|
||||
submit()
|
||||
}
|
||||
|
||||
fn enter(&self) -> Running<'_> {
|
||||
let mut s = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if !s.open && std::thread::current().id() != self.owner {
|
||||
self.waits.fetch_add(1, Ordering::Relaxed);
|
||||
let until = Instant::now() + SUBMIT_WAIT;
|
||||
while !s.open {
|
||||
// Not under the lock: the wake belongs to the window system.
|
||||
drop(s);
|
||||
(self.wake)();
|
||||
s = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if s.open {
|
||||
break;
|
||||
}
|
||||
let Some(left) = until.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()) else {
|
||||
self.timeouts.fetch_add(1, Ordering::Relaxed);
|
||||
break;
|
||||
};
|
||||
// Woken when the gate opens; asks again now and then in case a wake was lost.
|
||||
s = self.changed.wait_timeout(s, left.min(Duration::from_millis(50))).unwrap_or_else(PoisonError::into_inner).0;
|
||||
}
|
||||
}
|
||||
s.running = s.running.saturating_add(1);
|
||||
Running(self)
|
||||
}
|
||||
|
||||
/// Submissions that had to wait for the gate, and those that gave up waiting and went
|
||||
/// ahead (for the log).
|
||||
pub fn waited(&self) -> (u64, u64) {
|
||||
(self.waits.load(Ordering::Relaxed), self.timeouts.load(Ordering::Relaxed))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
/// The race itself, without a GPU: an owner that "reconfigures" between frames (it checks
|
||||
/// that nothing is submitting, as wgpu does) while four threads submit as fast as they can.
|
||||
/// Through the gate no submission ever overlaps a reconfiguration; and the test's own
|
||||
/// detector does see overlaps without it.
|
||||
#[test]
|
||||
fn nothing_is_submitted_while_the_gate_is_closed() {
|
||||
fn run(gated: bool) -> (u64, u64) {
|
||||
let frames = Arc::new(AtomicU64::new(0));
|
||||
let gate = Arc::new(SubmitGate::new(|| {}));
|
||||
let submitting = Arc::new(AtomicU64::new(0));
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let done = Arc::new(AtomicU64::new(0));
|
||||
let workers: Vec<_> = (0..4)
|
||||
.map(|_| {
|
||||
let (gate, submitting, stop, done) = (gate.clone(), submitting.clone(), stop.clone(), done.clone());
|
||||
std::thread::spawn(move || {
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
let submit = || {
|
||||
submitting.fetch_add(1, Ordering::SeqCst);
|
||||
// A moment's work, without the sleep's coarse clock.
|
||||
let t = Instant::now();
|
||||
while t.elapsed() < Duration::from_micros(20) {
|
||||
std::hint::spin_loop();
|
||||
}
|
||||
submitting.fetch_sub(1, Ordering::SeqCst);
|
||||
};
|
||||
if gated { gate.run(submit) } else { submit() }
|
||||
done.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut overlaps = 0;
|
||||
let until = Instant::now() + Duration::from_millis(300);
|
||||
while Instant::now() < until {
|
||||
// A frame: the gate is open for a moment.
|
||||
gate.open();
|
||||
std::thread::sleep(Duration::from_micros(200));
|
||||
assert!(gate.close(), "submissions under way end at once");
|
||||
// Between frames: the surface is reconfigured.
|
||||
for _ in 0..200 {
|
||||
overlaps += submitting.load(Ordering::SeqCst);
|
||||
}
|
||||
frames.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
gate.open();
|
||||
for w in workers {
|
||||
let _ = w.join();
|
||||
}
|
||||
(overlaps, done.load(Ordering::Relaxed))
|
||||
}
|
||||
let (overlaps, done) = run(true);
|
||||
assert_eq!(overlaps, 0, "a submission ran while the gate was closed");
|
||||
assert!(done > 100, "work still gets through: {done}");
|
||||
let (overlaps, _) = run(false);
|
||||
assert!(overlaps > 0, "the detector sees the race without the gate");
|
||||
}
|
||||
|
||||
/// A closed gate asks its owner for a frame, and the submission runs when that frame opens it.
|
||||
#[test]
|
||||
fn a_waiting_submission_asks_for_a_frame_and_runs_when_it_comes() {
|
||||
let asked = Arc::new(AtomicU64::new(0));
|
||||
let a = asked.clone();
|
||||
let gate = Arc::new(SubmitGate::new(move || {
|
||||
a.fetch_add(1, Ordering::SeqCst);
|
||||
}));
|
||||
let g = gate.clone();
|
||||
let t = Instant::now();
|
||||
let worker = std::thread::spawn(move || g.run(|| 7));
|
||||
while asked.load(Ordering::SeqCst) == 0 {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
gate.open();
|
||||
assert_eq!(worker.join().ok(), Some(7));
|
||||
assert!(t.elapsed() < SUBMIT_WAIT, "it didn't wait the timeout out");
|
||||
assert_eq!(gate.waited(), (1, 0));
|
||||
}
|
||||
|
||||
/// Nothing waits for ever: a window that draws no frames lets work through after
|
||||
/// [`SUBMIT_WAIT`]; the owner's own submissions never wait; and a submission that panics
|
||||
/// doesn't hold the gate.
|
||||
#[test]
|
||||
fn nothing_waits_for_ever() {
|
||||
let gate = Arc::new(SubmitGate::new(|| {}));
|
||||
// The owner (this thread), gate closed: at once.
|
||||
let t = Instant::now();
|
||||
assert_eq!(gate.run(|| 1), 1);
|
||||
assert!(t.elapsed() < SUBMIT_WAIT / 2);
|
||||
assert_eq!(gate.waited(), (0, 0));
|
||||
// Another thread, and no frame comes.
|
||||
let g = gate.clone();
|
||||
let t = Instant::now();
|
||||
assert_eq!(std::thread::spawn(move || g.run(|| 2)).join().ok(), Some(2));
|
||||
assert!(t.elapsed() >= SUBMIT_WAIT);
|
||||
assert_eq!(gate.waited(), (1, 1));
|
||||
// A panic inside a submission: counted out, so closing doesn't wait for it.
|
||||
gate.open();
|
||||
let g = gate.clone();
|
||||
assert!(std::thread::spawn(move || g.run(|| panic!("the driver said no"))).join().is_err());
|
||||
let t = Instant::now();
|
||||
assert!(gate.close());
|
||||
assert!(t.elapsed() < CLOSE_WAIT);
|
||||
// A submission that takes too long doesn't hold the owner's frame up for long.
|
||||
gate.open();
|
||||
let g = gate.clone();
|
||||
let slow = std::thread::spawn(move || g.run(|| std::thread::sleep(CLOSE_WAIT * 3)));
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
let t = Instant::now();
|
||||
assert!(!gate.close(), "it says the queue isn't left alone");
|
||||
assert!(t.elapsed() < CLOSE_WAIT * 2);
|
||||
let _ = slow.join();
|
||||
}
|
||||
}
|
||||
+46
-8
@@ -23,10 +23,13 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod binning;
|
||||
mod gate;
|
||||
pub mod gpu_binning;
|
||||
pub mod images;
|
||||
mod layers;
|
||||
|
||||
pub use gate::{CLOSE_WAIT, SUBMIT_WAIT, SubmitGate};
|
||||
|
||||
use anicraft_doc::DisplayList;
|
||||
use anicraft_render::{MAX_PIXELS, NeedsFull, Pixmap, RenderStats, View, paint::premultiply, prepare_scene};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -205,11 +208,21 @@ pub struct GpuRenderer {
|
||||
pub adapter: String,
|
||||
/// Whether the device is the window's (frames go to textures the window shows).
|
||||
pub shared: bool,
|
||||
/// When work may be submitted on the window's device ([`SubmitGate`], ADR 0105).
|
||||
gate: Option<Arc<SubmitGate>>,
|
||||
/// First device failure (an error in a render, an uncaptured error or the device's loss).
|
||||
/// Once set, the renderer refuses to draw and callers fall back to the CPU.
|
||||
broken: Arc<Mutex<Option<String>>>,
|
||||
}
|
||||
|
||||
/// Whose device a renderer draws on.
|
||||
enum Home {
|
||||
/// A headless device of its own.
|
||||
Own,
|
||||
/// The window's, with the gate its work is submitted through, if the window has one.
|
||||
Window(Option<Arc<SubmitGate>>),
|
||||
}
|
||||
|
||||
/// Checks an adapter and device can run the stage; the device's own limits are what count
|
||||
/// (a window's device may have asked for less than its adapter has).
|
||||
fn check(adapter: &wgpu::Adapter, limits: &wgpu::Limits, name: &str) -> Result<(), GpuError> {
|
||||
@@ -301,6 +314,18 @@ impl GpuRenderer {
|
||||
/// window's error handling stays as it was. `Err` means "use a device of our own, or the
|
||||
/// CPU".
|
||||
pub fn shared(adapter: &wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue) -> Result<GpuRenderer, GpuError> {
|
||||
Self::on_window(adapter, device, queue, None)
|
||||
}
|
||||
|
||||
/// [`GpuRenderer::shared`] for a window that reconfigures its surface while the renderer
|
||||
/// draws on other threads, which is every window: all its work, the starting self-test
|
||||
/// included, is submitted through `gate`, which the window's thread opens for its frames
|
||||
/// (ADR 0105).
|
||||
pub fn shared_gated(adapter: &wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue, gate: Arc<SubmitGate>) -> Result<GpuRenderer, GpuError> {
|
||||
Self::on_window(adapter, device, queue, Some(gate))
|
||||
}
|
||||
|
||||
fn on_window(adapter: &wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue, gate: Option<Arc<SubmitGate>>) -> Result<GpuRenderer, GpuError> {
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
let info = adapter.get_info();
|
||||
let name = format!("{} ({:?})", info.name, info.backend);
|
||||
@@ -309,7 +334,7 @@ impl GpuRenderer {
|
||||
}
|
||||
let limits = device.limits();
|
||||
check(adapter, &limits, &name)?;
|
||||
Self::build(device, queue, limits, name, info.backend, true, Arc::new(Mutex::new(None)))
|
||||
Self::build(device, queue, limits, name, info.backend, Home::Window(gate), Arc::new(Mutex::new(None)))
|
||||
}))
|
||||
.unwrap_or_else(|_| Err(GpuError::Unavailable("the GPU driver failed while starting".into())))
|
||||
}
|
||||
@@ -347,10 +372,10 @@ impl GpuRenderer {
|
||||
g.get_or_insert_with(|| format!("device lost: {msg}"));
|
||||
});
|
||||
}
|
||||
Self::build(device, queue, want, name, info.backend, false, broken)
|
||||
Self::build(device, queue, want, name, info.backend, Home::Own, broken)
|
||||
}
|
||||
|
||||
fn build(device: wgpu::Device, queue: wgpu::Queue, limits: wgpu::Limits, name: String, backend: wgpu::Backend, shared: bool, broken: Arc<Mutex<Option<String>>>) -> Result<GpuRenderer, GpuError> {
|
||||
fn build(device: wgpu::Device, queue: wgpu::Queue, limits: wgpu::Limits, name: String, backend: wgpu::Backend, home: Home, broken: Arc<Mutex<Option<String>>>) -> Result<GpuRenderer, GpuError> {
|
||||
let scopes = Scopes::push(&device);
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("anicraft-fine"), source: wgpu::ShaderSource::Wgsl(include_str!("fine.wgsl").into()) });
|
||||
let entry = |binding: u32, ty: wgpu::BindingType| wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::COMPUTE, ty, count: None };
|
||||
@@ -414,7 +439,11 @@ impl GpuRenderer {
|
||||
images: Mutex::new(images::Images::default()),
|
||||
limits,
|
||||
adapter: name,
|
||||
shared,
|
||||
shared: matches!(home, Home::Window(_)),
|
||||
gate: match home {
|
||||
Home::Window(gate) => gate,
|
||||
Home::Own => None,
|
||||
},
|
||||
broken,
|
||||
};
|
||||
r.self_test()?;
|
||||
@@ -576,7 +605,7 @@ impl GpuRenderer {
|
||||
let _ = self.pop(scopes);
|
||||
return Err(e);
|
||||
}
|
||||
self.queue.submit([enc.finish()]);
|
||||
self.submit(enc.finish());
|
||||
self.pop(scopes)?;
|
||||
timings.gpu = ms(t);
|
||||
Ok(GpuTexture { texture, view: tex_view, width: w, height: h, stats, timings, entries: cost.entries, pieces: cost.pieces, gpu_binned: job.binned.gpu.is_some() })
|
||||
@@ -596,7 +625,7 @@ impl GpuRenderer {
|
||||
wgpu::TexelCopyBufferInfo { buffer: &read, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row), rows_per_image: Some(t.height) } },
|
||||
wgpu::Extent3d { width: t.width, height: t.height, depth_or_array_layers: 1 },
|
||||
);
|
||||
self.queue.submit([enc.finish()]);
|
||||
self.submit(enc.finish());
|
||||
let bytes = self.map(&read, scopes)?;
|
||||
let mut out = Vec::with_capacity(t.width as usize * t.height as usize * 4);
|
||||
for r in bytes.chunks(row as usize) {
|
||||
@@ -606,6 +635,15 @@ impl GpuRenderer {
|
||||
})
|
||||
}
|
||||
|
||||
/// Hands finished commands to the queue: on a window's device only while its gate is open
|
||||
/// (a window can't reconfigure its surface while work is being submitted, ADR 0105).
|
||||
fn submit(&self, commands: wgpu::CommandBuffer) {
|
||||
match &self.gate {
|
||||
Some(gate) => gate.run(|| self.queue.submit([commands])),
|
||||
None => self.queue.submit([commands]),
|
||||
};
|
||||
}
|
||||
|
||||
/// Blocks until everything submitted so far has run (benchmarks).
|
||||
pub fn wait_idle(&self) -> Result<(), GpuError> {
|
||||
self.device.poll(wgpu::PollType::wait_indefinitely()).map(|_| ()).map_err(|e| GpuError::Device(e.to_string()))
|
||||
@@ -821,7 +859,7 @@ impl GpuRenderer {
|
||||
return Err(e);
|
||||
}
|
||||
enc.copy_buffer_to_buffer(&obuf, 0, &read, 0, out_bytes);
|
||||
self.queue.submit([enc.finish()]);
|
||||
self.submit(enc.finish());
|
||||
let bytes = self.map(&read, scopes)?;
|
||||
Ok(match output {
|
||||
Output::Premul8 => (bytes, None),
|
||||
@@ -852,7 +890,7 @@ impl GpuRenderer {
|
||||
let read = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("readback"), size: isize + gsize, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
|
||||
enc.copy_buffer_to_buffer(&ibuf, 0, &read, 0, isize);
|
||||
enc.copy_buffer_to_buffer(&gbuf, 0, &read, isize, gsize);
|
||||
self.queue.submit([enc.finish()]);
|
||||
self.submit(enc.finish());
|
||||
let bytes = self.map(&read, scopes)?;
|
||||
let words: Vec<u32> = bytes.as_chunks::<4>().0.iter().map(|w| u32::from_le_bytes(*w)).collect();
|
||||
let n = isize as usize / 4;
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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
@@ -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]
|
||||
|
||||
@@ -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));
|
||||
|
||||
Reference in new issue
Block a user