Skip to main content

pdfcer_function/function/
breaks.rs

1//! Where a one-input function stops being affine.
2
3use super::{Exponential, Kind, PdfFunction, Sampled, Stitching, clip};
4
5impl PdfFunction {
6    /// The inputs between which every output is affine in the one input `t`,
7    /// sorted, with the `/Domain` ends first and last; at most `cap` of them.
8    ///
9    /// A type 0 breaks at each sample position (its `/Encode` mapped back
10    /// onto `/Domain`), a type 2 with `/N` 0 or 1 only at the domain ends, a
11    /// type 3 at its `/Bounds` and at each sub-function's breaks mapped
12    /// through that sub-function's `/Encode`. Wherever a `/Range` clips an
13    /// output, the point it starts or stops clipping is a break too. A
14    /// function can jump at a break (a type 3 bound); outside the domain it
15    /// is constant.
16    ///
17    /// `None` when no such list exists or it is longer than `cap`: more than
18    /// one input, a type 2 with any other `/N`, a type 4, or a type 3 with
19    /// such a sub-function. A caller that needs an exact answer takes `None`
20    /// as "sample it some other way".
21    #[must_use]
22    pub fn affine_breaks(&self, cap: usize) -> Option<Vec<f64>> {
23        let &[[d0, d1]] = self.domain.as_slice() else {
24            return None;
25        };
26        let mut breaks = match &self.kind {
27            Kind::Sampled(s) => s.breaks(d0, d1, cap)?,
28            Kind::Exponential(e) => e.breaks()?,
29            Kind::Stitching(s) => s.breaks(d0, d1, cap)?,
30            Kind::PostScript(_) => return None,
31        };
32        breaks.extend([d0, d1]);
33        breaks.retain(|t| t.is_finite() && (d0..=d1).contains(t));
34        sort_dedup(&mut breaks);
35        if let Some(range) = self.range.as_deref() {
36            let crossings = self.crossings(&breaks, range)?;
37            breaks.extend(crossings);
38            sort_dedup(&mut breaks);
39        }
40        (breaks.len() <= cap).then_some(breaks)
41    }
42
43    /// [`affine_breaks`](Self::affine_breaks) for a consumer that also
44    /// clamps output `i` to `bounds[i]` (a colour space's component range):
45    /// adds each input where an output crosses one of those bounds, so the
46    /// clamped outputs are affine between neighbouring breaks too. Outputs
47    /// past `bounds.len()` are not clamped.
48    ///
49    /// `None` as for `affine_breaks`, or when the list grows past `cap`.
50    #[must_use]
51    pub fn affine_breaks_clamped(&self, cap: usize, bounds: &[[f64; 2]]) -> Option<Vec<f64>> {
52        let mut breaks = self.affine_breaks(cap)?;
53        let crossings = self.crossings(&breaks, bounds)?;
54        breaks.extend(crossings);
55        sort_dedup(&mut breaks);
56        (breaks.len() <= cap).then_some(breaks)
57    }
58
59    /// Where an output, affine between neighbouring `breaks` before the
60    /// `/Range` clip, crosses one of `bounds`. A bound the clip keeps the
61    /// output from reaching adds a harmless extra break.
62    fn crossings(&self, breaks: &[f64], bounds: &[[f64; 2]]) -> Option<Vec<f64>> {
63        let mut out = Vec::new();
64        for (&a, &b) in breaks.iter().zip(breaks.iter().skip(1)) {
65            let (fa, fb) = (self.unclipped(a, b)?, self.unclipped(b, a)?);
66            for ((&ya, &yb), &[lo, hi]) in fa.iter().zip(&fb).zip(bounds) {
67                for edge in [lo, hi] {
68                    if (ya - edge) * (yb - edge) < 0.0 {
69                        out.push(a + (b - a) * (edge - ya) / (yb - ya));
70                    }
71                }
72            }
73        }
74        Some(out)
75    }
76
77    /// The outputs at `t` before the `/Range` clip, taken from the side of
78    /// `t` facing `toward` (a type 3 can jump at `t`).
79    fn unclipped(&self, t: f64, toward: f64) -> Option<Vec<f64>> {
80        let [d0, d1] = *self.domain.first()?;
81        let x = clip(
82            if toward < t {
83                t.next_down().max(toward)
84            } else {
85                t
86            },
87            d0,
88            d1,
89        );
90        let mut out = Vec::new();
91        match &self.kind {
92            Kind::Sampled(s) => s.eval(&self.domain, &[x], &mut out).ok()?,
93            Kind::Exponential(e) => e.eval(&[x], &mut out),
94            Kind::Stitching(s) => s.eval(&self.domain, &[x], &mut out).ok()?,
95            Kind::PostScript(_) => return None,
96        }
97        Some(out)
98    }
99}
100
101impl Sampled {
102    /// Each sample position mapped back from `/Encode` onto `[d0, d1]`.
103    fn breaks(&self, d0: f64, d1: f64, cap: usize) -> Option<Vec<f64>> {
104        let (&[size], &[[e0, e1]]) = (self.size.as_slice(), self.encode.as_slice()) else {
105            return None;
106        };
107        if size > cap {
108            return None;
109        }
110        if e1 == e0 || d1 <= d0 {
111            return Some(Vec::new());
112        }
113        #[allow(clippy::cast_precision_loss)] // size <= cap, a table length
114        let at = |i: usize| d0 + (i as f64 - e0) * (d1 - d0) / (e1 - e0);
115        Some((0..size).map(at).collect())
116    }
117}
118
119impl Exponential {
120    /// Affine only for `/N` 0 or 1.
121    fn breaks(&self) -> Option<Vec<f64>> {
122        (self.n == 0.0 || self.n == 1.0).then(Vec::new)
123    }
124}
125
126impl Stitching {
127    /// `/Bounds`, plus each sub-function's breaks mapped onto its
128    /// sub-domain.
129    fn breaks(&self, d0: f64, d1: f64, cap: usize) -> Option<Vec<f64>> {
130        let starts = std::iter::once(d0).chain(self.bounds.iter().copied());
131        let ends = self.bounds.iter().copied().chain(std::iter::once(d1));
132        let mut out: Vec<f64> = self.bounds.clone();
133        for (((lo, hi), &[a, b]), f) in starts.zip(ends).zip(&self.encode).zip(&self.functions) {
134            out.extend([lo, hi]);
135            if b == a || hi <= lo {
136                continue;
137            }
138            for c in f.affine_breaks(cap)? {
139                out.push(lo + (c - a) * (hi - lo) / (b - a));
140            }
141            if out.len() > cap.saturating_mul(4) {
142                return None;
143            }
144        }
145        Some(out)
146    }
147}
148
149fn sort_dedup(v: &mut Vec<f64>) {
150    v.sort_by(f64::total_cmp);
151    v.dedup();
152}