Skip to content

Commit f69f956

Browse files
committed
GPU-FULL: merge pr/gpu-full (PR storytold#1065: headless screenshots read back GPU-drawn views; LIGHTCRAFT_GPU_LIMITS caps the adopted device)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> # Conflicts: # Cargo.lock # crates/catalog/src/store.rs # crates/ui-egui/src/panels/detail.rs # crates/ui-egui/src/render.rs # crates/ui-egui/src/tests_folder_drop.rs
2 parents 3fd277d + 19ba7ac commit f69f956

8 files changed

Lines changed: 275 additions & 44 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎apps/lightcraft/src/main.rs‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ struct App(LightcraftApp, PrefsWriter, Option<WindowTextures>, #[cfg(target_os =
6363
/// renderer (the GPU renderer runs on the window's device, see [`adopt_window_device`]).
6464
struct WindowTextures {
6565
device: eframe::wgpu::Device,
66+
queue: eframe::wgpu::Queue,
6667
renderer: std::sync::Arc<egui::mutex::RwLock<eframe::egui_wgpu::Renderer>>,
6768
}
6869

@@ -83,6 +84,16 @@ impl lightcraft_ui_egui::render::ScreenTextures for WindowTextures {
8384
fn free(&mut self, id: egui::TextureId) {
8485
self.renderer.write().free_texture(&id);
8586
}
87+
88+
fn read(&self, frame: &lightcraft_engine::media::ScreenFrame) -> Option<egui::ColorImage> {
89+
match lightcraft_engine::gpu::read_texture(&self.device, &self.queue, &frame.texture, frame.width, frame.height) {
90+
Ok(img) => Some(egui::ColorImage::from_rgba_unmultiplied([img.width, img.height], img.data.as_flattened())),
91+
Err(e) => {
92+
log::warn!("gpu: a view can't be read back for the screenshot: {e}");
93+
None
94+
}
95+
}
96+
}
8697
}
8798

8899
/// Render on the window's device (off the UI thread: building the kernels takes a moment), so the
@@ -102,7 +113,7 @@ fn adopt_window_device(rs: &eframe::egui_wgpu::RenderState, ctx: &egui::Context)
102113
if let Err(e) = spawned {
103114
log::warn!("gpu: {e}");
104115
}
105-
WindowTextures { device: rs.device.clone(), renderer: rs.renderer.clone() }
116+
WindowTextures { device: rs.device.clone(), queue: rs.queue.clone(), renderer: rs.renderer.clone() }
106117
}
107118

108119
impl eframe::App for App {

‎crates/gpu/src/ctx.rs‎

Lines changed: 136 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -344,11 +344,7 @@ impl Gpu {
344344
log::info!("gpu: {} has too few storage buffers per stage", info.name);
345345
return Err(format!("{} has too few storage buffers per shader stage ({} < 10)", info.name, limits.max_storage_buffers_per_shader_stage));
346346
}
347-
if let Some((binding, buffer)) = limits_override() {
348-
limits.max_storage_buffer_binding_size = limits.max_storage_buffer_binding_size.min(binding);
349-
limits.max_buffer_size = limits.max_buffer_size.min(buffer);
350-
log::info!("gpu: LIGHTCRAFT_GPU_LIMITS: storage bindings ≤ {} MiB, buffers ≤ {} MiB", binding >> 20, buffer >> 20);
351-
}
347+
limits = capped(limits, limits_override());
352348
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
353349
label: Some("lightcraft"),
354350
required_limits: limits.clone(),
@@ -358,6 +354,18 @@ impl Gpu {
358354
Gpu::with_device(device, queue, info, limits, false)
359355
}
360356

357+
/// The renderer on the window's device ([`crate::adopt_window_device`]), within its limits
358+
/// lowered by `LIGHTCRAFT_GPU_LIMITS` as a device of its own would be.
359+
pub fn adopt(device: wgpu::Device, queue: wgpu::Queue, info: wgpu::AdapterInfo) -> Result<Gpu, String> {
360+
Gpu::adopt_capped(device, queue, info, limits_override())
361+
}
362+
363+
/// [`Gpu::adopt`] with the limits override given (`LIGHTCRAFT_GPU_LIMITS`, parsed).
364+
fn adopt_capped(device: wgpu::Device, queue: wgpu::Queue, info: wgpu::AdapterInfo, cap: Option<(u64, u64)>) -> Result<Gpu, String> {
365+
let limits = capped(device.limits(), cap);
366+
Gpu::with_device(device, queue, info, limits, true)
367+
}
368+
361369
/// The renderer on an existing device: the window's (`window`, see [`crate::adopt_window_device`])
362370
/// or one [`Gpu::new`] created with `limits`. Builds the kernels (~0.4–2 s: not on the UI thread).
363371
pub fn with_device(device: wgpu::Device, queue: wgpu::Queue, info: wgpu::AdapterInfo, limits: wgpu::Limits, window: bool) -> Result<Gpu, String> {
@@ -645,6 +653,81 @@ fn limits_override() -> Option<(u64, u64)> {
645653
parse_limits(&std::env::var("LIGHTCRAFT_GPU_LIMITS").ok()?)
646654
}
647655

656+
/// `limits` lowered to `cap` ([`limits_override`]: storage binding bytes, buffer bytes).
657+
fn capped(mut limits: wgpu::Limits, cap: Option<(u64, u64)>) -> wgpu::Limits {
658+
if let Some((binding, buffer)) = cap {
659+
limits.max_storage_buffer_binding_size = limits.max_storage_buffer_binding_size.min(binding);
660+
limits.max_buffer_size = limits.max_buffer_size.min(buffer);
661+
log::info!("gpu: LIGHTCRAFT_GPU_LIMITS: storage bindings ≤ {} MiB, buffers ≤ {} MiB", binding >> 20, buffer >> 20);
662+
}
663+
limits
664+
}
665+
666+
/// See [`crate::read_texture`].
667+
pub(crate) fn read_texture(
668+
device: &wgpu::Device,
669+
queue: &wgpu::Queue,
670+
texture: &wgpu::Texture,
671+
width: usize,
672+
height: usize,
673+
) -> Result<lightcraft_raster::Rgba8, String> {
674+
if width == 0 || height == 0 {
675+
return Err("an empty texture".into());
676+
}
677+
let (Ok(w32), Ok(h32)) = (u32::try_from(width), u32::try_from(height)) else { return Err("texture too large".into()) };
678+
if w32 > texture.width() || h32 > texture.height() || texture.format() != wgpu::TextureFormat::Rgba8Unorm {
679+
return Err("not an 8-bit view texture of that size".into());
680+
}
681+
// texture copies take rows of a multiple of 256 bytes
682+
let stride = width.checked_mul(4).ok_or("texture too large")?.next_multiple_of(256);
683+
let size = stride.checked_mul(height).ok_or("texture too large")?;
684+
let (Ok(stride32), Ok(size64)) = (u32::try_from(stride), u64::try_from(size)) else { return Err("texture too large".into()) };
685+
let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
686+
let staging = device.create_buffer(&wgpu::BufferDescriptor {
687+
label: Some("view readback"),
688+
size: size64,
689+
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
690+
mapped_at_creation: false,
691+
});
692+
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("view readback") });
693+
enc.copy_texture_to_buffer(
694+
wgpu::TexelCopyTextureInfo { texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
695+
wgpu::TexelCopyBufferInfo {
696+
buffer: &staging,
697+
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(stride32), rows_per_image: Some(h32) },
698+
},
699+
wgpu::Extent3d { width: w32, height: h32, depth_or_array_layers: 1 },
700+
);
701+
queue.submit([enc.finish()]);
702+
if let Some(e) = pollster::block_on(scope.pop()) {
703+
return Err(format!("texture copy failed: {e}"));
704+
}
705+
let slice = staging.slice(..);
706+
let (tx, rx) = std::sync::mpsc::channel();
707+
slice.map_async(wgpu::MapMode::Read, move |r| {
708+
let _ = tx.send(r);
709+
});
710+
let wait = std::time::Duration::from_secs(10);
711+
device.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(wait) }).map_err(|e| format!("{e}"))?;
712+
match rx.recv_timeout(wait) {
713+
Ok(Ok(())) => {}
714+
Ok(Err(e)) => return Err(format!("{e}")),
715+
Err(e) => return Err(format!("map callback: {e}")),
716+
}
717+
let bytes = slice.get_mapped_range().map_err(|e| format!("{e:?}"))?;
718+
let mut data = Vec::with_capacity(width * height);
719+
for row in bytes.chunks(stride).take(height) {
720+
let row = row.get(..width * 4).ok_or("short readback row")?;
721+
data.extend(row.as_chunks::<4>().0.iter().copied());
722+
}
723+
drop(bytes);
724+
staging.unmap();
725+
if data.len() != width * height {
726+
return Err("incomplete readback".into());
727+
}
728+
Ok(lightcraft_raster::Rgba8 { width, height, data })
729+
}
730+
648731
fn parse_limits(v: &str) -> Option<(u64, u64)> {
649732
let v = v.trim().to_ascii_lowercase();
650733
match v.as_str() {
@@ -788,6 +871,54 @@ mod tests {
788871
assert_eq!(super::parse_limits("lots"), None);
789872
}
790873

874+
/// `LIGHTCRAFT_GPU_LIMITS` caps the window's device as it caps a device of its own (review of
875+
/// PR #1065: adopting the window's device skipped it, so a 1024 × 1024 RGB float buffer — 12 MiB —
876+
/// was taken under an 8 MiB cap).
877+
#[test]
878+
fn the_limits_override_caps_an_adopted_device() {
879+
let big = wgpu::Limits { max_storage_buffer_binding_size: 1 << 30, max_buffer_size: 1 << 31, ..wgpu::Limits::default() };
880+
let c = super::capped(big.clone(), super::parse_limits("8"));
881+
assert_eq!((c.max_storage_buffer_binding_size, c.max_buffer_size), (8 << 20, 16 << 20));
882+
let c = super::capped(big.clone(), None);
883+
assert_eq!((c.max_storage_buffer_binding_size, c.max_buffer_size), (1 << 30, 1 << 31));
884+
885+
let _lock = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
886+
let Some((device, queue, info)) = test_device() else {
887+
lightcraft_testkit::skip!(Gpu, "no GPU adapter");
888+
return;
889+
};
890+
let full = device.limits().max_storage_buffer_binding_size.min(device.limits().max_buffer_size);
891+
if full <= 12 << 20 {
892+
lightcraft_testkit::skip!(Gpu, "the adapter's buffers are already ≤ 12 MiB");
893+
return;
894+
}
895+
let g = super::Gpu::adopt_capped(device, queue, info, super::parse_limits("8")).expect("kernels build");
896+
assert!(g.window);
897+
assert_eq!(g.limit(), 8 << 20, "the cap applies to the adopted device");
898+
assert!(1024 * 1024 * 3 * 4 > g.limit(), "a 12 MiB buffer is over it");
899+
}
900+
901+
/// A device as eframe makes the window's (the adapter's own limits).
902+
fn test_device() -> Option<(wgpu::Device, wgpu::Queue, wgpu::AdapterInfo)> {
903+
let backends = crate::backend::compute_backends()?;
904+
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
905+
desc.backends = backends;
906+
desc.backend_options = crate::backend::backend_options();
907+
let instance = wgpu::Instance::new(desc);
908+
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?;
909+
let info = adapter.get_info();
910+
if info.device_type == wgpu::DeviceType::Cpu {
911+
return None;
912+
}
913+
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
914+
label: Some("test window"),
915+
required_limits: adapter.limits(),
916+
..Default::default()
917+
}))
918+
.ok()?;
919+
Some((device, queue, info))
920+
}
921+
791922
#[test]
792923
fn dispatches_stay_within_the_workgroup_limit() {
793924
// 1-D kernels over a 100 MP image and 2-D ones over 16k × 16k stay under 65535 per axis

‎crates/gpu/src/lib.rs‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -531,9 +531,8 @@ pub fn adopt_window_device(device: wgpu::Device, queue: wgpu::Queue, info: wgpu:
531531
Err(format!("software adapter ({}) skipped: the CPU pipeline is faster", info.name))
532532
} else {
533533
// (building the kernels is a long call into the driver: the crash sentinel covers it)
534-
let limits = device.limits();
535534
backend::with_init_marker(wgpu::Backends::from(info.backend), || {
536-
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| ctx::Gpu::with_device(device, queue, info, limits, true)))
535+
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| ctx::Gpu::adopt(device, queue, info)))
537536
.unwrap_or_else(|_| Err("kernel setup panicked".into()))
538537
})
539538
};
@@ -554,6 +553,21 @@ pub fn adopt_window_device(device: wgpu::Device, queue: wgpu::Queue, info: wgpu:
554553
}
555554
}
556555

