diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs index 9f769e5dfe..d5d1d31aea 100644 --- a/crates/compose/src/effects.rs +++ b/crates/compose/src/effects.rs @@ -54,8 +54,8 @@ use distance::{ }; use paint::dissolves; pub use paint::{ - bevel_contour_lut, glow_gradient_gain, glow_lut, glow_paint_lut, gradient_t, gradient_units, hash_noise, ranged_lut, sample_gradient, satin_lut, - spread_split, + aa_shift, anti_aliased_contour, bevel_contour_lut, glow_gradient_gain, glow_lut, glow_paint_lut, gradient_t, gradient_units, hash_noise, ranged_lut, + sample_gradient, satin_lut, spread_split, }; #[cfg(test)] use paint::{glow_map, lut_at, noise, offset, shadow_map}; @@ -246,6 +246,8 @@ impl FxMaps { } } +#[cfg(test)] +mod inner_shadow_anti_alias_tests; #[cfg(test)] mod outer_glow_noise_tests; diff --git a/crates/compose/src/effects/inner_shadow_anti_alias_tests.rs b/crates/compose/src/effects/inner_shadow_anti_alias_tests.rs new file mode 100644 index 0000000000..1b3f97315d --- /dev/null +++ b/crates/compose/src/effects/inner_shadow_anti_alias_tests.rs @@ -0,0 +1,298 @@ +//! #14934 - BUG-LAYER-STYLE-INNER-SHADOW-ANTI-ALIASED-IGNORED. +//! +//! Measured on the issue's test document: 400 x 300 px, 72 ppi, RGB 8 bit, white Background, a +//! pixel layer with an orange (255, 128, 0) rectangle at x 100..=299, y 75..=224. Black Inner +//! Shadow, Normal 100 %, Use Global Light off, Size 10, Distance 0, Choke 0, Noise 0, Contour +//! Gaussian. The tables are the G channel of the flattened image read from a layer edge inwards +//! (128 = the layer's own orange, 0 = full shadow): top = column x 200 from y 75 down, left = row +//! y 150 from x 100, bottom = column x 200 from y 224 up, right = row y 150 from x 299. +//! +//! Today `shadow_map` never reads `Shadow::anti_alias`, so both settings give one map: every edge +//! reads 58 81 103 116 122 125 126 127 128, and the issue's "with and without Anti-aliased" line +//! is exactly that. The reference application's Anti-aliased profile sits on an inner shadow whose +//! source sits a third of a pixel towards the top-left: the top and left edges read +//! 65 89 107 118 124 126 127 127 128, the bottom and right 49 74 96 112 121 125 126 127 128. + +use super::*; + +const DOC_W: usize = 400; +const DOC_H: usize = 300; + +/// The layer's alpha over the whole document: solid over x 100..=299, y 75..=224. +fn document_shape() -> Map { + let mut m = Map::new(DOC_W, DOC_H, 0.0); + for y in 75..=224 { + for x in 100..=299 { + m.v[y * DOC_W + x] = 1.0; + } + } + m +} + +fn curve(name: &str, pts: &[(f32, f32)]) -> Contour { + Contour::Custom { + name: name.into(), + points: pts.iter().map(|(input, output)| photocraft_doc::adjust::CurvePoint { input: *input, output: *output }).collect(), + // Every inner point of a built-in preset is a corner (the Contour picker stores it that + // way), so the curve is its polyline. + corners: (0..pts.len()).map(|i| i > 0 && i < pts.len() - 1).collect(), + } +} + +/// The Gaussian contour as the built-in preset carries it (`layer_style::CONTOURS`). +fn gaussian() -> Contour { + curve( + "Gaussian", + &[ + (0.0, 0.0), + (0.117, 0.023), + (0.172, 0.055), + (0.234, 0.117), + (0.305, 0.234), + (0.383, 0.414), + (0.523, 0.688), + (0.617, 0.812), + (0.703, 0.891), + (0.805, 0.953), + (1.0, 1.0), + ], + ) +} + +/// A second built-in preset, to show the gate is "the measured contour", not "any curve". +fn cone() -> Contour { + curve( + "Cone", + &[ + (0.0, 0.0), + (0.172, 0.477), + (0.195, 0.555), + (0.266, 0.711), + (0.383, 0.922), + (0.43, 0.969), + (0.477, 0.992), + (0.523, 0.992), + (0.57, 0.969), + (0.664, 0.859), + (0.703, 0.789), + (0.742, 0.711), + (0.836, 0.477), + (0.859, 0.398), + (0.914, 0.266), + (0.945, 0.156), + (0.977, 0.078), + (1.0, 0.0), + ], + ) +} + +/// The issue's Inner Shadow settings: black, Normal, 100 %, global light off, Choke `spread`. +fn shadow(size: f32, distance: f32, angle: f32, spread: f32, contour: Contour, anti_aliased: bool) -> Shadow { + Shadow { + common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), + color: photocraft_color::Color::BLACK, + angle, + use_global_light: false, + distance, + spread, + size, + contour, + anti_alias: anti_aliased, + noise: 0.0, + knocks_out: false, + } +} + +fn map(size: f32, distance: f32, angle: f32, spread: f32, contour: Contour, anti_aliased: bool) -> Map { + shadow_map(&document_shape(), &shadow(size, distance, angle, spread, contour, anti_aliased), &GlobalLight::default(), true, (0, 0)) +} + +/// The G channel of the orange layer under a black Normal inner shadow of coverage `c`. +fn g(c: f32) -> f32 { + 128.0 * (1.0 - c) +} + +/// The nine G values inwards from each of the issue's four edges, in the order it reads them. +fn ramps(m: &Map) -> [Vec; 4] { + let line = |first: (i64, i64), step: (i64, i64)| (0..9).map(|k| g(m.get(first.0 + k * step.0, first.1 + k * step.1))).collect(); + [line((200, 75), (0, 1)), line((100, 150), (1, 0)), line((200, 224), (0, -1)), line((299, 150), (-1, 0))] +} + +/// Assert each edge's ramp against `want` within `tol` levels. +fn assert_edges(m: &Map, want: &[&[f32]; 4], tol: f32, what: &str) { + for ((side, r), w) in ["top", "left", "bottom", "right"].iter().zip(ramps(m)).zip(want) { + for (d, (got, want)) in r.iter().zip(*w).enumerate() { + assert!((got - want).abs() <= tol, "{what}, {side} edge, {d} px in: {got:.1} vs measured {want} (within {tol})", got = got); + } + } +} + +/// A hash over every coverage value of a map: the map is bit-for-bit unchanged iff this is. +fn bit_hash(m: &Map) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for v in &m.v { + h = (h ^ u64::from(v.to_bits())).wrapping_mul(0x0000_0100_0000_01b3); + } + h +} + +/// Done when: on the issue's test document, Size 10 Gaussian with Anti-aliased gives the measured +/// top/left and bottom/right profiles within 3 levels. The two pairs of edges differ because the +/// source sits off-centre; the issue leaves *why* they differ unmeasured, and this test pins the +/// measured profiles rather than a rule for the unmeasured ones. +#[test] +fn anti_aliased_gaussian_gives_both_measured_profiles() { + let want: [&[f32]; 4] = [ + &[65.0, 89.0, 107.0, 118.0, 124.0, 126.0, 127.0, 127.0, 128.0], + &[65.0, 89.0, 107.0, 118.0, 124.0, 126.0, 127.0, 127.0, 128.0], + &[49.0, 74.0, 96.0, 112.0, 121.0, 125.0, 126.0, 127.0, 128.0], + &[49.0, 74.0, 96.0, 112.0, 121.0, 125.0, 126.0, 127.0, 128.0], + ]; + assert_edges(&map(10.0, 0.0, 0.0, 0.0, gaussian(), true), &want, 3.0, "Size 10 Gaussian, Anti-aliased"); +} + +/// Done when: without Anti-aliased the profiles stay as today. These are the G values `shadow_map` +/// gives on upstream/main for every Size 10 contour, and the issue's own "what happens today" line. +#[test] +fn without_anti_alias_the_profiles_stay_as_today() { + let today: [f32; 9] = [58.0, 81.0, 103.0, 116.0, 122.0, 125.0, 126.0, 127.0, 128.0]; + let m = map(10.0, 0.0, 0.0, 0.0, gaussian(), false); + for (side, r) in ["top", "left", "bottom", "right"].iter().zip(ramps(&m)) { + for (d, got) in r.iter().enumerate() { + assert_eq!(got.round() as i32, today[d] as i32, "Anti-aliased off moved the {side} edge, {d} px in: {got:.2}"); + } + } + // And the whole map is what it was: the issue's measured off-path, unchanged by the flag. + assert_eq!(bit_hash(&m), 0x2cf1_991d_b2c1_a195, "the Size 10 Gaussian off-path map moved"); + // The centre of the layer keeps its own colour with the flag on as with it off (measured + // 255.128.0 in both cases): the shadow map is empty there. + for aa in [false, true] { + assert_eq!(map(10.0, 0.0, 0.0, 0.0, gaussian(), aa).get(200, 150), 0.0, "the layer centre gained a shadow with Anti-aliased = {aa}"); + } +} + +/// The sub-pixel source sits inside the layer: an inner shadow still paints nothing outside the +/// shape, whatever the flag. A third of a pixel must not pull coverage through the layer edge. +#[test] +fn anti_aliased_still_paints_nothing_outside_the_layer() { + let m = map(10.0, 0.0, 0.0, 0.0, gaussian(), true); + for (x, y) in [(200i64, 74), (200, 225), (99, 150), (300, 150), (99, 74), (300, 225)] { + assert_eq!(m.get(x, y), 0.0, "inner shadow outside the layer at ({x},{y}) with Anti-aliased on"); + } + // The measured reach inwards is unchanged: 9 px in every edge still reads the layer's own 128. + for (side, first, step) in [("top", (200i64, 75), (0i64, 1)), ("left", (100, 150), (1, 0)), ("bottom", (200, 224), (0, -1)), ("right", (299, 150), (-1, 0))] + { + let deep = g(m.get(first.0 + 8 * step.0, first.1 + 8 * step.1)); + assert_eq!(deep.round() as i32, 128, "the {side} edge shadow reached further in with Anti-aliased on: {deep:.1} at 8 px"); + } +} + +/// Not measured: Anti-aliased with a contour other than Gaussian. Those keep today's map +/// bit-for-bit - the Linear default, a second built-in curve, and the Drop Shadow (its own item is +/// #14881). Hashes are the ones these maps had on upstream/main before the change. +#[test] +fn other_contours_and_the_drop_shadow_keep_todays_map() { + assert_eq!(bit_hash(&map(10.0, 0.0, 0.0, 0.0, Contour::Linear, true)), 0x2200_2b2d_61bc_9c2d, "a Linear-contour inner shadow with Anti-aliased moved"); + assert_eq!(bit_hash(&map(10.0, 0.0, 0.0, 0.0, cone(), true)), 0xb86c_68a7_8a2f_e689, "a Cone-contour inner shadow with Anti-aliased moved"); + let drop = |aa: bool| shadow_map(&document_shape(), &shadow(10.0, 0.0, 0.0, 0.0, gaussian(), aa), &GlobalLight::default(), false, (0, 0)); + assert_eq!(bit_hash(&drop(false)), 0x5e49_20b6_9751_cc45, "the Drop Shadow Gaussian map (Anti-aliased off) moved"); + assert_eq!(bit_hash(&drop(true)), 0x5e49_20b6_9751_cc45, "the Drop Shadow still ignores Anti-aliased (#14881)"); +} + +/// The flag off leaves every other Size, Distance and Choke exactly as it was. These are the whole +/// map hashes `shadow_map` gave on upstream/main c162cb6d6 before this change, copied out of the +/// probe run; they pin that the anti-aliased source is taken only when the flag is on. +#[test] +fn the_off_path_is_bit_for_bit_unchanged() { + let hashes: [(f32, u64); 8] = [ + (0.5, 0xe94d_157b_1934_6225), + (1.5, 0x87a1_3f9d_d043_dcb9), + (2.0, 0xbe9c_6dd8_2c2a_fead), + (3.0, 0x3208_8f2d_83f7_d11d), + (6.0, 0xda06_d874_0203_1369), + (10.0, 0x2cf1_991d_b2c1_a195), + (20.0, 0xfdf3_096c_5583_d1c1), + (250.0, 0x48ce_bfb8_fbe0_5379), + ]; + for (size, want) in hashes { + assert_eq!(bit_hash(&map(size, 0.0, 0.0, 0.0, gaussian(), false)), want, "the whole Size {size} inner shadow map (Anti-aliased off) moved"); + } + assert_eq!(bit_hash(&map(10.0, 5.0, 90.0, 0.0, gaussian(), false)), 0xe8fb_ce94_b436_f35b, "the Size 10 Distance 5 inner shadow map moved"); + assert_eq!(bit_hash(&map(10.0, 0.0, 0.0, 0.5, gaussian(), false)), 0x013f_77f0_d6ef_b7c1, "the Size 10 Choke 50 % inner shadow map moved"); +} + +// --------------------------------------------------------------------------------------------- +// Independent review of this PR: the offset was a constant applied at every Size, Choke and +// Distance with the flag on, and only Size 10 / Choke 0 was measured. The four probes below are +// the review's break inputs, written before the code changed. + +/// The review's first break: the issue's document with SIZE 1 (Angle 0, Distance 0, Choke 0, +/// Gaussian, Anti-aliased on). `spread_split(1, 0)` is `(0, 1)`, so `dilate` no-ops at a radius of +/// 0 and `blur(m, 1.0)` is the identity (`tent_kernel(1).0 == 0`, and `tent` returns at once): the +/// third-of-a-pixel source offset becomes the whole map. Coverage 1/3 through the Gaussian +/// contour (0.30) then lands on the bottom and right inner edges only, G 90 where the layer reads +/// its own 128, and nothing at the top and left - a one-sided black line that no measurement +/// shows, because Size 1 was never measured with the flag on. Today's Size 1 map is empty and +/// has to stay empty. +#[test] +fn anti_aliased_size_one_keeps_todays_empty_map() { + let off = map(1.0, 0.0, 0.0, 0.0, gaussian(), false); + assert!(off.v.iter().all(|v| *v == 0.0), "today's Size 1 inner shadow map is no longer empty"); + let on = map(1.0, 0.0, 0.0, 0.0, gaussian(), true); + for (side, x, y) in [("bottom", 200i64, 224), ("right", 299, 150), ("top", 200, 75), ("left", 100, 150)] { + let got = g(on.get(x, y)); + assert_eq!(got.round() as i32, 128, "Anti-aliased Size 1 painted the {side} inner edge: G {got:.1}"); + } + assert_eq!(bit_hash(&on), bit_hash(&off), "the Size 1 inner shadow map moved with Anti-aliased on"); +} + +/// The second degeneracy the review names: Size 2 with Choke 50 %. `spread_split(2, 0.5)` is +/// `(1, 1.0)`, a 1 px dilation plus a blur of width exactly 1 - the identity again - so the +/// offset would be the only soft thing in the map. That neighbour keeps today's output. +#[test] +fn anti_aliased_size_two_choke_half_keeps_todays_map() { + let off = map(2.0, 0.0, 0.0, 0.5, gaussian(), false); + let on = map(2.0, 0.0, 0.0, 0.5, gaussian(), true); + assert_eq!(bit_hash(&on), bit_hash(&off), "the Size 2 Choke 50 % inner shadow map moved with Anti-aliased on (its blur width is 1, the identity)"); +} + +/// The parity finding: with Choke above 0 the CPU recomputes its chamfer dilation distance on the +/// offset map (`blur::dilate`), while the GPU dilates with a whole-pixel-shifted distance field of +/// the unshifted shape (`fx::builders::spread_blur`), so the two compositors part by exactly the +/// third of a pixel the offset adds. #14934 measured Choke 0, so every Choke that dilates keeps +/// today's map. The boundary is the map both compositors can build alike: no dilation +/// (`spread_split`'s radius 0) and a blur wider than the identity. +#[test] +fn anti_aliased_choke_keeps_todays_map() { + let off = map(10.0, 0.0, 0.0, 0.5, gaussian(), false); + assert_eq!(bit_hash(&off), 0x013f_77f0_d6ef_b7c1, "the Size 10 Choke 50 % inner shadow map (Anti-aliased off) moved"); + assert_eq!( + bit_hash(&map(10.0, 0.0, 0.0, 0.5, gaussian(), true)), + 0x013f_77f0_d6ef_b7c1, + "Anti-aliased moved the Size 10 Choke 50 % map, where CPU and GPU cannot be made equal" + ); + // Choke 5 % dilates too (spread_split(10, 0.05) = (1, 9.5)) and stays on today's map. + assert_eq!( + bit_hash(&map(10.0, 0.0, 0.0, 0.05, gaussian(), true)), + bit_hash(&map(10.0, 0.0, 0.0, 0.05, gaussian(), false)), + "Anti-aliased moved the Size 10 Choke 5 % map" + ); +} + +/// Pattern 13 the other way round: the rule may not be keyed on the one measured document's +/// Size 10 either. Every Size whose blur is wider than the identity takes the offset at Choke 0, +/// and so does a Distance other than 0 - the offset is a rule in the inputs. Guard test: green +/// before and after, it states where the boundary must NOT sit. +#[test] +fn the_offset_follows_the_inputs_not_the_measured_size() { + for size in [1.5, 2.0, 3.0, 6.0, 20.0, 250.0] { + let off = bit_hash(&map(size, 0.0, 0.0, 0.0, gaussian(), false)); + assert_ne!( + bit_hash(&map(size, 0.0, 0.0, 0.0, gaussian(), true)), + off, + "Anti-aliased did nothing at Size {size}, Choke 0: the rule would be keyed on the measured Size 10" + ); + } + let dist_off = bit_hash(&map(10.0, 5.0, 90.0, 0.0, gaussian(), false)); + assert_ne!(bit_hash(&map(10.0, 5.0, 90.0, 0.0, gaussian(), true)), dist_off, "Anti-aliased did nothing at Size 10, Distance 5, Choke 0"); +} diff --git a/crates/compose/src/effects/paint.rs b/crates/compose/src/effects/paint.rs index ff3e374324..a1783051da 100644 --- a/crates/compose/src/effects/paint.rs +++ b/crates/compose/src/effects/paint.rs @@ -247,6 +247,57 @@ pub(super) fn offset(angle: f32, distance: f32) -> (f32, f32) { ((-a.cos() * distance).round(), (a.sin() * distance).round()) } +/// Whether an effect's Anti-aliased checkbox moves its source map: only for the contour the +/// reference application was measured with. #14934 (Inner Shadow) and #14951 (Outer Glow) both +/// measure Size 10 with the Gaussian contour and leave Anti-aliased with any other contour +/// unmeasured, so every other contour keeps today's map bit-for-bit. The built-in Gaussian preset +/// carries that name from the Contour picker and from a PSD import; an edited curve becomes +/// "Custom" and keeps today's map. Public because the GPU map program asks for the same rule, so +/// both compositors take the offset or neither does. +pub fn anti_aliased_contour(c: &Contour) -> bool { + matches!(c, Contour::Custom { name, .. } if name.eq_ignore_ascii_case("Gaussian")) +} + +/// Whether Choke / Spread `spread` of a `size` px soft effect leaves the map both issues measured: +/// one the two compositors build alike, and one whose edge is soft at all. `spread_split` splits +/// the Size into a dilation radius and a blur width, and both neighbours of the measured split are +/// degeneracies of that split rather than a guess about an unmeasured picture: +/// - a radius above 0 makes the CPU recompute its chamfer distance on the offset map +/// (`blur::dilate`), while the GPU dilates with a distance field of the unshifted shape shifted +/// by whole pixels only (`fx::builders::spread_blur`), so the two compositors part by exactly +/// the fraction of a pixel the offset adds. Keep those on today's map. +/// - a blur width of 1 or less is the identity (`blur::tent` returns at once, because +/// `tent_kernel(1).0 == 0`), and with the radius at 0 nothing else softens the edge either: at +/// Size 1, or at Size 2 with half Choke / Spread, the source offset would be the whole map - +/// coverage on the bottom and right inner edges of an Inner Shadow and one glowing line outside +/// the top and left of an Outer Glow, which no measurement shows. +/// +/// Radius 0 with a wider blur is the map both issues measured, whatever the Size: the rule is in +/// the inputs, not in the measured documents' Size 10. +fn anti_aliased_geometry(size: f32, spread: f32) -> bool { + let (r, bw) = spread_split(size, spread); + r <= 0.0 && bw > 1.0 +} + +/// The sub-pixel offset towards the top-left that an anti-aliased effect builds its map from, +/// added to the whole-pixel light offset. Both measured tables sit on a third of a pixel: with the +/// flag on, the Outer Glow reaches a pixel further at the top and left (its reported bounds grow +/// there) and a pixel less at the bottom and right, and the Inner Shadow is weaker at the top and +/// left edge and stronger at the bottom and right. Half a pixel overshoots (it puts the Inner +/// Shadow 5 levels and the Outer Glow 15 levels off the measured profiles); a third lands the +/// Inner Shadow within 1.4 levels of every measured pixel, and the glow within 4.6 at four +/// samples of eighteen and within 3 at the rest, which is where today's off-path profile already +/// sits from the reference. *Why* the two pairs of edges differ is not measured, so this +/// reproduces both profiles instead of guessing a rule for the unmeasured cases. The GPU map +/// program adds the same offset to its shift stage, so both compositors build the same geometry. +/// Only the configuration the issues measured takes it: the Gaussian contour +/// (`anti_aliased_contour`) with a Size and Choke / Spread `anti_aliased_geometry` allows, so the +/// offset is neither keyed to the measured Size nor applied to a map the two compositors build +/// differently. Every other neighbour keeps today's map bit-for-bit. +pub fn aa_shift(on: bool, c: &Contour, size: f32, spread: f32) -> f32 { + if on && anti_aliased_contour(c) && anti_aliased_geometry(size, spread) { -1.0 / 3.0 } else { 0.0 } +} + /// The lengths a 100 % gradient at `angle` spans in a `w` × `h` frame: the chord (Linear and /// Reflected) and the ellipse-norm length (Radial, Angle, Diamond; its half is the radius). pub fn gradient_units(angle: f32, w: f32, h: f32) -> (f32, f32) { @@ -394,8 +445,12 @@ pub fn spread_split(size: f32, spread: f32) -> (f32, f32) { pub(super) fn shadow_map(shape: &Map, s: &Shadow, light: &GlobalLight, inner: bool, origin: (i32, i32)) -> Map { let angle = if s.use_global_light { light.angle } else { s.angle }; let (dx, dy) = offset(angle, s.distance); + // #14934: an Anti-aliased Inner Shadow builds its map from the shape off-centre (`aa_shift`). + // Only the inner branch was measured, so a Drop Shadow keeps today's map (#14881 is its own), + // and `aa_shift` leaves every Choke that dilates and every Size whose blur is the identity. + let aa = aa_shift(inner && s.anti_alias, &s.contour, s.size, s.spread); let src = if inner { shape.clone().map(|a| 1.0 - a) } else { shape.clone() }; - let mut m = src.shifted(dx, dy, if inner { 1.0 } else { 0.0 }); + let mut m = src.shifted(dx + aa, dy + aa, if inner { 1.0 } else { 0.0 }); let (r, bw) = spread_split(s.size, s.spread); m = dilate(&m, r); blur(&mut m, bw); diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgsl index a1830302b4..a7c804ae53 100644 --- a/crates/gpu/src/compose.wgsl +++ b/crates/gpu/src/compose.wgsl @@ -1411,14 +1411,31 @@ fn ra(p: vec2) -> f32 { } fn mout(v: f32) -> vec4 { return vec4(v, 0.0, 0.0, 1.0); } -// Map::shifted by whole pixels: p0 = (dx, dy, outside, invert (1 - a before shifting)). +// Map::shifted, whole-pixel or sub-pixel: p0 = (dx, dy, outside, invert). The invert is taken per +// tap, as the CPU inverts its map before sampling it and uses `outside` for taps off the map. A +// whole-pixel offset weights its four taps 1 and 0, so it reads exactly the one texel the old +// whole-pixel path read; the arithmetic order matches `Map::shifted` term by term. +fn mtap(p: vec2, outside: f32, invert: f32) -> f32 { + if (!inside(p, chunk.size)) { return outside; } + let v = textureLoad(tex_a, p, 0).r; + if (invert > 0.5) { return 1.0 - v; } + return v; +} @fragment fn fs_mshift(in: VOut) -> @location(0) vec4 { - let s = local(in.pos) - vec2(i32(op.p0.x), i32(op.p0.y)); - if (!inside(s, chunk.size)) { return mout(op.p0.z); } - var v = textureLoad(tex_a, s, 0).r; - if (op.p0.w > 0.5) { v = 1.0 - v; } - return mout(v); + let p = local(in.pos); + let fx = floor(op.p0.x); + let fy = floor(op.p0.y); + let ax = op.p0.x - fx; + let ay = op.p0.y - fy; + let s = p - vec2(i32(fx), i32(fy)); + let v00 = mtap(s, op.p0.z, op.p0.w); + let v10 = mtap(s - vec2(1, 0), op.p0.z, op.p0.w); + let v01 = mtap(s - vec2(0, 1), op.p0.z, op.p0.w); + let v11 = mtap(s - vec2(1, 1), op.p0.z, op.p0.w); + let top = v00 * (1.0 - ax) + v10 * ax; + let bot = v01 * (1.0 - ax) + v11 * ax; + return mout(top * (1.0 - ay) + bot * ay); } // effects::dilate: inside (distance < 0) min(A + r, 1), else max(A, clamp(r + 0.5 - dist_outside)); diff --git a/crates/gpu/src/fx.rs b/crates/gpu/src/fx.rs index 2e949a42e1..48dc0eec2c 100644 --- a/crates/gpu/src/fx.rs +++ b/crates/gpu/src/fx.rs @@ -209,13 +209,14 @@ impl B { fn bevel_fields(&mut self, width: f32) -> [In; 2] { [FieldKind::BevelInside, FieldKind::BevelOutside].map(|k| self.field(k, width)) } - /// `Map::shifted` by whole pixels (`invert`: of `1 - a`); identity shifts of the plain map - /// are skipped. + /// `Map::shifted`, whole-pixel or sub-pixel (`invert`: of `1 - a`, per tap as the CPU inverts + /// its map before sampling); identity shifts of the plain map are skipped. A sub-pixel shift + /// reads the tap beyond its base, so the radius ceils rather than truncates. fn shift(&mut self, src: In, dx: f32, dy: f32, outside: f32, invert: bool) -> In { if dx == 0.0 && dy == 0.0 && !invert { return src; } - let r = dx.abs().max(dy.abs()) as i32; + let r = dx.abs().max(dy.abs()).ceil() as i32; self.push(stage(Kernel::MShift, Some(src), None, [dx, dy, outside, f32::from(u8::from(invert))], r)) } /// `dilate(src, r)` given `dist_outside(src)`. diff --git a/crates/gpu/src/fx/builders.rs b/crates/gpu/src/fx/builders.rs index e11aa1d75c..f1c18f975a 100644 --- a/crates/gpu/src/fx/builders.rs +++ b/crates/gpu/src/fx/builders.rs @@ -18,7 +18,16 @@ impl B { // shadow_map let angle = if s.use_global_light { light.angle } else { s.angle }; let (dx, dy) = offset(angle, s.distance); - let src = self.shift(In::Shape, dx, dy, if inner { 1.0 } else { 0.0 }, inner); + // #14934: an Anti-aliased Inner Shadow takes the CPU's sub-pixel source offset, on the + // CPU's gate only (`fx::aa_shift`: the inner branch, the Gaussian contour, and a Size and + // Choke that leave the map a shift plus a blur that is not the identity). A Drop Shadow + // keeps today's map (#14881). At a Choke that dilates the CPU recomputes its dilation + // distance on the offset map while this builder shifts the whole-pixel field of the + // unshifted shape, and at a blur of width 1 the offset would be the whole map: both + // neighbours take no offset here, which is what keeps them equal on both compositors + // (`anti_aliased_inner_shadow_gated_neighbours_match_the_cpu`). + let aa = fx::aa_shift(inner && s.anti_alias, &s.contour, s.size, s.spread); + let src = self.shift(In::Shape, dx + aa, dy + aa, if inner { 1.0 } else { 0.0 }, inner); let m = self.spread_blur(src, (s.size, s.spread), inner, dx, dy); self.finish(m, None, false, &s.contour, inner, 0); 1 diff --git a/crates/gpu/src/fx/tests.rs b/crates/gpu/src/fx/tests.rs index d796288eeb..af9ab806be 100644 --- a/crates/gpu/src/fx/tests.rs +++ b/crates/gpu/src/fx/tests.rs @@ -317,3 +317,161 @@ fn bands_end_at_the_coordinate_ceiling() { assert_eq!((bands[0].y0, bands[0].y1, bands[1].y1), (i32::MAX - 100, i32::MAX - 36, i32::MAX)); assert_eq!(super::bands(Rect::new(0, 0, 8, 10), 0).len(), 10, "a zero step still makes progress"); } + +/// #14934: the GPU's Inner Shadow program takes the same sub-pixel source offset as the CPU's +/// `shadow_map` - without a device, by asking what stages the effect builds. The measured gate +/// (Anti-aliased on, Gaussian contour, the inner branch) is what adds the stage; a Linear contour +/// or a Drop Shadow keeps the program, and the program key, exactly as it was. +#[test] +fn anti_aliased_inner_shadow_shifts_the_map_stage() { + use photocraft_doc::{Contour, FxCommon, Shadow}; + let pts: [(f32, f32); 11] = [ + (0.0, 0.0), + (0.117, 0.023), + (0.172, 0.055), + (0.234, 0.117), + (0.305, 0.234), + (0.383, 0.414), + (0.523, 0.688), + (0.617, 0.812), + (0.703, 0.891), + (0.805, 0.953), + (1.0, 1.0), + ]; + let gaussian = Contour::Custom { + name: "Gaussian".into(), + points: pts.iter().map(|(input, output)| photocraft_doc::adjust::CurvePoint { input: *input, output: *output }).collect(), + corners: (0..pts.len()).map(|i| i > 0 && i < pts.len() - 1).collect(), + }; + let shadow = |anti_aliased: bool, contour: Contour| Shadow { + common: FxCommon::new(BlendMode::Normal, 1.0), + color: photocraft_color::Color::BLACK, + angle: 0.0, + use_global_light: false, + distance: 0.0, + spread: 0.0, + size: 10.0, + contour, + anti_alias: anti_aliased, + noise: 0.0, + knocks_out: false, + }; + fn shift_stages(p: &MapProgram) -> Vec<&Stage> { + p.stages.iter().filter(|s| s.kernel == Kernel::MShift).collect() + } + let light = GlobalLight::default(); + let aa = photocraft_compose::effects::aa_shift(true, &gaussian, 10.0, 0.0); + assert_eq!(aa, -1.0 / 3.0, "the CPU offset the GPU has to copy at the measured Size 10, Choke 0"); + // The inner branch always takes one shift stage: it is where `1 - alpha` happens. At Distance 0 + // without Anti-aliased that stage is the identity, and that is what must change. + let off = program(&Effect::InnerShadow(shadow(false, gaussian.clone())), &light, false); + assert_eq!(shift_stages(&off).len(), 1, "the inner branch keeps its one (identity) shift stage"); + assert_eq!(shift_stages(&off)[0].p0, [0.0, 0.0, 1.0, 1.0], "p0 = (dx, dy, outside, invert) at Distance 0, Anti-aliased off"); + let on = program(&Effect::InnerShadow(shadow(true, gaussian.clone())), &light, false); + assert_eq!(shift_stages(&on).len(), 1, "the Anti-aliased inner shadow still builds one shift stage, not two"); + assert_eq!(shift_stages(&on)[0].p0, [aa, aa, 1.0, 1.0], "the shift stage must carry the CPU's sub-pixel source offset"); + assert!( + shift_stages(&on)[0].radius >= 1, + "a sub-pixel shift reads the tap beyond its base, so the stage radius must cover it: {}", + shift_stages(&on)[0].radius + ); + assert_ne!(on.key, off.key, "the flag has to invalidate the cached program"); + // Unmeasured cases keep today's stage: the contour gate is the CPU's. + let linear = program(&Effect::InnerShadow(shadow(true, Contour::Linear)), &light, false); + assert_eq!(shift_stages(&linear)[0].p0, [0.0, 0.0, 1.0, 1.0], "a Linear inner shadow still ignores Anti-aliased (#14934 leaves that contour unmeasured)"); + // A Drop Shadow (its own item is #14881) keeps its whole-pixel program either way. + let drop_on = program(&Effect::DropShadow(shadow(true, gaussian.clone())), &light, false); + let drop_off = program(&Effect::DropShadow(shadow(false, gaussian)), &light, false); + assert_eq!(shift_stages(&drop_on).len(), 0, "a Drop Shadow at Distance 0 takes no shift stage"); + assert_eq!(drop_on.key, drop_off.key, "the Drop Shadow still ignores Anti-aliased (#14881 is its own item)"); +} + +/// #14934 review: the GPU's gate is the CPU's rule, including its two degenerate neighbours. At +/// Size 1, and at Size 2 with Choke 50 %, the blur the map gets has width 1, which is the +/// identity, so a sub-pixel source offset would be the entire map; at any Choke that dilates the +/// CPU recomputes its distance field on the offset map while this builder shifts a whole-pixel +/// field of the unshifted shape. In every one of those the program must be the Anti-aliased-off +/// program, stage for stage and key for key. Away from the degeneracies the offset follows the +/// inputs, not the measured Size 10. +#[test] +fn anti_aliased_inner_shadow_stage_follows_the_measured_geometry() { + use photocraft_doc::{Contour, FxCommon, Shadow}; + let pts: [(f32, f32); 11] = [ + (0.0, 0.0), + (0.117, 0.023), + (0.172, 0.055), + (0.234, 0.117), + (0.305, 0.234), + (0.383, 0.414), + (0.523, 0.688), + (0.617, 0.812), + (0.703, 0.891), + (0.805, 0.953), + (1.0, 1.0), + ]; + let gaussian = || Contour::Custom { + name: "Gaussian".into(), + points: pts.iter().map(|(input, output)| photocraft_doc::adjust::CurvePoint { input: *input, output: *output }).collect(), + corners: (0..pts.len()).map(|i| i > 0 && i < pts.len() - 1).collect(), + }; + let shadow = |size: f32, spread: f32, distance: f32, anti_aliased: bool| Shadow { + common: FxCommon::new(BlendMode::Normal, 1.0), + color: photocraft_color::Color::BLACK, + angle: 0.0, + use_global_light: false, + distance, + spread, + size, + contour: gaussian(), + anti_alias: anti_aliased, + noise: 0.0, + knocks_out: false, + }; + // The inner branch always builds its source shift stage (it is where `1 - alpha` happens); a + // Choke that dilates at a Distance other than 0 adds a second one for the distance field. + let shift_key = |e: &Effect| -> (Vec<[f32; 4]>, u64) { + let p = program(e, &GlobalLight::default(), false); + (p.stages.iter().filter(|s| s.kernel == Kernel::MShift).map(|s| s.p0).collect(), p.key) + }; + let source_shift = |e: &Effect| -> [f32; 4] { + let (stages, _) = shift_key(e); + assert!(!stages.is_empty(), "the inner branch builds its source shift stage for {e:?}"); + stages[0] + }; + for (size, spread, what) in [ + (1.0, 0.0, "Size 1 (blur width 1: the identity)"), + (2.0, 0.5, "Size 2 Choke 50 % (blur width 1)"), + (10.0, 0.5, "Size 10 Choke 50 % (the CPU dilates an offset map, the GPU a whole-pixel field)"), + (10.0, 0.05, "Size 10 Choke 5 % (dilates 1 px too)"), + ] { + let on = shift_key(&Effect::InnerShadow(shadow(size, spread, 0.0, true))); + let off = shift_key(&Effect::InnerShadow(shadow(size, spread, 0.0, false))); + assert_eq!(on, off, "the {what} inner shadow program moved with Anti-aliased: on {:?}, off {:?}", on.0, off.0); + } + // Away from the degeneracies the rule is in the inputs: Size 1.5 and Size 20 take the offset + // exactly as the measured Size 10 does, and so does a Choke that dilates nothing. + let aa = -1.0f32 / 3.0; + for size in [1.5, 2.0, 3.0, 20.0] { + let p0 = source_shift(&Effect::InnerShadow(shadow(size, 0.0, 0.0, true))); + assert_eq!(p0, [aa, aa, 1.0, 1.0], "Size {size} at Choke 0 must carry the CPU's sub-pixel offset"); + } + let thin = shift_key(&Effect::InnerShadow(shadow(10.0, 0.04, 0.0, true))); + assert_eq!(thin.0, vec![[aa, aa, 1.0, 1.0]], "Choke 4 % dilates nothing (round(0.4) = 0), so the map shape is the measured one"); + let thin_off = shift_key(&Effect::InnerShadow(shadow(10.0, 0.04, 0.0, false))); + assert_ne!(thin.1, thin_off.1, "and the flag still invalidates that program's key"); + // The gate reads the Size and Choke, not the measured Distance 0: at Distance 5 (angle 0, so a + // whole-pixel light offset of -5, 0) the Choke 0 program carries that offset plus the third of + // a pixel, exactly as `shadow_map` shifts by `dx + aa`; the Choke 50 % program at the same + // Distance stays whole-pixel, gated like every other dilating Choke, and keeps its second + // (distance field) shift stage exactly as it does with the flag off. + let far_on = source_shift(&Effect::InnerShadow(shadow(10.0, 0.0, 5.0, true))); + assert_eq!(far_on, [-5.0 + aa, 0.0 + aa, 1.0, 1.0], "Size 10 Choke 0 at Distance 5 must carry the light offset plus the sub-pixel offset"); + let far_off = source_shift(&Effect::InnerShadow(shadow(10.0, 0.0, 5.0, false))); + assert_eq!(far_off, [-5.0, 0.0, 1.0, 1.0], "with the flag off the shift stays the whole-pixel light offset"); + let far_on_key = shift_key(&Effect::InnerShadow(shadow(10.0, 0.0, 5.0, true))).1; + assert_ne!(far_on_key, shift_key(&Effect::InnerShadow(shadow(10.0, 0.0, 5.0, false))).1, "and the flag invalidates the Distance 5 program key"); + let far_choke_on = shift_key(&Effect::InnerShadow(shadow(10.0, 0.5, 5.0, true))); + let far_choke_off = shift_key(&Effect::InnerShadow(shadow(10.0, 0.5, 5.0, false))); + assert_eq!(far_choke_on.0.len(), 2, "Choke 50 % at Distance 5 shifts the source and the distance field"); + assert_eq!(far_choke_on, far_choke_off, "the Choke 50 % program at Distance 5 stayed whole-pixel: on {:?}, off {:?}", far_choke_on.0, far_choke_off.0); +} diff --git a/crates/gpu/tests/it/parity.rs b/crates/gpu/tests/it/parity.rs index 7ccb4a5f8d..7dcf5b4ee6 100644 --- a/crates/gpu/tests/it/parity.rs +++ b/crates/gpu/tests/it/parity.rs @@ -3591,3 +3591,139 @@ fn sibling_compositors_have_independent_residency_and_configuration() { assert!(g.comp.resident_bytes() > 0); assert_ne!(g.comp.resident_budget(), sibling.resident_budget()); } + +// --------------------------------------------------------------------------------------------- +// #14934: the Inner Shadow's Anti-aliased checkbox has to reach the GPU map program too. + +/// The Gaussian contour as the built-in preset carries it - the contour #14934 measures with. +fn gaussian_contour() -> Contour { + let pts: [(f32, f32); 11] = [ + (0.0, 0.0), + (0.117, 0.023), + (0.172, 0.055), + (0.234, 0.117), + (0.305, 0.234), + (0.383, 0.414), + (0.523, 0.688), + (0.617, 0.812), + (0.703, 0.891), + (0.805, 0.953), + (1.0, 1.0), + ]; + Contour::Custom { + name: "Gaussian".into(), + points: pts.iter().map(|(input, output)| Cp { input: *input, output: *output }).collect(), + corners: (0..pts.len()).map(|i| i > 0 && i < pts.len() - 1).collect(), + } +} + +/// The issue's test document with the Inner Shadow's Size, Choke, Distance and Anti-aliased as given. +fn inner_shadow_doc(size: f32, spread: f32, distance: f32, anti_aliased: bool) -> Document { + let (w, h) = (400u32, 300u32); + let mut d = Document::new("14934", Size::new(w, h), ColorMode::Rgb, SampleType::U8); + let area = Rect::from_xywh(0, 0, w, h); + let mut bg = Layer::raster("Background", PixelFormat::RGBA8); + let white: Vec = (0..(w * h)).flat_map(|_| [1.0f32, 1.0, 1.0, 1.0]).collect(); + bg.surface_mut().unwrap().write_region(area, &white); + let mut px = Layer::raster("pixels", PixelFormat::RGBA8); + let orange: Vec = (0..h) + .flat_map(|y| (0..w).map(move |x| if (75..225).contains(&y) && (100..300).contains(&x) { [1.0f32, 0.501_960_8, 0.0, 1.0] } else { [0.0; 4] })) + .flatten() + .collect(); + px.surface_mut().unwrap().write_region(area, &orange); + px.effects.items = vec![Effect::InnerShadow(Shadow { + common: FxCommon::new(BlendMode::Normal, 1.0), + color: Color::BLACK, + angle: 0.0, + use_global_light: false, + distance, + spread, + size, + contour: gaussian_contour(), + anti_alias: anti_aliased, + noise: 0.0, + knocks_out: false, + })]; + d.layers = vec![bg, px].into(); + d +} + +/// The issue's test document: 400 x 300 px, 72 ppi, RGB 8 bit, white Background, a pixel layer +/// with an orange (255, 128, 0) rectangle at x 100..=299, y 75..=224 carrying a black Inner Shadow +/// (Normal 100 %, Use Global Light off, Size 10, Distance 0, Choke 0, Noise 0, Contour Gaussian) +/// with the Anti-aliased checkbox as given. +fn inner_shadow_issue_doc(anti_aliased: bool) -> Document { + inner_shadow_doc(10.0, 0.0, 0.0, anti_aliased) +} + +/// The nine G levels inwards from each of the issue's four edges of a 400 x 300 flatten. +fn inner_shadow_ramps(px: &[[f32; 4]]) -> [Vec; 4] { + let g = |x: i32, y: i32| px[(y * 400 + x) as usize][1] * 255.0; + let line = |first: (i32, i32), step: (i32, i32)| (0..9).map(|k| g(first.0 + k * step.0, first.1 + k * step.1)).collect(); + [line((200, 75), (0, 1)), line((100, 150), (1, 0)), line((200, 224), (0, -1)), line((299, 150), (-1, 0))] +} + +/// Done when (#14934): the GPU map program honours the Anti-aliased checkbox like the CPU. The +/// whole document (its 400 x 300 canvas also runs the paged 256 px compositor, where the sub-pixel +/// shift has to inflate the map windows) matches the CPU reference within one 8-bit step, and the +/// GPU's four edge ramps land on the issue's measured profile within 3 levels - which the +/// Anti-aliased-off render does not, on the top/left and the bottom/right edge each. +#[test] +fn anti_aliased_inner_shadow_matches_the_cpu_ramps() { + let Some(mut g) = gpu() else { return }; + let on = inner_shadow_issue_doc(true); + let off = inner_shadow_issue_doc(false); + check(&mut g, &on, "#14934 inner shadow, Anti-aliased"); + check(&mut g, &off, "#14934 inner shadow, Anti-aliased off"); + let gpu_on = render_to_vec(&mut g.comp, &g.device, &g.queue, &on, on.bounds()).expect("gpu render, Anti-aliased"); + let gpu_off = render_to_vec(&mut g.comp, &g.device, &g.queue, &off, off.bounds()).expect("gpu render, Anti-aliased off"); + let tl: &[f32] = &[65.0, 89.0, 107.0, 118.0, 124.0, 126.0, 127.0, 127.0, 128.0]; + let br: &[f32] = &[49.0, 74.0, 96.0, 112.0, 121.0, 125.0, 126.0, 127.0, 128.0]; + for ((side, got), want) in ["top", "left", "bottom", "right"].iter().zip(inner_shadow_ramps(&gpu_on)).zip([tl, tl, br, br]) { + for (d, (got, want)) in got.iter().zip(want).enumerate() { + assert!((got - want).abs() <= 3.0, "GPU {side} edge, {d} px in: {got:.1} vs measured {want}"); + } + } + let ramps_on = inner_shadow_ramps(&gpu_on); + let ramps_off = inner_shadow_ramps(&gpu_off); + assert!( + (ramps_on[0][0] - ramps_off[0][0]).abs() > 3.0, + "Anti-aliased moved nothing on the GPU's top edge: on {:.1}, off {:.1}", + ramps_on[0][0], + ramps_off[0][0] + ); + assert!( + (ramps_on[2][0] - ramps_off[2][0]).abs() > 3.0, + "Anti-aliased moved nothing on the GPU's bottom edge: on {:.1}, off {:.1}", + ramps_on[2][0], + ramps_off[2][0] + ); +} + +/// Review finding (#14934): with Choke above 0 the CPU recomputes its chamfer dilation distance on +/// the sub-pixel offset map (`effects::blur::dilate`), while `B::spread_blur` dilates the distance +/// field of the unshifted shape shifted by whole pixels only, so the two compositors part by the +/// third of a pixel the offset adds. The Size 1 and Size 2 / Choke 50 % rows are the other +/// neighbours the review names: there the blur has width 1, the identity, so the offset would be +/// the whole map. #14934 measured Choke 0 with a wider blur, so the offset is gated off at all of +/// them and this check pins the two compositors stay equal - while Choke 4 %, which dilates +/// nothing, keeps the offset and still has to agree. The last two rows pin where the offset stays +/// on at a Distance other than the measured 0: there the shift stage carries a whole-pixel light +/// offset plus the third of a pixel, which is the case the gate leaves on the anti-aliased path, +/// and the same pair at Choke 50 % stays gated at that Distance too. +#[test] +fn anti_aliased_inner_shadow_gated_neighbours_match_the_cpu() { + let Some(mut g) = gpu() else { return }; + for (size, spread, distance, what) in [ + (10.0, 0.5, 0.0, "Size 10 Choke 50 %"), + (10.0, 0.05, 0.0, "Size 10 Choke 5 %"), + (2.0, 0.5, 0.0, "Size 2 Choke 50 %"), + (1.0, 0.0, 0.0, "Size 1"), + (2.0, 0.0, 0.0, "Size 2 Choke 0 (offset on: both compositors shift the map the same way)"), + (10.0, 0.04, 0.0, "Size 10 Choke 4 % (dilates nothing, offset on)"), + (10.0, 0.0, 5.0, "Size 10 Choke 0 at Distance 5 (offset on, whole-pixel light offset)"), + (10.0, 0.5, 5.0, "Size 10 Choke 50 % at Distance 5 (still gated)"), + ] { + check(&mut g, &inner_shadow_doc(size, spread, distance, true), &format!("#14934 inner shadow, {what}, Anti-aliased")); + } +}