diff --git a/crates/doc/src/overprint.rs b/crates/doc/src/overprint.rs index 59ff63a392..58f6b5abc2 100644 --- a/crates/doc/src/overprint.rs +++ b/crates/doc/src/overprint.rs @@ -4,7 +4,7 @@ use std::sync::Arc; -use vectorcraft_color::{BlendMode, Color, Paint}; +use vectorcraft_color::{BlendMode, Color, GradientKind, Paint}; use crate::{Document, Node, NodeId, NodeKind}; @@ -55,7 +55,8 @@ impl OverprintBlack { }; match p { Paint::Solid { color, swatch, .. } => ink(color, swatch), - Paint::Gradient(g) => match g.freeform.as_ref().filter(|f| !f.points.is_empty()) { + // Only a freeform gradient draws its points; another kind draws its stops whatever it holds. + Paint::Gradient(g) => match g.freeform.as_ref().filter(|f| g.gradient.kind == GradientKind::Freeform && !f.points.is_empty()) { Some(f) => f.points.iter().all(|pt| is_black_ink(&pt.color, self.min_k, self.rich)), // Without points of its own a freeform gradient places them from its stops. None => !g.gradient.stops.is_empty() && g.gradient.stops.iter().all(|s| ink(&s.color, &s.swatch)), @@ -292,7 +293,7 @@ mod tests { fn a_freeform_gradient_is_black_when_every_point_is() { use vectorcraft_color::freeform::{Freeform, FreeformPoint}; let k = Color::cmyk(0.0, 0.0, 0.0, 1.0); - let mut g = vectorcraft_color::GradientPaint::new(Default::default()); + let mut g = vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient { kind: GradientKind::Freeform, ..Default::default() }); for s in &mut g.gradient.stops { s.color = k; } @@ -301,6 +302,11 @@ mod tests { let fill = |g: &vectorcraft_color::GradientPaint| Appearance::basic(Paint::Gradient(Box::new(g.clone())), Paint::None, 0.0); let mut n = Node::path(NodeId(1), Default::default(), fill(&g)); assert!(!OverprintBlack::default().apply(&mut n, &[]), "a cyan point is drawn, whatever the stops"); + // Another kind of gradient draws its black stops, not the points it still holds. + let mut linear = g.clone(); + linear.gradient.kind = GradientKind::Linear; + let mut n = Node::path(NodeId(1), Default::default(), fill(&linear)); + assert!(OverprintBlack::default().apply(&mut n, &[]), "a linear gradient is judged by its stops"); if let Some(f) = &mut g.freeform { f.points[1].color = Color::gray(1.0); } diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index c2b67757fc..c6b165bbd5 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -39,14 +39,15 @@ impl Exporter<'_> { cover(&mut ms, page, if m.clip { 0 } else { 255 }, 1.0); } // Mask art is a picture of its own: it takes no part in a knockout group around the object, - // and has no inks to overprint. + // and has no inks to overprint (its characters do not darken either). let knockout = std::mem::take(&mut self.knockout); let overprint = std::mem::take(&mut self.overprint); + let darken = std::mem::take(&mut self.darken_overprints); let image_left_out = self.image_left_out.replace(false); self.node(&mut ms, &m.art, page, true); let incomplete = self.image_left_out.unwrap_or(false); self.image_left_out = image_left_out.map(|outer| outer || incomplete); - (self.knockout, self.overprint) = (knockout, overprint); + (self.knockout, self.overprint, self.darken_overprints) = (knockout, overprint, darken); if incomplete { ms.pop(); ms.finish(); diff --git a/crates/pdf/src/print.rs b/crates/pdf/src/print.rs index a33a997971..b984da82d3 100644 --- a/crates/pdf/src/print.rs +++ b/crates/pdf/src/print.rs @@ -198,11 +198,14 @@ pub fn printed_document<'a>(doc: &'a Document, set: &PrintSettings) -> Cow<'a, D /// 100% gray, each to within half a percent ([`vectorcraft_doc::overprint::is_black_ink`]), or a /// gradient whose every stop is (every point of a freeform one), the characters' too, overprints. Rich black, RGB and Lab black, /// tints below 99.5%, and colors linked to a spot swatch or to Registration keep -/// knocking out ([`OverprintBlack::default`]). Art that overprints already keeps doing so. +/// knocking out ([`OverprintBlack::default`]). Art that overprints already keeps doing so. A +/// symbol instance that repaints its art is judged by the paints it prints with +/// ([`place_repainted_instances`]). fn separation_overprint_black(doc: &mut Document, set: &PrintSettings) { if set.output.mode != OutputMode::Separations || !set.output.overprint_black { return; } + place_repainted_instances(doc); let mut spots = doc.spot_names(); spots.push(vectorcraft_color::swatch::REGISTRATION.to_string()); let op = OverprintBlack::default(); @@ -212,6 +215,154 @@ fn separation_overprint_black(doc: &mut Document, set: &PrintSettings) { } } +/// Replace each symbol instance in `doc`'s layers and patterns whose own fill or stroke changes +/// ([`vectorcraft_doc::symbol_overrides::SymbolOverride`]) or fill stain repaint its symbol's art +/// ([`repaints`]), or whose symbol's art holds such an instance at any depth, with that art as +/// the instance prints it ([`Placing::instance`]). The symbols' own art stays as it is, and so do +/// hidden objects and template layers. Once the layers and patterns, with the art placed for +/// symbols already, hold [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects, the remaining instances +/// stay as they are, and so do instances whose art would draw deeper than +/// [`vectorcraft_doc::depth::MAX_DRAWN_DEPTH`]. +fn place_repainted_instances(doc: &mut Document) { + let holders = repainting_symbols(doc); + let art = || doc.layers.iter().chain(doc.patterns.iter().flat_map(|p| p.art.iter())); + if !art().any(|n| holds_repaint(n, &holders)) { + return; + } + let held = art().map(|n| n.count_with_masks() as u64).fold(0u64, u64::saturating_add); + let mut placing = + Placing { holders, heights: vectorcraft_doc::depth::DrawnHeights::of(doc), budget: vectorcraft_doc::MAX_SYMBOL_NODES.saturating_sub(held) }; + // The art placed for an instance holds the instances inside it: each pass places those, up + // to the depth objects are drawn to. + for _ in 0..=vectorcraft_doc::depth::MAX_DRAWN_DEPTH { + let mut changed = false; + for i in 0..doc.layers.len() { + if let Some(layer) = placing.subtree(doc, &doc.layers[i], 1) { + doc.layers[i] = layer; + changed = true; + } + } + for p in 0..doc.patterns.len() { + for i in 0..doc.patterns[p].art.len() { + if let Some(art) = placing.subtree(doc, &doc.patterns[p].art[i], 1) { + doc.patterns[p].art[i] = art; + changed = true; + } + } + } + if !changed { + return; + } + } +} + +/// Does symbol instance `n` repaint its symbol's art: with its own fill or stroke changes, or with +/// its fill's stain? +fn repaints(n: &Node) -> bool { + matches!(n.kind, NodeKind::SymbolInstance { .. }) + && (n.extras().symbol_overrides.iter().any(|o| o.fill.is_some() || o.stroke.is_some()) + || vectorcraft_doc::symbol_overrides::stain(n).is_some()) +} + +/// Does `n`'s subtree hold a repainting instance ([`repaints`]) or an instance of one of the +/// symbols `holders`? +fn holds_repaint(n: &Node, holders: &HashSet) -> bool { + repaints(n) + || matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if holders.contains(symbol)) + || n.children().is_some_and(|c| c.iter().any(|c| holds_repaint(c, holders))) +} + +/// The names of the symbols whose art holds a repainting instance ([`repaints`]) at any depth, +/// through the instances of other symbols too. +fn repainting_symbols(doc: &Document) -> HashSet { + let mut out = HashSet::new(); + loop { + let before = out.len(); + for s in &doc.symbols { + if !out.contains(&s.name) && holds_repaint(&s.art, &out) { + out.insert(s.name.clone()); + } + } + if out.len() == before { + return out; + } + } +} + +/// What [`place_repainted_instances`] places instances with. +struct Placing { + /// The symbols whose art holds a repainting instance ([`repainting_symbols`]). + holders: HashSet, + heights: vectorcraft_doc::depth::DrawnHeights, + /// The objects left to place. + budget: u64, +} + +impl Placing { + /// `n`'s subtree, `n` placed `level` deep, with its instances that [`Self::instance`] places + /// placed, copying only the nodes on the way to them; `None` when there is none. Hidden + /// objects and template layers do not print and are left as they are. + fn subtree(&mut self, doc: &Document, n: &Arc, level: usize) -> Option> { + if !n.visible || matches!(n.kind, NodeKind::Layer { template: true, .. }) { + return None; + } + if let Some(g) = self.instance(doc, n, level) { + return Some(Arc::new(g)); + } + let members: Vec<(usize, Arc)> = + n.children().into_iter().flatten().enumerate().filter_map(|(i, c)| Some((i, self.subtree(doc, c, level + 1)?))).collect(); + if members.is_empty() { + return None; + } + let mut copy = Arc::clone(n); + if let Some(children) = Arc::make_mut(&mut copy).children_mut() { + for (i, c) in members { + if let Some(slot) = children.get_mut(i) { + *slot = c; + } + } + } + Some(copy) + } + + /// Symbol instance `n`, placed `level` deep, when it repaints its art ([`repaints`]) or its + /// symbol is one of [`Self::holders`], as a group of that art placed as the exporter places + /// it, with the instance's id, name, visibility, transparency, opacity mask, effects and + /// attributes. `None` for other objects, for instances of a missing symbol, when the art does + /// not fit in [`Self::budget`] (which it is taken from), and when it would draw deeper than + /// [`vectorcraft_doc::depth::MAX_DRAWN_DEPTH`]. + fn instance(&mut self, doc: &Document, n: &Node, level: usize) -> Option { + let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return None }; + if !repaints(n) && !self.holders.contains(symbol) { + return None; + } + let sym = doc.symbols.iter().find(|s| s.name == *symbol)?; + let art = vectorcraft_doc::symbol_overrides::instance_art(&sym.art, n); + // The most objects placing it can make, counted before it is placed. + let most = doc.symbol_slice_map(symbol, *xf).map_or(art.count_with_masks() as u64, |m| m.most_placed(&art, doc)); + let left = self.budget.checked_sub(most)?; + let placed = doc.place_symbol_art(symbol, &art, *xf)?; + let mut g = Node::group(n.id, vec![Arc::new(placed)]); + g.name = n.name.clone(); + g.visible = n.visible; + g.opacity = n.opacity; + g.blend = n.blend; + g.isolate = n.isolate; + // One element of an enclosing knockout group, as the instance is: its pieces never knock + // each other out. + g.knockout = vectorcraft_doc::Knockout::Off; + g.knockout_shape = n.knockout_shape; + g.appearance.effects = n.appearance.effects.clone(); + g.extras_mut().mask = n.extras().mask.clone(); + g.extras_mut().attrs = n.extras().attrs.clone(); + if self.heights.deepest(&g, level) > vectorcraft_doc::depth::MAX_DRAWN_DEPTH { + return None; + } + self.budget = left; + Some(g) + } +} + /// Overprinting fills and strokes in composite output: discarded (they knock out) or simulated /// (drawn with Darken, as Overprint Preview shows them), after which nothing overprints any /// more; or preserved. Separations always honour them. diff --git a/crates/pdf/src/print/plates.rs b/crates/pdf/src/print/plates.rs index 30eae1d524..d84488d58d 100644 --- a/crates/pdf/src/print/plates.rs +++ b/crates/pdf/src/print/plates.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use vectorcraft_color::cms::{self, Cms, Model, ProfileKind}; use vectorcraft_color::swatch::REGISTRATION; -use vectorcraft_color::{BlendMode, Color, Paint}; +use vectorcraft_color::{BlendMode, Color, GradientKind, Paint}; use vectorcraft_doc::inks::{Link, StopPlates, inks, plates, spot_color, stop_inks, visit_node_colors}; use vectorcraft_doc::overprint::{darken_overprints, is_white}; use vectorcraft_doc::{AppearanceItem, ColorMode, Document, ImageBlob, Node, NodeKind}; @@ -139,7 +139,7 @@ impl<'a> Separator<'a> { const NONE: f32 = 0.005; match p { Paint::Solid { color, swatch, tint } => self.ink(plate, color, swatch.as_deref().map(|s| (s, *tint))) <= NONE, - Paint::Gradient(g) => match g.freeform.as_ref().filter(|f| !f.points.is_empty()) { + Paint::Gradient(g) => match g.freeform.as_ref().filter(|f| g.gradient.kind == GradientKind::Freeform && !f.points.is_empty()) { Some(f) => f.points.iter().all(|pt| self.ink(plate, &pt.color, None) <= NONE), None => { !g.gradient.stops.is_empty() diff --git a/crates/pdf/src/tests/print.rs b/crates/pdf/src/tests/print.rs index 52dc3dac48..d096b3385c 100644 --- a/crates/pdf/src/tests/print.rs +++ b/crates/pdf/src/tests/print.rs @@ -691,17 +691,23 @@ fn overprint_black_keeps_the_inks_under_solid_black_on_separations() { #[test] fn overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_plates() { - // 0.4% cyan beside 100% K counts as black, as does a freeform gradient of black points, and the - // cyan plate draws both as nothing. + // 0.4% cyan beside 100% K counts as black, as do a freeform gradient of black points and a + // linear gradient of black stops, and the cyan plate draws them all as nothing. let near = Paint::solid(Color::cmyk(0.004, 0.0, 0.0, 1.0)); let k = Color::cmyk(0.0, 0.0, 0.0, 1.0); let mut g = GradientPaint::new(Gradient::new(GradientKind::Freeform, vec![GradientStop::new(0.0, k), GradientStop::new(1.0, k)])); let points = vec![FreeformPoint::new(kurbo::Point::new(45.0, 20.0), k), FreeformPoint::new(kurbo::Point::new(55.0, 30.0), Color::gray(1.0))]; g.freeform = Some(Freeform { points, ..Default::default() }); + // A linear gradient draws its black stops, not the cyan point it still holds. + let mut linear = g.clone(); + linear.gradient.kind = GradientKind::Linear; + if let Some(f) = &mut linear.freeform { + f.points[1].color = Color::cmyk(1.0, 0.0, 0.0, 0.0); + } let square = |x: f64, fill: Paint| { Node::path(vectorcraft_doc::NodeId(0), shapes::rectangle(Rect::new(x, 15.0, x + 20.0, 35.0)), Appearance::basic(fill, Paint::None, 0.0)) }; - let d = over_cyan(vec![square(10.0, near), square(40.0, Paint::Gradient(Box::new(g)))]); + let d = over_cyan(vec![square(10.0, near), square(40.0, Paint::Gradient(Box::new(g))), square(70.0, Paint::Gradient(Box::new(linear)))]); let opts = PrintOptions { settings: settings(json!({"output": {"mode": "separations", "overprintBlack": true}})), postscript: true, @@ -713,7 +719,7 @@ fn overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_p doc.walk(|n| count += usize::from(n.appearance.fill().is_some_and(|f| !f.paint.is_none()))); count }; - assert_eq!((fills(&p.plates[0]), fills(&p.plates[3])), (1, 3), "the cyan plate, the Black plate"); + assert_eq!((fills(&p.plates[0]), fills(&p.plates[3])), (1, 4), "the cyan plate, the Black plate"); } #[test] @@ -746,6 +752,55 @@ fn a_type_objects_own_black_fill_overprints_on_separations() { assert!(darkens(json!({"output": {"mode": "separations", "overprintBlack": true}})), "Overprint Black: it overprints"); } +#[test] +fn overprint_black_follows_a_symbol_instances_own_fill_on_separations() { + use vectorcraft_doc::symbol_overrides::SymbolOverride; + let (k, magenta) = (Color::cmyk(0.0, 0.0, 0.0, 1.0), Color::cmyk(0.0, 1.0, 0.0, 0.0)); + let square = |x: f64, c: Color| { + let r = shapes::rectangle(Rect::new(x, 15.0, x + 20.0, 35.0)); + Arc::new(Node::path(vectorcraft_doc::NodeId(0), r, Appearance::basic(Paint::solid(c), Paint::None, 0.0))) + }; + let instance = |symbol: &str, fill: Color| { + let mut n = Node::new(vectorcraft_doc::NodeId(0), NodeKind::SymbolInstance { symbol: symbol.into(), xf: Default::default() }); + n.extras_mut().symbol_overrides = vec![SymbolOverride { path: vec![], fill: Some(Paint::solid(fill)), ..Default::default() }]; + n + }; + // An instance of "Outer", whose art is the magenta symbol's instance painted black, moved right. + let outer = + Node::new(vectorcraft_doc::NodeId(0), NodeKind::SymbolInstance { symbol: "Outer".into(), xf: kurbo::Affine::translate((140.0, 0.0)) }); + let mut d = over_cyan(vec![instance("Magenta", k), instance("Black", magenta), outer]); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: true, name: "Magenta".into(), art: square(10.0, magenta) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: true, name: "Black".into(), art: square(40.0, k) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Outer".into(), art: Arc::new(instance("Magenta", k)) }); + let opts = PrintOptions { settings: settings(json!({"output": {"mode": "separations", "overprintBlack": true}})), ..Default::default() }; + let p = plan(&d, &opts).unwrap(); + let cyan = render_region(&p.plates[0], Rect::new(0.0, 0.0, 200.0, 100.0), 1.0); + let inked = |x: u32| cyan.over_white(x, 25)[0] < 40; + assert!(inked(20), "a magenta symbol's instance painted black overprints the cyan"); + assert!(!inked(50), "a black symbol's instance painted magenta knocks the cyan out"); + assert!(inked(160), "the instance painted black inside another symbol's art overprints too"); + assert!(!d.symbols.iter().any(|s| s.art.has_overprint()), "the document keeps its own settings"); +} + +#[test] +fn overprinting_type_in_an_opacity_mask_does_not_darken_on_separations() { + // Mask art has no inks: an overprinting gray character in an inverted clipping mask keeps its + // luminance on every plate. + let style = vectorcraft_doc::CharStyle { fill: Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 0.5)), overprint_fill: true, ..Default::default() }; + let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "Hi", style); + let mut mask = vectorcraft_doc::OpacityMask::new(Node::new(vectorcraft_doc::NodeId(0), NodeKind::Text(Box::new(text))), true); + mask.invert = true; + let square = Node::path( + vectorcraft_doc::NodeId(0), + shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 90.0)), + Appearance::basic(Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), Paint::None, 0.0), + ) + .with_mask(Some(Box::new(mask))); + let d = over_cyan(vec![square]); + let bytes = job(&d, json!({"output": {"mode": "separations"}})).bytes; + assert!(!String::from_utf8_lossy(&bytes).contains("/Darken"), "the mask's character is drawn as it is"); +} + /// A 100 pt CMYK document with spot swatch `Gold` and a square filled with gradient `g`. fn gold_gradient_doc(g: GradientPaint) -> Document { let mut d = doc(100.0, 100.0, &[(Rect::new(0.0, 0.0, 50.0, 50.0), Paint::Gradient(Box::new(g)))]); diff --git a/docs/mcp.md b/docs/mcp.md index 61de0b46cd..a52e9a6694 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8541,7 +8541,8 @@ documents every field: fill, stroke or character paint of solid 100% process K or 100% gray, or a gradient whose every stop is (every color point of a freeform gradient), each to within half a percent (99.5% K counts, and so does 0.4% cyan beside it). Rich black, RGB and Lab black, tints below 99.5% and colors linked to a spot swatch or to Registration still - knock out. Only the printed copy is marked: the document and its own overprint settings do not change. Composite + knock out. A symbol instance's art is judged with the paints the instance prints it in, its own fill and stroke + changes and its fill's stain included. Only the printed copy is marked: the document and its own overprint settings do not change. Composite output ignores the option, and the Print dialog's Overprint Black checkbox is disabled unless Mode is Separations. - `graphics: {autoFlatness, flatness, fonts}` and `color: {intent, preserveNumbers}` (the intent colours separate with; without preserveNumbers CMYK colours are separated again).