diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 8813b122d92..323f243e9bd 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -1445,7 +1445,7 @@ fn shape_parts(layer: &Layer, clipped: &[Layer], rect: Rect, cx: &Ctx) -> Option fn split_parts(layer: &Layer, rect: Rect, cx: &Ctx) -> Option<(Buffer, Buffer, Option>)> { let LayerContent::Shape(sh) = &layer.content else { return None }; sh.stroke.as_ref()?; - let (fs, ss) = shape_split::split(sh, cx.canvas, cx.depth)?; + let (fs, ss) = shape_split::split_with_patterns(sh, cx.canvas, cx.depth, cx.patterns.source(), cx.mode)?; Some((surface_to_buffer(&fs, rect), surface_to_buffer(&ss, rect), mask_vals(layer, rect, cx))) } diff --git a/crates/compose/src/shape_split.rs b/crates/compose/src/shape_split.rs index 9f0143f889e..f0e2ecb6e58 100644 --- a/crates/compose/src/shape_split.rs +++ b/crates/compose/src/shape_split.rs @@ -6,14 +6,15 @@ use std::collections::HashMap; use std::hash::{Hash, Hasher}; use std::sync::{Mutex, OnceLock}; -use photocraft_color::{PixelFormat, SampleType}; +use photocraft_color::{ColorMode, PixelFormat, SampleType}; use photocraft_doc::vector::ShapeLayer; +use photocraft_doc::{Fill, Pattern}; use photocraft_geom::Rect; use photocraft_raster::Surface; /// (fill, stroke), last use, and the shape's pixels the stroke was fitted to (kept alive so /// their tile addresses, part of the key, can't be reused). -type Entry = ((Surface, Surface), u64, Option); +type Entry = ((Surface, Surface), u64, Option, Vec); fn cache() -> &'static Mutex<(HashMap, u64)> { static C: OnceLock, u64)>> = OnceLock::new(); @@ -48,10 +49,29 @@ pub fn purge_cache() -> usize { /// (Photoshop's rendering, `sh.cache`) reach past our fill, the part the fill doesn't explain is /// stroke: the stroke follows Photoshop's coverage (psd-tools double-stroke-effects). pub fn split(sh: &ShapeLayer, canvas: Rect, depth: SampleType) -> Option<(Surface, Surface)> { + split_with_patterns(sh, canvas, depth, &[], ColorMode::Rgb) +} + +/// Splits patterned paints with the same embedded tiles and colour mode as the shape cache. +pub fn split_with_patterns(sh: &ShapeLayer, canvas: Rect, depth: SampleType, patterns: &[Pattern], mode: ColorMode) -> Option<(Surface, Surface)> { sh.stroke.as_ref()?; let mut h = std::collections::hash_map::DefaultHasher::new(); (canvas.x0, canvas.y0, canvas.x1, canvas.y1).hash(&mut h); depth.hash(&mut h); + mode.hash(&mut h); + let mut used_patterns = Vec::new(); + for fill in sh.fill.iter().chain(sh.stroke.iter().map(|s| &s.paint)) { + if let Fill::Pattern { id, name, .. } = fill + && let Some(p) = photocraft_doc::pattern::find(patterns, id, name) + { + (&p.id, &p.name, p.width, p.height, p.surface.format()).hash(&mut h); + format!("{:?}", p.surface.default_pixel()).hash(&mut h); + for (k, tile) in p.surface.tiles() { + (k.tx, k.ty, std::sync::Arc::as_ptr(tile) as usize).hash(&mut h); + } + used_patterns.push(p.clone()); + } + } format!("{:?}{:?}{:?}{:?}", sh.path, sh.fill, sh.stroke, sh.live).hash(&mut h); if let Some(c) = &sh.cache { format!("{:?}{:?}", c.format(), c.default_pixel()).hash(&mut h); @@ -72,7 +92,9 @@ pub fn split(sh: &ShapeLayer, canvas: Rect, depth: SampleType) -> Option<(Surfac let fmt = PixelFormat::RGBA8.with_sample(depth); let fill_only = ShapeLayer { stroke: None, cache: None, ..sh.clone() }; let stroke_only = ShapeLayer { fill: None, cache: None, ..sh.clone() }; - let mut parts = (photocraft_vector::render_shape(&fill_only, fmt, canvas), photocraft_vector::render_shape(&stroke_only, fmt, canvas)); + let render = + |shape| photocraft_vector::CompiledShape::with_patterns(shape, photocraft_vector::DEFAULT_TOLERANCE, canvas, patterns, mode).render(fmt, canvas); + let mut parts = (render(&fill_only), render(&stroke_only)); if let Some(cache) = &sh.cache { fit_stroke(&parts.0, &mut parts.1, cache, canvas); } @@ -92,7 +114,7 @@ pub fn split(sh: &ShapeLayer, canvas: Rect, depth: SampleType) -> Option<(Surfac return Some(parts); } let tick = c.1; - c.0.insert(key, (parts.clone(), tick, sh.cache.clone())); + c.0.insert(key, (parts.clone(), tick, sh.cache.clone(), used_patterns)); Some(parts) } diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rs index b8c083c7af4..9f45e290847 100644 --- a/crates/gpu/src/plan.rs +++ b/crates/gpu/src/plan.rs @@ -720,7 +720,8 @@ impl<'a> Planner<'a> { if let LayerContent::Shape(sh) = &layer.content && !visible_clipped.is_empty() - && let Some((fill, stroke)) = photocraft_compose::shape_split::split(sh, self.cx.canvas, self.cx.depth) + && let Some((fill, stroke)) = + photocraft_compose::shape_split::split_with_patterns(sh, self.cx.canvas, self.cx.depth, self.cx.patterns, self.cx.mode) { // The vector stroke goes above the clipped layers: the fill is the clipping base, // the stroke is laid over the clipped result, then the masks apply to both @@ -997,7 +998,9 @@ impl<'a> Planner<'a> { // A stroked shape's vector stroke goes above its clipped layers and interior effects // (compose::split_parts): the fill and the stroke unmasked, the masks applied after. let split = match &layer.content { - LayerContent::Shape(sh) if sh.stroke.is_some() => photocraft_compose::shape_split::split(sh, canvas, self.cx.depth), + LayerContent::Shape(sh) if sh.stroke.is_some() => { + photocraft_compose::shape_split::split_with_patterns(sh, canvas, self.cx.depth, self.cx.patterns, self.cx.mode) + } _ => None, }; let (mut content, vstroke) = match split { diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rs index c61aee9b678..c996eb78905 100644 --- a/crates/gpu/tests/parity.rs +++ b/crates/gpu/tests/parity.rs @@ -1253,6 +1253,40 @@ fn checker_pattern() -> Pattern { Pattern::new("checker", s, 6, 5) } +#[test] +fn patterned_shape_fill_and_stroke_clip_and_effects_match_cpu() { + let Some(mut g) = gpu() else { return }; + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk] { + for effects in [false, true] { + let mut d = Document::new("pattern shape", Size::new(90, 70), mode, depth); + let p = checker_pattern(); + let fill = Fill::Pattern { id: p.id.clone(), name: p.name.clone(), scale: 1.3, angle: 23.0, link: true, phase: (2.0, -3.0) }; + d.patterns.push(p); + let mut sh = photocraft_doc::ShapeLayer { + path: photocraft_vector::shapes::rounded_rect(12.0, 12.0, 60.0, 40.0, [4.0; 4]), + fill: Some(fill.clone()), + stroke: Some(photocraft_doc::ShapeStroke { width: 4.0, paint: fill, align: photocraft_doc::StrokeAlign::Outside, ..Default::default() }), + ..Default::default() + }; + sh.cache = Some(photocraft_vector::render_shape_with_patterns(&sh, d.pixel_format(), d.bounds(), &d.patterns)); + assert!(sh.cache.as_ref().unwrap().rgba(30, 30)[3] > 0.5, "pattern fill must be visible before parity"); + assert!(sh.cache.as_ref().unwrap().rgba(9, 30)[3] > 0.5, "pattern stroke must be visible before parity"); + let mut layer = Layer::new("pattern", LayerContent::Shape(sh)); + if effects { + layer.mask = Some(mask(d.bounds(), 7, 0.6)); + layer.effects.items.push(Effect::DropShadow(shadow(BlendMode::Multiply, 0.6, 120.0, 4.0, 3.0, 0.0))); + } + d.layers.push(layer); + let mut clipped = noise_layer("clipped", d.pixel_format(), Rect::new(28, 0, 50, 70), 9, 0.5); + clipped.clipped = true; + d.layers.push(clipped); + fx_check(&mut g, &d, &format!("pattern shape {depth:?}/{mode:?}, effects {effects}")); + } + } + } +} + /// Every effect kind with several option combinations, one effect stack per case. fn effect_cases() -> Vec<(&'static str, Vec)> { let pat = checker_pattern(); diff --git a/crates/vector/src/lib.rs b/crates/vector/src/lib.rs index bd557ec50c1..df4c802e082 100644 --- a/crates/vector/src/lib.rs +++ b/crates/vector/src/lib.rs @@ -29,7 +29,7 @@ pub mod stroke; pub mod trace; use photocraft_color::{ColorMode, PixelFormat}; -use photocraft_doc::{Fill, FillRule, GradientStyle, Path, PathOp, ShapeLayer, ShapeStroke, StrokeAlign, VectorMask}; +use photocraft_doc::{Fill, FillRule, GradientStyle, Path, PathOp, Pattern, ShapeLayer, ShapeStroke, StrokeAlign, VectorMask}; use photocraft_geom::{Rect, TILE_SIZE}; use photocraft_raster::Surface; @@ -232,6 +232,10 @@ pub enum Paint { None, /// Straight RGBA. Solid([f32; 4]), + Pattern { + tile: std::sync::Arc, + placement: pattern::Placement, + }, Gradient { /// Colour stops sorted by location (straight RGBA). stops: Vec<(f32, [f32; 4])>, @@ -256,9 +260,13 @@ impl Paint { /// gradient field is honoured (midpoints, opacity stops, centre offset, dither, unsorted /// stops), rendering the same pixels as the compositor's fill layers; the parity tests in /// `photocraft-compose` (which this crate cannot depend on) keep the two in step. Pattern - /// fills are not rendered (transparent): they need the document's pattern table, which - /// lives above this crate. + /// paints need [`Paint::from_fill_with_patterns`] and the document's pattern table. pub fn from_fill(f: &Fill, bounds: (f64, f64, f64, f64), canvas: (f64, f64, f64, f64)) -> Paint { + Self::from_fill_with_patterns(f, bounds, canvas, &[], ColorMode::Rgb) + } + + /// Resolves pattern ids/names and samples them in the document's colour mode. + pub fn from_fill_with_patterns(f: &Fill, bounds: (f64, f64, f64, f64), canvas: (f64, f64, f64, f64), patterns: &[Pattern], mode: ColorMode) -> Paint { let rgba = |c: &photocraft_color::Color| { let v = c.to_rgb(); [v[0], v[1], v[2], c.alpha] @@ -284,7 +292,12 @@ impl Paint { frame, } } - Fill::Pattern { .. } => Paint::None, + Fill::Pattern { id, name, scale, angle, phase, link } => { + let tile = photocraft_doc::pattern::find(patterns, id, name).and_then(|p| pattern::Tile::new_in(p, mode)).map(std::sync::Arc::new); + let Some(tile) = tile else { return Paint::None }; + let anchor = (bounds.0.floor(), bounds.1.floor()); + Paint::Pattern { tile, placement: pattern::Placement::anchored(anchor, *link, *phase, *scale, *angle) } + } } } @@ -293,6 +306,10 @@ impl Paint { match self { Paint::None => [0.0; 4], Paint::Solid(c) => *c, + Paint::Pattern { tile, placement } => { + let (u, v) = placement.map(x, y); + tile.sample(u, v) + } Paint::Gradient { stops, midpoints, opacity_stops, style, layout, reverse, dither: dith, frame } => { let t = gradient_t(*style, layout.0, layout.1, *reverse, layout.2, *frame, x, y); let mut c = sample_stops(stops, midpoints, opacity_stops, t); @@ -470,13 +487,18 @@ impl CompiledShape { /// Compiles the shape at flattening tolerance `tol`. `canvas` is the frame gradients /// without "Align with layer" are laid out in. pub fn new(shape: &ShapeLayer, tol: f64, canvas: Rect) -> Self { + Self::with_patterns(shape, tol, canvas, &[], ColorMode::Rgb) + } + + /// Compiles both paints against the document's embedded pattern table. + pub fn with_patterns(shape: &ShapeLayer, tol: f64, canvas: Rect, patterns: &[Pattern], mode: ColorMode) -> Self { let pb = shape.path.control_bounds().unwrap_or((0.0, 0.0, 0.0, 0.0)); let cb = (f64::from(canvas.x0), f64::from(canvas.y0), f64::from(canvas.x1), f64::from(canvas.y1)); let area = fill_rasterizer(&shape.path, tol); let mut bounds = None; let fill = shape.fill.as_ref().map(|f| { bounds = area.pixel_bounds(); - (area.clone(), Paint::from_fill(f, pb, cb)) + (area.clone(), Paint::from_fill_with_patterns(f, pb, cb, patterns, mode)) }); let all_closed = shape.path.subpaths.iter().all(|s| s.closed); let mut align = None; @@ -493,7 +515,7 @@ impl CompiledShape { (Some(a), Some(b)) => Some(a.union(&b)), (a, b) => a.or(b), }; - (r, Paint::from_fill(&s.paint, pb, cb), s.opacity.clamp(0.0, 1.0)) + (r, Paint::from_fill_with_patterns(&s.paint, pb, cb, patterns, mode), s.opacity.clamp(0.0, 1.0)) }); if shape.path.inverted && shape.fill.is_some() { bounds = Some(Rect::new(i32::MIN / 4, i32::MIN / 4, i32::MAX / 4, i32::MAX / 4)); @@ -578,5 +600,10 @@ pub fn render_shape(shape: &ShapeLayer, format: PixelFormat, clip: Rect) -> Surf CompiledShape::new(shape, DEFAULT_TOLERANCE, clip).render(format, clip) } +/// Renders shape fill and stroke using the document's embedded patterns. +pub fn render_shape_with_patterns(shape: &ShapeLayer, format: PixelFormat, clip: Rect, patterns: &[Pattern]) -> Surface { + CompiledShape::with_patterns(shape, DEFAULT_TOLERANCE, clip, patterns, format.mode).render(format, clip) +} + #[cfg(test)] mod tests; diff --git a/crates/vector/tests/shape_patterns.rs b/crates/vector/tests/shape_patterns.rs new file mode 100644 index 00000000000..e32c6f54c44 --- /dev/null +++ b/crates/vector/tests/shape_patterns.rs @@ -0,0 +1,105 @@ +use photocraft_doc::{ColorMode, Fill, Pattern, PixelFormat, SampleType, ShapeLayer, ShapeStroke}; +use photocraft_geom::Rect; +use photocraft_raster::Surface; +use photocraft_vector::{Paint, pattern::Tile, render_shape_with_patterns}; + +fn pattern(sample: SampleType, mode: ColorMode) -> Pattern { + let format = PixelFormat::new(mode, sample, true); + let mut s = Surface::new(format); + for (x, rgba) in [(0, [0.9, 0.2, 0.1, 1.0]), (1, [0.1, 0.3, 0.9, 0.5])] { + let mut values = [0.0; 5]; + let n = photocraft_raster::from_rgba_into(&format, rgba, &mut values); + s.fill_rect(Rect::new(x, 0, x + 1, 2), &values[..n]); + } + Pattern::new("$$$/Patterns/Test=Tile", s, 2, 2) +} + +fn fill(p: &Pattern) -> Fill { + Fill::Pattern { id: p.id.clone(), name: p.name.clone(), scale: 1.0, angle: 0.0, link: true, phase: (0.0, 0.0) } +} + +fn close(a: [f32; 4], b: [f32; 4], tolerance: f32) { + for c in 0..4 { + assert!((a[c] - b[c]).abs() < tolerance, "{a:?} != {b:?}"); + } +} + +#[test] +fn pattern_shape_fill_and_stroke_render_at_every_depth_and_model() { + let canvas = Rect::new(0, 0, 32, 32); + for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] { + let p = pattern(sample, mode); + let fmt = PixelFormat::new(mode, sample, true); + let check = |actual: [f32; 4], expected: [f32; 4], where_: &str| { + for c in 0..4 { + assert!((actual[c] - expected[c]).abs() < 1e-4, "{sample:?}/{mode:?} {where_}: {actual:?} != {expected:?}"); + } + }; + // The cache stores the document's format. CMYK's decode/encode/decode + // roundtrip need not preserve RGB, even when the source tile is also CMYK. + let encoded = |x| { + let values = photocraft_raster::from_rgba(&fmt, p.surface.rgba(x, 0)); + Surface::with_default(fmt, &values).rgba(0, 0) + }; + let sh = ShapeLayer { path: photocraft_vector::shapes::rounded_rect(8.0, 8.0, 16.0, 16.0, [0.0; 4]), fill: Some(fill(&p)), ..Default::default() }; + let sampler = + Paint::from_fill_with_patterns(sh.fill.as_ref().unwrap(), (8.0, 8.0, 24.0, 24.0), (0.0, 0.0, 32.0, 32.0), std::slice::from_ref(&p), mode); + check(sampler.at(10.5, 10.5), p.surface.rgba(0, 0), "opaque tile sampler"); + check(sampler.at(11.5, 10.5), p.surface.rgba(1, 0), "half-alpha tile sampler"); + let surface = render_shape_with_patterns(&sh, fmt, canvas, std::slice::from_ref(&p)); + check(surface.rgba(10, 10), encoded(0), "opaque fill cache"); + check(surface.rgba(11, 10), encoded(1), "half-alpha fill cache"); + assert_eq!(surface.rgba(2, 2)[3], 0.0); + let stroke = ShapeLayer { fill: None, stroke: Some(ShapeStroke { width: 4.0, paint: fill(&p), ..Default::default() }), ..sh }; + let surface = render_shape_with_patterns(&stroke, fmt, canvas, std::slice::from_ref(&p)); + check(surface.rgba(8, 12), encoded(0), "stroke cache"); + assert_eq!(surface.rgba(16, 16)[3], 0.0); + } + } +} + +#[test] +fn pattern_lookup_placement_and_premultiplied_sampling() { + let p = pattern(SampleType::F32, ColorMode::Rgb); + let mut f = fill(&p); + if let Fill::Pattern { id, name, link, phase, scale, angle } = &mut f { + *id = "missing-id".into(); + *name = "tile".into(); + *link = false; + *phase = (4.0, 6.0); + *scale = 2.0; + *angle = 90.0; + } + let paint = Paint::from_fill_with_patterns(&f, (8.0, 8.0, 24.0, 24.0), (0.0, 0.0, 32.0, 32.0), std::slice::from_ref(&p), ColorMode::Rgb); + // Undo 90° and 2× scale: (5,5) relative to phase maps to tile centre (.5,.5). + close(paint.at(5.0, 5.0), p.surface.rgba(0, 0), 0.001); + assert!(matches!(Paint::from_fill(&f, (0.0, 0.0, 1.0, 1.0), (0.0, 0.0, 32.0, 32.0)), Paint::None)); + let tile = Tile::new(&p).unwrap(); + let a = p.surface.rgba(0, 0); + let b = p.surface.rgba(1, 0); + let alpha = (a[3] + b[3]) / 2.0; + close( + tile.sample(1.0, 0.5), + [(a[0] * a[3] + b[0] * b[3]) / (2.0 * alpha), (a[1] * a[3] + b[1] * b[3]) / (2.0 * alpha), (a[2] * a[3] + b[2] * b[3]) / (2.0 * alpha), alpha], + 0.001, + ); + close(tile.sample(-1.5, 0.5), a, 0.001); + assert_eq!(tile.sample(f64::NAN, 0.0), [0.0; 4]); + assert!(tile.sample(f64::MAX, -f64::MAX).iter().all(|v| v.is_finite())); +} + +#[test] +fn oversized_sparse_pattern_samples_without_a_second_full_surface() { + let p = Pattern { + id: "large".into(), + name: "large".into(), + width: 4096, + height: 4096, + surface: Surface::with_default(PixelFormat::RGBA8, &[0.2, 0.6, 0.9, 1.0]), + }; + let tile = Tile::new(&p).unwrap(); + close(tile.sample(4000.5, 2000.5), p.surface.rgba(4000, 2000), 0.001); + assert!(Tile::new(&Pattern { width: u32::MAX, ..p.clone() }).is_none()); + assert!(Tile::new(&Pattern { height: 0, ..p }).is_none()); +}