流式显卡合成加速小壹读屏和项目缩略图
This commit is contained in:
parent
498393326d
commit
eeea6e5a5b
@ -366,7 +366,7 @@ fn adopted_review_image(dir: &Path, doc: &Document, mapped: &Value, artifact: &V
|
||||
let area = Rect::new(x.floor() as i32, y.floor() as i32, (x + width).ceil() as i32, (y + height).ceil() as i32);
|
||||
let scale = (f64::from(max_side) / f64::from(area.width().max(area.height()))).min(1.0);
|
||||
let [w, h] = [area.width(), area.height()].map(|size| (f64::from(size) * scale).round().max(1.0) as u32);
|
||||
let image = photocraft_compose::render_reduced_rect(doc, area, w, h).to_rgba8();
|
||||
let image = photocraft_ui_egui::gpu_canvas::background_compose::render(doc, area, w, h).to_rgba8();
|
||||
Ok(egui::ColorImage::from_rgba_unmultiplied([w as usize, h as usize], &image.pixels))
|
||||
}
|
||||
|
||||
|
||||
@ -219,7 +219,7 @@ fn first_screen(doc: &Document) -> R<egui::ColorImage> {
|
||||
let scale = (360.0 / rect.width().max(rect.height()) as f32).min(1.0);
|
||||
let w = (rect.width() as f32 * scale).round().max(1.0) as u32;
|
||||
let h = (rect.height() as f32 * scale).round().max(1.0) as u32;
|
||||
let image = photocraft_compose::render_reduced_rect(doc, rect, w, h).to_rgba8();
|
||||
let image = photocraft_ui_egui::gpu_canvas::background_compose::render(doc, rect, w, h).to_rgba8();
|
||||
Ok(egui::ColorImage::from_rgba_unmultiplied([w as usize, h as usize], &image.pixels))
|
||||
}
|
||||
|
||||
|
||||
@ -37,7 +37,7 @@ impl ScreenReader {
|
||||
pub(super) fn render(native: &Document, area: Rect) -> R<Vec<u8>> {
|
||||
let scale = (1536.0 / f64::from(area.width().max(area.height()))).min(1.0);
|
||||
let [w, h] = [area.width(), area.height()].map(|size| (f64::from(size) * scale).round().max(1.0) as u32);
|
||||
let rendered = photocraft_compose::render_reduced_rect(native, area, w, h);
|
||||
let rendered = photocraft_ui_egui::gpu_canvas::background_compose::render(native, area, w, h);
|
||||
let rgb = rendered
|
||||
.px
|
||||
.into_iter()
|
||||
|
||||
@ -254,7 +254,7 @@ fn screen_rects(doc: &Document) -> R<Vec<Rect>> {
|
||||
fn preview(doc: &Document, rect: Rect) -> R<Vec<u8>> {
|
||||
let width = 720u32.min(rect.width());
|
||||
let height = (rect.height() as u64 * u64::from(width) / rect.width() as u64).max(1) as u32;
|
||||
let image = photocraft_compose::render_reduced_rect(doc, rect, width, height).to_rgba8();
|
||||
let image = photocraft_ui_egui::gpu_canvas::background_compose::render(doc, rect, width, height).to_rgba8();
|
||||
let image = photocraft_codecs::Image::from_u8(width, height, photocraft_codecs::ChannelLayout::Rgba, image.pixels).map_err(|_| "页面预览生成失败")?;
|
||||
photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).map_err(|_| "页面预览编码失败".into())
|
||||
}
|
||||
|
||||
@ -646,6 +646,7 @@ fn main() -> eframe::Result {
|
||||
app.watch_window_device(&rs.device);
|
||||
}
|
||||
}
|
||||
app.install_background_composition();
|
||||
let fallback_reason = std::env::var("PHOTOCRAFT_GPU_STARTUP_FAILURE").ok().or_else(|| {
|
||||
(app.perf.gpu_info.canvas == "cpu" && mode != photocraft_engine::prefs::RenderingMode::Cpu)
|
||||
.then(|| app.perf.gpu_info.fallback.clone())
|
||||
|
||||
@ -48,6 +48,7 @@ mod ctx;
|
||||
mod extents;
|
||||
mod fx_cache;
|
||||
mod reduced;
|
||||
mod reduced_composite;
|
||||
mod render;
|
||||
|
||||
pub use composite::{adjustment_quantum, blend_if_active, occludes_below, text_gamma};
|
||||
@ -72,6 +73,7 @@ pub use fx_cache::{DEFAULT_FX_CACHE_BUDGET, effect_cache_budget, effect_cache_by
|
||||
#[cfg(test)]
|
||||
use fx_cache::{effect_maps, effect_region, fx_region_bytes};
|
||||
pub use reduced::{PROXY_THUMBNAIL_PIXELS, render_reduced, render_reduced_damage, render_reduced_rect, thumbnail, thumbnail_buffer, thumbnail_size};
|
||||
pub use reduced_composite::CompositeReduction;
|
||||
#[cfg(test)]
|
||||
use reduced::{ReducedStats, render_reduced_in_bands, render_reduced_with};
|
||||
use render::in_blend_space;
|
||||
|
||||
@ -107,8 +107,6 @@ pub(crate) fn render_reduced_with(
|
||||
if fw == 0 || fh == 0 {
|
||||
return Buffer::transparent(if damage.is_some() { Rect::EMPTY } else { full });
|
||||
}
|
||||
// Output column / row of each document column / row: output pixel t covers [t·f/n, (t+1)·f/n).
|
||||
let span = |t: usize, f: usize, n: usize| (t * f / n, ((t + 1) * f / n).max(t * f / n + 1).min(f));
|
||||
// The output pixel whose span holds document column / row `x` (spans are contiguous: n <= f).
|
||||
let cell = |x: usize, f: usize, n: usize| ((x + 1) * n).saturating_sub(1) / f;
|
||||
// Output pixels to produce and the document area they cover.
|
||||
@ -298,3 +296,8 @@ pub(crate) fn render_reduced_with(
|
||||
}
|
||||
Buffer { rect: out, px: acc }
|
||||
}
|
||||
|
||||
/// Source samples of output pixel t along an axis.
|
||||
pub(crate) fn span(t: usize, f: usize, n: usize) -> (usize, usize) {
|
||||
(t * f / n, ((t + 1) * f / n).max(t * f / n + 1).min(f))
|
||||
}
|
||||
|
||||
@ -0,0 +1,69 @@
|
||||
use super::reduced::span;
|
||||
use super::{Buffer, Rect};
|
||||
|
||||
/// Accumulates disjoint composited rectangles into the CPU preview's integer sample spans.
|
||||
pub struct CompositeReduction {
|
||||
source: Rect,
|
||||
output: Buffer,
|
||||
columns: Vec<(usize, usize)>,
|
||||
}
|
||||
|
||||
impl CompositeReduction {
|
||||
pub fn new(source: Rect, width: u32, height: u32) -> Self {
|
||||
let extent = Rect::from_xywh(0, 0, width.clamp(1, source.width().max(1)), height.clamp(1, source.height().max(1)));
|
||||
let columns = (0..extent.width() as usize).map(|x| span(x, source.width() as usize, extent.width() as usize)).collect();
|
||||
Self { source, output: Buffer::transparent(extent), columns }
|
||||
}
|
||||
|
||||
/// Add one disjoint chunk. All chunks together must cover the source exactly once.
|
||||
pub fn add(&mut self, rect: Rect, pixels: &[[f32; 4]]) {
|
||||
let (sw, sh) = (self.source.width() as usize, self.source.height() as usize);
|
||||
let (w, h) = (self.output.rect.width() as usize, self.output.rect.height() as usize);
|
||||
let (x0, y0) = ((rect.x0 - self.source.x0) as usize, (rect.y0 - self.source.y0) as usize);
|
||||
let (cw, ch) = (rect.width() as usize, rect.height() as usize);
|
||||
if (w, h) == (sw, sh) {
|
||||
for (i, src) in pixels.chunks_exact(cw).enumerate() {
|
||||
let start = (y0 + i) * w + x0;
|
||||
self.output.px[start..start + cw].copy_from_slice(src);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let cell = |x: usize, full: usize, reduced: usize| ((x + 1) * reduced - 1) / full;
|
||||
let first_row = cell(y0, sh, h);
|
||||
let last_row = cell(y0 + ch - 1, sh, h);
|
||||
let first_col = cell(x0, sw, w);
|
||||
let last_col = cell(x0 + cw - 1, sw, w);
|
||||
for (row, out) in self.output.px[first_row * w..(last_row + 1) * w].chunks_exact_mut(w).enumerate() {
|
||||
let (a, b) = span(first_row + row, sh, h);
|
||||
for y in a.max(y0)..b.min(y0 + ch) {
|
||||
let src = &pixels[(y - y0) * cw..][..cw];
|
||||
for (out, &(a, b)) in out[first_col..=last_col].iter_mut().zip(&self.columns[first_col..=last_col]) {
|
||||
for pixel in &src[a.max(x0) - x0..b.min(x0 + cw) - x0] {
|
||||
for c in 0..3 {
|
||||
out[c] += pixel[c] * pixel[3];
|
||||
}
|
||||
out[3] += pixel[3];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn finish(mut self) -> Buffer {
|
||||
let (sw, sh) = (self.source.width() as usize, self.source.height() as usize);
|
||||
let (w, h) = (self.output.rect.width() as usize, self.output.rect.height() as usize);
|
||||
if sw != 0 && sh != 0 && (sw, sh) != (w, h) {
|
||||
for (y, row) in self.output.px.chunks_exact_mut(w).enumerate() {
|
||||
let (y0, y1) = span(y, sh, h);
|
||||
for (out, &(x0, x1)) in row.iter_mut().zip(&self.columns) {
|
||||
let alpha = out[3];
|
||||
if alpha > 0.0 {
|
||||
let samples = ((x1 - x0) * (y1 - y0)) as f32;
|
||||
*out = [out[0] / alpha, out[1] / alpha, out[2] / alpha, alpha / samples];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.output
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,211 @@
|
||||
//! Compare background composition using a long synthetic RGB document.
|
||||
//! `cargo run --release -p photocraft-gpu --example bench_background_render -- screen compare`
|
||||
//! Run each backend separately to profile the process working set without the other backend.
|
||||
//! Use `flatten cpu` with `RAYON_NUM_THREADS=1` to measure the serial reference.
|
||||
|
||||
use std::error::Error;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use photocraft_color::{BlendMode, ColorMode, SampleType};
|
||||
use photocraft_compose::{Buffer, flatten, render_reduced_rect};
|
||||
use photocraft_doc::{Document, Layer, LayerContent, LayerMask, SmartObject, SmartSource, TextLayer};
|
||||
use photocraft_geom::{Affine, Rect, Size};
|
||||
use photocraft_gpu::{Compositor, DeviceHealth, render_reduced};
|
||||
use photocraft_raster::Surface;
|
||||
|
||||
fn document() -> Document {
|
||||
let mut doc = Document::new("Long product page", Size::new(1440, 34838), ColorMode::Rgb, SampleType::U8);
|
||||
let mut backdrop = Surface::new(doc.pixel_format());
|
||||
backdrop.fill_rect(doc.bounds(), &[0.93, 0.91, 0.89, 1.0]);
|
||||
doc.layers.push(Layer::new("Background", LayerContent::Raster(backdrop)));
|
||||
for i in 0..299 {
|
||||
let y = (i / 10) * 1161 + (i % 10) * 83;
|
||||
let height = if i % 10 == 2 { 54 } else { 420 };
|
||||
let width = 960;
|
||||
let rect = Rect::from_xywh(56 + (i % 4) * 104, y, width, height);
|
||||
let mut surface = Surface::new(doc.pixel_format());
|
||||
let pixels: Vec<f32> = (0..width * height)
|
||||
.flat_map(|p| {
|
||||
let x = p % width;
|
||||
let row = p / width;
|
||||
let pattern = ((x * 13 + row * 19 + i as u32 * 7) % 173) as f32 / 255.0;
|
||||
let alpha = if height == 54 && (x / 8 + row / 5) % 4 == 0 { 0.0 } else { 0.79 };
|
||||
[pattern + 0.2, pattern + 0.1, 0.6 - pattern * 0.5, alpha]
|
||||
})
|
||||
.collect();
|
||||
surface.write_region(rect, &pixels);
|
||||
let content = match i % 10 {
|
||||
0 => LayerContent::Smart(SmartObject::new(
|
||||
SmartSource::Embedded { file_name: "product.png".into(), bytes: Arc::new(Vec::new()) },
|
||||
Affine::IDENTITY,
|
||||
Some(surface),
|
||||
)),
|
||||
2 => LayerContent::Text(TextLayer { text: "Product details".into(), cache: Some(surface), ..Default::default() }),
|
||||
_ => LayerContent::Raster(surface),
|
||||
};
|
||||
let mut layer = Layer::new(format!("Layer {i}"), content);
|
||||
layer.opacity = if i % 10 == 2 { 1.0 } else { 0.88 };
|
||||
layer.blend = match i % 5 {
|
||||
0 => BlendMode::Multiply,
|
||||
1 => BlendMode::Screen,
|
||||
_ => BlendMode::Normal,
|
||||
};
|
||||
if i % 7 == 0 {
|
||||
let mut mask = LayerMask::reveal_all();
|
||||
mask.surface.fill_rect(Rect::from_xywh(rect.x0 + 70, y + 19, 320, 30), &[0.45]);
|
||||
layer.mask = Some(mask);
|
||||
}
|
||||
doc.layers.push(layer);
|
||||
}
|
||||
doc
|
||||
}
|
||||
|
||||
fn parity(cpu: &Buffer, gpu: &Buffer) -> (f32, f64) {
|
||||
assert_eq!(cpu.rect, gpu.rect);
|
||||
let mut max: f32 = 0.0;
|
||||
let mut sum = 0.0;
|
||||
for (cpu, gpu) in cpu.px.iter().zip(&gpu.px) {
|
||||
for (a, b) in cpu.iter().zip(gpu) {
|
||||
let difference = (a - b).abs();
|
||||
max = max.max(difference);
|
||||
sum += f64::from(difference);
|
||||
}
|
||||
}
|
||||
(max * 255.0, sum * 255.0 / (cpu.px.len() * 4) as f64)
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let args: Vec<_> = std::env::args().skip(1).collect();
|
||||
let [case, backend, ..] = args.as_slice() else {
|
||||
return Err("usage: bench_background_render screen|page|thumbnail|local|flatten cpu|gpu|compare|frame-cpu|frame-gpu".into());
|
||||
};
|
||||
let doc = document();
|
||||
let (rect, w, h) = match case.as_str() {
|
||||
"screen" => (doc.bounds(), 63, 1536),
|
||||
"page" => (Rect::from_xywh(0, 5806, 1440, 2903), 762, 1536),
|
||||
"thumbnail" => (Rect::from_xywh(0, 0, 1440, 2903), 179, 360),
|
||||
"local" => (Rect::from_xywh(248, 8072, 768, 768), 768, 768),
|
||||
"flatten" => {
|
||||
measure("flatten cpu", || std::hint::black_box(flatten(&doc)));
|
||||
return Ok(());
|
||||
}
|
||||
_ => return Err("unknown case".into()),
|
||||
};
|
||||
let render_cpu = || render_reduced_rect(&doc, rect, w, h);
|
||||
if backend == "cpu" {
|
||||
measure(&format!("{case} cpu"), render_cpu);
|
||||
return Ok(());
|
||||
}
|
||||
let start = Instant::now();
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env());
|
||||
let adapter = pollster::block_on(instance.request_adapter(&Default::default()))?;
|
||||
let info = adapter.get_info();
|
||||
let (device, queue) = pollster::block_on(adapter.request_device(&Default::default()))?;
|
||||
let health = DeviceHealth::watch(&device);
|
||||
let mut compositor = Compositor::try_new_with_format(&device, Compositor::preferred_acc_format(&adapter))?;
|
||||
compositor.set_health(health.clone());
|
||||
println!(
|
||||
"{} {:?}, texture limit {}, setup {:.3} ms",
|
||||
info.name,
|
||||
info.backend,
|
||||
device.limits().max_texture_dimension_2d,
|
||||
start.elapsed().as_secs_f64() * 1000.0
|
||||
);
|
||||
let render_gpu = || render_reduced(&mut compositor, &device, &queue, &doc, rect, [w, h], u64::MAX);
|
||||
match backend.as_str() {
|
||||
"gpu" => {
|
||||
measure(&format!("{case} gpu"), render_gpu)?;
|
||||
}
|
||||
"compare" => {
|
||||
let cpu = measure(&format!("{case} cpu"), render_cpu);
|
||||
let gpu = measure(&format!("{case} gpu"), render_gpu)?;
|
||||
let (max, mean) = parity(&cpu, &gpu);
|
||||
println!("max {max:.5}/255, mean {mean:.5}/255");
|
||||
}
|
||||
"frame-cpu" => {
|
||||
measure_frames(&device, &queue, &health, || measure(&format!("{case} cpu"), render_cpu));
|
||||
}
|
||||
"frame-gpu" => {
|
||||
measure_frames(&device, &queue, &health, || measure(&format!("{case} gpu"), render_gpu))?;
|
||||
}
|
||||
_ => return Err("unknown backend".into()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn measure<T>(label: &str, run: impl FnOnce() -> T) -> T {
|
||||
let start = Instant::now();
|
||||
let result = run();
|
||||
println!("{label} {:.3} ms", start.elapsed().as_secs_f64() * 1000.0);
|
||||
result
|
||||
}
|
||||
|
||||
fn measure_frames<T>(device: &wgpu::Device, queue: &wgpu::Queue, health: &DeviceHealth, render: impl FnOnce() -> T) -> T {
|
||||
use std::sync::{
|
||||
Barrier,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
use std::time::Duration;
|
||||
|
||||
let target = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("simulated 60 Hz canvas"),
|
||||
size: wgpu::Extent3d { width: 1440, height: 900, depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
view_formats: &[],
|
||||
});
|
||||
let view = target.create_view(&Default::default());
|
||||
let begin = Barrier::new(2);
|
||||
let finished = AtomicBool::new(false);
|
||||
let (result, mut frames) = std::thread::scope(|scope| {
|
||||
let timer = scope.spawn(|| {
|
||||
let interval = Duration::from_secs_f64(1.0 / 60.0);
|
||||
let mut frames = Vec::new();
|
||||
let mut deadline = Instant::now();
|
||||
begin.wait();
|
||||
while !finished.load(Ordering::Acquire) {
|
||||
std::thread::sleep(deadline.saturating_duration_since(Instant::now()));
|
||||
if finished.load(Ordering::Acquire) {
|
||||
break;
|
||||
}
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
{
|
||||
let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("simulated UI frame"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &view,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color { r: (frames.len() % 2) as f64, g: 0.4, b: 0.6, a: 1.0 }),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})],
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
let submission = queue.submit([encoder.finish()]);
|
||||
if !health.wait(device, Some(submission)) {
|
||||
break;
|
||||
}
|
||||
frames.push(deadline.elapsed().as_secs_f64() * 1000.0);
|
||||
deadline = (deadline + interval).max(Instant::now());
|
||||
}
|
||||
frames
|
||||
});
|
||||
begin.wait();
|
||||
let result = render();
|
||||
finished.store(true, Ordering::Release);
|
||||
(result, timer.join().expect("frame sampler"))
|
||||
});
|
||||
frames.sort_by(f64::total_cmp);
|
||||
if !frames.is_empty() {
|
||||
let at = |percent: usize| frames[(frames.len() * percent).div_ceil(100) - 1];
|
||||
println!("frames={}, p50={:.3} ms, p95={:.3} ms, max={:.3} ms", frames.len(), at(50), at(95), at(100));
|
||||
}
|
||||
result
|
||||
}
|
||||
@ -157,7 +157,7 @@ use paging::first_error;
|
||||
#[cfg(test)]
|
||||
use paging::{lru_victims, uniform_buffer_len};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use readback::{render_to_vec, render_to_vec_stats};
|
||||
pub use readback::{render_reduced, render_to_vec, render_to_vec_stats};
|
||||
#[cfg(test)]
|
||||
use textures::TexKind;
|
||||
use textures::{CachedPattern, FxEntry, FxKey, ResKey, Resident, Tex};
|
||||
|
||||
@ -68,3 +68,40 @@ pub fn render_to_vec_stats(
|
||||
}
|
||||
Ok((out, stats))
|
||||
}
|
||||
|
||||
/// Stream bounded GPU batches into the CPU preview's sample spans. Only the current batch is
|
||||
/// mapped, and its submission completes before queuing the next one on the shared device.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn render_reduced(
|
||||
comp: &mut Compositor,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
doc: &Document,
|
||||
rect: Rect,
|
||||
size: [u32; 2],
|
||||
budget: u64,
|
||||
) -> Result<photocraft_compose::Buffer, Unsupported> {
|
||||
const PAGE: u32 = 512;
|
||||
const ROWS: i32 = 256;
|
||||
const BUDGET: u64 = 256 << 20;
|
||||
const READBACK_BYTES: u64 = PAGE as u64 * ROWS as u64 * 16;
|
||||
let rect = rect.intersect(&doc.bounds());
|
||||
let [width, height] = size;
|
||||
let mut reduction = photocraft_compose::CompositeReduction::new(rect, width, height);
|
||||
let available = budget.checked_sub(READBACK_BYTES).ok_or_else(|| Unsupported("preview exceeds GPU memory budget".into()))?;
|
||||
comp.set_texture_limit(PAGE);
|
||||
comp.set_memory_budget(available.min(BUDGET));
|
||||
comp.set_composite_cache_budget(0);
|
||||
for y in (rect.y0..rect.y1).step_by(ROWS as usize) {
|
||||
for x in (rect.x0..rect.x1).step_by(PAGE as usize) {
|
||||
let batch = Rect::new(x, y, (x + PAGE as i32).min(rect.x1), (y + ROWS).min(rect.y1));
|
||||
if !comp.fits_budget(doc, batch) {
|
||||
return Err(Unsupported("preview batch exceeds GPU memory budget".into()));
|
||||
}
|
||||
let pixels = render_to_vec(comp, device, queue, doc, batch)?;
|
||||
reduction.add(batch, &pixels);
|
||||
std::thread::yield_now();
|
||||
}
|
||||
}
|
||||
Ok(reduction.finish())
|
||||
}
|
||||
|
||||
@ -191,6 +191,8 @@ impl PhotocraftApp {
|
||||
window_lost: false,
|
||||
window_recovery_retry: None,
|
||||
gpu_render_state: None,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
background_composition: false,
|
||||
gpu_fault: None,
|
||||
gpu_oom_retries: 0,
|
||||
started: None,
|
||||
|
||||
@ -32,9 +32,20 @@ impl PhotocraftApp {
|
||||
self.perf.gpu_info.canvas = "gpu".into();
|
||||
self.window_device = Some((rs.device.clone(), gpu.health().clone()));
|
||||
self.gpu = Some(gpu);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if self.background_composition {
|
||||
self.install_background_composition();
|
||||
}
|
||||
self.prefs_rt.gpu_style = None;
|
||||
}
|
||||
|
||||
/// Make the window's compositor pipelines available to desktop background previews.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn install_background_composition(&mut self) {
|
||||
self.background_composition = true;
|
||||
gpu_canvas::background_compose::install(self.gpu.as_ref());
|
||||
}
|
||||
|
||||
/// Whether the document canvas currently draws on the GPU (false on the CPU path, and after
|
||||
/// the device was lost).
|
||||
pub fn gpu_active(&self) -> bool {
|
||||
@ -50,6 +61,10 @@ impl PhotocraftApp {
|
||||
/// its loss is handled like the GPU canvas's (see `gpu_status::check_window`).
|
||||
pub fn watch_window_device(&mut self, device: &eframe::wgpu::Device) {
|
||||
self.window_device = Some((device.clone(), photocraft_gpu::DeviceHealth::watch(device)));
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if self.background_composition {
|
||||
gpu_canvas::background_compose::install(None);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the window's graphics device was lost, so the app saves its documents for
|
||||
|
||||
@ -65,6 +65,9 @@ pub use perf::{GpuInfo, Perf, backend_name, now_ms};
|
||||
pub use resources::CanvasStyle;
|
||||
use resources::{DocTextures, Resources, identity_lut_bytes, lut_bind_group};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[path = "gpu_canvas/background_compose.rs"]
|
||||
pub mod background_compose;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use resources::f32_bytes;
|
||||
#[cfg(test)]
|
||||
use setup::device_limits_for;
|
||||
|
||||
@ -0,0 +1,130 @@
|
||||
use std::sync::Mutex;
|
||||
|
||||
use photocraft_compose::{Buffer, render_reduced_rect};
|
||||
use photocraft_doc::Document;
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_gpu::{DeviceHealth, Unsupported, render_reduced};
|
||||
|
||||
use super::{GpuCanvas, RenderState, Resources};
|
||||
|
||||
// The smallest source region that benefited from GPU readback in the product-page benchmark.
|
||||
const MIN_SOURCE_PIXELS: u64 = 4_000_000;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Source {
|
||||
state: RenderState,
|
||||
health: DeviceHealth,
|
||||
}
|
||||
|
||||
static SOURCE: Mutex<Option<Source>> = Mutex::new(None);
|
||||
static RENDER: Mutex<()> = Mutex::new(());
|
||||
|
||||
pub(crate) fn install(canvas: Option<&GpuCanvas>) {
|
||||
*SOURCE.lock().unwrap_or_else(std::sync::PoisonError::into_inner) =
|
||||
canvas.map(|canvas| Source { state: canvas.rs.clone(), health: canvas.health().clone() });
|
||||
}
|
||||
|
||||
/// Render a background preview using the canvas's compiled GPU pipelines. Headless consumers and
|
||||
/// canvases without hardware composition use the CPU.
|
||||
pub fn render(doc: &Document, rect: Rect, width: u32, height: u32) -> Buffer {
|
||||
let area = u64::from(rect.width()) * u64::from(rect.height());
|
||||
if area >= MIN_SOURCE_PIXELS && (width < rect.width() || height < rect.height()) && rect.intersect(&doc.bounds()) == rect {
|
||||
let _render = RENDER.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let source = SOURCE.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
|
||||
if let Some(buffer) = source.as_ref().and_then(|source| source.render(doc, rect, width, height)) {
|
||||
return buffer;
|
||||
}
|
||||
}
|
||||
render_reduced_rect(doc, rect, width, height)
|
||||
}
|
||||
|
||||
impl Source {
|
||||
fn render(&self, doc: &Document, rect: Rect, width: u32, height: u32) -> Option<Buffer> {
|
||||
if self.health.fault().is_some()
|
||||
|| std::env::var_os("PHOTOCRAFT_CPU_COMPOSE").is_some()
|
||||
|| photocraft_gpu::Compositor::preferred_acc_format(&self.state.adapter) != eframe::wgpu::TextureFormat::Rgba32Float
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// The sibling shares the pipelines, but owns its draw resources. Release the egui
|
||||
// renderer lock before submitting or waiting, and release the sibling's pages after use.
|
||||
let (mut compositor, budget) = {
|
||||
let renderer = self.state.renderer.read();
|
||||
let resources = renderer.callback_resources.get::<Resources>()?;
|
||||
(resources.compositor.as_ref()?.sibling(), resources.compositor_budget)
|
||||
};
|
||||
match render_reduced(&mut compositor, &self.state.device, &self.state.queue, doc, rect, [width, height], budget.unwrap_or(u64::MAX)) {
|
||||
Ok(buffer) => Some(buffer),
|
||||
Err(Unsupported(error)) => {
|
||||
log::debug!("background preview GPU composition declined: {error}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use photocraft_doc::{ColorMode, Layer, SampleType};
|
||||
use photocraft_geom::Size;
|
||||
|
||||
#[test]
|
||||
fn jiansun_reduced_preview_without_device_is_cpu_exact() {
|
||||
let mut doc = Document::new("CPU preview", Size::new(1440, 3000), ColorMode::Rgb, SampleType::U8);
|
||||
let mut layer = Layer::raster("content", doc.pixel_format());
|
||||
layer.surface_mut().unwrap().fill_rect(doc.bounds(), &[0.75, 0.25, 0.38, 0.8]);
|
||||
doc.layers.push(layer);
|
||||
let expected = render_reduced_rect(&doc, doc.bounds(), 179, 360);
|
||||
assert_eq!(render(&doc, doc.bounds(), 179, 360), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jiansun_headless_gpu_preview_splices_pages_and_detects_device_loss() {
|
||||
let _gpu = photocraft_testkit::gpu::gpu_lock();
|
||||
let output = std::sync::Arc::new(Mutex::new(None));
|
||||
let capture = output.clone();
|
||||
let harness = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
|
||||
// The test harness has an offscreen render device and no window surface.
|
||||
egui_kittest::Harness::builder().wgpu_setup(crate::gpu_canvas::wgpu_setup()).build_eframe(move |cc| {
|
||||
if let Some(state) = cc.wgpu_render_state.as_ref() {
|
||||
let canvas = GpuCanvas::new(state);
|
||||
*capture.lock().unwrap() = Some(Source { state: state.clone(), health: canvas.health().clone() });
|
||||
}
|
||||
crate::PhotocraftApp::new(photocraft_engine::Session::new(), Default::default())
|
||||
})
|
||||
}));
|
||||
let Ok(_harness) = harness else { return };
|
||||
let Some(source) = output.lock().unwrap().take() else { return };
|
||||
let format = photocraft_gpu::Compositor::preferred_acc_format(&source.state.adapter);
|
||||
if format != eframe::wgpu::TextureFormat::Rgba32Float {
|
||||
return;
|
||||
}
|
||||
let mut compositor = photocraft_gpu::Compositor::try_new_with_format(&source.state.device, format).expect("GPU pipelines");
|
||||
compositor.set_health(source.health.clone());
|
||||
let limit = source.state.device.limits().max_texture_dimension_2d;
|
||||
let size = Size::new(512, limit + 19);
|
||||
let mut doc = Document::new("Tall preview", size, ColorMode::Rgb, SampleType::U8);
|
||||
let mut layer = Layer::raster("content", doc.pixel_format());
|
||||
let raster = layer.surface_mut().unwrap();
|
||||
raster.fill_rect(doc.bounds(), &[0.7, 0.18, 0.3, 0.53]);
|
||||
for y in (0..doc.bounds().y1).step_by(509) {
|
||||
raster.fill_rect(Rect::from_xywh(11, y, 250, 23).intersect(&doc.bounds()), &[0.11, 0.45, 0.75, 0.91]);
|
||||
}
|
||||
doc.layers.push(layer);
|
||||
source.state.renderer.write().callback_resources.get_mut::<Resources>().unwrap().compositor = Some(compositor);
|
||||
let cpu = render_reduced_rect(&doc, doc.bounds(), 61, 777);
|
||||
let gpu = source.render(&doc, doc.bounds(), 61, 777).expect("headless GPU reduced preview");
|
||||
let (mut max, mut total) = (0.0_f32, 0.0_f64);
|
||||
for (a, b) in gpu.px.iter().flatten().zip(cpu.px.iter().flatten()) {
|
||||
let difference = (a - b).abs();
|
||||
max = max.max(difference);
|
||||
total += f64::from(difference);
|
||||
}
|
||||
assert!(max <= 1.0 / 255.0, "max error {max}");
|
||||
assert!(total / (gpu.px.len() * 4) as f64 <= 0.1 / 255.0, "average error {total}");
|
||||
source.state.device.destroy();
|
||||
assert!(!source.health.wait(&source.state.device, None));
|
||||
assert!(source.render(&doc, doc.bounds(), 61, 777).is_none());
|
||||
}
|
||||
}
|
||||
@ -675,6 +675,8 @@ pub struct PhotocraftApp {
|
||||
/// The render state the GPU canvas was built on, kept after it is dropped so Retry GPU can
|
||||
/// build a new one on the same device (see `gpu_status::choose_recovery`, #6577).
|
||||
gpu_render_state: Option<eframe::egui_wgpu::RenderState>,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
background_composition: bool,
|
||||
/// Why the GPU canvas was dropped (see `gpu_status::fall_back`).
|
||||
gpu_fault: Option<photocraft_gpu::Fault>,
|
||||
/// Out-of-memory errors this session after which the GPU canvas was rebuilt by itself (#6564).
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user