Skip to main content

pdf/
shading.rs

1// shading -- gradients (axial and radial shadings, ISO 32000-1 8.7.4.5) and hatches for
2// Canvas::shade, fill_shading and fill_hatch
3//
4// A gradient becomes a shading dictionary of type 2 (axial) or 3 (radial) in DeviceRGB.  Its
5// colour function: one Type 2 function (exponential, N 1) from colour to colour, or for more stops
6// a Type 3 stitching function of such pieces, one per stretch between two stops; stops at the same
7// t (a hard edge) leave out the empty stretch between them, so Bounds always rise.  Before the
8// first stop and after the last the colour stays the first / last stop's.  The stops' alpha:
9// all the same -> the constant fill alpha (ExtGState ca); different -> a luminosity soft mask whose
10// group paints the same geometry as a DeviceGray shading of the alphas (Canvas builds it).
11//
12// Hatches are stroked lines, not tiling patterns: pdfium draws the cells of a rotated tiling
13// pattern with hairline gaps and one-pixel steps where they meet, and both pdfium and Poppler round
14// the cell step to whole device pixels, so the lines drift from where they belong.  A hatch clips
15// to the path and strokes parallel lines over its bounding box in one path (one `S`, so a hatch's
16// alpha applies once).
17
18use alloc::vec::Vec;
19
20use crate::canvas::alpha_key;
21use crate::geom::Rgb;
22use crate::obj::{self, num};
23
24/// the geometry of a gradient, in the user space of the canvas at the time it is painted
25#[derive(Clone, Copy, Debug, PartialEq)]
26pub enum ShadingKind {
27    /// colour runs from `from` (t = 0) to `to` (t = 1), constant across (PDF type 2)
28    Axial { from: [f64; 2], to: [f64; 2] },
29    /// circles from (from, r0) at t = 0 to (to, r1) at t = 1 (PDF type 3); radii >= 0
30    Radial { from: [f64; 2], r0: f64, to: [f64; 2], r1: f64 },
31}
32
33/// a gradient for Canvas::shade and Canvas::fill_shading
34#[derive(Clone, Debug, PartialEq)]
35pub struct Shading {
36    pub kind: ShadingKind,
37    /// (t in 0..=1 ascending, colour, alpha 0..=1); at least one stop.  Stops with a NaN t are
38    /// dropped, t is clamped to 0..=1 and the stops sorted by it (stable: two stops at the same t
39    /// make a hard edge); a NaN alpha is opaque
40    pub stops: Vec<(f64, Rgb, f64)>,
41    /// paint beyond t < 0 / t > 1 with the end colours (PDF /Extend), default (true, true)
42    pub extend: (bool, bool),
43}
44
45impl Shading {
46    /// an axial gradient from `from` to `to`, extended at both ends
47    pub fn axial(from: [f64; 2], to: [f64; 2], stops: &[(f64, Rgb, f64)]) -> Shading {
48        Shading { kind: ShadingKind::Axial { from, to }, stops: stops.to_vec(), extend: (true, true) }
49    }
50
51    /// a radial gradient from the circle (from, r0) to (to, r1), extended at both ends
52    pub fn radial(from: [f64; 2], r0: f64, to: [f64; 2], r1: f64, stops: &[(f64, Rgb, f64)]) -> Shading {
53        Shading { kind: ShadingKind::Radial { from, r0, to, r1 }, stops: stops.to_vec(), extend: (true, true) }
54    }
55}
56
57/// parallel lines for Canvas::fill_hatch; two hatches over the same path cross
58#[derive(Clone, Copy, Debug, PartialEq)]
59pub struct Hatch {
60    /// direction of the lines in the canvas's user space, radians from +x towards +y: counter-
61    /// clockwise on the page where y points up (Origin::BottomLeft), clockwise where it points down
62    /// (Origin::TopLeft, as Canvas::rotate)
63    pub angle: f64,
64    /// distance between neighbouring lines (user space units), > 0
65    pub spacing: f64,
66    /// line width (user space units), > 0; at least `spacing` fills the path solid
67    pub width: f64,
68    pub color: Rgb,
69    /// 0 to 1, times the canvas's fill alpha
70    pub alpha: f64,
71    /// a point one of the lines runs through (user space)
72    pub origin: [f64; 2],
73}
74
75impl Hatch {
76    /// opaque lines through (0, 0)
77    pub fn new(angle: f64, spacing: f64, width: f64, color: Rgb) -> Hatch {
78        Hatch { angle, spacing, width, color, alpha: 1.0, origin: [0.0, 0.0] }
79    }
80}
81
82/// t in millionths (exact as a PDF number), colour, alpha in thousandths
83#[derive(Clone, Copy)]
84struct Stop {
85    t: u32,
86    c: Rgb,
87    a: u16,
88}
89
90const T_ONE: u32 = 1_000_000;
91
92/// what a gradient comes to
93pub(crate) enum Prepared {
94    /// nothing to paint (no stops, coordinates not finite, a negative radius)
95    Invalid,
96    /// degenerate geometry (axial from = to, radial with both radii 0): the whole area in the last
97    /// stop's colour and alpha, as SVG does
98    Solid(Rgb, u16),
99    /// a radial gradient between two equal circles: only the disk, in the last stop's colour
100    Disk([f64; 2], f64, Rgb, u16),
101    /// a shading dictionary (without << >>) and its alpha
102    Shade(Vec<u8>, Alpha),
103}
104
105pub(crate) enum Alpha {
106    /// one alpha for all stops, thousandths (1000: opaque)
107    Const(u16),
108    /// the alphas differ: the DeviceGray shading of the soft mask's group
109    Mask(Vec<u8>),
110}
111
112/// the same bytes when written: what a reader sees as equal
113fn same(a: f64, b: f64) -> bool {
114    let (mut x, mut y) = (Vec::new(), Vec::new());
115    num(&mut x, a);
116    num(&mut y, b);
117    x == y
118}
119
120fn sanitize(s: &Shading) -> Vec<Stop> {
121    let mut v: Vec<Stop> = s
122        .stops
123        .iter()
124        .filter(|(t, ..)| !t.is_nan())
125        .map(|&(t, c, a)| Stop { t: (t.clamp(0.0, 1.0) * T_ONE as f64 + 0.5) as u32, c: c.clamped(), a: alpha_key(a) })
126        .collect();
127    v.sort_by_key(|s| s.t);
128    v
129}
130
131pub(crate) fn prepare(s: &Shading) -> Prepared {
132    let stops = sanitize(s);
133    let Some(&last) = stops.last() else { return Prepared::Invalid };
134    match s.kind {
135        ShadingKind::Axial { from, to } => {
136            if !from.iter().chain(to.iter()).all(|v| v.is_finite()) {
137                return Prepared::Invalid;
138            }
139            if same(from[0], to[0]) && same(from[1], to[1]) {
140                return Prepared::Solid(last.c, last.a);
141            }
142        }
143        ShadingKind::Radial { from, r0, to, r1 } => {
144            if !from.iter().chain(to.iter()).chain([r0, r1].iter()).all(|v| v.is_finite()) || r0 < 0.0 || r1 < 0.0 {
145                return Prepared::Invalid;
146            }
147            if same(r0, 0.0) && same(r1, 0.0) {
148                return Prepared::Solid(last.c, last.a);
149            }
150            if same(from[0], to[0]) && same(from[1], to[1]) && same(r0, r1) {
151                return Prepared::Disk(from, r0.max(r1), last.c, last.a);
152            }
153        }
154    }
155    // the stops padded to t = 0 and t = 1 with the end colours
156    let mut pts: Vec<Stop> = Vec::with_capacity(stops.len() + 2);
157    if stops[0].t > 0 {
158        pts.push(Stop { t: 0, ..stops[0] });
159    }
160    pts.extend_from_slice(&stops);
161    if last.t < T_ONE {
162        pts.push(Stop { t: T_ONE, ..last });
163    }
164    let rgb = |p: &Stop| [p.c.r, p.c.g, p.c.b];
165    let mut func = Vec::new();
166    function(&mut func, &pts, &rgb);
167    let dict = shading_dict(&s.kind, b"DeviceRGB", &func, s.extend);
168    let alpha = if stops.iter().all(|p| p.a == stops[0].a) {
169        Alpha::Const(stops[0].a)
170    } else {
171        let mut func = Vec::new();
172        function(&mut func, &pts, &|p: &Stop| [p.a as f64 / 1000.0]);
173        Alpha::Mask(shading_dict(&s.kind, b"DeviceGray", &func, s.extend))
174    };
175    Prepared::Shade(dict, alpha)
176}
177
178/// `<< /ShadingType .. >>` without the brackets
179fn shading_dict(kind: &ShadingKind, cs: &[u8], func: &[u8], extend: (bool, bool)) -> Vec<u8> {
180    let mut o = Vec::new();
181    match *kind {
182        ShadingKind::Axial { from, to } => {
183            o.extend_from_slice(b"/ShadingType 2 /ColorSpace ");
184            obj::name(&mut o, cs);
185            o.extend_from_slice(b" /Coords ");
186            obj::nums(&mut o, &[from[0], from[1], to[0], to[1]]);
187        }
188        ShadingKind::Radial { from, r0, to, r1 } => {
189            o.extend_from_slice(b"/ShadingType 3 /ColorSpace ");
190            obj::name(&mut o, cs);
191            o.extend_from_slice(b" /Coords ");
192            obj::nums(&mut o, &[from[0], from[1], r0, to[0], to[1], r1]);
193        }
194    }
195    o.extend_from_slice(b" /Extend [");
196    o.extend_from_slice(if extend.0 { b"true " } else { b"false " });
197    o.extend_from_slice(if extend.1 { b"true]" } else { b"false]" });
198    o.extend_from_slice(b" /Function ");
199    o.extend_from_slice(func);
200    o
201}
202
203/// a Type 2 function (N 1) from c0 to c1 over 0..1
204fn type2(o: &mut Vec<u8>, c0: &[f64], c1: &[f64]) {
205    o.extend_from_slice(b"<< /FunctionType 2 /Domain [0 1] /C0 ");
206    obj::nums(o, c0);
207    o.extend_from_slice(b" /C1 ");
208    obj::nums(o, c1);
209    o.extend_from_slice(b" /N 1 >>");
210}
211
212/// the function through the points (t from 0 to 1, rising, equal t allowed): one Type 2 function
213/// for one stretch or one value, else a Type 3 stitching function of one Type 2 per stretch of
214/// positive length
215fn function<const N: usize>(o: &mut Vec<u8>, pts: &[Stop], val: &dyn Fn(&Stop) -> [f64; N]) {
216    let first = val(&pts[0]);
217    if pts.iter().all(|p| val(p) == first) {
218        type2(o, &first, &first);
219        return;
220    }
221    let segs: Vec<usize> = (0..pts.len() - 1).filter(|&i| pts[i].t < pts[i + 1].t).collect();
222    if let [i] = segs[..] {
223        type2(o, &val(&pts[i]), &val(&pts[i + 1]));
224        return;
225    }
226    o.extend_from_slice(b"<< /FunctionType 3 /Domain [0 1] /Functions [");
227    for (k, &i) in segs.iter().enumerate() {
228        if k > 0 {
229            o.push(b' ');
230        }
231        type2(o, &val(&pts[i]), &val(&pts[i + 1]));
232    }
233    o.extend_from_slice(b"] /Bounds [");
234    for (k, &i) in segs[1..].iter().enumerate() {
235        if k > 0 {
236            o.push(b' ');
237        }
238        num(o, pts[i].t as f64 / T_ONE as f64);
239    }
240    o.extend_from_slice(b"] /Encode [");
241    for k in 0..segs.len() {
242        if k > 0 {
243            o.push(b' ');
244        }
245        o.extend_from_slice(b"0 1");
246    }
247    o.extend_from_slice(b"] >>");
248}
249
250/// the most lines one hatch draws (beyond that it is ignored)
251pub(crate) const MAX_HATCH_LINES: f64 = 100_000.0;
252
253fn floor(x: f64) -> f64 {
254    let i = x as i64 as f64;
255    if i > x { i - 1.0 } else { i }
256}
257
258fn ceil(x: f64) -> f64 {
259    let i = x as i64 as f64;
260    if i < x { i + 1.0 } else { i }
261}
262
263/// the hatch's lines over the box [x0, y0, x1, y1] (user space) as (start, end) pairs; None when
264/// there would be more than MAX_HATCH_LINES (or the numbers run away)
265pub(crate) fn hatch_lines(h: &Hatch, bb: [f64; 4]) -> Option<Vec<[f64; 4]>> {
266    let (s, c) = gfx::xform::sincos(h.angle);
267    let (d, n) = ([c, s], [-s, c]);
268    let corners = [[bb[0], bb[1]], [bb[2], bb[1]], [bb[2], bb[3]], [bb[0], bb[3]]];
269    let along = |p: &[f64; 2], v: [f64; 2]| (p[0] - h.origin[0]) * v[0] + (p[1] - h.origin[1]) * v[1];
270    let (mut n0, mut n1, mut t0, mut t1) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY);
271    for p in &corners {
272        n0 = n0.min(along(p, n));
273        n1 = n1.max(along(p, n));
274        t0 = t0.min(along(p, d));
275        t1 = t1.max(along(p, d));
276    }
277    // lines up to half a width outside still reach into the box; the ends a width beyond it
278    let half = h.width / 2.0;
279    let (k0, k1) = ((n0 - half) / h.spacing, (n1 + half) / h.spacing);
280    if !(k0.is_finite() && k1.is_finite() && k0.abs() < 1e15 && k1.abs() < 1e15) || k1 - k0 > MAX_HATCH_LINES {
281        return None;
282    }
283    let (k0, k1) = (ceil(k0), floor(k1));
284    let (t0, t1) = (t0 - h.width, t1 + h.width);
285    let mut out = Vec::new();
286    let mut k = k0;
287    while k <= k1 {
288        let o = [h.origin[0] + n[0] * k * h.spacing, h.origin[1] + n[1] * k * h.spacing];
289        out.push([o[0] + d[0] * t0, o[1] + d[1] * t0, o[0] + d[0] * t1, o[1] + d[1] * t1]);
290        k += 1.0;
291    }
292    Some(out)
293}