Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

GPU: gradients with coincident stops fall back to the CPU compositor (#2005)

Raghav45b22e7403f3
diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs
index a656892cf..25d9c778d 100644
--- a/crates/gpu/src/lib.rs
+++ b/crates/gpu/src/lib.rs
@@ -26,7 +26,8 @@
//! Vector masks (rasterised once per mask state into a combined mask texture), layers clipped to
//! pass-through groups, stroked shapes with clipped layers (fill and stroke split once per shape
//! state), pattern fills and artboards are planned like everything else. What remains
-//! (Multichannel documents, patterns larger than the texture limit) returns [`Unsupported`];
+//! (Multichannel documents, patterns larger than the texture limit, uncached gradients with
+//! coincident colour or opacity stops) returns [`Unsupported`];
//! callers fall back to the CPU compositor.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rs
index ffc17d27d..e42b7dd89 100644
--- a/crates/gpu/src/plan.rs
+++ b/crates/gpu/src/plan.rs
@@ -788,20 +788,20 @@ impl<'a> Planner<'a> {
Ok(s)
}
_ => {
- let p = self.content_pass(layer);
+ let p = self.content_pass(layer)?;
Ok(self.emit(p))
}
}
}
/// The Content pass of a raster / text / shape / smart / fill layer.
- fn content_pass(&self, layer: &'a Layer) -> Pass<'a> {
+ fn content_pass(&self, layer: &'a Layer) -> Result<Pass<'a>, Unsupported> {
let mut p = Pass::new(Kernel::Content, 0);
p.mask = self.mask_use(layer);
match &layer.content {
LayerContent::Fill(f) => match &layer.fill_cache {
Some(c) if c.fill == *f => self.surface_tex(&mut p, layer.id, &c.surface),
- _ => self.fill(&mut p, f, photocraft_compose::fill_frame(layer, self.cx.canvas)),
+ _ => self.fill(&mut p, f, photocraft_compose::fill_frame(layer, self.cx.canvas))?,
},
_ => {
if let Some(s) = layer.surface() {
@@ -809,7 +809,7 @@ impl<'a> Planner<'a> {
}
}
}
- p
+ Ok(p)
}
fn surface_tex(&self, p: &mut Pass<'a>, id: LayerId, s: &'a Surface) {
@@ -820,13 +820,15 @@ impl<'a> Planner<'a> {
}
}
- fn fill(&self, p: &mut Pass<'a>, f: &Fill, frame: photocraft_geom::Rect) {
+ fn fill(&self, p: &mut Pass<'a>, f: &Fill, frame: photocraft_geom::Rect) -> Result<(), Unsupported> {
match f {
Fill::Solid(c) => {
let rgb = c.to_rgb();
p.color = [rgb[0], rgb[1], rgb[2], c.alpha];
}
- Fill::Gradient { angle, scale, style, reverse, offset, dither, .. } => {
+ Fill::Gradient { stops, opacity_stops, angle, scale, style, reverse, offset, dither, .. } => {
+ check_gradient_stops(stops)?;
+ check_gradient_stops(opacity_stops)?;
p.gradient = true;
// compose::render_fill: whole-pixel end points (fill_layout).
let (angle, scale, offset) = photocraft_compose::fill_layout::gradient_layout(*style, *angle, *scale, *offset, frame);
@@ -848,6 +850,7 @@ impl<'a> Planner<'a> {
// Pattern fills fall back to the CPU compositor (see `check`).
Fill::Pattern { .. } => {}
}
+ Ok(())
}
/// composite_atop: `layer` onto `base`, restricted to the base's alpha, honouring the
@@ -897,6 +900,9 @@ impl<'a> Planner<'a> {
if !adjustment_on_gpu(adj) {
return Err(Unsupported(format!("{} on CMYK/Lab channels (evaluated on the CPU)", adj.label())));
}
+ if let Adjustment::GradientMap { stops, .. } = adj {
+ check_gradient_stops(stops)?;
+ }
let mut p = Pass::new(Kernel::Adjust, 0);
p.a = Some(src);
let (kind, params, lut) = adjustment_program(adj, self.cx.transfer, self.cx.depth);
@@ -975,6 +981,24 @@ impl<'a> Planner<'a> {
}
let items: Vec<&'a Effect> = layer.effects.items.iter().filter(|e| e.enabled()).collect();
+ for e in &items {
+ let gradient = match e {
+ Effect::GradientOverlay { gradient, .. } => Some(gradient),
+ Effect::Stroke(s) => match &s.paint {
+ FxPaint::Gradient(g) => Some(g),
+ _ => None,
+ },
+ Effect::OuterGlow(g) | Effect::InnerGlow(g) => match &g.paint {
+ FxPaint::Gradient(g) => Some(g),
+ _ => None,
+ },
+ _ => None,
+ };
+ if let Some(g) = gradient {
+ check_gradient_stops(&g.stops)?;
+ check_gradient_stops(&g.opacity_stops)?;
+ }
+ }
// Linked patterns tile from the effects reference point (else the layer's top-left).
let anchor = layer.effects.reference.unwrap_or((f64::from(sb.x0), f64::from(sb.y0)));
let vector_shape = matches!(layer.content, LayerContent::Shape(_)) && !outline;
@@ -1598,6 +1622,19 @@ fn gradient_rows(g: &Gradient) -> Vec<[f32; 4096]> {
rows
}
+/// Linear interpolation between LUT entries cannot preserve a discontinuity. Let the canvas
+/// use the CPU oracle for coincident stops, including opacity stops and unsorted fill ramps
+/// (which `gradient_fill::Ramp` sorts). Check only ramps we will sample: cached fills and
+/// disabled effects can still use the GPU.
+fn check_gradient_stops<T>(stops: &[(f32, T)]) -> Result<(), Unsupported> {
+ let mut positions: Vec<f32> = stops.iter().map(|s| s.0).collect();
+ positions.sort_by(f32::total_cmp);
+ if positions.windows(2).any(|w| w[0] == w[1]) {
+ return Err(Unsupported("coincident gradient stops (composited on the CPU)".into()));
+ }
+ Ok(())
+}
+
/// Mode index used by the shader (declaration order of [`BlendMode`]).
pub fn mode_index(m: BlendMode) -> i32 {
match m {
diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rs
index 7f65e1413..0b700d5f1 100644
--- a/crates/gpu/tests/parity.rs
+++ b/crates/gpu/tests/parity.rs
@@ -347,6 +347,131 @@ fn groups_masks_and_clipping() {
}
}
+#[test]
+fn hard_stop_gradients_match_cpu_or_fall_back() {
+ let Some(mut g) = gpu() else { return };
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let mut d = Document::new("hard stops", Size::new(8, 2), ColorMode::Rgb, depth);
+ let mut fill =
+ Fill::gradient(vec![(0.0, Color::BLACK), (0.5, Color::WHITE), (0.5, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false);
+ for opacity in [false, true] {
+ if opacity && let Fill::Gradient { stops, opacity_stops, .. } = &mut fill {
+ *stops = vec![(0.0, Color::WHITE), (1.0, Color::WHITE)];
+ *opacity_stops = vec![(0.0, 0.0), (0.5, 1.0), (0.5, 0.0), (1.0, 1.0)];
+ }
+ d.layers.clear();
+ d.layers.push(Layer::new("gradient", LayerContent::Fill(fill.clone())));
+ let cpu = photocraft_compose::render(&d, d.bounds());
+ assert_eq!(cpu.px[4], [1.0; 4]);
+ let out = match render_to_vec(&mut g.comp, &g.device, &g.queue, &d, d.bounds()) {
+ Ok(out) => out,
+ Err(e) => {
+ assert!(e.0.contains("coincident gradient stops"), "{e}");
+ photocraft_compose::render(&d, d.bounds()).px
+ }
+ };
+ let worst = worst_diff(&cpu.px, &out);
+ assert!(worst.0 <= TOL, "{depth:?}: diff {}/255, cpu {:?}, gpu {:?}", worst.0 * 255.0, cpu.px[worst.1], out[worst.1]);
+ assert!(g.comp.supports(&d).is_err(), "hard stops must request the canvas's CPU fallback");
+ }
+
+ // The ordinary two-stop control must still render on the GPU.
+ d.layers[0].content = LayerContent::Fill(Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false));
+ check(&mut g, &d, &format!("linear gradient control {depth:?}"));
+ }
+}
+
+#[test]
+fn hard_stop_fill_fallback_respects_caches_and_visibility() {
+ use photocraft_doc::FillCache;
+ use photocraft_raster::Surface;
+
+ for opacity in [false, true] {
+ // Non-adjacent duplicates must be caught too: the CPU sorts fill stops.
+ let mut fill = Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false);
+ if let Fill::Gradient { stops, opacity_stops, .. } = &mut fill {
+ if opacity {
+ *opacity_stops = vec![(0.5, 1.0), (0.0, 0.0), (0.5, 0.0), (1.0, 1.0)];
+ } else {
+ *stops = vec![(0.5, Color::WHITE), (0.0, Color::BLACK), (0.5, Color::BLACK), (1.0, Color::WHITE)];
+ }
+ }
+ let mut d = Document::new("hard stops", Size::new(8, 2), ColorMode::Rgb, SampleType::U8);
+ d.layers.push(Layer::new("gradient", LayerContent::Fill(fill.clone())));
+ assert_gradient_fallback(&d);
+
+ d.layers[0].visible = false;
+ assert!(photocraft_gpu::plan(&d).is_ok(), "hidden fill is not sampled");
+ d.layers[0].visible = true;
+ d.layers[0].fill_cache = Some(FillCache { fill: fill.clone(), surface: Surface::with_default(d.pixel_format(), &[1.0; 4]) });
+ assert!(photocraft_gpu::plan(&d).is_ok(), "matching fill cache is sampled instead of the ramp");
+ if let LayerContent::Fill(Fill::Gradient { reverse, .. }) = &mut d.layers[0].content {
+ *reverse = true;
+ }
+ assert_gradient_fallback(&d);
+
+ // Group and clipping routes must propagate Unsupported to the canvas too.
+ d.layers[0] = Layer::group("group", vec![Layer::new("gradient", LayerContent::Fill(fill.clone()))]);
+ assert_gradient_fallback(&d);
+ let mut clipped = Layer::new("clipped", LayerContent::Fill(fill));
+ clipped.clipped = true;
+ d.layers = vec![Layer::new("base", LayerContent::Fill(Fill::Solid(Color::WHITE))), clipped];
+ assert_gradient_fallback(&d);
+ d.layers.push(Layer::new("cover", LayerContent::Fill(Fill::Solid(Color::WHITE))));
+ assert!(photocraft_gpu::plan(&d).is_ok(), "occluded gradients are not sampled");
+ }
+}
+
+fn assert_gradient_fallback(d: &Document) {
+ let e = photocraft_gpu::plan(d).unwrap_err();
+ assert!(e.0.contains("coincident gradient stops"), "{e}");
+}
+
+#[test]
+fn hard_stop_effects_and_gradient_maps_request_cpu() {
+ let mut d = Document::with_background("hard stops", Size::new(8, 2), ColorMode::Rgb, SampleType::U8, Color::WHITE);
+ for opacity in [false, true] {
+ for position in [0.0, 0.5, 1.0] {
+ let mut gradient = Gradient::default();
+ if opacity {
+ gradient.opacity_stops = vec![(position, 1.0), (position, 0.0)];
+ } else {
+ gradient.stops = vec![(position, Color::WHITE), (position, Color::BLACK)];
+ }
+ let paint = FxPaint::Gradient(gradient.clone());
+ let effects = [
+ Effect::GradientOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), gradient, dither: false },
+ Effect::Stroke(StrokeFx { common: FxCommon::new(BlendMode::Normal, 1.0), size: 1.0, position: StrokePosition::Inside, paint: paint.clone() }),
+ Effect::InnerGlow(glow(paint.clone(), GlowTechnique::Softer, 1.0, 0.0, GlowSource::Edge)),
+ Effect::OuterGlow(glow(paint, GlowTechnique::Softer, 1.0, 0.0, GlowSource::Edge)),
+ ];
+ for effect in effects {
+ d.layers[0].effects.items = vec![effect];
+ assert_gradient_fallback(&d);
+ d.layers[0].effects.enabled = false;
+ assert!(photocraft_gpu::plan(&d).is_ok(), "disabled effects are not sampled");
+ d.layers[0].effects.enabled = true;
+ d.layers[0].effects.items[0].set_enabled(false);
+ assert!(photocraft_gpu::plan(&d).is_ok(), "disabled effect is not sampled");
+ }
+ }
+ }
+ d.layers[0].effects.items.clear();
+ d.layers.push(Layer::new(
+ "map",
+ LayerContent::Adjustment(Adjustment::GradientMap {
+ stops: vec![(0.0, [0.0; 3]), (0.5, [1.0; 3]), (0.5, [0.0; 3]), (1.0, [1.0; 3])],
+ reverse: false,
+ dither: false,
+ }),
+ ));
+ assert_gradient_fallback(&d);
+ d.layers[1].clipped = true;
+ assert_gradient_fallback(&d);
+ d.layers[1].visible = false;
+ assert!(photocraft_gpu::plan(&d).is_ok());
+}
+
#[test]
fn fills_and_dissolve() {
let Some(mut g) = gpu() else { return };