Skip to main content

pltrs_render/
quad_mesh.rs

1//! Flat-shaded quadrilateral meshes (the arguments of matplotlib's
2//! `draw_quad_mesh`).
3
4use std::ops::Range;
5
6use pltrs_core::{Affine2D, Path, Point, Rgba};
7
8use crate::collection::PathCollection;
9
10/// A grid of quadrilaterals, one colour per cell.
11#[derive(Clone, Copy, Debug)]
12pub struct QuadMesh<'a> {
13    /// Maps the vertices to display coordinates.
14    pub master_transform: Affine2D,
15    /// Cells per row (matplotlib's `meshWidth`).
16    pub columns: usize,
17    /// The `(rows + 1) × (columns + 1)` vertices, row by row.
18    pub coordinates: &'a [Point],
19    /// Cell colours, row by row; empty = no fills.
20    pub facecolors: &'a [Rgba],
21    /// Edge colours; empty = no strokes.
22    pub edgecolors: &'a [Rgba],
23    /// Whether the cells are anti-aliased.
24    pub antialiased: bool,
25}
26
27/// The fields of a [`QuadMesh`] owned rather than borrowed, for a drawing
28/// kept until it is drawn (what a program drew through a renderer of its
29/// own, see `pltrs::artist::Drawing`).
30#[derive(Clone, Debug, Default, PartialEq)]
31pub struct QuadMeshData {
32    /// Maps the vertices to display coordinates.
33    pub master_transform: Affine2D,
34    /// Cells per row (matplotlib's `meshWidth`).
35    pub columns: usize,
36    /// The `(rows + 1) × (columns + 1)` vertices, row by row.
37    pub coordinates: Vec<Point>,
38    /// Cell colours, row by row; empty = no fills.
39    pub facecolors: Vec<Rgba>,
40    /// Edge colours; empty = no strokes.
41    pub edgecolors: Vec<Rgba>,
42    /// Whether the cells are anti-aliased.
43    pub antialiased: bool,
44}
45
46impl QuadMeshData {
47    /// The mesh these fields describe.
48    pub fn view(&self) -> QuadMesh<'_> {
49        QuadMesh {
50            master_transform: self.master_transform,
51            columns: self.columns,
52            coordinates: &self.coordinates,
53            facecolors: &self.facecolors,
54            edgecolors: &self.edgecolors,
55            antialiased: self.antialiased,
56        }
57    }
58}
59
60/// The corners numpy outlines a cell through (see [`QuadMesh::cell_paths`]).
61const NUMPY_CORNERS: [(usize, usize); 4] = [(0, 0), (0, 1), (1, 1), (1, 0)];
62
63/// The corners Agg outlines a cell through (see
64/// [`QuadMesh::agg_cell_paths`]).
65const AGG_CORNERS: [(usize, usize); 4] = [(0, 0), (1, 0), (1, 1), (0, 1)];
66
67impl QuadMesh<'_> {
68    /// Vertex `(row, col)`.
69    fn vertex(&self, row: usize, col: usize) -> Point {
70        self.coordinates[row * (self.columns + 1) + col]
71    }
72
73    /// Number of cells.
74    pub(crate) fn cell_count(&self) -> usize {
75        let stride = self.columns + 1;
76        let rows = (self.coordinates.len() / stride).saturating_sub(1);
77        rows * self.columns
78    }
79
80    /// The closed outline of cell `index` (row by row) through the given
81    /// corners (offsets of row and column from the cell's first vertex).
82    fn outline(&self, index: usize, corners: [(usize, usize); 4]) -> [Point; 5] {
83        let (r, c) = (index / self.columns, index % self.columns);
84        let [a, b, d, e] = corners.map(|(dr, dc)| self.vertex(r + dr, c + dc));
85        [a, b, d, e, a]
86    }
87
88    /// The cells as matplotlib's `QuadMesh._convert_mesh_to_paths` outlines
89    /// them: `(r, c) → (r, c + 1) → (r + 1, c + 1) → (r + 1, c) → (r, c)`.
90    pub fn cell_paths(&self) -> Vec<Path> {
91        (0..self.cell_count())
92            .map(|cell| Path::polyline(self.outline(cell, NUMPY_CORNERS).to_vec()))
93            .collect()
94    }
95
96    /// The cells as Agg's `QuadMeshGenerator` walks them:
97    /// `(r, c) → (r + 1, c) → (r + 1, c + 1) → (r, c + 1) → (r, c)`.
98    pub(crate) fn agg_cell_paths(&self) -> Vec<Path> {
99        let mut paths = Vec::new();
100        self.agg_cell_paths_into(0..self.cell_count(), &mut paths);
101        paths
102    }
103
104    /// [`agg_cell_paths`](Self::agg_cell_paths) of the cells in `cells`,
105    /// written over `paths` to reuse their allocations.
106    pub(crate) fn agg_cell_paths_into(&self, cells: Range<usize>, paths: &mut Vec<Path>) {
107        paths.truncate(cells.len());
108        for (slot, cell) in cells.enumerate() {
109            let outline = self.outline(cell, AGG_CORNERS);
110            match paths.get_mut(slot) {
111                Some(path) => path.vertices_mut().copy_from_slice(&outline),
112                None => paths.push(Path::polyline(outline.to_vec())),
113            }
114        }
115    }
116
117    /// The path collection drawing `paths` with the mesh's colours, one
118    /// line width (`linewidths`) and anti-aliasing flag (`antialiased`).
119    pub(crate) fn collection<'p>(
120        &self,
121        paths: &'p [Path],
122        linewidths: &'p [f64],
123        antialiased: &'p [bool],
124    ) -> PathCollection<'p>
125    where
126        Self: 'p,
127    {
128        PathCollection {
129            master_transform: self.master_transform,
130            paths,
131            facecolors: self.facecolors,
132            edgecolors: self.edgecolors,
133            linewidths,
134            antialiased,
135            ..PathCollection::default()
136        }
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143
144    #[test]
145    fn cells_in_matplotlib_and_agg_order() {
146        let coordinates: Vec<Point> = (0..2)
147            .flat_map(|r| (0..3).map(move |c| Point::new(f64::from(c), f64::from(r))))
148            .collect();
149        let mesh = QuadMesh {
150            master_transform: Affine2D::IDENTITY,
151            columns: 2,
152            coordinates: &coordinates,
153            facecolors: &[],
154            edgecolors: &[],
155            antialiased: false,
156        };
157        let numpy = mesh.cell_paths();
158        assert_eq!(numpy.len(), 2);
159        assert_eq!(
160            numpy[1].vertices(),
161            &[
162                Point::new(1.0, 0.0),
163                Point::new(2.0, 0.0),
164                Point::new(2.0, 1.0),
165                Point::new(1.0, 1.0),
166                Point::new(1.0, 0.0)
167            ]
168        );
169        assert_eq!(mesh.agg_cell_paths()[1].vertices()[1], Point::new(1.0, 1.0));
170        assert_eq!(mesh.cell_count(), 2);
171        // Written over earlier paths, a range gives the same outlines.
172        let mut paths = mesh.agg_cell_paths();
173        mesh.agg_cell_paths_into(1..2, &mut paths);
174        assert_eq!(paths, &mesh.agg_cell_paths()[1..]);
175        let empty = QuadMesh {
176            coordinates: &coordinates[..3],
177            ..mesh
178        };
179        assert_eq!(empty.cell_paths(), Vec::<Path>::new());
180        let owned = QuadMeshData {
181            columns: 2,
182            coordinates: coordinates.clone(),
183            ..QuadMeshData::default()
184        };
185        assert_eq!(owned.view().cell_paths(), numpy);
186    }
187}