Skip to main content

plotters_ternary/series/
bands.rs

1use std::sync::Arc;
2
3use plotters::style::{RGBAColor, ShapeStyle};
4use ternary_contours::{ContourBand, ContourBandSet, RegularTernaryScalarField};
5
6use super::SeriesError;
7
8type BandStyleCallback = dyn Fn(usize, Option<f64>, Option<f64>) -> ShapeStyle + Send + Sync;
9type ScalarColorMap = dyn Fn(f64) -> RGBAColor + Send + Sync;
10type ScalarMapParts<'a> = (
11    &'a RegularTernaryScalarField,
12    Option<(f64, f64)>,
13    ScalarMapResolution,
14    f64,
15    bool,
16    Arc<ScalarColorMap>,
17);
18
19/// Select which band boundaries are stroked after the non-overlapping fills.
20///
21/// OuterRegions draws each assembled exterior and hole boundary once.
22/// Fragments is primarily diagnostic: it can make internal fragment seams
23/// visible and is therefore never the default.
24#[derive(Clone, Copy)]
25pub enum ContourBandBorderMode {
26    /// Do not stroke band boundaries. Use isolines for inter-band boundaries.
27    None,
28    /// Stroke only assembled region and hole boundaries.
29    OuterRegions(ShapeStyle),
30    /// Stroke every clipped elementary-triangle fragment.
31    Fragments(ShapeStyle),
32}
33
34#[derive(Clone)]
35pub enum ContourBandStylePolicy {
36    Uniform(ShapeStyle),
37    Ordered(Vec<ShapeStyle>),
38    ByBand(Arc<BandStyleCallback>),
39}
40
41impl ContourBandStylePolicy {
42    pub(crate) fn style_for(
43        &self,
44        index: usize,
45        band: &ContourBand,
46    ) -> Result<ShapeStyle, SeriesError> {
47        match self {
48            Self::Uniform(style) => Ok(*style),
49            Self::Ordered(styles) if styles.is_empty() => {
50                Err(SeriesError::EmptyContourBandStyleCollection)
51            }
52            Self::Ordered(styles) => Ok(styles[index % styles.len()]),
53            Self::ByBand(callback) => Ok(callback(index, band.lower, band.upper)),
54        }
55    }
56}
57
58pub struct TernaryContourBandSeries<'a> {
59    bands: &'a ContourBandSet,
60    styles: ContourBandStylePolicy,
61    border: ContourBandBorderMode,
62}
63
64impl<'a> TernaryContourBandSeries<'a> {
65    pub fn new<S: Into<ShapeStyle>>(bands: &'a ContourBandSet, style: S) -> Self {
66        Self {
67            bands,
68            styles: ContourBandStylePolicy::Uniform(style.into()),
69            border: ContourBandBorderMode::None,
70        }
71    }
72    pub fn style_by_band<F>(mut self, callback: F) -> Self
73    where
74        F: Fn(usize, Option<f64>, Option<f64>) -> ShapeStyle + Send + Sync + 'static,
75    {
76        self.styles = ContourBandStylePolicy::ByBand(Arc::new(callback));
77        self
78    }
79    pub fn styles(mut self, styles: Vec<ShapeStyle>) -> Self {
80        self.styles = ContourBandStylePolicy::Ordered(styles);
81        self
82    }
83    /// Stroke each assembled region boundary once, including hole boundaries.
84    ///
85    /// This preserves the legacy method name while avoiding doubled internal
86    /// fragment seams.
87    pub fn border_style<S: Into<ShapeStyle>>(mut self, style: S) -> Self {
88        self.border = ContourBandBorderMode::OuterRegions(style.into());
89        self
90    }
91
92    /// Stroke every elementary-triangle band fragment.
93    ///
94    /// This is useful for diagnostics only; ordinary figures should use
95    /// border_style or isolines instead.
96    pub fn fragment_border_style<S: Into<ShapeStyle>>(mut self, style: S) -> Self {
97        self.border = ContourBandBorderMode::Fragments(style.into());
98        self
99    }
100
101    /// Disable all band-border strokes.
102    pub const fn without_border(mut self) -> Self {
103        self.border = ContourBandBorderMode::None;
104        self
105    }
106
107    pub(crate) fn into_parts(
108        self,
109    ) -> (
110        &'a ContourBandSet,
111        ContourBandStylePolicy,
112        ContourBandBorderMode,
113    ) {
114        (self.bands, self.styles, self.border)
115    }
116}
117
118#[derive(Clone, Copy, Debug, Eq, PartialEq)]
119/// Resolution of the flat-colour microtriangle approximation.
120///
121/// Adaptive currently means a deterministic uniform refinement selected by its
122/// maximum depth; it does not inspect colours per triangle. This keeps output
123/// bounded and backend-independent until a true adaptive policy is introduced.
124pub enum ScalarMapResolution {
125    Fixed { subdivisions_per_edge: usize },
126    Adaptive { max_depth: u8 },
127}
128impl Default for ScalarMapResolution {
129    fn default() -> Self {
130        Self::Fixed {
131            subdivisions_per_edge: 4,
132        }
133    }
134}
135impl ScalarMapResolution {
136    pub(crate) fn intervals(self) -> Result<usize, SeriesError> {
137        match self {
138            Self::Fixed {
139                subdivisions_per_edge,
140            } if (1..=64).contains(&subdivisions_per_edge) => Ok(subdivisions_per_edge),
141            Self::Adaptive { max_depth } if max_depth <= 6 => Ok(1usize << max_depth),
142            Self::Fixed {
143                subdivisions_per_edge,
144            } => Err(SeriesError::InvalidScalarMapResolution {
145                value: subdivisions_per_edge,
146            }),
147            Self::Adaptive { max_depth } => Err(SeriesError::InvalidScalarMapResolution {
148                value: usize::from(max_depth),
149            }),
150        }
151    }
152}
153
154pub struct TernaryScalarMapSeries<'a> {
155    field: &'a RegularTernaryScalarField,
156    range: Option<(f64, f64)>,
157    resolution: ScalarMapResolution,
158    opacity: f64,
159    reversed: bool,
160    color_map: Arc<ScalarColorMap>,
161}
162impl<'a> TernaryScalarMapSeries<'a> {
163    pub fn new(field: &'a RegularTernaryScalarField) -> Self {
164        Self {
165            field,
166            range: None,
167            resolution: ScalarMapResolution::default(),
168            opacity: 1.0,
169            reversed: false,
170            color_map: Arc::new(default_color_map),
171        }
172    }
173    pub fn range(mut self, minimum: f64, maximum: f64) -> Self {
174        self.range = Some((minimum, maximum));
175        self
176    }
177    pub fn resolution(mut self, resolution: ScalarMapResolution) -> Self {
178        self.resolution = resolution;
179        self
180    }
181    pub fn opacity(mut self, opacity: f64) -> Self {
182        self.opacity = opacity;
183        self
184    }
185    /// Reverse the normalised colour-map coordinate without changing field data.
186    pub const fn reversed(mut self) -> Self {
187        self.reversed = !self.reversed;
188        self
189    }
190
191    pub fn color_map<F>(mut self, color_map: F) -> Self
192    where
193        F: Fn(f64) -> RGBAColor + Send + Sync + 'static,
194    {
195        self.color_map = Arc::new(color_map);
196        self
197    }
198    pub(crate) fn into_parts(self) -> ScalarMapParts<'a> {
199        (
200            self.field,
201            self.range,
202            self.resolution,
203            self.opacity,
204            self.reversed,
205            self.color_map,
206        )
207    }
208}
209/// Number of flat microtriangles emitted for one elementary field triangle.
210pub(crate) const fn microtriangle_count(intervals: usize) -> usize {
211    intervals * intervals
212}
213
214pub(crate) fn default_color_map(value: f64) -> RGBAColor {
215    let value = value.clamp(0.0, 1.0);
216    RGBAColor(
217        (255.0 * value) as u8,
218        (80.0 * (1.0 - (2.0 * value - 1.0).abs())) as u8,
219        (255.0 * (1.0 - value)) as u8,
220        1.0,
221    )
222}
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227    use plotters::style::{BLACK, Color, RED};
228
229    #[test]
230    fn ordered_band_styles_cycle_and_empty_collections_are_rejected() {
231        let field = RegularTernaryScalarField::new(1, vec![0.0, 1.0, 2.0]).unwrap();
232        let bands = ContourBandSet::compute(
233            &field,
234            &[1.0],
235            ternary_contours::ContourBandOptions::linear(),
236        )
237        .unwrap();
238        let band = &bands.bands[0];
239        let styles = ContourBandStylePolicy::Ordered(vec![BLACK.filled(), RED.filled()]);
240        assert_eq!(styles.style_for(0, band).unwrap(), BLACK.filled());
241        assert_eq!(styles.style_for(3, band).unwrap(), RED.filled());
242        assert!(matches!(
243            ContourBandStylePolicy::Ordered(Vec::new()).style_for(0, band),
244            Err(SeriesError::EmptyContourBandStyleCollection)
245        ));
246    }
247
248    #[test]
249    fn scalar_map_resolution_is_bounded_and_deterministic() {
250        assert_eq!(
251            ScalarMapResolution::Fixed {
252                subdivisions_per_edge: 4
253            }
254            .intervals()
255            .unwrap(),
256            4
257        );
258        assert_eq!(
259            ScalarMapResolution::Adaptive { max_depth: 3 }
260                .intervals()
261                .unwrap(),
262            8
263        );
264        assert!(
265            ScalarMapResolution::Fixed {
266                subdivisions_per_edge: 0
267            }
268            .intervals()
269            .is_err()
270        );
271        assert_eq!(microtriangle_count(4), 16);
272    }
273
274    #[test]
275    fn reverse_map_toggles_without_changing_other_options() {
276        let field = RegularTernaryScalarField::new(1, vec![0.0, 1.0, 2.0]).unwrap();
277        let (_, _, _, _, reversed, _) = TernaryScalarMapSeries::new(&field).reversed().into_parts();
278        assert!(reversed);
279    }
280}