Print: an overprinting gradient keeps the ink below where it puts none on PostScript plates

A PostScript plate has no blending modes, so an overprinting gradient
whose stops mix zero and nonzero ink of a plate was drawn whole on it,
and its paper-white part knocked out the ink below.

On a plate, the EPS writer now clips an overprinting gradient to where
it puts the plate's ink down. Linear, radial and diamond gradients leave
out the stretches between paper-white stops and the padding past a
paper-white end stop. Conic gradients leave out their paper-white
wedges, and freeform gradients leave out their paper-white cells (masked
at Level 3, clipped at Level 2). Fills, strokes (within, along and
across) and characters are covered, on process and spot plates. Where
the gradient puts ink down it is drawn as before, and a gradient with
ink everywhere is written unchanged.

On PostScript plates, a stop or point of an overprinting gradient whose
color counts as black, with up to half a percent of another ink, now
puts none of that other ink down, as a solid fill of that color already
does. PDF plates are unchanged.
This commit is contained in:
dotCooCoo
2026-11-17 11:02:04 -08:00
parent 36b5a5920c
commit 556e1552d8
6 changed files with 546 additions and 33 deletions
+1 -1
View File
@@ -70,7 +70,7 @@ fn sheet(p: &PrintPage, job: &PrintJob) -> Result<(String, Vec<Page>), String> {
}
let opts = |region: Rect| EpsOptions { level: job.level, region, ..EpsOptions::default() };
let art_opts = opts(r);
let art = Scene::new(p.doc, &art_opts).run();
let art = Scene::new(p.doc, &art_opts).on_plate(p.ink.is_some()).run();
// The marks' area: the drawing space the page shows (within the tile).
let paper = Rect::new(0.0, 0.0, w, h);
let shown = if p.view.determinant().abs() > 1e-12 { p.view.inverse().transform_rect_bbox(paper) } else { paper };
+185 -3
View File
@@ -1,9 +1,12 @@
//! PostScript print jobs: DSC page comments, the setup of each sheet, and a file the PostScript
//! reader reads back.
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
use vectorcraft_geom::{Affine, Rect, shapes};
use vectorcraft_color::{
Color, Freeform, FreeformPoint, Gradient, GradientGeom, GradientKind, GradientPaint, GradientSpread, GradientStop, Paint, Swatch,
};
use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeId, NodeKind, StrokeGradientMode, TextObject};
use vectorcraft_geom::{Affine, Point, Rect, Vec2, shapes};
use vectorcraft_testkit::raster::{Image, render_region};
use super::*;
@@ -110,3 +113,182 @@ fn separations_screens_flatness_negatives_and_tiles() {
assert!(print(&[], &[], &job).is_err());
assert!(print(&[PrintPage { size: (f64::NAN, 1.0), ..page(&d, None) }], &[0], &job).is_err());
}
/// A 200 × 100 pt CMYK document with spot swatch `Ink` (100% K): a rectangle over the whole page
/// painted `under`, when there is one, then `art`.
fn over(under: Option<Paint>, art: &[Node]) -> Document {
let mut d = Document::new(200.0, 100.0);
d.color_mode = vectorcraft_doc::ColorMode::Cmyk;
d.swatches.push(Swatch { name: "Ink".into(), paint: Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)), global: true, spot: true });
let layer = d.layers[0].id;
let under = under.map(|p| Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 100.0)), Appearance::basic(p, Paint::None, 0.0)));
for mut n in under.into_iter().chain(art.iter().cloned()) {
n.id = d.alloc_id();
d.insert(Some(layer), usize::MAX, n).unwrap();
}
d
}
/// Ink `ink`'s plate of `d` as the print plan separates it for PostScript, and as a PostScript
/// separation at `level` read back, both drawn at 1 px a point.
fn plate_of(d: &Document, ink: &str, level: Level) -> (Image, Image) {
let area = Rect::new(0.0, 0.0, 200.0, 100.0);
let settings = serde_json::from_value(serde_json::json!({"output": {"mode": "separations"}})).unwrap();
let plan = vectorcraft_pdf::plan(d, &vectorcraft_pdf::PrintOptions { settings, postscript: true, ..Default::default() }).unwrap();
let i = plan.sheets.iter().find(|s| s.ink.as_ref().is_some_and(|p| p.name == ink)).and_then(|s| s.plate).unwrap();
let plate = &plan.plates[i];
let page = PrintPage {
doc: plate,
size: (200.0, 100.0),
view: Affine::IDENTITY,
window: None,
place: Affine::IDENTITY,
copies: &[],
area,
marks: None,
negative: false,
ink: Some((ink, 85.0, 15.0)),
};
let out = print(&[page], &[0], &PrintJob { level, ..PrintJob::default() }).unwrap();
assert!(level == Level::Three || !text(&out).contains("shfill"), "Level 2 has no smooth shadings");
let back = crate::import(&out.bytes).unwrap().document;
(render_region(plate, area, 1.0), render_region(&back, area, 1.0))
}
/// Ink `ink`'s PostScript plate of `art` over a page of 100% `ink` (`under`), checked against the
/// plate of `art` alone: where `art` puts none of the ink down, the ink under it prints, and
/// where it puts ink down, its own amount prints. The pixels of the page where `art` alone puts
/// no ink, those of them where the ink under it does not print, and the pixels where `art` puts
/// ink down that do not print its amount.
fn keeps_the_ink_below(art: &[Node], under: &Paint, ink: &str, level: Level) -> (usize, usize, usize) {
let (alone, _) = plate_of(&over(None, art), ink, level);
let (_, printed) = plate_of(&over(Some(under.clone()), art), ink, level);
// Pixels whose neighbors all have paper (or all have ink) on the plate of `art` alone: an
// edge falls on either side of a pixel's center, and the edge of the inked part is lightest.
let around = |x: u32, y: u32, paper: bool| {
(x.saturating_sub(1)..=(x + 1).min(alone.width - 1))
.all(|i| (y.saturating_sub(1)..=(y + 1).min(alone.height - 1)).all(|j| (alone.over_white(i, j)[0] >= 254) == paper))
};
let (mut paper, mut knocked_out, mut wrong) = (0, 0, 0);
for y in 0..alone.height {
for x in 0..alone.width {
let (a, p) = (alone.over_white(x, y)[0], printed.over_white(x, y)[0]);
if around(x, y, true) {
paper += 1;
knocked_out += usize::from(p > 60);
} else if around(x, y, false) {
wrong += usize::from(a.abs_diff(p) > 48);
}
}
}
(paper, knocked_out, wrong)
}
/// A rectangle from (20, 10) to (180, 90) with `fill` and `stroke` (16 pt), each set to
/// overprint.
fn overprinting(fill: Paint, stroke: Paint) -> Node {
let mut n = Node::path(NodeId(0), shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Appearance::basic(fill, stroke, 16.0));
for it in &mut n.appearance.items {
*it.overprint_mut() = true;
}
n
}
/// `stops` (offset, color) as a `kind` gradient placed at `geom`, spreading as `spread`.
fn gradient(kind: GradientKind, stops: &[(f32, Color)], geom: GradientGeom, spread: GradientSpread) -> Paint {
let stops = stops.iter().map(|(o, c)| GradientStop::new(*o, *c)).collect();
let mut g = GradientPaint::new(Gradient { spread, repeats: 2, ..Gradient::new(kind, stops) });
g.geom = Some(geom);
Paint::Gradient(Box::new(g))
}
#[test]
fn an_overprinting_gradient_keeps_the_ink_below_where_it_puts_none_on_a_postscript_plate() {
// Cyan in the outer stops, none from 0.3 to 0.6 (magenta only there).
let (inked, none) = (Color::cmyk(0.6, 0.3, 0.0, 0.0), Color::cmyk(0.0, 0.3, 0.0, 0.0));
let stops = [(0.0, inked), (0.3, none), (0.6, none), (1.0, inked)];
let c = Point::new(100.0, 50.0);
let around = GradientGeom { start: c, end: c + Vec2::new(70.0, -20.0), aspect: 0.7, focal: None };
let across = GradientGeom { start: Point::new(30.0, 40.0), end: Point::new(170.0, 60.0), aspect: 1.0, focal: None };
let pad = GradientSpread::Pad;
let fills = [
("linear", gradient(GradientKind::Linear, &stops, across, pad)),
("radial", gradient(GradientKind::Radial, &stops, around, pad)),
("off-center radial", gradient(GradientKind::Radial, &stops, GradientGeom { focal: Some(c + Vec2::new(-20.0, 10.0)), ..around }, pad)),
("conic", gradient(GradientKind::Conic, &stops, around, pad)),
("diamond", gradient(GradientKind::Diamond, &stops, around, pad)),
("repeating linear", gradient(GradientKind::Linear, &stops, across, GradientSpread::Repeat)),
("reflecting radial", gradient(GradientKind::Radial, &stops, around, GradientSpread::Reflect)),
// A hard edge: two stops at 0.5, the inked half first.
("hard edge", gradient(GradientKind::Linear, &[(0.0, inked), (0.5, inked), (0.5, none), (1.0, none)], across, pad)),
// Starting and ending with no cyan, padding past both ends.
("none at the ends", gradient(GradientKind::Linear, &[(0.2, none), (0.4, none), (0.5, inked), (0.8, none)], across, pad)),
];
// Many stretches with no cyan.
let many: Vec<(f32, Color)> = (0..16).map(|i| (i as f32 / 15.0, if i % 4 < 2 { inked } else { none })).collect();
let fills = fills.into_iter().chain([("many stops", gradient(GradientKind::Linear, &many, across, pad))]);
let cyan = Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0));
let cases: Vec<_> = fills.map(|(name, fill)| (name, overprinting(fill, Paint::None), cyan.clone(), "Cyan")).collect();
assert_keeps_the_ink_below(&cases);
}
/// [`keeps_the_ink_below`] for each of `cases` (a name, the art, the paint under it and the ink
/// of the plate) at Level 3 and Level 2, with every case that fails named.
fn assert_keeps_the_ink_below(cases: &[(&str, Node, Paint, &str)]) {
let mut failed = vec![];
for (name, art, under, ink) in cases {
for level in [Level::Three, Level::Two] {
let (paper, knocked_out, wrong) = keeps_the_ink_below(std::slice::from_ref(art), under, ink, level);
if knocked_out + wrong >= 100 {
failed.push(format!("{name} at level {level:?}: {knocked_out} of {paper} knocked out, {wrong} of the others differ"));
}
}
}
assert!(failed.is_empty(), "{failed:#?}");
}
#[test]
fn overprinting_gradient_strokes_type_freeforms_and_spot_inks_keep_the_ink_below_on_postscript_plates() {
let (inked, none) = (Color::cmyk(0.6, 0.3, 0.0, 0.0), Color::cmyk(0.0, 0.3, 0.0, 0.0));
let stops = [(0.0, inked), (0.3, none), (0.6, none), (1.0, inked)];
let across = GradientGeom { start: Point::new(30.0, 40.0), end: Point::new(170.0, 60.0), aspect: 1.0, focal: None };
let linear = gradient(GradientKind::Linear, &stops, across, GradientSpread::Pad);
let stroked = |mode: StrokeGradientMode| {
let mut n = overprinting(Paint::None, linear.clone());
if let Some(st) = n.appearance.stroke_mut() {
st.gradient_mode = mode;
}
n
};
// Type: a gradient placed on the characters' bounds.
let on_type = GradientPaint::new(Gradient::new(GradientKind::Linear, stops.iter().map(|(o, c)| GradientStop::new(*o, *c)).collect()));
let style = CharStyle { fill: Paint::Gradient(Box::new(on_type)), overprint_fill: true, size: 80.0, ..Default::default() };
let text = Node::new(NodeId(0), NodeKind::Text(Box::new(TextObject::point(Point::new(20.0, 85.0), "HIM", style))));
// A freeform gradient with wide spreads of pure color around its points: none of the cyan
// around the left one.
let mut freeform = GradientPaint::new(Gradient::new(GradientKind::Freeform, vec![GradientStop::new(0.0, none), GradientStop::new(1.0, inked)]));
let pure = |at: Point, c: Color| FreeformPoint { spread: 0.9, ..FreeformPoint::new(at, c) };
let points = vec![pure(Point::new(50.0, 50.0), none), pure(Point::new(150.0, 50.0), inked)];
freeform.freeform = Some(Freeform { points, ..Default::default() });
// A spot ink's own plate: its tints in the outer stops, none of it from 0.3 to 0.6.
let tint = |t: f32| GradientStop { swatch: Some("Ink".into()), tint: t, ..GradientStop::new(0.0, Color::cmyk(0.0, 0.0, 0.0, t)) };
let spot = [
GradientStop { offset: 0.0, ..tint(0.8) },
GradientStop::new(0.3, none),
GradientStop::new(0.6, none),
GradientStop { offset: 1.0, ..tint(0.5) },
];
let mut on_spot = GradientPaint::new(Gradient::new(GradientKind::Linear, spot.to_vec()));
on_spot.geom = Some(across);
let cyan = Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0));
let full = Paint::Solid { color: Color::cmyk(0.0, 0.0, 0.0, 1.0), swatch: Some("Ink".into()), tint: 1.0 };
let cases = [
("stroke within", stroked(StrokeGradientMode::Within), cyan.clone(), "Cyan"),
("stroke along", stroked(StrokeGradientMode::Along), cyan.clone(), "Cyan"),
("stroke across", stroked(StrokeGradientMode::Across), cyan.clone(), "Cyan"),
("type", text, cyan.clone(), "Cyan"),
("freeform", overprinting(Paint::Gradient(Box::new(freeform)), Paint::None), cyan, "Cyan"),
("spot", overprinting(Paint::Gradient(Box::new(on_spot)), Paint::None), full, "Ink"),
];
assert_keeps_the_ink_below(&cases);
}
+263 -16
View File
@@ -8,6 +8,7 @@ use std::sync::Arc;
use kurbo::Shape;
use vectorcraft_color::{BlendMode, Color, GradientKind, GradientPaint, Paint};
use vectorcraft_doc::overprint::is_white;
use vectorcraft_doc::{
AppearanceItem, ColorMode, Document, Effect, ImageBlob, LineCap, LineJoin, Node, NodeKind, StrokeAlign, StrokeLayer, SymbolBoxes, TextObject,
};
@@ -213,6 +214,14 @@ impl GradientSpace {
GradientSpace::Inks(_, n) => *n,
}
}
/// Whether components `c` in this space are paper white: no ink, or full light.
fn paper(&self, c: &[f32]) -> bool {
match self {
GradientSpace::Process(Space::Gray | Space::Rgb) => c.iter().all(|v| *v >= 1.0),
GradientSpace::Process(Space::Cmyk) | GradientSpace::Inks(..) => c.iter().all(|v| *v <= 0.0),
}
}
}
/// A gradient's stops as written: offsets from 0 to 1 and the components in its space.
@@ -287,6 +296,12 @@ pub(crate) struct Scene<'a> {
max_body: usize,
/// Symbols and brush art being written inside one another.
nest: u32,
/// The document is a separation's plate: every color is the gray of one ink's coverage
/// ([`Self::on_plate`]).
plate: bool,
/// The gradient being painted overprints on a plate: where it is paper white it puts none of
/// the plate's ink down, and the plate below it is left as it is ([`Self::inked_spans`]).
keep_below: bool,
}
impl<'a> Scene<'a> {
@@ -315,9 +330,19 @@ impl<'a> Scene<'a> {
pending: 0,
max_body: MAX_BODY,
nest: 0,
plate: false,
keep_below: false,
}
}
/// This scene drawing a separation's plate when `plate` is true: an overprinting gradient
/// paints only where it puts the plate's ink down, as an overprinting solid color that puts
/// none down is drawn as nothing on it.
pub fn on_plate(mut self, plate: bool) -> Self {
self.plate = plate;
self
}
/// This scene with a page body of at most `max` bytes.
#[cfg(test)]
pub fn with_max_body(mut self, max: usize) -> Self {
@@ -689,13 +714,20 @@ impl<'a> Scene<'a> {
self.line("q");
push_path(&mut self.body, bp);
self.body.push_str(clip_op(rule));
self.paint_area(p, bounds, bp.bounding_box());
self.paint_overprinting(overprint, p, bounds, bp.bounding_box());
self.line("Q");
}
}
self.overprint_off(on);
}
/// [`Self::paint_area`] for a fill or stroke that overprints when `overprint` is true.
fn paint_overprinting(&mut self, overprint: bool, p: &Paint, bounds: Rect, area: Rect) {
let keep = std::mem::replace(&mut self.keep_below, self.plate && overprint);
self.paint_area(p, bounds, area);
self.keep_below = keep;
}
/// Paint all of `area` (inside the current clip) with gradient or pattern `p`, placed on
/// `bounds`.
fn paint_area(&mut self, p: &Paint, bounds: Rect, area: Rect) {
@@ -786,7 +818,7 @@ impl<'a> Scene<'a> {
self.line("q");
push_path(&mut self.body, bp);
self.line("strokepath W");
self.paint_area(p, paint_bounds, w.reach(st, bounds));
self.paint_overprinting(st.overprint, p, paint_bounds, w.reach(st, bounds));
self.line("Q");
}
}
@@ -1152,7 +1184,8 @@ impl<'a> Scene<'a> {
/// Paint all of `area` (inside the current clip) with linear, radial, conic or diamond gradient
/// `g`, placed on `bounds`: a smooth shading at Level 3, else stepped fills (a conic: wedges at
/// both levels; a diamond: four linear gradients, [`Self::diamond_quadrants`]).
/// both levels; a diamond: four linear gradients, [`Self::diamond_quadrants`]). Overprinting
/// on a plate, it is clipped to the levels where it puts ink down ([`Self::inked_spans`]).
fn gradient(&mut self, g: &GradientPaint, bounds: Rect, area: Rect) {
let geom = g.resolve(bounds);
// One mixed around the hue wheel that reflects is repeated from its curve's stops, which
@@ -1185,7 +1218,7 @@ impl<'a> Scene<'a> {
}
let (space, stops) = self.gradient_stops(&g.gradient);
if !stops.windows(2).any(|w| w[1].0 > w[0].0) {
if let Some((_, c)) = stops.first() {
if let Some((_, c)) = stops.first().filter(|(_, c)| !(self.keep_below && space.paper(c))) {
self.set_comps(&space, c);
self.rect_fill(area);
}
@@ -1193,20 +1226,47 @@ impl<'a> Scene<'a> {
}
let space = &space;
let smooth = self.o.level == Level::Three && !self.o.compatible_gradients;
let spans = if g.gradient.kind == GradientKind::Conic { None } else { self.inked_spans(space, &stops) };
match g.gradient.kind {
GradientKind::Conic => self.conic_steps(&geom, area, space, &stops, &g.gradient),
GradientKind::Diamond => self.diamond_quadrants(&geom, area, space, &stops, smooth),
GradientKind::Diamond => {
// Its levels are diamonds about the center, the square's edge at 1.
let frame = geom.diamond_frame();
if let Some(spans) = &spans {
let Some(frame) = frame else {
// Without a frame it is its last stop everywhere.
if stops.last().is_some_and(|(_, c)| !space.paper(c)) {
self.diamond_quadrants(&geom, area, space, &stops, smooth);
}
return;
};
let level = |t: f64| (t > 0.0).then(|| frame * BezPath::from_vec(diamond(t)));
self.line("q");
let clipped = self.clip_rings(spans, area.inflate(1.0, 1.0), level);
if clipped {
self.diamond_quadrants(&geom, area, space, &stops, smooth);
}
self.line("Q");
return;
}
self.diamond_quadrants(&geom, area, space, &stops, smooth);
}
GradientKind::Radial => {
let r = geom.length().max(1e-6);
let squash = geom.radial_squash();
let inv = squash.inverse();
let (f, c) = (inv * geom.focal_point(), geom.start);
let local = inv.transform_rect_bbox(area);
self.line("q");
let _ = writeln!(self.body, "{} cm", ps::matrix(squash));
if smooth {
self.shading(3, space, &[f.x, f.y, 0.0, c.x, c.y, r], &stops);
} else {
self.radial_steps(f, c, r, inv.transform_rect_bbox(area), space, &stops);
// Its levels are circles from the focal point, at 1 the circle of radius `r`.
let level = |t: f64| (t > 0.0).then(|| kurbo::Circle::new(f + (c - f) * t, r * t).to_path(0.01));
if spans.as_ref().is_none_or(|spans| self.clip_rings(spans, local.inflate(1.0, 1.0), level)) {
if smooth {
self.shading(3, space, &[f.x, f.y, 0.0, c.x, c.y, r], &stops);
} else {
self.radial_steps(f, c, r, local, space, &stops);
}
}
self.line("Q");
}
@@ -1215,15 +1275,121 @@ impl<'a> Scene<'a> {
if s.distance(e) < 1e-9 {
e = s + Vec2::new(1.0, 0.0);
}
if smooth {
self.shading(2, space, &[s.x, s.y, e.x, e.y], &stops);
if let Some(spans) = &spans {
self.line("q");
if self.clip_strips(spans, s, e, area) {
self.linear(s, e, area, space, &stops, smooth);
}
self.line("Q");
} else {
self.linear_steps(s, e, area, space, &stops);
self.linear(s, e, area, space, &stops, smooth);
}
}
}
}
/// A linear gradient from `s` to `e` over `area`: a smooth shading, else stepped fills.
fn linear(&mut self, s: Point, e: Point, area: Rect, space: &GradientSpace, stops: &[(f64, Vec<f32>)], smooth: bool) {
if smooth {
self.shading(2, space, &[s.x, s.y, e.x, e.y], stops);
} else {
self.linear_steps(s, e, area, space, stops);
}
}
/// Where an overprinting gradient with `stops` in `space` puts ink on a plate
/// ([`Self::keep_below`]): the spans of its levels outside every stretch between two stops of
/// paper white and outside the padding past an end whose stop is paper white, in order, an
/// end padding with ink unbounded. `None` when the gradient puts ink everywhere or does not
/// overprint on a plate; empty when it puts none down.
fn inked_spans(&self, space: &GradientSpace, stops: &[(f64, Vec<f32>)]) -> Option<Vec<(f64, f64)>> {
if !self.keep_below {
return None;
}
let stretches: Vec<_> = stops.windows(2).filter(|w| w[1].0 > w[0].0).collect();
let (first, last) = (stretches.first()?, stretches.last()?);
// The padding takes the end stop's color stepped and the end stretch's color smooth.
let before = stops.first().is_some_and(|s| space.paper(&s.1)) && space.paper(&first[0].1);
let after = stops.last().is_some_and(|s| space.paper(&s.1)) && space.paper(&last[1].1);
let mut blank: Vec<(f64, f64)> = vec![];
let mut add = |a: f64, b: f64| match blank.last_mut() {
Some(l) if l.1 >= a => l.1 = l.1.max(b),
_ => blank.push((a, b)),
};
if before {
add(f64::NEG_INFINITY, first[0].0);
}
for w in &stretches {
if space.paper(&w[0].1) && space.paper(&w[1].1) {
add(w[0].0, w[1].0);
}
}
if after {
add(last[1].0, f64::INFINITY);
}
if blank.is_empty() {
return None;
}
let mut inked = vec![];
let mut from = f64::NEG_INFINITY;
for (a, b) in blank {
if a > from {
inked.push((from, a));
}
from = b;
}
if from < f64::INFINITY {
inked.push((from, f64::INFINITY));
}
Some(inked)
}
/// Clip to the parts of `area` where a linear gradient from `s` to `e` has a level in `spans`:
/// a strip across the gradient for each. False, with nothing written, when no span reaches
/// into `area`.
fn clip_strips(&mut self, spans: &[(f64, f64)], s: Point, e: Point, area: Rect) -> bool {
let d = e - s;
let len = d.hypot();
// Gradient space: x along the gradient (0 to 1), y across it in points.
let frame = Affine::new([d.x, d.y, -d.y / len, d.x / len, s.x, s.y]);
let local = frame.inverse().transform_rect_bbox(area.inflate(1.0, 1.0));
let mut bp = BezPath::new();
for &(a, b) in spans {
let (a, b) = (a.max(local.x0), b.min(local.x1));
if a < b {
bp.extend((frame * Rect::new(a, local.y0, b, local.y1).to_path(0.1)).iter());
}
}
self.clip_path(&bp, FillRule::NonZero)
}
/// Clip to the levels in `spans` of a gradient whose level `t` is bounded by `level(t)` (a
/// closed path holding every lower level; `None` for a level without area): for each span
/// the ring between its levels, an unbounded end at `outer`, even-odd. False, with nothing
/// written, when no span has area.
fn clip_rings(&mut self, spans: &[(f64, f64)], outer: Rect, level: impl Fn(f64) -> Option<BezPath>) -> bool {
let mut bp = BezPath::new();
for &(a, b) in spans {
let edge = if b.is_finite() { level(b) } else { Some(outer.to_path(0.1)) };
let Some(edge) = edge else { continue };
bp.extend(edge.iter());
if let Some(inner) = level(a).filter(|_| a.is_finite()) {
bp.extend(inner.iter());
}
}
self.clip_path(&bp, FillRule::EvenOdd)
}
/// Clip to `bp` by `rule`. False, with nothing written, when `bp` is empty.
fn clip_path(&mut self, bp: &BezPath, rule: FillRule) -> bool {
if bp.elements().is_empty() {
return false;
}
push_path(&mut self.body, bp);
self.body.push_str(clip_op(rule));
true
}
/// A conic gradient as [`CONIC_WEDGE_COUNT`] solid wedges about its center covering `area`
/// (PostScript has no conic shading), each running on to the seam under the next, so no
/// hairline shows between neighbors ([`vectorcraft_color::GradientGeom::conic_wedges`]).
@@ -1243,7 +1409,24 @@ impl<'a> Scene<'a> {
Some(w) => w[1].1.clone(),
None => stops.last().map_or_else(Vec::new, |s| s.1.clone()),
};
for (pts, t) in geom.conic_wedges(area, g.conic_wedge_count(CONIC_WEDGE_COUNT), true) {
let count = g.conic_wedge_count(CONIC_WEDGE_COUNT);
// Overprinting on a plate: clipped to the wedges that put ink down, each up to the next.
let clipped = self.keep_below && {
let wedges = geom.conic_wedges(area, count, false);
let inked: Vec<_> = wedges.iter().filter(|(_, t)| !space.paper(&at(spread(*t)))).collect();
if inked.is_empty() {
return;
}
inked.len() < wedges.len() && {
let mut bp = BezPath::new();
for (pts, _) in inked {
bp.extend(BezPath::from_vec(polygon(pts)).iter());
}
self.line("q");
self.clip_path(&bp, FillRule::NonZero)
}
};
for (pts, t) in geom.conic_wedges(area, count, true) {
self.set_comps(space, &at(spread(t)));
for (i, p) in pts.iter().enumerate() {
push_nums(&mut self.body, &[p.x, p.y]);
@@ -1251,6 +1434,9 @@ impl<'a> Scene<'a> {
}
self.line("closepath fill");
}
if clipped {
self.line("Q");
}
}
/// A diamond gradient over `area` as four linear gradients, each clipped to a quadrant of its
@@ -1442,20 +1628,68 @@ impl<'a> Scene<'a> {
let field = g.freeform_on(b).model_field(spread_scale(b));
let q = |v: f32| (unit(v) * 255.0).round() as u8;
let (w, h) = (u32::from(cols), u32::from(rows));
// Overprinting on a plate: the cells of paper white put none of the ink down, so they are
// left out, as clear pixels at Level 3 and outside a clip of the other cells at Level 2.
let blank: Option<Vec<bool>> = self.keep_below.then(|| field.grid(area, cols, rows).map(|(c, _)| is_white(&Paint::solid(c))).collect());
let blank = blank.filter(|b| b.contains(&true));
if blank.as_ref().is_some_and(|b| !b.contains(&false)) {
return;
}
let keyed = self.o.level == Level::Three;
let clear = |i: usize, a: u8| if keyed && blank.as_ref().is_some_and(|b| b[i]) { 0 } else { a };
let image = if field.model() == Some(Model::Cmyk) || (self.cmyk && field.model() == Some(Model::Gray)) {
let inks: Vec<u8> = field
.grid(area, cols, rows)
.flat_map(|(color, a)| {
.enumerate()
.flat_map(|(i, (color, a))| {
let [c, m, y, k] = color.to_cmyk();
[q(c), q(m), q(y), q(k), q(a)]
[q(c), q(m), q(y), q(k), clear(i, q(a))]
})
.collect();
self.encode_inks(&inks, w, h)
} else {
let rgba: Vec<u8> = field.display_grid(area, cols, rows).flat_map(|(c, a)| [q(c[0]), q(c[1]), q(c[2]), q(a)]).collect();
let rgba: Vec<u8> =
field.display_grid(area, cols, rows).enumerate().flat_map(|(i, (c, a))| [q(c[0]), q(c[1]), q(c[2]), clear(i, q(a))]).collect();
self.encode_image(&rgba, w, h)
};
let Some(image) = image else { return };
let cells = blank.filter(|_| !keyed).map(|b| {
let (cw, ch) = (area.width() / f64::from(cols), area.height() / f64::from(rows));
let mut bp = BezPath::new();
for (row, line) in b.chunks(usize::from(cols)).enumerate() {
let mut col = 0;
while col < line.len() {
let start = col;
while col < line.len() && !line[col] {
col += 1;
}
if col > start {
let (y0, y1) = (area.y0 + row as f64 * ch, area.y0 + (row + 1) as f64 * ch);
bp.extend(Rect::new(area.x0 + start as f64 * cw, y0, area.x0 + col as f64 * cw, y1).to_path(0.1).iter());
}
col += 1;
}
}
bp
});
if let Some(bp) = &cells {
// Each row's run of cells is a rectangle of five path elements, about 60 bytes.
if self.size().saturating_add(bp.elements().len().saturating_mul(12)).saturating_add(image.inline_len) > self.max_body {
self.warn(TOO_LARGE);
return;
}
self.line("q");
self.clip_path(bp, FillRule::NonZero);
}
self.place_field(image, place);
if cells.is_some() {
self.line("Q");
}
}
/// Place freeform gradient image `image` on the unit square mapped by `place`, drawn from an
/// image already kept when one is encoded the same.
fn place_field(&mut self, image: ImageCode, place: Affine) {
let key = image.content_key();
let found =
self.fields.get(&key).and_then(|bucket| bucket.iter().copied().find(|&i| self.codes.get(i).is_some_and(|c| c.same_image(&image))));
@@ -1849,6 +2083,19 @@ fn image_code(prelude: String, dict: String, filter: &'static str, op: &'static
code
}
/// The closed polygon through `pts`.
fn polygon(pts: &[Point]) -> Vec<kurbo::PathEl> {
let mut els: Vec<kurbo::PathEl> =
pts.iter().enumerate().map(|(i, p)| if i == 0 { kurbo::PathEl::MoveTo(*p) } else { kurbo::PathEl::LineTo(*p) }).collect();
els.push(kurbo::PathEl::ClosePath);
els
}
/// The square with corners (±`t`, 0) and (0, ±`t`).
fn diamond(t: f64) -> Vec<kurbo::PathEl> {
polygon(&[Point::new(t, 0.0), Point::new(0.0, t), Point::new(-t, 0.0), Point::new(0.0, -t)])
}
/// `a` to `b` at `t`.
fn mix(a: &[f32], b: &[f32], t: f32) -> Vec<f32> {
a.iter().zip(b).map(|(x, y)| x + (y - x) * t).collect()
+60 -13
View File
@@ -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, GradientKind, Paint};
use vectorcraft_color::{BlendMode, Color, GradientKind, GradientStop, Paint};
use vectorcraft_doc::inks::{Link, StopPlates, inks, plates, spot_color, stop_inks, visit_node_colors};
use vectorcraft_doc::overprint::{darken_overprints, is_black_ink, is_white};
use vectorcraft_doc::{AppearanceItem, ColorMode, Document, ImageBlob, Node, NodeKind};
@@ -174,33 +174,74 @@ impl<'a> Separator<'a> {
/// spot swatch, to Registration or to a swatch the document lacks: up to the half a percent of
/// another ink such a black may carry counts as none.
fn no_ink(&self, plate: &str, p: &Paint) -> bool {
let process = |swatch: Option<&str>| swatch.is_none_or(|n| n != REGISTRATION && self.doc.swatch(n).is_some_and(|w| !w.spot));
let none = |c: &Color, process: bool, ink: f32| ink <= 0.0 || (self.postscript && process && ink <= 0.005 && is_black_ink(c, 1.0, false));
match p {
Paint::Solid { color, swatch, tint } => {
none(color, process(swatch.as_deref()), self.ink(plate, color, swatch.as_deref().map(|s| (s, *tint))))
self.none(color, self.process(swatch.as_deref()), self.ink(plate, color, swatch.as_deref().map(|s| (s, *tint))))
}
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| none(&pt.color, true, self.ink(plate, &pt.color, None))),
None => {
!g.gradient.stops.is_empty()
&& g.gradient.stops.iter().all(|s| {
let ink = self.stop_ink(plate, &s.color, s.swatch.as_deref().map(|n| (n, s.tint)), s.plates);
none(&s.color, s.plates.is_none() && process(s.swatch.as_deref()), ink)
})
}
Some(f) => f.points.iter().all(|pt| self.point_none(plate, &pt.color)),
None => !g.gradient.stops.is_empty() && g.gradient.stops.iter().all(|s| self.stop_none(plate, s)),
},
_ => false,
}
}
/// Whether a color linked to swatch `swatch` separates as process inks: no link, or a link
/// to a process swatch the document has, other than Registration.
fn process(&self, swatch: Option<&str>) -> bool {
swatch.is_none_or(|n| n != REGISTRATION && self.doc.swatch(n).is_some_and(|w| !w.spot))
}
/// Whether `ink` of color `c` (separating as process inks when `process` is true) counts as
/// none, as [`Self::no_ink`] says.
fn none(&self, c: &Color, process: bool, ink: f32) -> bool {
ink <= 0.0 || (self.postscript && process && ink <= 0.005 && is_black_ink(c, 1.0, false))
}
/// Whether gradient stop `s` puts none of ink `plate` down, as [`Self::no_ink`] says.
fn stop_none(&self, plate: &str, s: &GradientStop) -> bool {
let ink = self.stop_ink(plate, &s.color, s.swatch.as_deref().map(|n| (n, s.tint)), s.plates);
self.none(&s.color, s.plates.is_none() && self.process(s.swatch.as_deref()), ink)
}
/// Whether a freeform gradient's point of color `c` puts none of ink `plate` down, as
/// [`Self::no_ink`] says.
fn point_none(&self, plate: &str, c: &Color) -> bool {
self.none(c, true, self.ink(plate, c, None))
}
/// On a PostScript plate, make paper white the stops and points of overprinting gradient `p`
/// that put none of ink `plate` down while others do ([`Self::no_ink`]'s rule for each): the
/// writer leaves the plate below as it is where the gradient is paper white.
fn clear_inkless_stops(&self, plate: &str, p: &mut Paint) {
let Paint::Gradient(g) = p else { return };
if !self.postscript {
return;
}
let paper = Color::Gray { k: 0.0 };
match g.freeform.as_mut().filter(|f| g.gradient.kind == GradientKind::Freeform && !f.points.is_empty()) {
Some(f) => {
for pt in f.points.iter_mut().filter(|pt| self.point_none(plate, &pt.color)) {
pt.color = paper;
}
}
None => {
for s in g.gradient.stops.iter_mut().filter(|s| self.stop_none(plate, s)) {
*s = GradientStop { color: paper, swatch: None, tint: 1.0, plates: None, ..s.clone() };
}
}
}
}
/// Overprinting fills and strokes of `a`'s subtree with a Normal blending mode, and
/// overprinting character fills and strokes, that put none of ink `plate` down leave its plate
/// as it is: they are drawn as nothing on it (white ones with `discard_white` aside, which
/// knock out). A writer without blending modes (PostScript) then keeps the ink below them,
/// where it would draw their Darken as a knockout. One that puts any ink down is drawn, and on
/// a PostScript plate its ink replaces the ink below, as a nonzero component of an overprinting
/// color replaces the backdrop's with overprint mode 1 (ISO 32000-1, 11.7.4.2).
/// color replaces the backdrop's with overprint mode 1 (ISO 32000-1, 11.7.4.2). On a
/// PostScript plate, the stops and points of such a gradient that put none of the ink down
/// become paper white ([`Self::clear_inkless_stops`]), which the writer leaves out there.
fn clear_inkless_overprints(&self, plate: &str, a: &mut Arc<Node>, discard_white: bool) {
let inkless = |overprint: bool, p: &Paint| overprint && !p.is_none() && !(discard_white && is_white(p)) && self.no_ink(plate, p);
let n = Arc::make_mut(a);
@@ -211,15 +252,21 @@ impl<'a> Separator<'a> {
};
if normal && inkless(it.overprint(), it.paint()) {
*it.paint_mut() = Paint::None;
} else if normal && it.overprint() {
self.clear_inkless_stops(plate, it.paint_mut());
}
}
if let NodeKind::Text(t) = &mut n.kind {
for r in &mut t.runs {
if inkless(r.style.overprint_fill, &r.style.fill) {
r.style.fill = Paint::None;
} else if r.style.overprint_fill {
self.clear_inkless_stops(plate, &mut r.style.fill);
}
if inkless(r.style.overprint_stroke, &r.style.stroke) {
r.style.stroke = Paint::None;
} else if r.style.overprint_stroke {
self.clear_inkless_stops(plate, &mut r.style.stroke);
}
}
}
+36
View File
@@ -925,6 +925,42 @@ fn overprinting_paints_keep_their_faint_ink_on_postscript_plates() {
}
}
#[test]
fn a_near_black_stop_of_an_overprinting_gradient_puts_no_cyan_on_postscript_plates() {
// 0.4% cyan beside 100% K counts as black on a PostScript plate stop by stop, as a solid fill
// of it does: the cyan plate draws that stop of an overprinting gradient as paper white. A
// PDF plate and a gradient that does not overprint keep the 0.4%.
let stops = vec![GradientStop::new(0.0, Color::cmyk(0.004, 0.0, 0.0, 1.0)), GradientStop::new(1.0, Color::cmyk(0.5, 0.0, 0.0, 0.0))];
let fade = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
let square = |x: f64, overprint: bool| {
let r = shapes::rectangle(Rect::new(x, 15.0, x + 20.0, 35.0));
let mut n = Node::path(vectorcraft_doc::NodeId(0), r, Appearance::basic(fade.clone(), Paint::None, 0.0));
if let Some(f) = n.appearance.fill_mut() {
f.overprint = overprint;
}
n
};
let d = over_cyan(vec![square(10.0, true), square(40.0, false)]);
// The cyan plate's stops of each gradient, in thousandths of the ink.
let stops = |postscript: bool| {
let opts = PrintOptions { settings: settings(json!({"output": {"mode": "separations"}})), postscript, ..Default::default() };
let p = plan(&d, &opts).unwrap();
let mut all = vec![];
p.plates[0].walk(|n| {
if let Some(Paint::Gradient(g)) = n.appearance.fill().map(|f| &f.paint) {
let gray = |s: &GradientStop| match s.color {
Color::Gray { k } if s.swatch.is_none() => (k * 1000.0).round(),
c => panic!("{c:?}"),
};
all.push(g.gradient.stops.iter().map(gray).collect::<Vec<_>>());
}
});
all
};
assert_eq!(stops(true), [[0.0, 500.0], [4.0, 500.0]], "PostScript: the overprinting gradient, the other");
assert_eq!(stops(false), [[4.0, 500.0], [4.0, 500.0]], "PDF");
}
#[test]
fn overprinting_type_leaves_the_inks_below_on_separations() {
let style = vectorcraft_doc::CharStyle { fill: Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)), ..Default::default() };
+1
View File
@@ -2067,6 +2067,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Desktop print transport uses `craft-print` for CUPS and modern Windows. Sheet composition, copies, separations and colour management remain in VectorCraft. The Print dialog's Media list also carries the Japanese papers — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (250 × 353 and 176 × 250 mm, kept so settings and presets saved before them keep their paper), and はがき 100 × 148 mm, 往復はがき 148 × 200 mm, 封筒 長形3号 120 × 235 mm, 長形4号 90 × 225 mm, 角形2号 240 × 332 mm, 角形3号 216 × 277 mm and 四六判 127 × 188 mm; the JSON id or the dialog label names a paper, any case and spacing (`B5 (JIS)` or `b5jis`) (`crates/pdf/src/print/settings.rs`, `crates/pdf/src/tests/print.rs`). The print-preview and physical-device fidelity gaps remain, so print scores and hours are unchanged.
- The Print dialog's Document Ink Options list shows an icon before each spot ink's name, and a click on it prints that one ink as process inks (on the Cyan, Magenta, Yellow and Black plates, with no plate of its own) or as a spot ink again, as [the help page](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) describes for single spot colors. Other spot inks keep their plates, and spot gradient stops and DCS images' spot plates follow each ink's choice (`print.setup {settings: {output: {inks: [{name, convertToProcess: true}]}}}`, kept with the document and in print presets; `print.preview` lists every ink as `documentInks`). These are VectorCraft's own rules: Convert All Spot Colors to Process converts every spot ink and dims the icons while keeping each ink's own choice, a converted ink's Print, Frequency and Angle are dimmed and kept, and process inks and Registration have no icon. Evidence: `print::one_spot_ink_converts_to_process_and_the_others_keep_their_plates`, `print::converting_every_spot_ink_overrides_and_keeps_each_inks_own_choice`, `print::a_spot_gradient_stop_prints_its_process_plates`, `cmykimages::a_dcs_image_converts_only_the_spot_ink_chosen`, `tests::print::a_spot_ink_converted_to_process_is_saved_and_listed_without_a_plate`, `dialogs::tests_print::a_spot_inks_icon_converts_it_to_process_and_back`. Print scores and hours are unchanged.
- The Print dialog's Output section has Overprint Black under Convert All Spot Colors to Process, off by default and available with Separations ([Print color separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) lists it among the separation options): black art then leaves the inks under it on the other plates (`print.setup {settings: {output: {overprintBlack: true}}}`, kept with the document and in print presets). Solid 100% K or 100% gray fills, strokes and characters (to within half a percent, as Edit › Edit Colors › Overprint Black counts them), and gradients whose every stop (every color point of a freeform gradient) is, overprint; rich, RGB, Lab, spot-linked and lighter blacks are not marked, paints already set to overprint keep that setting, and only the printed copy is marked. These limits are VectorCraft's own rules. Characters set to overprint now also leave the inks below them on printed PDF plates, a type object's own fill in a PDF is drawn with its blending mode, and Edit › Edit Colors › Overprint Black counts a gradient with a stop linked to a spot swatch as a spot black, as it counts a solid one, and a freeform gradient by the color points it draws from. On a plate, an overprinting paint that puts none of that plate's ink down is drawn as nothing; on PostScript plates so is up to half a percent of another ink in a color that counts as black, and any other faint ink stays on the plate. Evidence: `print::overprint_black_keeps_the_inks_under_solid_black_on_separations`, `print::overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_plates`, `print::overprinting_paints_keep_their_faint_ink_on_postscript_plates`, `print::overprinting_type_leaves_the_inks_below_on_separations`, `print::a_type_objects_own_black_fill_overprints_on_separations`, `tests::print::overprint_black_is_saved_with_the_setup_and_in_presets`, `overprint::tests::a_gradient_with_a_spot_linked_stop_is_black_only_with_spot`, `overprint::tests::a_freeform_gradient_is_black_when_every_point_is`. Print scores and hours are unchanged.
- On a PostScript plate, an overprinting gradient that puts the plate's ink down in some places and none in others leaves the ink below where it puts none: the stretches between stops of paper white and the padding past an end stop of paper white are clipped out of a linear, radial or diamond gradient, the wedges of paper white out of a conic one, and the cells of paper white out of a freeform one (masked at Level 3, clipped at Level 2). This holds for fills, strokes and characters, and on spot plates. Where the gradient puts ink down, its amount replaces the ink below as before. A stop or point with up to half a percent of another ink in a color that counts as black puts none down, as a solid fill of that color does. PDF plates are unchanged. These are VectorCraft's own rules. Evidence: `print::tests::an_overprinting_gradient_keeps_the_ink_below_where_it_puts_none_on_a_postscript_plate` and `print::tests::overprinting_gradient_strokes_type_freeforms_and_spot_inks_keep_the_ink_below_on_postscript_plates` (`vectorcraft-eps`), `tests::print::a_near_black_stop_of_an_overprinting_gradient_puts_no_cyan_on_postscript_plates`.
- The Print dialog's General section (and the print preset editor) has a link button after Scale W and H, as the Custom scale has one on [the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/print-documents-in-illustrator.html), where turning it off scales the width and height apart. While it is on, typing either percentage sets the other, and turning it on sets H to W. It is on for new settings, dimmed with the fields unless Scaling is Custom or a tiling choice, toggled with a click, Space or Enter, and named with its on or off state for screen readers. W and H take 1–1000% in the fields. The link is kept with the document's print settings and in print presets (`print.setup {settings: {scale: {linked}}}`); settings saved without it read it as off, so they print as before. Its default, the tiling choices and the agent rules are VectorCraft's own. Evidence: `print::the_scale_link_is_on_for_new_settings_and_off_for_a_saved_scale_without_it`, `tests::print::the_scale_link_keeps_width_and_height_equal`, `tests::print::a_scale_saved_without_the_link_keeps_its_width_and_height`, `dialogs::tests_print::the_scale_link_keeps_scale_width_and_height_equal`, `dialogs::tests_print::a_print_preset_keeps_the_scale_link`. Print scores and hours are unchanged.
- A PDF, PDF-compatible `.ai` or `.ait` opened from its pages or its editing copy opens with the File Info that its XMP packet and its document information dictionary give: the title (`dc:title`, its `x-default` item first, else Info `Title`), the author, description, keywords, copyright status, notice and URL, and the created and modified dates, the XMP packet's value where both give one (`crates/pdf/src/tests/file_info.rs`, `crates/engine/src/tests/fileinfo.rs`). An SVG opens with the title of its root `<title>`. The title is File Info's alone (`DocMetadata::title`): the document's name stays the file's name with its extension, a file that gives no title leaves File Info with that name, and exports (PDF, SVG, PNG, EPS, `.ai`) and native saves carry it; changing the title in File Info sets the document's name as before (#3626).
- PDF export and PDF-compatible `.ai` and `.ait` saves write the document's File Info created date as the file's creation date, or the time of writing when the document has none, and the time of writing as its modification date; the page information mark still prints the time of writing (`crates/engine/src/tests/fileinfo.rs`, `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/marks.rs`).