556+
/// The pixels of a texture on `device` (a [`DisplayFrame`]'s, or any `Rgba8Unorm` texture with
557+
/// `COPY_SRC`): for a headless screenshot of a view drawn straight from the GPU, and for tests. The
558+
/// app never needs them to draw. Waits for the GPU (at most a few seconds); `Err` when the copy or
559+
/// the wait fails.
560+
#[cfg(not(target_arch = "wasm32"))]
561+
pub fn read_texture(
562+
device: &wgpu::Device,
563+
queue: &wgpu::Queue,
564+
texture: &wgpu::Texture,
565+
width: usize,
566+
height: usize,
567+
) -> Result<lightcraft_raster::Rgba8, String> {
568+
ctx::read_texture(device, queue, texture, width, height)
569+
}
570+
557571
#[cfg(not(target_arch = "wasm32"))]
558572
fn run(
559573
src: &Arc<Rgb32f>,

‎crates/gpu/tests/display.rs‎

Lines changed: 3 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ use lightcraft_develop::{DevelopSettings, Spot};
99
use lightcraft_geom::Point;
1010
use lightcraft_gpu::{Output, wgpu};
1111
use lightcraft_pipeline::{Overlay, PixelWindow, Quality, RenderRequest, SourceInfo, StageCache};
12-
use lightcraft_raster::Rgba8;
1312

1413
/// A device made the way eframe makes the window's (adapter limits, the window's backends).
1514
fn window_device() -> Option<(wgpu::Device, wgpu::Queue, wgpu::AdapterInfo)> {
@@ -28,43 +27,14 @@ fn window_device() -> Option<(wgpu::Device, wgpu::Queue, wgpu::AdapterInfo)> {
2827
Some((device, queue, info))
2928
}
3029

31-
/// The texture's pixels (test only: the app never reads them back).
32-
fn read_texture(device: &wgpu::Device, queue: &wgpu::Queue, t: &wgpu::Texture, w: usize, h: usize) -> Rgba8 {
33-
let stride = (w * 4).next_multiple_of(256);
34-
let buf = device.create_buffer(&wgpu::BufferDescriptor {
35-
label: None,
36-
size: (stride * h) as u64,
37-
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
38-
mapped_at_creation: false,
39-
});
40-
let mut enc = device.create_command_encoder(&Default::default());
41-
enc.copy_texture_to_buffer(
42-
wgpu::TexelCopyTextureInfo { texture: t, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
43-
wgpu::TexelCopyBufferInfo {
44-
buffer: &buf,
45-
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(stride as u32), rows_per_image: Some(h as u32) },
46-
},
47-
wgpu::Extent3d { width: w as u32, height: h as u32, depth_or_array_layers: 1 },
48-
);
49-
queue.submit([enc.finish()]);
50-
buf.slice(..).map_async(wgpu::MapMode::Read, |_| {});
51-
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
52-
let bytes = buf.slice(..).get_mapped_range().unwrap().to_vec();
53-
let data = (0..h).flat_map(|y| (0..w).map(move |x| (y, x))).map(|(y, x)| {
54-
let o = y * stride + x * 4;
55-
[bytes[o], bytes[o + 1], bytes[o + 2], bytes[o + 3]]
56-
});
57-
Rgba8 { width: w, height: h, data: data.collect() }
58-
}
59-
6030
#[test]
6131
fn display_renders_match_readback_renders() {
6232
let Some((device, queue, info)) = window_device() else {
63-
eprintln!("skipped: no GPU adapter");
33+
lightcraft_testkit::skip!(Gpu, "no GPU adapter");
6434
return;
6535
};
6636
if info.device_type == wgpu::DeviceType::Cpu {
67-
eprintln!("skipped: software adapter");
37+
lightcraft_testkit::skip!(Gpu, "software adapter");
6838
return;
6939
}
7040
lightcraft_gpu::adopt_window_device(device.clone(), queue.clone(), info).expect("adopted");
@@ -85,7 +55,7 @@ fn display_renders_match_readback_renders() {
8555
match lightcraft_gpu::render_display(&src, &raw, &s, &req, Some(&stages)).expect("display render") {
8656
Output::Display { frame, histogram } => {
8757
assert_eq!((frame.width, frame.height), (pixels.image.width, pixels.image.height));
88-
let shown = read_texture(&device, &queue, &frame.texture, frame.width, frame.height);
58+
let shown = lightcraft_gpu::read_texture(&device, &queue, &frame.texture, frame.width, frame.height).expect("readback");
8959
assert!(shown.data == pixels.image.data, "{w}×{h}: the texture holds the readback's pixels");
9060
assert_eq!(histogram, pixels.histogram);
9161
}

‎crates/ui-egui/Cargo.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ lightcraft-denoise = { workspace = true, features = ["runtime"] }
3737
lightcraft-codecs = { workspace = true }
3838
lightcraft-faces = { workspace = true }
3939
lightcraft-merge = { workspace = true }
40+
# a device for the GPU-resident view test (`render.rs`)
41+
pollster = { workspace = true }
4042

4143
[build-dependencies]
4244
serde_json = { workspace = true }

0 commit comments

Comments
 (0)