M13.6: PDF/AI text, images, tiling patterns, blend modes, soft masks, pages; clip groups to masks / Merge Paths
Text with embedded TrueType, CFF (Type1C / CIDFontType0C / OpenType), Type 1 and Type 3 fonts, standard-14 fallback to the bundled OFL fonts; Flate / DCT / inline / stencil images with SMask, Indexed and ICC alternates; luminosity / alpha soft masks and the 16 blend modes in the SVG render tree; tiling patterns; calculator functions; file.import page and Footage::page; Create Shapes from Vector Layer keeps clips (page clips as layer masks, nested clips as Merge Paths Intersect). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
ed46bc0cce
commit
7d944ca494
+120
-7
@@ -13,7 +13,7 @@ use std::collections::HashMap;
|
||||
pub use color::parse_color;
|
||||
pub use kurbo::{Affine, BezPath};
|
||||
pub use pathdata::parse_path_data;
|
||||
pub use raster::{rasterize, rasterize_with};
|
||||
pub use raster::{blend_pixel, rasterize, rasterize_with};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Error {
|
||||
@@ -173,6 +173,88 @@ pub struct Group {
|
||||
/// Clipping paths in the group's space (after `transform`); the children show only where
|
||||
/// every one of them covers (PDF / EPS clipping; SVG `clipPath` is not read yet).
|
||||
pub clip: Vec<(BezPath, FillRule)>,
|
||||
/// How the group composites onto what is below it (PDF blend modes; SVG `mix-blend-mode`
|
||||
/// is not read yet).
|
||||
pub blend: BlendMode,
|
||||
/// A soft mask (PDF `SMask` in the graphics state): the group shows where the mask's
|
||||
/// luminosity (or alpha) is high.
|
||||
pub mask: Option<Box<SoftMask>>,
|
||||
}
|
||||
|
||||
impl Group {
|
||||
/// An empty, opaque, unclipped group.
|
||||
pub fn new(name: &str) -> Group {
|
||||
Group { name: name.to_string(), transform: Affine::IDENTITY, opacity: 1.0, children: vec![], clip: vec![], blend: BlendMode::Normal, mask: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// Separable and non-separable blend modes (ISO 32000-1 §11.3.5; the same formulas as the
|
||||
/// W3C Compositing and Blending Level 1 specification).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum BlendMode {
|
||||
#[default]
|
||||
Normal,
|
||||
Multiply,
|
||||
Screen,
|
||||
Overlay,
|
||||
Darken,
|
||||
Lighten,
|
||||
ColorDodge,
|
||||
ColorBurn,
|
||||
HardLight,
|
||||
SoftLight,
|
||||
Difference,
|
||||
Exclusion,
|
||||
Hue,
|
||||
Saturation,
|
||||
Color,
|
||||
Luminosity,
|
||||
}
|
||||
|
||||
impl BlendMode {
|
||||
/// A PDF blend mode name (`/Multiply` …); unknown names are Normal.
|
||||
pub fn from_pdf_name(n: &str) -> BlendMode {
|
||||
use BlendMode::*;
|
||||
match n {
|
||||
"Multiply" => Multiply,
|
||||
"Screen" => Screen,
|
||||
"Overlay" => Overlay,
|
||||
"Darken" => Darken,
|
||||
"Lighten" => Lighten,
|
||||
"ColorDodge" => ColorDodge,
|
||||
"ColorBurn" => ColorBurn,
|
||||
"HardLight" => HardLight,
|
||||
"SoftLight" => SoftLight,
|
||||
"Difference" => Difference,
|
||||
"Exclusion" => Exclusion,
|
||||
"Hue" => Hue,
|
||||
"Saturation" => Saturation,
|
||||
"Color" => Color,
|
||||
"Luminosity" => Luminosity,
|
||||
_ => Normal,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A soft mask: `content` is drawn in the masked group's space; its luminosity (composited
|
||||
/// over `backdrop`) or its alpha is the mask.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SoftMask {
|
||||
pub content: Group,
|
||||
pub luminosity: bool,
|
||||
pub backdrop: [f64; 3],
|
||||
}
|
||||
|
||||
/// A raster image: `width`×`height` straight RGBA8 pixels; `transform` maps pixel space (y
|
||||
/// down, pixel `(0, 0)` at the top-left corner) to the parent's space.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Image {
|
||||
pub name: String,
|
||||
pub transform: Affine,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub rgba: std::sync::Arc<Vec<u8>>,
|
||||
pub opacity: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -180,6 +262,7 @@ pub struct Group {
|
||||
pub enum Node {
|
||||
Group(Group),
|
||||
Shape(Shape),
|
||||
Image(Image),
|
||||
}
|
||||
|
||||
/// A parsed SVG document. `root.transform` maps the viewBox to `width`×`height` pixels.
|
||||
@@ -207,6 +290,7 @@ impl Doc {
|
||||
match c {
|
||||
Node::Group(sub) => walk(sub, m, o, out),
|
||||
Node::Shape(s) => out.push((m * s.transform, o * s.opacity, s)),
|
||||
Node::Image(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -669,7 +753,7 @@ impl<'a, 'i> Parser<'a, 'i> {
|
||||
for c in n.children() {
|
||||
self.node(c, &st, &mut children, depth + 1);
|
||||
}
|
||||
out.push(Node::Group(Group { name: Self::element_name(n), transform, opacity, children, clip: vec![] }));
|
||||
out.push(Node::Group(Group { name: Self::element_name(n), transform, opacity, children, clip: vec![], blend: BlendMode::Normal, mask: None }));
|
||||
}
|
||||
"svg" => {
|
||||
// Nested viewport.
|
||||
@@ -688,7 +772,15 @@ impl<'a, 'i> Parser<'a, 'i> {
|
||||
self.node(c, &st, &mut children, depth + 1);
|
||||
}
|
||||
(self.vw, self.vh) = saved;
|
||||
out.push(Node::Group(Group { name: Self::element_name(n), transform: Affine::translate((x, y)) * vb, opacity, children, clip: vec![] }));
|
||||
out.push(Node::Group(Group {
|
||||
name: Self::element_name(n),
|
||||
transform: Affine::translate((x, y)) * vb,
|
||||
opacity,
|
||||
children,
|
||||
clip: vec![],
|
||||
blend: BlendMode::Normal,
|
||||
mask: None,
|
||||
}));
|
||||
}
|
||||
"use" => {
|
||||
let Some(target) = self.href(n) else { return };
|
||||
@@ -709,11 +801,19 @@ impl<'a, 'i> Parser<'a, 'i> {
|
||||
for c in target.children() {
|
||||
self.node(c, &sst, &mut inner, depth + 1);
|
||||
}
|
||||
children.push(Node::Group(Group { name: Self::element_name(target), transform: vb, opacity: o, children: inner, clip: vec![] }));
|
||||
children.push(Node::Group(Group {
|
||||
name: Self::element_name(target),
|
||||
transform: vb,
|
||||
opacity: o,
|
||||
children: inner,
|
||||
clip: vec![],
|
||||
blend: BlendMode::Normal,
|
||||
mask: None,
|
||||
}));
|
||||
} else {
|
||||
self.node(target, &st, &mut children, depth + 1);
|
||||
}
|
||||
out.push(Node::Group(Group { name: Self::element_name(n), transform, opacity, children, clip: vec![] }));
|
||||
out.push(Node::Group(Group { name: Self::element_name(n), transform, opacity, children, clip: vec![], blend: BlendMode::Normal, mask: None }));
|
||||
}
|
||||
"path" | "rect" | "circle" | "ellipse" | "line" | "polyline" | "polygon" => {
|
||||
if !st.visible {
|
||||
@@ -753,7 +853,15 @@ impl<'a, 'i> Parser<'a, 'i> {
|
||||
self.node(c, &st, &mut children, depth + 1);
|
||||
}
|
||||
if !children.is_empty() {
|
||||
out.push(Node::Group(Group { name: Self::element_name(n), transform, opacity, children, clip: vec![] }));
|
||||
out.push(Node::Group(Group {
|
||||
name: Self::element_name(n),
|
||||
transform,
|
||||
opacity,
|
||||
children,
|
||||
clip: vec![],
|
||||
blend: BlendMode::Normal,
|
||||
mask: None,
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -945,7 +1053,12 @@ pub fn parse(bytes: &[u8]) -> Result<Doc, Error> {
|
||||
p.node(c, &rst, &mut children, 1);
|
||||
}
|
||||
let transform = viewbox_transform(root, dw, dh);
|
||||
Ok(Doc { width: dw, height: dh, root: Group { name: "svg".into(), transform, opacity, children, clip: vec![] }, skipped: std::mem::take(&mut p.skipped) })
|
||||
Ok(Doc {
|
||||
width: dw,
|
||||
height: dh,
|
||||
root: Group { name: "svg".into(), transform, opacity, children, clip: vec![], blend: BlendMode::Normal, mask: None },
|
||||
skipped: std::mem::take(&mut p.skipped),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+221
-29
@@ -6,7 +6,7 @@ use effectcraft_raster::{Image, Mask};
|
||||
use kurbo::{Affine, Point, Shape as _};
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::{Doc, FillRule, Gradient, GradientKind, Group, Node, Paint, Shape, Spread};
|
||||
use crate::{BlendMode, Doc, FillRule, Gradient, GradientKind, Group, Node, Paint, Shape, Spread};
|
||||
|
||||
fn mat3(a: Affine) -> Mat3 {
|
||||
let c = a.as_coeffs();
|
||||
@@ -31,38 +31,166 @@ fn draw_group(g: &Group, m: Affine, opacity: f64, dst: &mut Image) {
|
||||
if o <= 0.0 {
|
||||
return;
|
||||
}
|
||||
if !g.clip.is_empty() {
|
||||
// Draw the children on their own, keep what every clip path covers, composite.
|
||||
let mut tmp = Image::new(dst.width, dst.height);
|
||||
for c in &g.children {
|
||||
draw_node(c, m, 1.0, &mut tmp);
|
||||
}
|
||||
for (path, rule) in &g.clip {
|
||||
let rule = match rule {
|
||||
FillRule::NonZero => effectcraft_path::FillRule::NonZero,
|
||||
FillRule::EvenOdd => effectcraft_path::FillRule::EvenOdd,
|
||||
};
|
||||
let cov = effectcraft_path::fill_coverage(std::slice::from_ref(path), &mat3(m), dst.width, dst.height, rule);
|
||||
tmp.data.par_iter_mut().zip(cov.data.par_iter()).for_each(|(p, c)| {
|
||||
for v in p.iter_mut() {
|
||||
*v *= c;
|
||||
}
|
||||
});
|
||||
}
|
||||
over(dst, &tmp, o as f32);
|
||||
return;
|
||||
}
|
||||
if g.opacity < 1.0 && g.children.len() > 1 {
|
||||
let mut tmp = Image::new(dst.width, dst.height);
|
||||
for c in &g.children {
|
||||
draw_node(c, m, 1.0, &mut tmp);
|
||||
}
|
||||
over(dst, &tmp, o as f32);
|
||||
} else {
|
||||
let isolated = !g.clip.is_empty() || g.mask.is_some() || g.blend != BlendMode::Normal || (g.opacity < 1.0 && g.children.len() > 1);
|
||||
if !isolated {
|
||||
for c in &g.children {
|
||||
draw_node(c, m, o, dst);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Draw the children on their own, keep what every clip path covers and the soft mask
|
||||
// lets through, then composite with the group's opacity and blend mode.
|
||||
let mut tmp = Image::new(dst.width, dst.height);
|
||||
for c in &g.children {
|
||||
draw_node(c, m, 1.0, &mut tmp);
|
||||
}
|
||||
for (path, rule) in &g.clip {
|
||||
let rule = match rule {
|
||||
FillRule::NonZero => effectcraft_path::FillRule::NonZero,
|
||||
FillRule::EvenOdd => effectcraft_path::FillRule::EvenOdd,
|
||||
};
|
||||
let cov = effectcraft_path::fill_coverage(std::slice::from_ref(path), &mat3(m), dst.width, dst.height, rule);
|
||||
tmp.data.par_iter_mut().zip(cov.data.par_iter()).for_each(|(p, c)| {
|
||||
for v in p.iter_mut() {
|
||||
*v *= c;
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(sm) = &g.mask {
|
||||
let mut mk = Image::new(dst.width, dst.height);
|
||||
draw_group(&sm.content, m, 1.0, &mut mk);
|
||||
let bc = sm.backdrop.map(|v| v as f32);
|
||||
let lum = sm.luminosity;
|
||||
tmp.data.par_iter_mut().zip(mk.data.par_iter()).for_each(|(p, q)| {
|
||||
let k = if lum {
|
||||
// The mask group composited over its backdrop colour, then its luminosity.
|
||||
let c = [0, 1, 2].map(|i| q[i] + bc[i] * (1.0 - q[3]));
|
||||
0.3 * c[0] + 0.59 * c[1] + 0.11 * c[2]
|
||||
} else {
|
||||
q[3]
|
||||
};
|
||||
let k = k.clamp(0.0, 1.0);
|
||||
for v in p.iter_mut() {
|
||||
*v *= k;
|
||||
}
|
||||
});
|
||||
}
|
||||
if g.blend == BlendMode::Normal {
|
||||
over(dst, &tmp, o as f32);
|
||||
} else {
|
||||
let mode = g.blend;
|
||||
let k = o as f32;
|
||||
dst.data.par_iter_mut().zip(tmp.data.par_iter()).for_each(|(d, s)| {
|
||||
let s = [s[0] * k, s[1] * k, s[2] * k, s[3] * k];
|
||||
if s[3] > 0.0 {
|
||||
*d = blend_pixel(mode, *d, s);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// `src` composited onto `dst` with a blend mode (both premultiplied RGBA):
|
||||
/// `co = cs·(1 − αb) + cb·(1 − αs) + αs·αb·B(cb, cs)` (ISO 32000-1 §11.3.6).
|
||||
pub fn blend_pixel(mode: BlendMode, dst: [f32; 4], src: [f32; 4]) -> [f32; 4] {
|
||||
let (ab, as_) = (dst[3], src[3]);
|
||||
let un = |c: [f32; 4]| if c[3] > 0.0 { [c[0] / c[3], c[1] / c[3], c[2] / c[3]] } else { [0.0; 3] };
|
||||
let (cb, cs) = (un(dst), un(src));
|
||||
let b = blend_color(mode, cb, cs);
|
||||
let mut out = [0.0; 4];
|
||||
for i in 0..3 {
|
||||
out[i] = src[i] * (1.0 - ab) + dst[i] * (1.0 - as_) + as_ * ab * b[i];
|
||||
}
|
||||
out[3] = as_ + ab * (1.0 - as_);
|
||||
out
|
||||
}
|
||||
|
||||
fn blend_color(mode: BlendMode, cb: [f32; 3], cs: [f32; 3]) -> [f32; 3] {
|
||||
use BlendMode::*;
|
||||
let sep = |f: fn(f32, f32) -> f32| [f(cb[0], cs[0]), f(cb[1], cs[1]), f(cb[2], cs[2])];
|
||||
fn hard(b: f32, s: f32) -> f32 {
|
||||
if s <= 0.5 {
|
||||
b * 2.0 * s
|
||||
} else {
|
||||
let t = 2.0 * s - 1.0;
|
||||
b + t - b * t
|
||||
}
|
||||
}
|
||||
match mode {
|
||||
Normal => cs,
|
||||
Multiply => sep(|b, s| b * s),
|
||||
Screen => sep(|b, s| b + s - b * s),
|
||||
Overlay => sep(|b, s| hard(s, b)),
|
||||
Darken => sep(f32::min),
|
||||
Lighten => sep(f32::max),
|
||||
ColorDodge => sep(|b, s| {
|
||||
if b <= 0.0 {
|
||||
0.0
|
||||
} else if s >= 1.0 {
|
||||
1.0
|
||||
} else {
|
||||
(b / (1.0 - s)).min(1.0)
|
||||
}
|
||||
}),
|
||||
ColorBurn => sep(|b, s| {
|
||||
if b >= 1.0 {
|
||||
1.0
|
||||
} else if s <= 0.0 {
|
||||
0.0
|
||||
} else {
|
||||
1.0 - ((1.0 - b) / s).min(1.0)
|
||||
}
|
||||
}),
|
||||
HardLight => sep(hard),
|
||||
SoftLight => sep(|b, s| {
|
||||
if s <= 0.5 {
|
||||
b - (1.0 - 2.0 * s) * b * (1.0 - b)
|
||||
} else {
|
||||
let d = if b <= 0.25 { ((16.0 * b - 12.0) * b + 4.0) * b } else { b.sqrt() };
|
||||
b + (2.0 * s - 1.0) * (d - b)
|
||||
}
|
||||
}),
|
||||
Difference => sep(|b, s| (b - s).abs()),
|
||||
Exclusion => sep(|b, s| b + s - 2.0 * b * s),
|
||||
Hue => set_lum(set_sat(cs, sat(cb)), lum(cb)),
|
||||
Saturation => set_lum(set_sat(cb, sat(cs)), lum(cb)),
|
||||
Color => set_lum(cs, lum(cb)),
|
||||
Luminosity => set_lum(cb, lum(cs)),
|
||||
}
|
||||
}
|
||||
|
||||
fn lum(c: [f32; 3]) -> f32 {
|
||||
0.3 * c[0] + 0.59 * c[1] + 0.11 * c[2]
|
||||
}
|
||||
|
||||
fn clip_color(c: [f32; 3]) -> [f32; 3] {
|
||||
let l = lum(c);
|
||||
let n = c[0].min(c[1]).min(c[2]);
|
||||
let x = c[0].max(c[1]).max(c[2]);
|
||||
let mut c = c;
|
||||
if n < 0.0 && l - n > 0.0 {
|
||||
c = c.map(|v| l + (v - l) * l / (l - n));
|
||||
}
|
||||
if x > 1.0 && x - l > 0.0 {
|
||||
c = c.map(|v| l + (v - l) * (1.0 - l) / (x - l));
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
fn set_lum(c: [f32; 3], l: f32) -> [f32; 3] {
|
||||
let d = l - lum(c);
|
||||
clip_color(c.map(|v| v + d))
|
||||
}
|
||||
|
||||
fn sat(c: [f32; 3]) -> f32 {
|
||||
c[0].max(c[1]).max(c[2]) - c[0].min(c[1]).min(c[2])
|
||||
}
|
||||
|
||||
fn set_sat(c: [f32; 3], s: f32) -> [f32; 3] {
|
||||
let (mx, mn) = (c[0].max(c[1]).max(c[2]), c[0].min(c[1]).min(c[2]));
|
||||
if mx - mn <= 0.0 {
|
||||
return [0.0; 3];
|
||||
}
|
||||
c.map(|v| (v - mn) * s / (mx - mn))
|
||||
}
|
||||
|
||||
fn draw_node(n: &Node, m: Affine, opacity: f64, dst: &mut Image) {
|
||||
@@ -77,9 +205,73 @@ fn draw_node(n: &Node, m: Affine, opacity: f64, dst: &mut Image) {
|
||||
draw_shape(s, m, opacity * s.opacity, dst);
|
||||
}
|
||||
}
|
||||
Node::Image(im) => draw_image(im, m, opacity * im.opacity, dst),
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw a raster image: bilinear samples inside the image's (anti-aliased) quadrilateral.
|
||||
fn draw_image(im: &crate::Image, m: Affine, opacity: f64, dst: &mut Image) {
|
||||
let (iw, ih) = (im.width as usize, im.height as usize);
|
||||
if iw == 0 || ih == 0 || im.rgba.len() < iw * ih * 4 || opacity <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let full = m * im.transform;
|
||||
let inv = full.inverse();
|
||||
if !inv.as_coeffs().iter().all(|v| v.is_finite()) {
|
||||
return;
|
||||
}
|
||||
let quad = kurbo::Rect::new(0.0, 0.0, iw as f64, ih as f64).to_path(0.01);
|
||||
let cov = effectcraft_path::fill_coverage(std::slice::from_ref(&quad), &mat3(full), dst.width, dst.height, effectcraft_path::FillRule::NonZero);
|
||||
let w = dst.width as usize;
|
||||
if w == 0 {
|
||||
return;
|
||||
}
|
||||
let px = |x: usize, y: usize| -> [f32; 4] {
|
||||
let i = (y * iw + x) * 4;
|
||||
let a = im.rgba[i + 3] as f32 / 255.0;
|
||||
[im.rgba[i] as f32 / 255.0 * a, im.rgba[i + 1] as f32 / 255.0 * a, im.rgba[i + 2] as f32 / 255.0 * a, a]
|
||||
};
|
||||
// Pixel footprint in image pixels: box-filter heavy minification instead of aliasing.
|
||||
let c = inv.as_coeffs();
|
||||
let fx = (c[0] * c[0] + c[1] * c[1]).sqrt();
|
||||
let fy = (c[2] * c[2] + c[3] * c[3]).sqrt();
|
||||
let taps = (fx.max(fy).ceil() as usize).clamp(1, 8);
|
||||
let k = opacity as f32;
|
||||
dst.data.par_chunks_mut(w).enumerate().for_each(|(y, row)| {
|
||||
for (x, d) in row.iter_mut().enumerate() {
|
||||
let cv = cov.data[y * w + x];
|
||||
if cv <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let mut acc = [0.0f32; 4];
|
||||
for ty in 0..taps {
|
||||
for tx in 0..taps {
|
||||
let sx = x as f64 + (tx as f64 + 0.5) / taps as f64;
|
||||
let sy = y as f64 + (ty as f64 + 0.5) / taps as f64;
|
||||
let p = inv * Point::new(sx, sy);
|
||||
let (u, v) = ((p.x - 0.5).clamp(0.0, iw as f64 - 1.0), (p.y - 0.5).clamp(0.0, ih as f64 - 1.0));
|
||||
let (x0, y0) = (u.floor() as usize, v.floor() as usize);
|
||||
let (x1, y1) = ((x0 + 1).min(iw - 1), (y0 + 1).min(ih - 1));
|
||||
let (a, b) = ((u - x0 as f64) as f32, (v - y0 as f64) as f32);
|
||||
let (p00, p10, p01, p11) = (px(x0, y0), px(x1, y0), px(x0, y1), px(x1, y1));
|
||||
for i in 0..4 {
|
||||
acc[i] += (p00[i] * (1.0 - a) + p10[i] * a) * (1.0 - b) + (p01[i] * (1.0 - a) + p11[i] * a) * b;
|
||||
}
|
||||
}
|
||||
}
|
||||
let n = (taps * taps) as f32;
|
||||
let s = acc.map(|v| v / n * cv * k);
|
||||
if s[3] <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
for i in 0..3 {
|
||||
d[i] = s[i] + d[i] * (1.0 - s[3]);
|
||||
}
|
||||
d[3] = s[3] + d[3] * (1.0 - s[3]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// `dst = src·k over dst` (premultiplied).
|
||||
fn over(dst: &mut Image, src: &Image, k: f32) {
|
||||
dst.data.par_iter_mut().zip(src.data.par_iter()).for_each(|(d, s)| {
|
||||
|
||||
Reference in New Issue
Block a user