1use std::rc::Rc;
4
5use pltrs_core::{Affine2D, Path, Point, Rgba};
6
7use crate::gc::{Dashes, GraphicsContext};
8
9#[derive(Clone, Debug, Default)]
15pub struct PathCollection<'a> {
16 pub master_transform: Affine2D,
18 pub paths: &'a [Path],
20 pub path_transforms: &'a [Affine2D],
22 pub offsets: &'a [Point],
24 pub facecolors: &'a [Rgba],
26 pub edgecolors: &'a [Rgba],
28 pub hatchcolors: &'a [Rgba],
30 pub linewidths: &'a [f64],
32 pub dashes: &'a [Dashes],
34 pub antialiased: &'a [bool],
36 pub urls: &'a [Option<String>],
38}
39
40#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
43pub enum ItemCycle {
44 #[default]
49 RawPaths,
50 Agg,
55}
56
57#[derive(Clone, Debug)]
59pub struct CollectionItem<'a> {
60 pub path: &'a Path,
62 pub path_index: usize,
65 pub offset: Point,
67 pub transform: Affine2D,
69 pub gc: Rc<GraphicsContext>,
72 pub fill: Option<Rgba>,
74}
75
76impl<'a> PathCollection<'a> {
77 pub fn len(&self) -> usize {
79 if self.paths.is_empty() {
80 return 0;
81 }
82 self.paths
83 .len()
84 .max(self.path_transforms.len())
85 .max(self.offsets.len())
86 }
87
88 fn raw_path_count(&self) -> usize {
90 if self.paths.is_empty() {
91 0
92 } else {
93 self.paths.len().max(self.path_transforms.len())
94 }
95 }
96
97 pub fn raw_paths(&self) -> impl Iterator<Item = (&'a Path, Affine2D)> + '_ {
101 (0..self.raw_path_count()).map(|i| {
102 let own = cycled(self.path_transforms, i).copied().unwrap_or_default();
103 (
104 &self.paths[i % self.paths.len()],
105 own.then(self.master_transform),
106 )
107 })
108 }
109
110 pub fn uses_per_path(&self) -> usize {
114 let raw = self.raw_path_count();
115 if raw == 0 || (self.facecolors.is_empty() && self.edgecolors.is_empty()) {
116 return 0;
117 }
118 self.len().div_ceil(raw)
119 }
120
121 pub fn is_empty(&self) -> bool {
123 self.len() == 0
124 || (self.facecolors.is_empty()
125 && self.edgecolors.is_empty()
126 && self.hatchcolors.is_empty())
127 }
128
129 pub fn items(&self, base: &GraphicsContext) -> impl Iterator<Item = CollectionItem<'a>> + '_ {
138 self.items_cycled(base, ItemCycle::RawPaths)
139 }
140
141 pub fn items_cycled(
144 &self,
145 base: &GraphicsContext,
146 cycle: ItemCycle,
147 ) -> impl Iterator<Item = CollectionItem<'a>> + '_ {
148 let count = match cycle {
149 _ if self.is_empty() => 0,
150 ItemCycle::RawPaths => self.len(),
151 ItemCycle::Agg => self.paths.len().max(self.offsets.len()),
152 };
153 let raw_count = self.raw_path_count();
154 let mut shared = Rc::new(base.clone());
155 if self.edgecolors.is_empty() {
156 Rc::make_mut(&mut shared).linewidth = 0.0;
157 }
158 (0..count).filter_map(move |i| {
159 let offset = cycled(self.offsets, i).copied().unwrap_or(Point::ORIGIN);
160 if !offset.is_finite() {
161 return None;
162 }
163 if let Some(&edge) = cycled(self.edgecolors, i) {
164 let gc = Rc::make_mut(&mut shared);
165 if let Some(&width) = cycled(self.linewidths, i) {
166 gc.linewidth = width;
167 }
168 if let Some(dashes) = cycled(self.dashes, i) {
169 gc.dashes.clone_from(dashes);
170 }
171 if edge.is_transparent() {
172 gc.linewidth = 0.0;
173 } else {
174 gc.foreground = edge;
175 }
176 }
177 if let Some(&aa) = cycled(self.antialiased, i) {
178 Rc::make_mut(&mut shared).antialiased = aa;
179 }
180 if let Some(url) = cycled(self.urls, i) {
181 Rc::make_mut(&mut shared).url.clone_from(url);
182 }
183 if let Some(&color) = cycled(self.hatchcolors, i)
184 && let Some(hatch) = Rc::make_mut(&mut shared).hatch.as_mut()
185 {
186 hatch.color = color;
187 }
188 let fill = cycled(self.facecolors, i)
189 .copied()
190 .filter(|c| !c.is_transparent());
191 let (path_index, shape, own) = match cycle {
192 ItemCycle::RawPaths => {
195 let raw = wrap(i, raw_count);
196 let shape = wrap(raw, self.paths.len());
197 (raw, shape, cycled(self.path_transforms, raw))
198 }
199 ItemCycle::Agg => {
200 let shape = wrap(i, self.paths.len());
201 (shape, shape, cycled(self.path_transforms, i))
202 }
203 };
204 let own = own.copied().unwrap_or_default();
208 let transform = match cycle {
209 ItemCycle::RawPaths => own.then(self.master_transform),
210 ItemCycle::Agg => own.agg_then(self.master_transform),
211 }
212 .translate(offset.x, offset.y);
213 Some(CollectionItem {
214 path: &self.paths[shape],
215 path_index,
216 offset,
217 transform,
218 gc: Rc::clone(&shared),
219 fill,
220 })
221 })
222 }
223}
224
225#[derive(Clone, Debug, Default, PartialEq)]
229pub struct PathCollectionData {
230 pub master_transform: Affine2D,
232 pub paths: Vec<Path>,
234 pub path_transforms: Vec<Affine2D>,
236 pub offsets: Vec<Point>,
238 pub facecolors: Vec<Rgba>,
240 pub edgecolors: Vec<Rgba>,
242 pub hatchcolors: Vec<Rgba>,
244 pub linewidths: Vec<f64>,
246 pub dashes: Vec<Dashes>,
248 pub antialiased: Vec<bool>,
250 pub urls: Vec<Option<String>>,
252}
253
254impl PathCollectionData {
255 pub fn view(&self) -> PathCollection<'_> {
257 PathCollection {
258 master_transform: self.master_transform,
259 paths: &self.paths,
260 path_transforms: &self.path_transforms,
261 offsets: &self.offsets,
262 facecolors: &self.facecolors,
263 edgecolors: &self.edgecolors,
264 hatchcolors: &self.hatchcolors,
265 linewidths: &self.linewidths,
266 dashes: &self.dashes,
267 antialiased: &self.antialiased,
268 urls: &self.urls,
269 }
270 }
271}
272
273fn cycled<T>(items: &[T], i: usize) -> Option<&T> {
275 (!items.is_empty()).then(|| &items[wrap(i, items.len())])
276}
277
278fn wrap(i: usize, len: usize) -> usize {
281 if i < len { i } else { i % len }
282}
283
284#[cfg(test)]
285mod tests {
286 use super::*;
287
288 #[test]
289 fn cycles_properties_and_skips_non_finite_offsets() {
290 let paths = [Path::unit_rectangle()];
291 let offsets = [
292 Point::new(1.0, 1.0),
293 Point::new(f64::NAN, 0.0),
294 Point::new(3.0, 3.0),
295 ];
296 let faces = [Rgba::BLACK, Rgba::TRANSPARENT];
297 let collection = PathCollection {
298 paths: &paths,
299 offsets: &offsets,
300 facecolors: &faces,
301 ..PathCollection::default()
302 };
303 let items: Vec<_> = collection.items(&GraphicsContext::default()).collect();
304 assert_eq!(items.len(), 2);
305 assert_eq!(items[0].fill, Some(Rgba::BLACK));
306 assert_eq!(
307 items[1].fill,
308 Some(Rgba::BLACK),
309 "third item cycles back to the first face"
310 );
311 assert_eq!(items[1].transform.translation_part(), Point::new(3.0, 3.0));
312 assert_eq!(
313 items[0].gc.linewidth, 0.0,
314 "no edge colours means no stroke"
315 );
316 }
317
318 #[test]
319 fn transparent_edges_disable_stroke() {
320 let paths = [Path::unit_rectangle(), Path::unit_circle()];
321 let edges = [Rgba::BLACK, Rgba::TRANSPARENT];
322 let widths = [2.0];
323 let collection = PathCollection {
324 paths: &paths,
325 edgecolors: &edges,
326 linewidths: &widths,
327 ..PathCollection::default()
328 };
329 let items: Vec<_> = collection.items(&GraphicsContext::default()).collect();
330 assert_eq!(items[0].gc.linewidth, 2.0);
331 assert_eq!(items[1].gc.linewidth, 0.0);
332 assert_eq!(items[1].fill, None);
333 }
334
335 #[test]
336 fn agg_items_leave_extra_transforms_undrawn() {
337 let paths = [Path::unit_rectangle(), Path::unit_circle()];
338 let transforms = [
339 Affine2D::scaling(2.0, 2.0),
340 Affine2D::scaling(3.0, 3.0),
341 Affine2D::scaling(4.0, 4.0),
342 ];
343 let offsets = [Point::ORIGIN; 4];
344 let faces = [Rgba::BLACK];
345 let collection = PathCollection {
346 paths: &paths[..1],
347 path_transforms: &transforms,
348 facecolors: &faces,
349 ..PathCollection::default()
350 };
351 let gc = GraphicsContext::default();
352 assert_eq!(collection.items(&gc).count(), 3);
353 let agg: Vec<_> = collection.items_cycled(&gc, ItemCycle::Agg).collect();
354 assert_eq!(agg.len(), 1);
355 assert_eq!(agg[0].transform, transforms[0]);
356 let collection = PathCollection {
359 paths: &paths,
360 offsets: &offsets,
361 ..collection
362 };
363 let shapes = |cycle| {
364 collection
365 .items_cycled(&gc, cycle)
366 .map(|item| (item.path.vertices().len(), item.transform))
367 .collect::<Vec<_>>()
368 };
369 let (rect, circle) = (paths[0].vertices().len(), paths[1].vertices().len());
370 assert_eq!(
371 shapes(ItemCycle::Agg),
372 [
373 (rect, transforms[0]),
374 (circle, transforms[1]),
375 (rect, transforms[2]),
376 (circle, transforms[0]),
377 ]
378 );
379 assert_eq!(shapes(ItemCycle::RawPaths)[3], (rect, transforms[0]));
380 }
381
382 #[test]
383 fn empty_collections_draw_nothing() {
384 let collection = PathCollection::default();
385 assert!(collection.is_empty());
386 assert_eq!(collection.items(&GraphicsContext::default()).count(), 0);
387 assert!(PathCollectionData::default().view().is_empty());
388 }
389
390 #[test]
391 fn owned_arguments_describe_the_same_collection() {
392 let data = PathCollectionData {
393 paths: vec![Path::unit_rectangle()],
394 offsets: vec![Point::new(1.0, 2.0), Point::new(3.0, 4.0)],
395 facecolors: vec![Rgba::BLACK],
396 ..PathCollectionData::default()
397 };
398 let items: Vec<_> = data.view().items(&GraphicsContext::default()).collect();
399 assert_eq!(items.len(), 2);
400 assert_eq!(items[1].offset, Point::new(3.0, 4.0));
401 }
402}