* claim: #7521 * fix: headless pictures return their draw counts with the picture `the_renderer_counts_what_it_draws` drew with `Capturer::rgba` and then read `Capturer::last_stats()`. The capturer is shared with the binary's other tests, which draw on it from parallel threads, so another picture could land between the two calls and the test read its counts (e.g. 10224 triangles for the empty design). `Capturer::rgba_with_stats` returns the picture and its counts, read while the call still holds the device. `last_stats()` is removed; this test was its only caller (the performance overlay reads the viewport renderer's own stats handle). New test `pictures_drawn_at_once_each_count_their_own` draws empty and box designs from eight threads on the shared capturer. Against the old pair it failed 25 of 40 full runs of the `capture` binary; it passes with the new call. * fix: a headless picture waits for its read-back's answer A picture maps its read-back buffer, waits for its submission with `device.poll(PollType::Wait)`, and then checked once with `try_recv` whether the map callback had run. wgpu calls a finished mapping's callback from whichever thread next maintains the device, in a poll or in any `queue.submit`, after it lets go of the device. When another thread got there first, the wait returned with the mapping done but its callback not yet called, and the picture failed with "not supported yet: reading a picture back without waiting for the browser", the error meant for a browser. On the shared capturer, the other thread is another picture's device check (`probe_lost` submits nothing before it takes the capturer's lock), so the `capture` tests failed now and then: `bad_picture_sizes_are_errors` (its last 8 x 8 picture), `pictures_show_a_plain_cut_without_the_hatch`, `pictures_blend_a_line_that_is_not_opaque`. In the app, the window's frames are submitted on the device its thumbnails and `ui.render` pictures are drawn on. A native picture now waits for the answer, up to the picture timeout; a browser still answers later, on its own. New test `pictures_read_back_while_another_thread_uses_the_device`: 2,000 small pictures while another thread polls their device. Without the fix it failed 19 of 20 runs (1 to 7 pictures each); with it, 150 of 150 runs pass. `bad_picture_sizes_are_errors` now prints the error it gets.
This commit is contained in:
2 files changed
+96
-16
No files matched your search
+28
-13
@@ -15,7 +15,7 @@ use solidcraft_geom::Vec3;
|
||||
use solidcraft_render::{AnalysisMode, Camera, Rgb, SECTION_CAP, Scene};
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
use crate::view::{AccessMap, Frame, GpuScene, GpuTarget, Renderer, analysis_colors, analysis_uniform};
|
||||
use crate::view::{AccessMap, DrawStats, Frame, GpuScene, GpuTarget, Renderer, analysis_colors, analysis_uniform};
|
||||
use crate::{GpuError, Result, caught, error_scopes};
|
||||
|
||||
/// The colour format pictures are drawn in: sRGB bytes as they are, like the viewport's usual
|
||||
@@ -176,6 +176,17 @@ impl Capturer {
|
||||
/// [`Capturer::rgba`] with `highlight` drawn as the viewport draws its highlight scene
|
||||
/// (selection and hover feedback), over the model scene.
|
||||
pub fn rgba_highlighted(&self, scene: &Scene, highlight: Option<GpuScene>, cam: &Camera, width: u32, height: u32) -> Result<Vec<u8>> {
|
||||
self.draw(scene, highlight, cam, width, height).map(|(rgba, _)| rgba)
|
||||
}
|
||||
|
||||
/// [`Capturer::rgba`] and what the picture drew ([`DrawStats`]). Both come from the same
|
||||
/// turn on the device, so another thread's picture can't put its counts in their place.
|
||||
pub fn rgba_with_stats(&self, scene: &Scene, cam: &Camera, width: u32, height: u32) -> Result<(Vec<u8>, DrawStats)> {
|
||||
self.draw(scene, None, cam, width, height)
|
||||
}
|
||||
|
||||
/// The picture and what it drew, both read while this call has the device to itself.
|
||||
fn draw(&self, scene: &Scene, highlight: Option<GpuScene>, cam: &Camera, width: u32, height: u32) -> Result<(Vec<u8>, DrawStats)> {
|
||||
if !(1..=self.max_side).contains(&width) || !(1..=self.max_side).contains(&height) {
|
||||
return Err(GpuError::Render(format!("a picture is 1 to {} pixels a side, not {width} × {height}", self.max_side)));
|
||||
}
|
||||
@@ -288,11 +299,7 @@ impl Capturer {
|
||||
device
|
||||
.poll(wgpu::PollType::Wait { submission_index: Some(submission), timeout: Some(TIMEOUT) })
|
||||
.map_err(|e| GpuError::Render(format!("waiting for the picture: {e}")))?;
|
||||
match rx.try_recv() {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(e)) => return Err(GpuError::Render(format!("reading the picture back: {e}"))),
|
||||
Err(_) => return Err(GpuError::Unsupported("reading a picture back without waiting for the browser".into())),
|
||||
}
|
||||
read_back(&rx)?;
|
||||
let data = slice.get_mapped_range().map_err(|e| GpuError::Render(format!("reading the picture back: {e}")))?;
|
||||
let mut rgba = Vec::with_capacity((row as usize) * (height as usize));
|
||||
for r in data.chunks(padded as usize).take(height as usize) {
|
||||
@@ -301,13 +308,8 @@ impl Capturer {
|
||||
if rgba.len() != (row as usize) * (height as usize) {
|
||||
return Err(GpuError::Render("the picture read back short".into()));
|
||||
}
|
||||
Ok(rgba)
|
||||
}
|
||||
|
||||
/// What the last picture drew ([`crate::view::DrawStats`]).
|
||||
pub fn last_stats(&self) -> crate::view::DrawStats {
|
||||
let Ok(state) = self.state.lock() else { return Default::default() };
|
||||
state.renderer.stats().lock().map(|s| *s).unwrap_or_default()
|
||||
let stats = state.renderer.stats().lock().map(|s| *s).unwrap_or_default();
|
||||
Ok((rgba, stats))
|
||||
}
|
||||
|
||||
/// [`Capturer::rgba`] as PNG bytes.
|
||||
@@ -464,6 +466,19 @@ fn watch_lost(device: &wgpu::Device) -> Arc<AtomicBool> {
|
||||
lost
|
||||
}
|
||||
|
||||
/// The answer to a picture's read-back, once the wait for its submission is over. The read-back
|
||||
/// is ready by then, but its answer may still be on its way: any other submit or poll on the
|
||||
/// device (the window's frames, another picture's device check) can pick it up and answer it on
|
||||
/// its own thread once it lets go of the device. So a native picture waits for the answer; a
|
||||
/// browser answers later, on its own, and a picture can't wait for it there.
|
||||
fn read_back(answer: &std::sync::mpsc::Receiver<std::result::Result<(), wgpu::BufferAsyncError>>) -> Result<()> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let answer = answer.recv_timeout(TIMEOUT).map_err(|e| GpuError::Render(format!("reading the picture back: {e}")))?;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let answer = answer.try_recv().map_err(|_| GpuError::Unsupported("reading a picture back without waiting for the browser".into()))?;
|
||||
answer.map_err(|e| GpuError::Render(format!("reading the picture back: {e}")))
|
||||
}
|
||||
|
||||
/// The background gradient: the viewport's top colour at the top, its bottom one at the bottom,
|
||||
/// mixed in sRGB as the window paints it.
|
||||
const BACKGROUND_SHADER: &str = r#"
|
||||
|
||||
@@ -105,8 +105,8 @@ fn the_renderer_counts_what_it_draws() {
|
||||
let cam = view::home_camera(s);
|
||||
let scene = view::scene_with_guides(s, &cam, None, Guides { grid: false, axes: false });
|
||||
let triangles: usize = scene.meshes.iter().map(|m| m.mesh.triangles.len()).sum();
|
||||
c.rgba(&scene, &cam, 160, 100).unwrap();
|
||||
(c.last_stats(), triangles as u64)
|
||||
let (_, stats) = c.rgba_with_stats(&scene, &cam, 160, 100).unwrap();
|
||||
(stats, triangles as u64)
|
||||
};
|
||||
let (empty, _) = drawn(&Session::default());
|
||||
assert_eq!((empty.triangles, empty.line_segments), (0, 0), "{empty:?}");
|
||||
@@ -121,6 +121,32 @@ fn the_renderer_counts_what_it_draws() {
|
||||
assert!(two.line_segments > one.line_segments, "{two:?}");
|
||||
}
|
||||
|
||||
/// Each picture's counts are its own while other threads draw on the same capturer: an empty
|
||||
/// design never reports another thread's box, and a box never reports an empty design's
|
||||
/// nothing. The counts were once read in a second call after the picture, and another thread's
|
||||
/// picture could land in between.
|
||||
#[test]
|
||||
fn pictures_drawn_at_once_each_count_their_own() {
|
||||
let Some(c) = capturer() else { return };
|
||||
let scene = |s: &Session| {
|
||||
let cam = view::home_camera(s);
|
||||
(view::scene_with_guides(s, &cam, None, Guides { grid: false, axes: false }), cam)
|
||||
};
|
||||
let empty = scene(&Session::default());
|
||||
let solid = scene(&session(&[("solid.box", json!({"length": 40, "width": 30, "height": 20}))]));
|
||||
std::thread::scope(|t| {
|
||||
for k in 0..8 {
|
||||
let (name, (sc, cam), drawn) = if k % 2 == 0 { ("empty", &empty, false) } else { ("box", &solid, true) };
|
||||
t.spawn(move || {
|
||||
for i in 0..50 {
|
||||
let (_, stats) = c.rgba_with_stats(sc, cam, 64, 48).unwrap();
|
||||
assert_eq!(stats.triangles > 0, drawn, "{name}, picture {i}: {stats:?}");
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The ground grid and the origin's axes each change the picture.
|
||||
#[test]
|
||||
fn guides_change_the_picture() {
|
||||
@@ -318,5 +344,44 @@ fn bad_picture_sizes_are_errors() {
|
||||
assert!(c.rgba(&sc, &Camera::default(), w, h).is_err(), "{w} x {h}");
|
||||
}
|
||||
// And the device still draws.
|
||||
assert!(c.rgba(&sc, &Camera::default(), 8, 8).is_ok());
|
||||
let drawn = c.rgba(&sc, &Camera::default(), 8, 8);
|
||||
assert!(drawn.is_ok(), "{:?}", drawn.err());
|
||||
}
|
||||
|
||||
/// Pictures read back while another thread uses their device: the app's window submits its
|
||||
/// frames on the device its thumbnails and `ui.render` pictures are drawn on, and on the shared
|
||||
/// capturer every picture checks its device while another one reads back. Any submit or poll can
|
||||
/// take a picture's finished read-back and answer it on its own thread a moment after the
|
||||
/// picture's wait is over; the picture used to give up then ("reading a picture back without
|
||||
/// waiting for the browser", now and then in this binary's other tests).
|
||||
#[test]
|
||||
fn pictures_read_back_while_another_thread_uses_the_device() {
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
let policy = solidcraft_gpu::select::Policy::from_env().unwrap();
|
||||
let Some((adapter, _)) = solidcraft_gpu::select::pick(policy) else {
|
||||
assert!(std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "no GPU adapter under the {} policy", policy.name());
|
||||
eprintln!("skipping: no GPU adapter under the {} policy", policy.name());
|
||||
return;
|
||||
};
|
||||
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
|
||||
required_features: solidcraft_gpu::depth_features(&adapter),
|
||||
required_limits: wgpu::Limits::downlevel_defaults().using_resolution(adapter.limits()),
|
||||
..Default::default()
|
||||
}))
|
||||
.unwrap();
|
||||
let c = Capturer::new(&adapter, device.clone(), queue).unwrap();
|
||||
let sc = solidcraft_engine::render::Scene::default();
|
||||
const PICTURES: usize = 2000;
|
||||
let done = AtomicBool::new(false);
|
||||
let failed: Vec<String> = std::thread::scope(|t| {
|
||||
t.spawn(|| {
|
||||
while !done.load(Ordering::Relaxed) {
|
||||
let _ = device.poll(wgpu::PollType::Poll);
|
||||
}
|
||||
});
|
||||
let failed = (0..PICTURES).filter_map(|i| c.rgba(&sc, &Camera::default(), 8, 8).err().map(|e| format!("picture {i}: {e}"))).collect();
|
||||
done.store(true, Ordering::Relaxed);
|
||||
failed
|
||||
});
|
||||
assert!(failed.is_empty(), "{} of {PICTURES} pictures failed, the first: {:?}", failed.len(), failed.first());
|
||||
}
|
||||
Reference in new issue
Block a user