Skip to main content

pltrs_render/
gc.rs

1//! The graphics context: stroke, fill-modifier and clipping state for a draw call.
2
3use pltrs_core::path::convert::SketchParams;
4use pltrs_core::{Affine2D, Bbox, Path, Rgba};
5
6/// How the ends of open strokes are drawn.
7#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
8pub enum CapStyle {
9    /// Flush with the end point.
10    #[default]
11    Butt,
12    /// Squared off, extending half the line width past the end point.
13    Projecting,
14    /// A semicircle around the end point.
15    Round,
16}
17
18pltrs_core::archive_enum!(CapStyle {
19    Butt,
20    Projecting,
21    Round,
22});
23
24/// How stroke segments are joined at corners.
25#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
26pub enum JoinStyle {
27    /// Sharp corner (subject to the miter limit).
28    Miter,
29    /// Rounded corner.
30    #[default]
31    Round,
32    /// Cut-off corner.
33    Bevel,
34}
35
36pltrs_core::archive_enum!(JoinStyle {
37    Miter,
38    Round,
39    Bevel,
40});
41
42impl CapStyle {
43    /// Parses matplotlib's names (`"butt"`, `"projecting"`, `"round"`).
44    pub fn from_name(name: &str) -> Option<Self> {
45        Some(match name {
46            "butt" => Self::Butt,
47            "projecting" => Self::Projecting,
48            "round" => Self::Round,
49            _ => return None,
50        })
51    }
52
53    /// matplotlib's name for the style.
54    pub const fn name(self) -> &'static str {
55        match self {
56            Self::Butt => "butt",
57            Self::Projecting => "projecting",
58            Self::Round => "round",
59        }
60    }
61}
62
63impl JoinStyle {
64    /// Parses matplotlib's names (`"miter"`, `"round"`, `"bevel"`).
65    pub fn from_name(name: &str) -> Option<Self> {
66        Some(match name {
67            "miter" => Self::Miter,
68            "round" => Self::Round,
69            "bevel" => Self::Bevel,
70            _ => return None,
71        })
72    }
73
74    /// matplotlib's name for the style.
75    pub const fn name(self) -> &'static str {
76        match self {
77            Self::Miter => "miter",
78            Self::Round => "round",
79            Self::Bevel => "bevel",
80        }
81    }
82}
83
84/// A dash pattern in points: alternating on/off lengths starting at
85/// `offset` (matplotlib's `(offset, dash_list)` of a graphics context).
86///
87/// A line without a dash list and one with an empty list both draw
88/// solid, but the SVG, PDF and PGF backends write an empty list where
89/// they write none for no list, as matplotlib does.
90///
91/// ```
92/// use pltrs_render::Dashes;
93/// assert!(Dashes::solid().is_solid() && Dashes::new(0.0, Vec::new()).is_solid());
94/// assert_ne!(Dashes::solid(), Dashes::new(0.0, Vec::new()));
95/// assert!(!Dashes::new(1.0, vec![3.0, 1.0]).is_solid());
96/// ```
97#[derive(Clone, Debug, Default, PartialEq)]
98pub struct Dashes {
99    /// Distance into the pattern at which the stroke starts.
100    pub offset: f64,
101    /// On/off lengths, or `None` for no dash list (matplotlib's `None`).
102    pub pattern: Option<Vec<f64>>,
103}
104
105pltrs_core::archive_struct!(Dashes { offset, pattern });
106
107impl Dashes {
108    /// A solid line: no dash list.
109    pub const fn solid() -> Self {
110        Self {
111            offset: 0.0,
112            pattern: None,
113        }
114    }
115
116    /// The on/off lengths `pattern` from `offset` on; an empty pattern
117    /// draws solid.
118    pub const fn new(offset: f64, pattern: Vec<f64>) -> Self {
119        Self {
120            offset,
121            pattern: Some(pattern),
122        }
123    }
124
125    /// The on/off lengths, empty without a dash list.
126    pub fn lengths(&self) -> &[f64] {
127        self.pattern.as_deref().unwrap_or_default()
128    }
129
130    /// Returns `true` when the pattern draws a continuous line.
131    pub fn is_solid(&self) -> bool {
132        self.lengths().iter().all(|&len| len <= 0.0)
133    }
134}
135
136/// A hatch fill drawn over a path's face.
137#[derive(Clone, Debug, PartialEq)]
138pub struct Hatch {
139    /// matplotlib hatch pattern, e.g. `"//"`, `"x"`, `"o."`.
140    pub pattern: String,
141    /// Colour of the hatch lines.
142    pub color: Rgba,
143    /// Hatch line width in points.
144    pub linewidth: f64,
145}
146
147pltrs_core::archive_struct!(Hatch {
148    pattern,
149    color,
150    linewidth
151});
152
153/// Parameters of the hand-drawn "sketch" path filter.
154#[derive(Clone, Copy, Debug, PartialEq)]
155pub struct Sketch {
156    /// Amplitude of the wiggle perpendicular to the line, in pixels.
157    pub scale: f64,
158    /// Length of the wiggle along the line, in pixels.
159    pub length: f64,
160    /// Factor by which the length is randomly shrunk or expanded.
161    pub randomness: f64,
162}
163
164pltrs_core::archive_struct!(Sketch {
165    scale,
166    length,
167    randomness
168});
169
170impl Sketch {
171    /// The path converters' sketch filter settings.
172    pub(crate) fn params(self) -> SketchParams {
173        SketchParams::new(self.scale, Some(self.length), Some(self.randomness))
174    }
175}
176
177/// An arbitrary clip region: a path and the transform to display space.
178#[derive(Clone, Debug, PartialEq)]
179pub struct ClipPath {
180    /// The region's outline.
181    pub path: Path,
182    /// Maps `path` to display coordinates.
183    pub transform: Affine2D,
184    /// Whether the outline is made anew each time a renderer is handed
185    /// it, as matplotlib's fancy boxes and arrows build a new `Path` at
186    /// every `get_path`: a renderer that keeps the last clip path it
187    /// rasterized (matplotlib's Agg, which knows a path by its vertex
188    /// array) never finds such an outline among those it kept.
189    pub rebuilt: bool,
190}
191
192impl ClipPath {
193    /// A clip region that is the same path each time it is handed over.
194    #[must_use]
195    pub fn new(path: Path, transform: Affine2D) -> Self {
196        Self {
197            path,
198            transform,
199            rebuilt: false,
200        }
201    }
202
203    /// The region, made anew each time it is handed over when `rebuilt`
204    /// (see the field [`rebuilt`](Self::rebuilt)).
205    #[must_use]
206    pub fn with_rebuilt(self, rebuilt: bool) -> Self {
207        Self { rebuilt, ..self }
208    }
209}
210
211/// Snapping behaviour for rectilinear paths.
212#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
213pub enum SnapMode {
214    /// Snap paths consisting only of horizontal/vertical segments.
215    #[default]
216    Auto,
217    /// Always snap vertices to pixel centres.
218    Always,
219    /// Never snap.
220    Never,
221}
222
223pltrs_core::archive_enum!(SnapMode {
224    Auto,
225    Always,
226    Never,
227});
228
229/// Everything about *how* a primitive is drawn, mirroring matplotlib's
230/// `GraphicsContextBase`. Lengths are in points unless stated otherwise;
231/// coordinates are display pixels with the origin at the bottom left.
232#[derive(Clone, Debug, PartialEq)]
233pub struct GraphicsContext {
234    /// Stroke colour.
235    pub foreground: Rgba,
236    /// When set, replaces the alpha of the stroke and fill colours.
237    pub alpha: Option<f64>,
238    /// Anti-aliasing on/off.
239    pub antialiased: bool,
240    /// Line end style.
241    pub cap: CapStyle,
242    /// Line join style.
243    pub join: JoinStyle,
244    /// Line width in points (0 disables stroking).
245    pub linewidth: f64,
246    /// Dash pattern in points.
247    pub dashes: Dashes,
248    /// Rectangular clip region in display coordinates.
249    pub clip_rect: Option<Bbox>,
250    /// Arbitrary clip region.
251    pub clip_path: Option<ClipPath>,
252    /// Hatch drawn over filled faces.
253    pub hatch: Option<Hatch>,
254    /// Pixel snapping.
255    pub snap: SnapMode,
256    /// Hand-drawn wobble.
257    pub sketch: Option<Sketch>,
258    /// Hyperlink target (vector backends).
259    pub url: Option<String>,
260    /// Group identifier (vector backends).
261    pub gid: Option<String>,
262}
263
264impl Default for GraphicsContext {
265    fn default() -> Self {
266        Self {
267            foreground: Rgba::BLACK,
268            alpha: None,
269            antialiased: true,
270            cap: CapStyle::Butt,
271            join: JoinStyle::Round,
272            linewidth: 1.0,
273            dashes: Dashes::solid(),
274            clip_rect: None,
275            clip_path: None,
276            hatch: None,
277            snap: SnapMode::Auto,
278            sketch: None,
279            url: None,
280            gid: None,
281        }
282    }
283}
284
285impl GraphicsContext {
286    /// The effective stroke colour (alpha override applied).
287    pub fn stroke_color(&self) -> Rgba {
288        self.apply_alpha(self.foreground)
289    }
290
291    /// The effective colour for a face fill (alpha override applied).
292    pub fn fill_color(&self, face: Rgba) -> Rgba {
293        self.apply_alpha(face)
294    }
295
296    /// Whether anything visible would be stroked.
297    pub fn strokes(&self) -> bool {
298        self.linewidth > 0.0 && !self.stroke_color().is_transparent()
299    }
300
301    fn apply_alpha(&self, color: Rgba) -> Rgba {
302        self.alpha.map_or(color, |a| color.with_alpha(a))
303    }
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309
310    #[test]
311    fn alpha_override_applies_to_stroke_and_fill() {
312        let gc = GraphicsContext {
313            foreground: Rgba::new(1.0, 0.0, 0.0, 0.2),
314            alpha: Some(0.5),
315            ..GraphicsContext::default()
316        };
317        assert_eq!(gc.stroke_color().a, 0.5);
318        assert_eq!(gc.fill_color(Rgba::WHITE).a, 0.5);
319        assert!(gc.strokes());
320    }
321
322    #[test]
323    fn style_names_round_trip() {
324        for cap in [CapStyle::Butt, CapStyle::Projecting, CapStyle::Round] {
325            assert_eq!(CapStyle::from_name(cap.name()), Some(cap));
326        }
327        for join in [JoinStyle::Miter, JoinStyle::Round, JoinStyle::Bevel] {
328            assert_eq!(JoinStyle::from_name(join.name()), Some(join));
329        }
330        assert_eq!(CapStyle::from_name("square"), None);
331    }
332
333    #[test]
334    fn zero_length_dash_patterns_are_solid() {
335        assert!(Dashes::solid().is_solid());
336        assert!(Dashes::new(0.0, vec![0.0, 0.0]).is_solid());
337        assert!(Dashes::new(2.0, Vec::new()).is_solid());
338        assert!(!Dashes::new(0.0, vec![3.0, 1.0]).is_solid());
339        assert_eq!(Dashes::solid().lengths(), []);
340    }
341}