1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
//! Batched drawing of many paths with per-item properties.
use std::rc::Rc;
use pltrs_core::{Affine2D, Path, Point, Rgba};
use crate::gc::{Dashes, GraphicsContext};
/// The arguments of matplotlib's `draw_path_collection`.
///
/// Every per-item sequence is *cycled* to the item count (see
/// [`ItemCycle`]); an empty sequence means "use the base graphics context"
/// (or, for colours, "do not fill/stroke").
#[derive(Clone, Debug, Default)]
pub struct PathCollection<'a> {
/// Applied after each item's own transform.
pub master_transform: Affine2D,
/// Item shapes.
pub paths: &'a [Path],
/// Per-item transforms applied before `master_transform`.
pub path_transforms: &'a [Affine2D],
/// Per-item translations in display coordinates.
pub offsets: &'a [Point],
/// Face colours; empty = no fills.
pub facecolors: &'a [Rgba],
/// Edge colours; empty = no strokes.
pub edgecolors: &'a [Rgba],
/// Hatch colours.
pub hatchcolors: &'a [Rgba],
/// Edge line widths in points.
pub linewidths: &'a [f64],
/// Edge dash patterns.
pub dashes: &'a [Dashes],
/// Per-item anti-aliasing.
pub antialiased: &'a [bool],
/// Per-item hyperlinks.
pub urls: &'a [Option<String>],
}
/// How the items of a [`PathCollection`] cycle through its shapes and
/// their transforms, which matplotlib's backends do two ways.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ItemCycle {
/// `RendererBase._iter_collection`, which the vector backends use:
/// `max(max(paths, path_transforms), offsets)` items, item `i` drawing
/// the raw path (a shape with its transform, see
/// [`PathCollection::raw_paths`]) `i mod max(paths, path_transforms)`.
#[default]
RawPaths,
/// Agg's `draw_path_collection`: `max(paths, offsets)` items, item `i`
/// drawing shape `i mod paths` with transform `i mod
/// path_transforms`, so that transforms beyond the items are never
/// drawn.
Agg,
}
/// One resolved item of a [`PathCollection`].
#[derive(Clone, Debug)]
pub struct CollectionItem<'a> {
/// The shape.
pub path: &'a Path,
/// Index of the shape in [`PathCollection::raw_paths`] (in `paths`
/// for items in [`ItemCycle::Agg`]).
pub path_index: usize,
/// Translation of the item in display coordinates.
pub offset: Point,
/// Full transform to display coordinates (offset included).
pub transform: Affine2D,
/// The graphics context with per-item overrides applied, shared with
/// the items before it until an override changes it.
pub gc: Rc<GraphicsContext>,
/// Face colour, or `None` when the item is not filled.
pub fill: Option<Rgba>,
}
impl<'a> PathCollection<'a> {
/// Number of items that will be drawn (before skipping non-finite offsets).
pub fn len(&self) -> usize {
if self.paths.is_empty() {
return 0;
}
self.paths
.len()
.max(self.path_transforms.len())
.max(self.offsets.len())
}
/// Number of distinct shapes: `max(paths, path_transforms)`.
fn raw_path_count(&self) -> usize {
if self.paths.is_empty() {
0
} else {
self.paths.len().max(self.path_transforms.len())
}
}
/// Every shape with its transform before the offset (matplotlib's
/// `_iter_collection_raw_paths`); items refer to them by
/// [`CollectionItem::path_index`].
pub fn raw_paths(&self) -> impl Iterator<Item = (&'a Path, Affine2D)> + '_ {
(0..self.raw_path_count()).map(|i| {
let own = cycled(self.path_transforms, i).copied().unwrap_or_default();
(
&self.paths[i % self.paths.len()],
own.then(self.master_transform),
)
})
}
/// How often each raw path is used, rounded up (matplotlib's
/// `_iter_collection_uses_per_path`); zero when nothing is filled or
/// stroked.
pub fn uses_per_path(&self) -> usize {
let raw = self.raw_path_count();
if raw == 0 || (self.facecolors.is_empty() && self.edgecolors.is_empty()) {
return 0;
}
self.len().div_ceil(raw)
}
/// Returns `true` when nothing would be drawn.
pub fn is_empty(&self) -> bool {
self.len() == 0
|| (self.facecolors.is_empty()
&& self.edgecolors.is_empty()
&& self.hatchcolors.is_empty())
}
/// Resolves every drawable item, exactly as matplotlib's
/// `RendererBase._iter_collection` does: items with non-finite offsets
/// are skipped, fully transparent faces become unfilled, and fully
/// transparent edges disable stroking.
///
/// The context is copied only when an override changes it while an
/// earlier item still holds it, so items dropped before the next is
/// taken share one context.
pub fn items(&self, base: &GraphicsContext) -> impl Iterator<Item = CollectionItem<'a>> + '_ {
self.items_cycled(base, ItemCycle::RawPaths)
}
/// [`PathCollection::items`], cycling through the shapes and their
/// transforms as `cycle` says.
pub fn items_cycled(
&self,
base: &GraphicsContext,
cycle: ItemCycle,
) -> impl Iterator<Item = CollectionItem<'a>> + '_ {
let count = match cycle {
_ if self.is_empty() => 0,
ItemCycle::RawPaths => self.len(),
ItemCycle::Agg => self.paths.len().max(self.offsets.len()),
};
let raw_count = self.raw_path_count();
let mut shared = Rc::new(base.clone());
if self.edgecolors.is_empty() {
Rc::make_mut(&mut shared).linewidth = 0.0;
}
(0..count).filter_map(move |i| {
let offset = cycled(self.offsets, i).copied().unwrap_or(Point::ORIGIN);
if !offset.is_finite() {
return None;
}
if let Some(&edge) = cycled(self.edgecolors, i) {
let gc = Rc::make_mut(&mut shared);
if let Some(&width) = cycled(self.linewidths, i) {
gc.linewidth = width;
}
if let Some(dashes) = cycled(self.dashes, i) {
gc.dashes.clone_from(dashes);
}
if edge.is_transparent() {
gc.linewidth = 0.0;
} else {
gc.foreground = edge;
}
}
if let Some(&aa) = cycled(self.antialiased, i) {
Rc::make_mut(&mut shared).antialiased = aa;
}
if let Some(url) = cycled(self.urls, i) {
Rc::make_mut(&mut shared).url.clone_from(url);
}
if let Some(&color) = cycled(self.hatchcolors, i)
&& let Some(hatch) = Rc::make_mut(&mut shared).hatch.as_mut()
{
hatch.color = color;
}
let fill = cycled(self.facecolors, i)
.copied()
.filter(|c| !c.is_transparent());
let (path_index, shape, own) = match cycle {
// Items cycle through the raw paths, as matplotlib's
// `_iter_collection` cycles through the path ids.
ItemCycle::RawPaths => {
let raw = wrap(i, raw_count);
let shape = wrap(raw, self.paths.len());
(raw, shape, cycled(self.path_transforms, raw))
}
ItemCycle::Agg => {
let shape = wrap(i, self.paths.len());
(shape, shape, cycled(self.path_transforms, i))
}
};
// Agg composes the item's transform with the master's in C++
// (`trans *= master_transform`), the vector backends' iteration
// with numpy.
let own = own.copied().unwrap_or_default();
let transform = match cycle {
ItemCycle::RawPaths => own.then(self.master_transform),
ItemCycle::Agg => own.agg_then(self.master_transform),
}
.translate(offset.x, offset.y);
Some(CollectionItem {
path: &self.paths[shape],
path_index,
offset,
transform,
gc: Rc::clone(&shared),
fill,
})
})
}
}
/// The arguments of a [`PathCollection`] owned rather than borrowed, for
/// a drawing kept until it is drawn (what a program drew through a
/// renderer of its own, see `pltrs::artist::Drawing`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PathCollectionData {
/// Applied after each item's own transform.
pub master_transform: Affine2D,
/// Item shapes.
pub paths: Vec<Path>,
/// Per-item transforms applied before `master_transform`.
pub path_transforms: Vec<Affine2D>,
/// Per-item translations in display coordinates.
pub offsets: Vec<Point>,
/// Face colours; empty = no fills.
pub facecolors: Vec<Rgba>,
/// Edge colours; empty = no strokes.
pub edgecolors: Vec<Rgba>,
/// Hatch colours.
pub hatchcolors: Vec<Rgba>,
/// Edge line widths in points.
pub linewidths: Vec<f64>,
/// Edge dash patterns.
pub dashes: Vec<Dashes>,
/// Per-item anti-aliasing.
pub antialiased: Vec<bool>,
/// Per-item hyperlinks.
pub urls: Vec<Option<String>>,
}
impl PathCollectionData {
/// The collection these arguments describe.
pub fn view(&self) -> PathCollection<'_> {
PathCollection {
master_transform: self.master_transform,
paths: &self.paths,
path_transforms: &self.path_transforms,
offsets: &self.offsets,
facecolors: &self.facecolors,
edgecolors: &self.edgecolors,
hatchcolors: &self.hatchcolors,
linewidths: &self.linewidths,
dashes: &self.dashes,
antialiased: &self.antialiased,
urls: &self.urls,
}
}
}
/// Item `i` of `items` repeated cyclically, or `None` when there are none.
fn cycled<T>(items: &[T], i: usize) -> Option<&T> {
(!items.is_empty()).then(|| &items[wrap(i, items.len())])
}
/// `i % len`, without the division in the usual case of an index in range
/// (collections draw thousands of items per call).
fn wrap(i: usize, len: usize) -> usize {
if i < len { i } else { i % len }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cycles_properties_and_skips_non_finite_offsets() {
let paths = [Path::unit_rectangle()];
let offsets = [
Point::new(1.0, 1.0),
Point::new(f64::NAN, 0.0),
Point::new(3.0, 3.0),
];
let faces = [Rgba::BLACK, Rgba::TRANSPARENT];
let collection = PathCollection {
paths: &paths,
offsets: &offsets,
facecolors: &faces,
..PathCollection::default()
};
let items: Vec<_> = collection.items(&GraphicsContext::default()).collect();
assert_eq!(items.len(), 2);
assert_eq!(items[0].fill, Some(Rgba::BLACK));
assert_eq!(
items[1].fill,
Some(Rgba::BLACK),
"third item cycles back to the first face"
);
assert_eq!(items[1].transform.translation_part(), Point::new(3.0, 3.0));
assert_eq!(
items[0].gc.linewidth, 0.0,
"no edge colours means no stroke"
);
}
#[test]
fn transparent_edges_disable_stroke() {
let paths = [Path::unit_rectangle(), Path::unit_circle()];
let edges = [Rgba::BLACK, Rgba::TRANSPARENT];
let widths = [2.0];
let collection = PathCollection {
paths: &paths,
edgecolors: &edges,
linewidths: &widths,
..PathCollection::default()
};
let items: Vec<_> = collection.items(&GraphicsContext::default()).collect();
assert_eq!(items[0].gc.linewidth, 2.0);
assert_eq!(items[1].gc.linewidth, 0.0);
assert_eq!(items[1].fill, None);
}
#[test]
fn agg_items_leave_extra_transforms_undrawn() {
let paths = [Path::unit_rectangle(), Path::unit_circle()];
let transforms = [
Affine2D::scaling(2.0, 2.0),
Affine2D::scaling(3.0, 3.0),
Affine2D::scaling(4.0, 4.0),
];
let offsets = [Point::ORIGIN; 4];
let faces = [Rgba::BLACK];
let collection = PathCollection {
paths: &paths[..1],
path_transforms: &transforms,
facecolors: &faces,
..PathCollection::default()
};
let gc = GraphicsContext::default();
assert_eq!(collection.items(&gc).count(), 3);
let agg: Vec<_> = collection.items_cycled(&gc, ItemCycle::Agg).collect();
assert_eq!(agg.len(), 1);
assert_eq!(agg[0].transform, transforms[0]);
// With more offsets than raw paths, Agg cycles the shapes and the
// transforms apart; the raw paths cycle together.
let collection = PathCollection {
paths: &paths,
offsets: &offsets,
..collection
};
let shapes = |cycle| {
collection
.items_cycled(&gc, cycle)
.map(|item| (item.path.vertices().len(), item.transform))
.collect::<Vec<_>>()
};
let (rect, circle) = (paths[0].vertices().len(), paths[1].vertices().len());
assert_eq!(
shapes(ItemCycle::Agg),
[
(rect, transforms[0]),
(circle, transforms[1]),
(rect, transforms[2]),
(circle, transforms[0]),
]
);
assert_eq!(shapes(ItemCycle::RawPaths)[3], (rect, transforms[0]));
}
#[test]
fn empty_collections_draw_nothing() {
let collection = PathCollection::default();
assert!(collection.is_empty());
assert_eq!(collection.items(&GraphicsContext::default()).count(), 0);
assert!(PathCollectionData::default().view().is_empty());
}
#[test]
fn owned_arguments_describe_the_same_collection() {
let data = PathCollectionData {
paths: vec![Path::unit_rectangle()],
offsets: vec![Point::new(1.0, 2.0), Point::new(3.0, 4.0)],
facecolors: vec![Rgba::BLACK],
..PathCollectionData::default()
};
let items: Vec<_> = data.view().items(&GraphicsContext::default()).collect();
assert_eq!(items.len(), 2);
assert_eq!(items[1].offset, Point::new(3.0, 4.0));
}
}