Skip to main content

plotters_ternary/series/
draw.rs

1use plotters::backend::DrawingBackend;
2use plotters::chart::SeriesAnno;
3use plotters::element::{EmptyElement, PathElement, Text};
4use plotters::style::{Color, ShapeStyle};
5
6use crate::chart::{TernaryChart, TernaryChartError};
7use crate::coord::TernaryPoint;
8
9use super::{
10    AnnotationClipMode, AnnotationError, ContourBandBorderMode, MarkerElement, MarkerStyle,
11    PointMarkerStyleProvider, PolygonElement, SeriesError, TernaryContourBandSeries,
12    TernaryContourSeries, TernaryLineSeries, TernaryPointSeries, TernaryPolygon,
13    TernaryScalarMapSeries, TernarySmoothSeries, TernaryText, prepare_points_with_source,
14    prepare_polygon, prepare_polyline,
15    smooth::{SmoothPreparation, prepare_smooth_polyline},
16};
17
18/// A ternary-aware series that can submit owned Plotters elements to a chart.
19///
20/// This trait exists so [`TernaryChart::draw_series`] can accept both line and
21/// built-in point series while returning Plotters' native annotation object.
22pub trait TernarySeries<DB: DrawingBackend> {
23    #[doc(hidden)]
24    fn draw<'chart, 'series>(
25        self,
26        chart: &'chart mut TernaryChart<'series, DB>,
27    ) -> Result<&'chart mut SeriesAnno<'series, DB>, TernaryChartError<DB::ErrorType>>
28    where
29        DB: 'series;
30}
31
32impl<DB, I, P> TernarySeries<DB> for TernaryLineSeries<I>
33where
34    DB: DrawingBackend,
35    I: IntoIterator<Item = P>,
36    P: Into<TernaryPoint>,
37{
38    fn draw<'chart, 'series>(
39        self,
40        chart: &'chart mut TernaryChart<'series, DB>,
41    ) -> Result<&'chart mut SeriesAnno<'series, DB>, TernaryChartError<DB::ErrorType>>
42    where
43        DB: 'series,
44    {
45        let (points, style, normalization, tolerance, invalid_policy) = self.into_parts();
46        let paths = prepare_polyline(
47            chart.geometry,
48            chart.viewport,
49            points,
50            normalization,
51            tolerance,
52            invalid_policy,
53        )?;
54        let elements = paths.into_iter().map(|path| {
55            let coordinates: Vec<_> = path.into_iter().map(|point| (point.x, point.y)).collect();
56            PathElement::new(coordinates, style)
57        });
58        chart.context.draw_series(elements).map_err(Into::into)
59    }
60}
61
62impl<DB, I, P, Provider> TernarySeries<DB> for TernaryPointSeries<I, Provider>
63where
64    DB: DrawingBackend,
65    I: IntoIterator<Item = P>,
66    P: Into<TernaryPoint>,
67    Provider: PointMarkerStyleProvider,
68{
69    fn draw<'chart, 'series>(
70        self,
71        chart: &'chart mut TernaryChart<'series, DB>,
72    ) -> Result<&'chart mut SeriesAnno<'series, DB>, TernaryChartError<DB::ErrorType>>
73    where
74        DB: 'series,
75    {
76        let (
77            points,
78            size,
79            legacy_style,
80            marker,
81            explicit_style,
82            provider,
83            clip_mode,
84            normalization,
85            tolerance,
86            invalid_policy,
87        ) = self.into_parts();
88        if size == 0 {
89            return Err(SeriesError::InvalidMarkerSize { size }.into());
90        }
91        let fallback =
92            explicit_style.unwrap_or(MarkerStyle::from_legacy(marker, legacy_style).map_err(
93                |source| SeriesError::Marker {
94                    index: None,
95                    source,
96                },
97            )?);
98        let elements = prepare_points_with_source(
99            chart.geometry,
100            chart.viewport,
101            points,
102            normalization,
103            tolerance,
104            invalid_policy,
105            clip_mode,
106        )?
107        .into_iter()
108        .map(|point| {
109            let style = provider.marker_style(point.index, point.composition, &fallback);
110            MarkerElement::new((point.cartesian.x, point.cartesian.y), size, style).map_err(
111                |source| SeriesError::Marker {
112                    index: Some(point.index),
113                    source,
114                },
115            )
116        })
117        .collect::<Result<Vec<_>, _>>()?;
118        chart.context.draw_series(elements).map_err(Into::into)
119    }
120}
121
122impl<DB, I, P> TernarySeries<DB> for TernaryPolygon<I>
123where
124    DB: DrawingBackend,
125    I: IntoIterator<Item = P>,
126    P: Into<TernaryPoint>,
127{
128    fn draw<'chart, 'series>(
129        self,
130        chart: &'chart mut TernaryChart<'series, DB>,
131    ) -> Result<&'chart mut SeriesAnno<'series, DB>, TernaryChartError<DB::ErrorType>>
132    where
133        DB: 'series,
134    {
135        let (points, fill, border, normalization, tolerance) = self.into_parts();
136        let polygon = prepare_polygon(
137            points,
138            chart.geometry,
139            chart.viewport,
140            normalization,
141            tolerance,
142        )
143        .map_err(SeriesError::Polygon)?;
144        let vertices = polygon
145            .vertices()
146            .iter()
147            .map(|point| (point.x, point.y))
148            .collect();
149        chart
150            .context
151            .draw_series(std::iter::once(PolygonElement::new(vertices, fill, border)))
152            .map_err(Into::into)
153    }
154}
155
156impl<DB> TernarySeries<DB> for TernaryText
157where
158    DB: DrawingBackend,
159{
160    fn draw<'chart, 'series>(
161        self,
162        chart: &'chart mut TernaryChart<'series, DB>,
163    ) -> Result<&'chart mut SeriesAnno<'series, DB>, TernaryChartError<DB::ErrorType>>
164    where
165        DB: 'series,
166    {
167        let (point, text, style, anchor, offset, clip_mode, rotation, normalization, tolerance) =
168            self.into_parts();
169        let logical = chart
170            .geometry
171            .project(point, normalization, tolerance)
172            .map_err(|source| SeriesError::Annotation(AnnotationError::InvalidAnchor { source }))?;
173        let visible =
174            clip_mode == AnnotationClipMode::None || chart.viewport.contains(logical, tolerance)?;
175        if !visible {
176            return chart
177                .context
178                .draw_series(std::iter::empty::<PathElement<(f64, f64)>>())
179                .map_err(Into::into);
180        }
181        let text_style = style
182            .plotters_style()
183            .pos(anchor.plotters_pos())
184            .transform(rotation.plotters_transform());
185        let element =
186            EmptyElement::at((logical.x, logical.y)) + Text::new(text, offset, text_style);
187        chart
188            .context
189            .draw_series(std::iter::once(element))
190            .map_err(Into::into)
191    }
192}
193
194impl<DB, I, P> TernarySeries<DB> for TernarySmoothSeries<I>
195where
196    DB: DrawingBackend,
197    I: IntoIterator<Item = P>,
198    P: Into<TernaryPoint>,
199{
200    fn draw<'chart, 'series>(
201        self,
202        chart: &'chart mut TernaryChart<'series, DB>,
203    ) -> Result<&'chart mut SeriesAnno<'series, DB>, TernaryChartError<DB::ErrorType>>
204    where
205        DB: 'series,
206    {
207        let (
208            points,
209            style,
210            interpolation,
211            samples_per_interval,
212            normalization,
213            tolerance,
214            invalid_policy,
215        ) = self.into_parts();
216        let paths = prepare_smooth_polyline(
217            chart.geometry,
218            chart.viewport,
219            points,
220            SmoothPreparation {
221                interpolation,
222                samples_per_interval,
223                normalization,
224                tolerance,
225                invalid_policy,
226            },
227        )?;
228        let elements = paths.into_iter().map(|path| {
229            let coordinates: Vec<_> = path.into_iter().map(|point| (point.x, point.y)).collect();
230            PathElement::new(coordinates, style)
231        });
232        chart.context.draw_series(elements).map_err(Into::into)
233    }
234}
235
236impl<'contour, DB> TernarySeries<DB> for TernaryContourSeries<'contour>
237where
238    DB: DrawingBackend,
239{
240    fn draw<'chart, 'series>(
241        self,
242        chart: &'chart mut TernaryChart<'series, DB>,
243    ) -> Result<&'chart mut SeriesAnno<'series, DB>, TernaryChartError<DB::ErrorType>>
244    where
245        DB: 'series,
246    {
247        let parts = self.into_parts();
248        if matches!(parts.legend, super::ContourLegendPolicy::None) {
249            let mut elements = Vec::new();
250            for (index, level) in parts.contours.levels.iter().enumerate() {
251                let style = parts.styles.style_for(index, level.value)?;
252                elements.extend(contour_level_elements(chart, level, style)?);
253            }
254            return chart.context.draw_series(elements).map_err(Into::into);
255        }
256
257        for (index, level) in parts.contours.levels.iter().enumerate() {
258            let style = parts.styles.style_for(index, level.value)?;
259            let elements = contour_level_elements(chart, level, style)?;
260            let annotation = chart.context.draw_series(elements)?;
261            if parts.legend.selected(index, level.value)? {
262                annotation
263                    .label((parts.formatter)(level.value))
264                    .legend(move |(x, y)| PathElement::new([(x, y), (x + 24, y)], style));
265            }
266        }
267        chart
268            .context
269            .draw_series(std::iter::empty::<PathElement<(f64, f64)>>())
270            .map_err(Into::into)
271    }
272}
273
274fn contour_level_elements<DB: DrawingBackend>(
275    chart: &TernaryChart<'_, DB>,
276    level: &crate::ContourLevel,
277    style: plotters::style::ShapeStyle,
278) -> Result<Vec<PathElement<(f64, f64)>>, SeriesError> {
279    let mut elements = Vec::new();
280    for path in &level.paths {
281        let mut source = path
282            .points
283            .iter()
284            .copied()
285            .map(|point| TernaryPoint::from(point.as_array()))
286            .collect::<Vec<_>>();
287        if path.closed && !source.is_empty() {
288            source.push(source[0]);
289        }
290        let visible = prepare_polyline(
291            chart.geometry,
292            chart.viewport,
293            source,
294            crate::coord::Normalization::RequireUnitSum,
295            chart.tolerance,
296            super::InvalidPointPolicy::Error,
297        )?;
298        elements.extend(visible.into_iter().map(|path| {
299            PathElement::new(
300                path.into_iter()
301                    .map(|point| (point.x, point.y))
302                    .collect::<Vec<_>>(),
303                style,
304            )
305        }));
306    }
307    Ok(elements)
308}
309
310impl<'bands, DB> TernarySeries<DB> for TernaryContourBandSeries<'bands>
311where
312    DB: DrawingBackend,
313{
314    fn draw<'chart, 'series>(
315        self,
316        chart: &'chart mut TernaryChart<'series, DB>,
317    ) -> Result<&'chart mut SeriesAnno<'series, DB>, TernaryChartError<DB::ErrorType>>
318    where
319        DB: 'series,
320    {
321        let (bands, styles, border_mode) = self.into_parts();
322        let mut elements = Vec::new();
323        for (index, band) in bands.bands.iter().enumerate() {
324            let fill = styles.style_for(index, band)?;
325            // Draw non-overlapping simple core fragments rather than an exterior
326            // ring alone. This leaves ContourRegion holes transparent and reveals
327            // whatever was rendered below the band layer.
328            for fragment in band.fragments() {
329                let polygon = prepare_polygon(
330                    fragment
331                        .vertices()
332                        .iter()
333                        .copied()
334                        .map(|point| TernaryPoint::from(point.as_array())),
335                    chart.geometry,
336                    chart.viewport,
337                    crate::coord::Normalization::RequireUnitSum,
338                    chart.tolerance,
339                )
340                .map_err(SeriesError::Polygon)?;
341                let fragment_border = match border_mode {
342                    ContourBandBorderMode::Fragments(style) => Some(style),
343                    ContourBandBorderMode::None | ContourBandBorderMode::OuterRegions(_) => None,
344                };
345                elements.push(PolygonElement::new(
346                    polygon
347                        .vertices()
348                        .iter()
349                        .map(|point| (point.x, point.y))
350                        .collect(),
351                    Some(fill),
352                    fragment_border,
353                ));
354            }
355            if let ContourBandBorderMode::OuterRegions(style) = border_mode {
356                for region in &band.regions {
357                    for ring in std::iter::once(&region.exterior).chain(region.holes.iter()) {
358                        let polygon = prepare_polygon(
359                            ring.iter()
360                                .copied()
361                                .map(|point| TernaryPoint::from(point.as_array())),
362                            chart.geometry,
363                            chart.viewport,
364                            crate::coord::Normalization::RequireUnitSum,
365                            chart.tolerance,
366                        )
367                        .map_err(SeriesError::Polygon)?;
368                        elements.push(PolygonElement::new(
369                            polygon
370                                .vertices()
371                                .iter()
372                                .map(|point| (point.x, point.y))
373                                .collect(),
374                            None,
375                            Some(style),
376                        ));
377                    }
378                }
379            }
380        }
381        chart.context.draw_series(elements).map_err(Into::into)
382    }
383}
384
385impl<'field, DB> TernarySeries<DB> for TernaryScalarMapSeries<'field>
386where
387    DB: DrawingBackend,
388{
389    fn draw<'chart, 'series>(
390        self,
391        chart: &'chart mut TernaryChart<'series, DB>,
392    ) -> Result<&'chart mut SeriesAnno<'series, DB>, TernaryChartError<DB::ErrorType>>
393    where
394        DB: 'series,
395    {
396        let (field, requested_range, resolution, opacity, reversed, color_map) = self.into_parts();
397        let intervals = resolution.intervals()?;
398        if !opacity.is_finite() || !(0.0..=1.0).contains(&opacity) {
399            return Err(SeriesError::InvalidScalarMapOpacity { opacity }.into());
400        }
401        let automatic_range = requested_range.is_none();
402        let (minimum, maximum) = requested_range.unwrap_or_else(|| {
403            field.values().iter().copied().fold(
404                (f64::INFINITY, f64::NEG_INFINITY),
405                |(minimum, maximum), value| (minimum.min(value), maximum.max(value)),
406            )
407        });
408        if !minimum.is_finite()
409            || !maximum.is_finite()
410            || (maximum < minimum)
411            || (!automatic_range && maximum == minimum)
412        {
413            return Err(SeriesError::InvalidContourColorRange {
414                minimum,
415                maximum,
416                stroke_width: 1,
417            }
418            .into());
419        }
420        let constant_range = maximum == minimum;
421
422        let mut elements = Vec::new();
423        for triangle in field
424            .elementary_triangles()
425            .map_err(SeriesError::ScalarMapField)?
426        {
427            let coordinates = [
428                TernaryPoint::from(
429                    field
430                        .composition(triangle.vertices[0])
431                        .map_err(SeriesError::ScalarMapField)?,
432                ),
433                TernaryPoint::from(
434                    field
435                        .composition(triangle.vertices[1])
436                        .map_err(SeriesError::ScalarMapField)?,
437                ),
438                TernaryPoint::from(
439                    field
440                        .composition(triangle.vertices[2])
441                        .map_err(SeriesError::ScalarMapField)?,
442                ),
443            ];
444            let values = [
445                field
446                    .value(triangle.vertices[0])
447                    .map_err(SeriesError::ScalarMapField)?,
448                field
449                    .value(triangle.vertices[1])
450                    .map_err(SeriesError::ScalarMapField)?,
451                field
452                    .value(triangle.vertices[2])
453                    .map_err(SeriesError::ScalarMapField)?,
454            ];
455            for micro in microtriangles(coordinates, values, intervals) {
456                // For a piecewise-linear field this mean is exactly the value
457                // at the microtriangle centroid. Plotters fills the primitive
458                // flatly; it does not perform Gouraud interpolation.
459                let average = (micro.values[0] + micro.values[1] + micro.values[2]) / 3.0;
460                let mut normalized = if constant_range {
461                    0.5
462                } else {
463                    ((average - minimum) / (maximum - minimum)).clamp(0.0, 1.0)
464                };
465                if reversed {
466                    normalized = 1.0 - normalized;
467                }
468                let polygon = prepare_polygon(
469                    micro.points,
470                    chart.geometry,
471                    chart.viewport,
472                    crate::coord::Normalization::RequireUnitSum,
473                    chart.tolerance,
474                )
475                .map_err(SeriesError::Polygon)?;
476                let color = color_map(normalized).mix(opacity);
477                elements.push(PolygonElement::new(
478                    polygon
479                        .vertices()
480                        .iter()
481                        .map(|point| (point.x, point.y))
482                        .collect(),
483                    Some(ShapeStyle::from(color).filled()),
484                    None,
485                ));
486            }
487        }
488        chart.context.draw_series(elements).map_err(Into::into)
489    }
490}
491
492#[derive(Clone, Copy)]
493struct ScalarMicroTriangle {
494    points: [TernaryPoint; 3],
495    values: [f64; 3],
496}
497
498fn microtriangles(
499    points: [TernaryPoint; 3],
500    values: [f64; 3],
501    intervals: usize,
502) -> Vec<ScalarMicroTriangle> {
503    let mut result = Vec::with_capacity(super::bands::microtriangle_count(intervals));
504    let sample = |i: usize, j: usize| {
505        let u = i as f64 / intervals as f64;
506        let v = j as f64 / intervals as f64;
507        let w = 1.0 - u - v;
508        let coordinates = points.map(TernaryPoint::as_array);
509        let value = values[0] * w + values[1] * u + values[2] * v;
510        (
511            TernaryPoint::new(
512                coordinates[0][0] * w + coordinates[1][0] * u + coordinates[2][0] * v,
513                coordinates[0][1] * w + coordinates[1][1] * u + coordinates[2][1] * v,
514                coordinates[0][2] * w + coordinates[1][2] * u + coordinates[2][2] * v,
515            ),
516            value,
517        )
518    };
519    for i in 0..intervals {
520        for j in 0..(intervals - i) {
521            let (a, av) = sample(i, j);
522            let (b, bv) = sample(i + 1, j);
523            let (c, cv) = sample(i, j + 1);
524            result.push(ScalarMicroTriangle {
525                points: [a, b, c],
526                values: [av, bv, cv],
527            });
528            if i + j + 1 < intervals {
529                let (d, dv) = sample(i + 1, j + 1);
530                result.push(ScalarMicroTriangle {
531                    points: [b, d, c],
532                    values: [bv, dv, cv],
533                });
534            }
535        }
536    }
537    result
538}