From af651a6f5697a43b9e6babee26a4991b8737e75c Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Fri, 2 Oct 2026 11:06:05 -0400 Subject: [PATCH] M12.2: viewer on gpu The desktop viewer builds the GPU compositor on egui-wgpu's device and, with Mercury GPU Acceleration, renders frames into RGBA8 textures that are registered with egui-wgpu and drawn directly (no readback); the RAM preview cache holds them under a video-memory budget. Pixels are read back only on demand (Info panel, eyedroppers, histograms). Project Settings gets the Video Rendering and Effects renderer choice. ui_gpu test: GPU viewer frame matches the CPU one (skips without an adapter). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/Cargo.toml | 1 + crates/ui-egui/src/frames.rs | 101 +++++++++++++++---- crates/ui-egui/src/lib.rs | 66 +++++++++++- crates/ui-egui/src/panels/effect_controls.rs | 8 +- crates/ui-egui/src/panels/forms.rs | 11 ++ crates/ui-egui/src/panels/info.rs | 4 + crates/ui-egui/src/panels/misc.rs | 2 +- crates/ui-egui/src/panels/project.rs | 4 +- crates/ui-egui/src/panels/timeline.rs | 2 +- crates/ui-egui/src/panels/viewer.rs | 51 ++++++++-- crates/ui-egui/tests/ui_gpu.rs | 56 ++++++++++ 11 files changed, 269 insertions(+), 37 deletions(-) create mode 100644 crates/ui-egui/tests/ui_gpu.rs diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index d7c5ea7e..31cd782c 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -19,6 +19,7 @@ effectcraft-path = { workspace = true } effectcraft-text = { workspace = true } effectcraft-render = { workspace = true } effectcraft-engine = { workspace = true } +effectcraft-gpu = { workspace = true } egui = { workspace = true } eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } serde = { workspace = true } diff --git a/crates/ui-egui/src/frames.rs b/crates/ui-egui/src/frames.rs index a703620a..3c3e5df1 100644 --- a/crates/ui-egui/src/frames.rs +++ b/crates/ui-egui/src/frames.rs @@ -6,6 +6,11 @@ //! //! wasm32 has no threads: jobs wait in the same priority queue and [`Frames::pump`] renders them //! on the UI thread between egui frames, within a time budget. +//! +//! With Mercury GPU Acceleration (a [`Gpu`] on egui-wgpu's device and the project's renderer set +//! to the GPU) frames stay on the GPU: the compositor writes an RGBA8 texture that the viewer +//! registers with egui-wgpu and draws directly; pixels are read back only when something needs +//! them (Info panel, eyedroppers, histograms). use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::{Arc, Mutex}; @@ -13,8 +18,34 @@ use std::sync::{Arc, Mutex}; use effectcraft_engine::project::{ItemId, Project}; use effectcraft_engine::render::{ExprHost, FootageSource, LayerCache, RenderOpts, Renderer}; use effectcraft_engine::time::Tick; +use effectcraft_gpu::{DisplayFrame, Gpu}; use rayon::prelude::*; +/// GPU frames kept for RAM preview (bytes of video memory). +const GPU_BUDGET: usize = 1 << 30; + +/// A rendered viewer frame: CPU pixels or a GPU texture. +#[derive(Clone)] +pub enum FrameImage { + Cpu(Arc), + Gpu(Arc), +} + +impl FrameImage { + pub fn size(&self) -> [usize; 2] { + match self { + FrameImage::Cpu(c) => c.size, + FrameImage::Gpu(f) => [f.width as usize, f.height as usize], + } + } + fn bytes(&self) -> usize { + self.size()[0] * self.size()[1] * 4 + } + fn is_gpu(&self) -> bool { + matches!(self, FrameImage::Gpu(_)) + } +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct FrameKey { pub revision: u64, @@ -27,26 +58,55 @@ pub struct FrameKey { } struct Cache { - map: HashMap>, + map: HashMap, order: VecDeque, bytes: usize, + /// Bytes of GPU frames (also counted in `bytes`). + gpu_bytes: usize, budget: usize, } impl Cache { - fn insert(&mut self, k: FrameKey, img: Arc) { - let sz = img.pixels.len() * 4; - if self.map.insert(k, img).is_none() { + fn insert(&mut self, k: FrameKey, img: FrameImage) { + let (sz, gpu) = (img.bytes(), img.is_gpu()); + if let Some(old) = self.map.insert(k, img) { + self.forget(&old); + } else { self.order.push_back(k); - self.bytes += sz; + } + self.bytes += sz; + if gpu { + self.gpu_bytes += sz; } while self.bytes > self.budget { let Some(old) = self.order.pop_front() else { break }; - if let Some(i) = self.map.remove(&old) { - self.bytes -= i.pixels.len() * 4; + self.remove(&old); + } + // Video memory: drop the oldest GPU frames past their own budget. + while self.gpu_bytes > GPU_BUDGET { + let Some(i) = self.order.iter().position(|k| self.map.get(k).is_some_and(FrameImage::is_gpu)) else { break }; + if let Some(old) = self.order.remove(i) { + self.remove(&old); } } } + fn forget(&mut self, img: &FrameImage) { + self.bytes -= img.bytes(); + if img.is_gpu() { + self.gpu_bytes -= img.bytes(); + } + } + fn remove(&mut self, k: &FrameKey) { + if let Some(i) = self.map.remove(k) { + self.forget(&i); + } + } + fn evict_to_budget(&mut self) { + while self.bytes > self.budget { + let Some(old) = self.order.pop_front() else { break }; + self.remove(&old); + } + } } /// What a render job needs (all cheap clones). @@ -56,6 +116,8 @@ pub struct RenderSource { pub footage: Arc, pub expr: Option>, pub layer_cache: Arc, + /// GPU compositor on the viewer's device (Mercury GPU Acceleration), if available. + pub gpu: Option, } pub struct Frames { @@ -76,7 +138,7 @@ impl Default for Frames { #[cfg(not(target_arch = "wasm32"))] let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).clamp(2, 16); Frames { - cache: Arc::new(Mutex::new(Cache { map: HashMap::new(), order: VecDeque::new(), bytes: 0, budget: 3 << 30 })), + cache: Arc::new(Mutex::new(Cache { map: HashMap::new(), order: VecDeque::new(), bytes: 0, gpu_bytes: 0, budget: 3 << 30 })), inflight: Arc::new(Mutex::new(HashSet::new())), queue: Arc::new(Mutex::new(Queue::default())), #[cfg(not(target_arch = "wasm32"))] @@ -109,7 +171,7 @@ impl Frames { } } - pub fn get(&self, k: &FrameKey) -> Option> { + pub fn get(&self, k: &FrameKey) -> Option { self.cache.lock().ok()?.map.get(k).cloned() } @@ -134,12 +196,7 @@ impl Frames { pub fn set_budget(&self, bytes: usize) { if let Ok(mut c) = self.cache.lock() { c.budget = bytes; - while c.bytes > c.budget { - let Some(old) = c.order.pop_front() else { break }; - if let Some(i) = c.map.remove(&old) { - c.bytes -= i.pixels.len() * 4; - } - } + c.evict_to_budget(); } } @@ -152,6 +209,7 @@ impl Frames { c.map.clear(); c.order.clear(); c.bytes = 0; + c.gpu_bytes = 0; } } @@ -266,8 +324,17 @@ impl Worker { let mut r = Renderer::new(&job.src.project, job.src.footage.as_ref(), job.opts); r.expr = job.src.expr.as_deref(); r.cache = Some(&job.src.layer_cache); - let img = r.comp_frame(job.comp, job.t); - let ci = Arc::new(to_color_image(&img)); + r.accel = job.src.gpu.as_ref().map(|g| g as &dyn effectcraft_engine::render::Accelerator); + // The GPU leaves the frame in a texture for the viewer; otherwise (Software Only, no + // adapter, or a frame the GPU cannot finish here) the CPU renders it. + let gpu_frame = match (&job.src.gpu, r.active_accel()) { + (Some(g), Some(_)) => g.render_display(&r, job.comp, job.t), + _ => None, + }; + let ci = match gpu_frame { + Some(f) => FrameImage::Gpu(Arc::new(f)), + None => FrameImage::Cpu(Arc::new(to_color_image(&r.comp_frame(job.comp, job.t)))), + }; if job.urgent && let Ok(mut l) = last.lock() { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9a032442..5e0b67c6 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -118,10 +118,20 @@ pub struct EffectcraftApp { next_token: u64, pub(crate) last_ui_time: f64, pub(crate) toast: Option<(String, f64)>, - /// Texture of the frame shown in the viewer and the key it came from. + /// Texture of the last CPU frame shown in the viewer and the key it came from. pub(crate) viewer_tex: Option<(egui::TextureHandle, FrameKey)>, - /// Last displayed image (for the Info panel colour picker). + /// The last GPU frame shown: its egui texture id (registered with egui-wgpu), key and texture. + pub(crate) viewer_native: Option<(egui::TextureId, FrameKey, Arc)>, + /// The texture the viewer draws and its frame key (CPU or GPU frame). + pub(crate) viewer_shown: Option<(egui::TextureId, FrameKey)>, + /// Last displayed image (Info panel colour, eyedroppers, histograms). GPU frames fill it on + /// demand ([`EffectcraftApp::viewer_pixels`]). pub(crate) viewer_image: Option>, + /// egui-wgpu's device, once the first frame arrives (desktop and WebGPU). + pub(crate) wgpu: Option, + /// The GPU compositor on that device (None: no usable adapter → CPU only). + pub(crate) gpu: Option, + gpu_checked: bool, /// Commands from the native menu bar. pub command_inbox: Option>, /// Pointer position in comp pixels (Info panel). @@ -167,7 +177,12 @@ impl EffectcraftApp { last_ui_time: 0.0, toast: None, viewer_tex: None, + viewer_native: None, + viewer_shown: None, viewer_image: None, + wgpu: None, + gpu: None, + gpu_checked: false, command_inbox: None, pointer_comp: None, dialog_state: Default::default(), @@ -272,9 +287,53 @@ impl EffectcraftApp { footage: self.session.footage.clone(), expr: self.session.expr.clone(), layer_cache: self.session.layer_cache.clone(), + gpu: self.gpu.clone(), } } + /// Set up the GPU compositor on egui-wgpu's device (once). Without an adapter that runs + /// compute shaders (WebGL2, software GL) everything stays on the CPU. + pub(crate) fn init_gpu(&mut self, frame: &eframe::Frame) { + if self.gpu_checked { + return; + } + self.gpu_checked = true; + let Some(rs) = frame.wgpu_render_state() else { return }; + match effectcraft_gpu::Gpu::new(&rs.adapter, rs.device.clone(), rs.queue.clone()) { + Ok(g) => { + log::info!("GPU compositor: {}", effectcraft_engine::render::Accelerator::name(&g)); + self.session.accel = Some(Arc::new(g.clone())); + self.gpu = Some(g); + self.wgpu = Some(rs.clone()); + } + Err(e) => log::info!("GPU compositor unavailable: {e}"), + } + } + + /// The viewer shows a frame composited on the GPU (drawn from its wgpu texture). + pub fn viewer_on_gpu(&self) -> bool { + matches!((&self.viewer_shown, &self.viewer_native), (Some(s), Some(n)) if s.1 == n.1) + } + + /// The GPU compositor's adapter, when the viewer has one. + pub fn gpu_adapter(&self) -> Option { + self.gpu.as_ref().map(effectcraft_engine::render::Accelerator::name) + } + + /// The viewer's current pixels as 8-bit premultiplied RGBA, reading a GPU frame back the + /// first time something asks for it. + pub fn viewer_pixels(&mut self) -> Option> { + if self.viewer_image.is_none() + && let (Some((_, _, f)), Some(g)) = (&self.viewer_native, &self.gpu) + && self.viewer_shown.as_ref().map(|s| s.1) == self.viewer_native.as_ref().map(|n| n.1) + && let Some(bytes) = g.read_display(f) + { + let px = bytes.chunks_exact(4).map(|c| egui::Color32::from_rgba_premultiplied(c[0], c[1], c[2], c[3])).collect(); + self.viewer_image = Some(Arc::new(egui::ColorImage::new([f.width as usize, f.height as usize], px))); + } + self.viewer_image.clone() + } + /// The render scale used by the viewer right now. pub fn viewer_scale(&self, zoom: f32, ppp: f32) -> f64 { if self.playback.playing && self.ui.viewer.res == state::Resolution::Auto { @@ -811,7 +870,8 @@ impl eframe::App for EffectcraftApp { self.collect_screenshots(ctx); } - fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { + fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { + self.init_gpu(frame); if !self.fonts_ready { ui.ctx().request_repaint(); return; diff --git a/crates/ui-egui/src/panels/effect_controls.rs b/crates/ui-egui/src/panels/effect_controls.rs index eda2ed76..78facbcc 100644 --- a/crates/ui-egui/src/panels/effect_controls.rs +++ b/crates/ui-egui/src/panels/effect_controls.rs @@ -528,8 +528,8 @@ fn curves_size(width: f32) -> f32 { } /// Cached histogram of the displayed frame (recomputed when the frame changes). -fn frame_histogram(app: &EffectcraftApp, ctx: &egui::Context) -> Option> { - let img = app.viewer_image.clone()?; +fn frame_histogram(app: &mut EffectcraftApp, ctx: &egui::Context) -> Option> { + let img = app.viewer_pixels()?; let key = std::sync::Arc::as_ptr(&img) as usize; let id = egui::Id::new("ec-histogram"); if let Some((k, h)) = ctx.data(|d| d.get_temp::<(usize, std::sync::Arc<[[u32; 256]; 5]>)>(id)) @@ -969,6 +969,10 @@ pub fn viewer_hook( app.ui.fx_pick = None; return; }; + if pick.kind == "color" { + // GPU frames: read the shown frame back for sampling. + app.viewer_pixels(); + } let resp = ui.interact(map.area, egui::Id::new("viewer-fx-pick"), Sense::click()); app.auto.add("viewer.fxPick", map.area, &pick.name); let hint = if pick.kind == "point" { format!("Click to set {}", pick.name) } else { format!("Click to sample {}", pick.name) }; diff --git a/crates/ui-egui/src/panels/forms.rs b/crates/ui-egui/src/panels/forms.rs index e0f1a5f2..0f1edda6 100644 --- a/crates/ui-egui/src/panels/forms.rs +++ b/crates/ui-egui/src/panels/forms.rs @@ -253,6 +253,10 @@ pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool { } "file.projectSettings" if p.as_object().is_none_or(|m| m.is_empty()) => { let st = &s.project.settings; + let gpu_label = match &s.accel { + Some(a) => format!("Mercury GPU Acceleration ({})", a.name()), + None => "Mercury GPU Acceleration (no GPU: software)".to_string(), + }; let depth = match st.bit_depth.label() { l if l.starts_with("16") => 1, l if l.starts_with("32") => 2, @@ -287,6 +291,13 @@ pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool { ), Field::bool("linearize", "Linearize working space", st.linearize), Field::bool("blendLinear", "Blend colors using 1.0 gamma", st.blend_linear), + // Video Rendering and Effects ▸ Use. + Field::choice( + "renderer", + "Video rendering and effects", + &[(gpu_label.as_str(), json!("gpu")), ("Mercury Software Only", json!("software"))], + usize::from(!st.gpu_acceleration), + ), ], ) } diff --git a/crates/ui-egui/src/panels/info.rs b/crates/ui-egui/src/panels/info.rs index dd8354e6..aeaeb355 100644 --- a/crates/ui-egui/src/panels/info.rs +++ b/crates/ui-egui/src/panels/info.rs @@ -10,6 +10,10 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { let p = ui.painter().with_clip_rect(rect); let x0 = rect.min.x + 12.0; let mut y = rect.min.y + 14.0; + if app.pointer_comp.is_some() { + // GPU frames: read the shown frame back for sampling. + app.viewer_pixels(); + } let (rgba, xy) = match (app.pointer_comp, &app.viewer_image) { (Some([cx, cy]), Some(img)) => { let comp = app.session.active_comp(); diff --git a/crates/ui-egui/src/panels/misc.rs b/crates/ui-egui/src/panels/misc.rs index 056e6acd..d54d9fdd 100644 --- a/crates/ui-egui/src/panels/misc.rs +++ b/crates/ui-egui/src/panels/misc.rs @@ -69,7 +69,7 @@ pub fn preview(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { yy += 26.0; if let Some(c) = comp { let cid = app.session.active_comp_id().map(|i| i.0).unwrap_or(0); - let scale = app.viewer_tex.as_ref().map(|(_, k)| k.scale).unwrap_or(1000); + let scale = app.viewer_shown.as_ref().map(|(_, k)| k.scale).unwrap_or(1000); let cached = app.frames.cached_frames(app.session.revision, cid, scale).len(); let total = c.frame_rate.frame_at(c.work_area.1) - c.frame_rate.frame_at(c.work_area.0); let bar = Rect::from_min_size(pos2(rect.min.x + 12.0, yy), vec2(rect.width() - 24.0, 6.0)); diff --git a/crates/ui-egui/src/panels/project.rs b/crates/ui-egui/src/panels/project.rs index 31d7d4de..d7d1cd9a 100644 --- a/crates/ui-egui/src/panels/project.rs +++ b/crates/ui-egui/src/panels/project.rs @@ -82,10 +82,10 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { p.rect_filled(thumb.shrink(4.0), 2.0, Color32::from_rgb((s.color[0] * 255.0) as u8, (s.color[1] * 255.0) as u8, (s.color[2] * 255.0) as u8)); } ItemKind::Comp(_) => { - if let Some((tex, k)) = &app.viewer_tex + if let Some((tex, k)) = &app.viewer_shown && k.comp == it.id.0 { - p.image(tex.id(), thumb, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + p.image(*tex, thumb, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } else { icons::paint(&p, Rect::from_center_size(thumb.center(), vec2(24.0, 24.0)), Icon::Comp, t.text_dim); } diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rs index be891090..0d0b7023 100644 --- a/crates/ui-egui/src/panels/timeline.rs +++ b/crates/ui-egui/src/panels/timeline.rs @@ -579,7 +579,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { } } // Cache bar (green: cached frames at the viewer's resolution). - let scale_key = app.viewer_tex.as_ref().map(|(_, k)| k.scale).unwrap_or(1000); + let scale_key = app.viewer_shown.as_ref().map(|(_, k)| k.scale).unwrap_or(1000); let cached = app.frames.cached_frames(app.session.revision, cid.0, scale_key); let fd = comp.frame_duration().seconds(); let cy0 = ruler.min.y + 11.0; diff --git a/crates/ui-egui/src/panels/viewer.rs b/crates/ui-egui/src/panels/viewer.rs index a02c9b3a..00f9a20c 100644 --- a/crates/ui-egui/src/panels/viewer.rs +++ b/crates/ui-egui/src/panels/viewer.rs @@ -381,16 +381,9 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { let key = app.frame_key(cid, frame, scale); app.request_frame_urgent(cid, frame, scale); if let Some(img) = app.frames.get(&key) { - let stale = app.viewer_tex.as_ref().is_none_or(|(_, k)| *k != key); + let stale = app.viewer_shown.as_ref().is_none_or(|(_, k)| *k != key); if stale { - match &mut app.viewer_tex { - Some((tex, k)) if tex.size() == img.size => { - tex.set((*img).clone(), egui::TextureOptions::LINEAR); - *k = key; - } - _ => app.viewer_tex = Some((ctx.load_texture("viewer-frame", (*img).clone(), egui::TextureOptions::LINEAR), key)), - } - app.viewer_image = Some(img); + show_frame(app, &ctx, key, img); } } if app.ui.viewer.transparency_grid { @@ -399,10 +392,10 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { let bg = comp.background; painter.rect_filled(comp_rect, 0.0, Color32::from_rgb((bg[0] * 255.0) as u8, (bg[1] * 255.0) as u8, (bg[2] * 255.0) as u8)); } - if let Some((tex, k)) = &app.viewer_tex + if let Some((tex, k)) = &app.viewer_shown && k.comp == cid.0 { - painter.image(tex.id(), comp_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + painter.image(*tex, comp_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } painter.rect_stroke(comp_rect, 0.0, Stroke::new(1.0, Color32::from_black_alpha(160)), StrokeKind::Outside); app.auto.add("viewer.comp", comp_rect, &comp_name); @@ -1490,3 +1483,39 @@ pub(crate) fn hex_rgb(s: &str) -> Option<[u8; 3]> { let p = |i: usize| u8::from_str_radix(&h[i..i + 2], 16).ok(); Some([p(0)?, p(2)?, p(4)?]) } + +/// Put a rendered frame on screen: CPU pixels go into an egui texture; GPU frames are drawn +/// straight from their wgpu texture (registered with egui-wgpu, no readback). +fn show_frame(app: &mut EffectcraftApp, ctx: &egui::Context, key: crate::frames::FrameKey, img: crate::frames::FrameImage) { + use crate::frames::FrameImage; + match img { + FrameImage::Cpu(img) => { + match &mut app.viewer_tex { + Some((tex, k)) if tex.size() == img.size => { + tex.set((*img).clone(), egui::TextureOptions::LINEAR); + *k = key; + } + _ => app.viewer_tex = Some((ctx.load_texture("viewer-frame", (*img).clone(), egui::TextureOptions::LINEAR), key)), + } + app.viewer_shown = app.viewer_tex.as_ref().map(|(t, k)| (t.id(), *k)); + app.viewer_image = Some(img); + } + FrameImage::Gpu(f) => { + let Some(rs) = &app.wgpu else { return }; + let view = f.texture.create_view(&Default::default()); + let mut ren = rs.renderer.write(); + let id = match &app.viewer_native { + Some((id, _, _)) => { + ren.update_egui_texture_from_wgpu_texture(&rs.device, &view, eframe::wgpu::FilterMode::Linear, *id); + *id + } + None => ren.register_native_texture(&rs.device, &view, eframe::wgpu::FilterMode::Linear), + }; + drop(ren); + app.viewer_native = Some((id, key, f)); + app.viewer_shown = Some((id, key)); + // Pixels are read back on demand (viewer_pixels). + app.viewer_image = None; + } + } +} diff --git a/crates/ui-egui/tests/ui_gpu.rs b/crates/ui-egui/tests/ui_gpu.rs new file mode 100644 index 00000000..399535d4 --- /dev/null +++ b/crates/ui-egui/tests/ui_gpu.rs @@ -0,0 +1,56 @@ +//! The viewer on the GPU compositor (egui_kittest with wgpu): frames are drawn from GPU textures +//! and match the CPU viewer. Skips without a GPU adapter (CI). Set `EC_SNAPSHOT_DIR` to keep PNGs. + +use effectcraft_engine::Session; +use effectcraft_ui_egui::EffectcraftApp; +use egui_kittest::Harness; +use serde_json::json; + +fn settle(h: &mut Harness<'_, EffectcraftApp>) { + for _ in 0..600 { + h.step(); + if h.state().frames.inflight() == 0 && h.state().frames.last_ms.lock().map(|v| *v > 0.0).unwrap_or(false) { + break; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + for _ in 0..4 { + h.step(); + } +} + +#[test] +fn viewer_draws_gpu_frames_that_match_the_cpu() { + if effectcraft_gpu::Gpu::headless().is_none() { + eprintln!("no GPU adapter: skipping"); + return; + } + let mut s = Session::default(); + s.execute("file.openDemoProject", json!({})).unwrap(); + s.execute("time.set", json!({"time": 2.0})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|_| EffectcraftApp::new(s)); + settle(&mut h); + assert!(h.state().gpu_adapter().is_some(), "GPU compositor on egui-wgpu's device"); + assert!(h.state().viewer_on_gpu(), "viewer frame comes from the GPU"); + let gpu_px = h.state_mut().viewer_pixels().expect("read back the GPU frame"); + let gpu_shot = h.render().expect("render"); + // Mercury Software Only: the same frame from the CPU. + h.state_mut().session.execute("render.backend", json!({"backend": "cpu"})).unwrap(); + settle(&mut h); + assert!(!h.state().viewer_on_gpu()); + let cpu_px = h.state_mut().viewer_pixels().expect("CPU frame"); + let cpu_shot = h.render().expect("render"); + assert_eq!(gpu_px.size, cpu_px.size); + let mut worst = 0i32; + let mut over = 0usize; + for (a, b) in gpu_px.pixels.iter().zip(&cpu_px.pixels) { + let d = a.to_array().iter().zip(b.to_array()).map(|(x, y)| (*x as i32 - y as i32).abs()).max().unwrap_or(0); + worst = worst.max(d); + over += usize::from(d > 1); + } + assert!(over * 1000 <= gpu_px.pixels.len() * 3 && worst <= 4, "viewer GPU vs CPU: {over} pixels > 1/255, worst {worst}/255"); + if let Ok(d) = std::env::var("EC_SNAPSHOT_DIR") { + gpu_shot.save(format!("{d}/ui_gpu_viewer.png")).unwrap(); + cpu_shot.save(format!("{d}/ui_cpu_viewer.png")).unwrap(); + } +}