Skip to main content

plotters_ternary/chart/
mesh.rs

1use std::sync::Arc;
2
3use plotters::backend::DrawingBackend;
4use plotters::element::{Drawable, EmptyElement, PathElement, PointCollection, Text};
5use plotters::style::text_anchor::{HPos, Pos, VPos};
6use plotters_backend::{BackendCoord, DrawingErrorKind};
7
8use plotters::style::{
9    BLACK, Color, FontStyle, IntoFont, IntoTextStyle, RGBAColor, RGBColor, ShapeStyle, TextStyle,
10};
11
12use super::rotated_text::RotatedText;
13use super::{TernaryChart, TernaryChartError};
14use crate::Tolerance;
15use crate::coord::{
16    CartesianSegment, Component, TernaryCartesian, TernaryGeometry, clip_segment_with_parameters,
17};
18
19const DEFAULT_MAJOR_STEP: f64 = 0.1;
20const MAX_TICK_INTERVALS: usize = 10_000;
21
22/// Semantic component axis. A/B/C remain semantic when vertices are reordered.
23#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
24pub enum TernaryAxis {
25    A,
26    B,
27    C,
28}
29impl TernaryAxis {
30    pub const ALL: [Self; 3] = [Self::A, Self::B, Self::C];
31    pub const fn component(self) -> Component {
32        match self {
33            Self::A => Component::A,
34            Self::B => Component::B,
35            Self::C => Component::C,
36        }
37    }
38    const fn index(self) -> usize {
39        self.component().index()
40    }
41    fn from_component(component: Component) -> Self {
42        match component {
43            Component::A => Self::A,
44            Component::B => Self::B,
45            Component::C => Self::C,
46        }
47    }
48}
49
50/// Deterministic positions for an axis. `Count(n)` means `n` intervals, so it
51/// has `n + 1` candidates before endpoint-label policy is applied.
52#[derive(Clone, Debug, PartialEq)]
53pub enum TickSpec {
54    Count(usize),
55    Step(f64),
56    Values(Vec<f64>),
57}
58
59#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
60pub enum TickRangeMode {
61    #[default]
62    FullCompositionRange,
63    VisibleRange,
64}
65#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
66pub enum CroppedAxisPolicy {
67    #[default]
68    TriangleEdgesOnly,
69}
70#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
71pub enum TickDirection {
72    Inward,
73    #[default]
74    Outward,
75    Both,
76}
77#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
78pub enum EndpointLabelPolicy {
79    Both,
80    MinimumOnly,
81    MaximumOnly,
82    InteriorOnly,
83    None,
84    #[default]
85    AutoAvoidDuplicates,
86}
87#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
88pub enum CornerLabelVisibility {
89    #[default]
90    Auto,
91    Always,
92    VisibleCornersOnly,
93    Hidden,
94}
95
96/// Generated numeric-label formatting. Custom formatters may return Unicode.
97#[derive(Clone)]
98pub enum AxisLabelFormat {
99    Decimal { precision: usize },
100    Percentage { precision: usize },
101    Custom(Arc<dyn Fn(f64) -> String + Send + Sync + 'static>),
102}
103impl Default for AxisLabelFormat {
104    fn default() -> Self {
105        Self::Decimal { precision: 1 }
106    }
107}
108impl AxisLabelFormat {
109    pub fn format(&self, value: f64) -> String {
110        match self {
111            Self::Decimal { precision } => format!("{value:.precision$}"),
112            Self::Percentage { precision } => format!("{:.precision$}%", value * 100.0),
113            Self::Custom(formatter) => formatter(value),
114        }
115    }
116}
117
118/// Owned Plotters-compatible text attributes for independently configured axes.
119#[derive(Clone)]
120pub struct AxisTextStyle {
121    family: String,
122    size: u32,
123    font_style: FontStyle,
124    color: RGBAColor,
125}
126impl AxisTextStyle {
127    pub fn new<S: Into<String>>(
128        family: S,
129        size: u32,
130        font_style: FontStyle,
131        color: RGBAColor,
132    ) -> Self {
133        Self {
134            family: family.into(),
135            size,
136            font_style,
137            color,
138        }
139    }
140    pub fn sans_serif(size: u32, font_style: FontStyle, color: RGBAColor) -> Self {
141        Self::new("sans-serif", size, font_style, color)
142    }
143    pub const fn size(&self) -> u32 {
144        self.size
145    }
146    pub fn family(&self) -> &str {
147        &self.family
148    }
149    pub const fn font_style(&self) -> FontStyle {
150        self.font_style
151    }
152    pub const fn color(&self) -> RGBAColor {
153        self.color
154    }
155    fn from_plotters(style: TextStyle<'_>) -> Self {
156        let color = style.color;
157        Self::new(
158            style.font.get_name().to_owned(),
159            style.font.get_size().round().max(0.0) as u32,
160            style.font.get_style(),
161            RGBAColor(color.rgb.0, color.rgb.1, color.rgb.2, color.alpha),
162        )
163    }
164    pub(crate) fn plotters_style(&self) -> TextStyle<'_> {
165        (self.family.as_str(), self.size, self.font_style)
166            .into_font()
167            .color(&self.color)
168    }
169}
170
171/// Final-output pixel dimensions and style for one tick class.
172#[derive(Clone, Copy, Debug, PartialEq)]
173pub struct TickStyle {
174    style: ShapeStyle,
175    length: u32,
176    direction: TickDirection,
177}
178impl TickStyle {
179    pub const fn new(style: ShapeStyle, length: u32, direction: TickDirection) -> Self {
180        Self {
181            style,
182            length,
183            direction,
184        }
185    }
186    pub const fn style(self) -> ShapeStyle {
187        self.style
188    }
189    pub const fn length(self) -> u32 {
190        self.length
191    }
192    pub const fn direction(self) -> TickDirection {
193        self.direction
194    }
195}
196
197/// Axis-name placement override for cropped charts.
198#[derive(Clone, Copy, Debug, Default, PartialEq)]
199pub enum AxisNamePosition {
200    #[default]
201    Auto,
202    Logical(TernaryCartesian),
203    Hidden,
204}
205
206/// Configuration for one semantic axis. It is supplied through
207/// `TernaryMeshConfig::axis`, `axis_a`, `axis_b`, or `axis_c`.
208#[derive(Clone)]
209pub struct TernaryAxisConfig {
210    visible: bool,
211    major_ticks: TickSpec,
212    minor_ticks: Option<TickSpec>,
213    major_grid: bool,
214    minor_grid: bool,
215    ticks: bool,
216    tick_labels: bool,
217    range_mode: TickRangeMode,
218    cropped_policy: CroppedAxisPolicy,
219    endpoint_labels: EndpointLabelPolicy,
220    major_tick: TickStyle,
221    minor_tick: TickStyle,
222    major_grid_style: ShapeStyle,
223    minor_grid_style: ShapeStyle,
224    tick_label_style: AxisTextStyle,
225    tick_label_offset: u32,
226    label_format: AxisLabelFormat,
227    name: Option<String>,
228    name_style: AxisTextStyle,
229    name_offset: u32,
230    name_position: AxisNamePosition,
231}
232impl Default for TernaryAxisConfig {
233    fn default() -> Self {
234        Self {
235            visible: true,
236            major_ticks: TickSpec::Step(DEFAULT_MAJOR_STEP),
237            minor_ticks: None,
238            major_grid: true,
239            minor_grid: false,
240            // Existing mesh calls retain their pre-M5 no-tick/no-number look.
241            ticks: false,
242            tick_labels: false,
243            range_mode: TickRangeMode::FullCompositionRange,
244            cropped_policy: CroppedAxisPolicy::TriangleEdgesOnly,
245            endpoint_labels: EndpointLabelPolicy::AutoAvoidDuplicates,
246            major_tick: TickStyle::new(BLACK.stroke_width(1), 8, TickDirection::Outward),
247            minor_tick: TickStyle::new(BLACK.stroke_width(1), 4, TickDirection::Outward),
248            major_grid_style: RGBColor(185, 190, 198).stroke_width(1),
249            minor_grid_style: RGBColor(225, 229, 235).stroke_width(1),
250            tick_label_style: AxisTextStyle::sans_serif(18, FontStyle::Normal, BLACK.to_rgba()),
251            tick_label_offset: 8,
252            label_format: AxisLabelFormat::default(),
253            name: None,
254            name_style: AxisTextStyle::sans_serif(26, FontStyle::Bold, BLACK.to_rgba()),
255            name_offset: 24,
256            name_position: AxisNamePosition::Auto,
257        }
258    }
259}
260impl TernaryAxisConfig {
261    pub fn visible(&mut self, value: bool) -> &mut Self {
262        self.visible = value;
263        self
264    }
265    pub fn major_ticks(&mut self, value: TickSpec) -> &mut Self {
266        self.major_ticks = value;
267        self
268    }
269    pub fn minor_ticks(&mut self, value: TickSpec) -> &mut Self {
270        self.minor_ticks = Some(value);
271        self
272    }
273    pub fn hide_minor_ticks(&mut self) -> &mut Self {
274        self.minor_ticks = None;
275        self
276    }
277    pub fn draw_major_grid(&mut self, value: bool) -> &mut Self {
278        self.major_grid = value;
279        self
280    }
281    pub fn draw_minor_grid(&mut self, value: bool) -> &mut Self {
282        self.minor_grid = value;
283        self
284    }
285    pub fn draw_ticks(&mut self, value: bool) -> &mut Self {
286        self.ticks = value;
287        self
288    }
289    pub fn draw_tick_labels(&mut self, value: bool) -> &mut Self {
290        self.tick_labels = value;
291        self
292    }
293    pub fn tick_range_mode(&mut self, value: TickRangeMode) -> &mut Self {
294        self.range_mode = value;
295        self
296    }
297    pub fn cropped_axis_policy(&mut self, value: CroppedAxisPolicy) -> &mut Self {
298        self.cropped_policy = value;
299        self
300    }
301    pub fn endpoint_label_policy(&mut self, value: EndpointLabelPolicy) -> &mut Self {
302        self.endpoint_labels = value;
303        self
304    }
305    pub fn major_tick_style<S: Into<ShapeStyle>>(&mut self, value: S) -> &mut Self {
306        self.major_tick.style = value.into();
307        self
308    }
309    pub fn minor_tick_style<S: Into<ShapeStyle>>(&mut self, value: S) -> &mut Self {
310        self.minor_tick.style = value.into();
311        self
312    }
313    pub fn major_tick_length(&mut self, value: u32) -> &mut Self {
314        self.major_tick.length = value;
315        self
316    }
317    pub fn minor_tick_length(&mut self, value: u32) -> &mut Self {
318        self.minor_tick.length = value;
319        self
320    }
321    pub fn major_tick_direction(&mut self, value: TickDirection) -> &mut Self {
322        self.major_tick.direction = value;
323        self
324    }
325    pub fn minor_tick_direction(&mut self, value: TickDirection) -> &mut Self {
326        self.minor_tick.direction = value;
327        self
328    }
329    pub fn major_grid_style<S: Into<ShapeStyle>>(&mut self, value: S) -> &mut Self {
330        self.major_grid_style = value.into();
331        self
332    }
333    pub fn minor_grid_style<S: Into<ShapeStyle>>(&mut self, value: S) -> &mut Self {
334        self.minor_grid_style = value.into();
335        self
336    }
337    pub fn tick_label_style(&mut self, value: AxisTextStyle) -> &mut Self {
338        self.tick_label_style = value;
339        self
340    }
341    pub fn tick_label_offset(&mut self, value: u32) -> &mut Self {
342        self.tick_label_offset = value;
343        self
344    }
345    pub fn label_format(&mut self, value: AxisLabelFormat) -> &mut Self {
346        self.label_format = value;
347        self
348    }
349    pub fn label_formatter<F>(&mut self, value: F) -> &mut Self
350    where
351        F: Fn(f64) -> String + Send + Sync + 'static,
352    {
353        self.label_format = AxisLabelFormat::Custom(Arc::new(value));
354        self
355    }
356    pub fn axis_name<S: Into<String>>(&mut self, value: S) -> &mut Self {
357        self.name = Some(value.into());
358        self
359    }
360    pub fn hide_axis_name(&mut self) -> &mut Self {
361        self.name = None;
362        self
363    }
364    pub fn axis_name_style(&mut self, value: AxisTextStyle) -> &mut Self {
365        self.name_style = value;
366        self
367    }
368    pub fn axis_name_offset(&mut self, value: u32) -> &mut Self {
369        self.name_offset = value;
370        self
371    }
372    pub fn axis_name_position(&mut self, value: AxisNamePosition) -> &mut Self {
373        self.name_position = value;
374        self
375    }
376}
377
378/// Plotters-like configuration for ternary mesh, ticks, and labels.
379pub struct TernaryMeshConfig<'chart, 'series, DB: DrawingBackend> {
380    chart: &'chart mut TernaryChart<'series, DB>,
381    axes: [TernaryAxisConfig; 3],
382    boundary_style: ShapeStyle,
383    corner_names: [Option<String>; 3],
384    corner_label_style: AxisTextStyle,
385    corner_label_offset: u32,
386    corner_visibility: CornerLabelVisibility,
387    draw_corner_names: bool,
388    draw_grid: bool,
389    draw_boundary: bool,
390}
391impl<'chart, 'series, DB: DrawingBackend> TernaryMeshConfig<'chart, 'series, DB> {
392    pub(crate) fn new(chart: &'chart mut TernaryChart<'series, DB>) -> Self {
393        Self {
394            chart,
395            axes: std::array::from_fn(|_| TernaryAxisConfig::default()),
396            boundary_style: BLACK.stroke_width(2),
397            corner_names: [None, None, None],
398            corner_label_style: AxisTextStyle::sans_serif(28, FontStyle::Bold, BLACK.to_rgba()),
399            corner_label_offset: 16,
400            corner_visibility: CornerLabelVisibility::Auto,
401            draw_corner_names: true,
402            draw_grid: true,
403            draw_boundary: true,
404        }
405    }
406    /// Configure an independent semantic axis without exposing geometric edge ids.
407    pub fn axis<F>(mut self, axis: TernaryAxis, configure: F) -> Self
408    where
409        F: FnOnce(&mut TernaryAxisConfig),
410    {
411        configure(&mut self.axes[axis.index()]);
412        self
413    }
414    pub fn axis_a<F>(self, configure: F) -> Self
415    where
416        F: FnOnce(&mut TernaryAxisConfig),
417    {
418        self.axis(TernaryAxis::A, configure)
419    }
420    pub fn axis_b<F>(self, configure: F) -> Self
421    where
422        F: FnOnce(&mut TernaryAxisConfig),
423    {
424        self.axis(TernaryAxis::B, configure)
425    }
426    pub fn axis_c<F>(self, configure: F) -> Self
427    where
428        F: FnOnce(&mut TernaryAxisConfig),
429    {
430        self.axis(TernaryAxis::C, configure)
431    }
432
433    /// Compatibility shortcut: use one major-grid step for all three axes.
434    pub fn major_step(mut self, step: f64) -> Self {
435        for axis in &mut self.axes {
436            axis.major_ticks = TickSpec::Step(step);
437        }
438        self
439    }
440    pub fn boundary_style<S: Into<ShapeStyle>>(mut self, style: S) -> Self {
441        self.boundary_style = style.into();
442        self
443    }
444    pub fn major_grid_style<S: Into<ShapeStyle>>(mut self, style: S) -> Self {
445        let style = style.into();
446        for axis in &mut self.axes {
447            axis.major_grid_style = style;
448        }
449        self
450    }
451    pub fn minor_grid_style<S: Into<ShapeStyle>>(mut self, style: S) -> Self {
452        let style = style.into();
453        for axis in &mut self.axes {
454            axis.minor_grid_style = style;
455        }
456        self
457    }
458    /// Backwards-compatible common text style; explicit per-axis setters take precedence when called later.
459    pub fn text_style<'style, S>(mut self, style: S) -> Self
460    where
461        S: IntoTextStyle<'style>,
462    {
463        let style = AxisTextStyle::from_plotters(style.into_text_style(self.chart.plotting_area()));
464        for axis in &mut self.axes {
465            axis.name_style = style.clone();
466            axis.tick_label_style = style.clone();
467        }
468        self.corner_label_style = style;
469        self
470    }
471    pub fn axis_name_style<'style, S>(mut self, style: S) -> Self
472    where
473        S: IntoTextStyle<'style>,
474    {
475        let style = AxisTextStyle::from_plotters(style.into_text_style(self.chart.plotting_area()));
476        for axis in &mut self.axes {
477            axis.name_style = style.clone();
478        }
479        self
480    }
481    pub fn corner_label_style<'style, S>(mut self, style: S) -> Self
482    where
483        S: IntoTextStyle<'style>,
484    {
485        self.corner_label_style =
486            AxisTextStyle::from_plotters(style.into_text_style(self.chart.plotting_area()));
487        self
488    }
489    pub fn axis_a_name<S: Into<String>>(mut self, value: S) -> Self {
490        self.axes[0].name = Some(value.into());
491        self
492    }
493    pub fn axis_b_name<S: Into<String>>(mut self, value: S) -> Self {
494        self.axes[1].name = Some(value.into());
495        self
496    }
497    pub fn axis_c_name<S: Into<String>>(mut self, value: S) -> Self {
498        self.axes[2].name = Some(value.into());
499        self
500    }
501    pub fn corner_a_name<S: Into<String>>(mut self, value: S) -> Self {
502        self.corner_names[0] = Some(value.into());
503        self
504    }
505    pub fn corner_b_name<S: Into<String>>(mut self, value: S) -> Self {
506        self.corner_names[1] = Some(value.into());
507        self
508    }
509    pub fn corner_c_name<S: Into<String>>(mut self, value: S) -> Self {
510        self.corner_names[2] = Some(value.into());
511        self
512    }
513    pub fn axis_label_offset(mut self, value: u32) -> Self {
514        for axis in &mut self.axes {
515            axis.name_offset = value;
516        }
517        self
518    }
519    pub fn corner_label_offset(mut self, value: u32) -> Self {
520        self.corner_label_offset = value;
521        self
522    }
523    pub fn corner_label_visibility(mut self, value: CornerLabelVisibility) -> Self {
524        self.corner_visibility = value;
525        self
526    }
527    pub fn hide_axis_names(mut self) -> Self {
528        for axis in &mut self.axes {
529            axis.name = None;
530        }
531        self
532    }
533    pub fn hide_corner_names(mut self) -> Self {
534        self.draw_corner_names = false;
535        self
536    }
537    pub fn hide_grid_lines(mut self) -> Self {
538        self.draw_grid = false;
539        self
540    }
541    pub fn hide_triangle_boundary(mut self) -> Self {
542        self.draw_boundary = false;
543        self
544    }
545    pub fn hide_ticks(mut self) -> Self {
546        for axis in &mut self.axes {
547            axis.ticks = false;
548        }
549        self
550    }
551    pub fn hide_tick_labels(mut self) -> Self {
552        for axis in &mut self.axes {
553            axis.tick_labels = false;
554        }
555        self
556    }
557
558    /// Freeze this configuration for layered drawing.
559    ///
560    /// The returned mesh is independent of the chart borrow. It can therefore
561    /// draw grid geometry, release the chart for data series, then draw the
562    /// foreground simplex frame and final-resolution text.
563    pub fn build(self) -> TernaryMesh {
564        self.split().1
565    }
566
567    /// Draw every mesh phase immediately for backwards compatibility.
568    ///
569    /// Prefer [`TernaryMesh::draw_background`], data series,
570    /// [`TernaryMesh::draw_foreground`], and [`TernaryMesh::draw_text`] when
571    /// data must remain behind a thick triangle frame.
572    pub fn draw(self) -> Result<(), TernaryChartError<DB::ErrorType>> {
573        let (chart, mesh) = self.split();
574        mesh.draw_background(chart)?;
575        mesh.draw_foreground(chart)?;
576        mesh.draw_text(chart)
577    }
578    /// Draw all geometry immediately at native resolution.
579    pub fn draw_geometry(self) -> Result<(), TernaryChartError<DB::ErrorType>> {
580        let (chart, mesh) = self.split();
581        mesh.draw_background(chart)?;
582        mesh.draw_foreground(chart)
583    }
584    /// Draw all geometry immediately with final-layout dimensions scaled for PNG supersampling.
585    pub fn draw_geometry_scaled(self, scale: u32) -> Result<(), TernaryChartError<DB::ErrorType>> {
586        let (chart, mesh) = self.split();
587        mesh.draw_background_scaled(chart, scale)?;
588        mesh.draw_foreground_scaled(chart, scale)
589    }
590    /// Draw only final-resolution text. This emits no line, grid, or boundary geometry.
591    pub fn draw_text(self) -> Result<(), TernaryChartError<DB::ErrorType>> {
592        let (chart, mesh) = self.split();
593        mesh.draw_text(chart)
594    }
595
596    fn split(self) -> (&'chart mut TernaryChart<'series, DB>, TernaryMesh) {
597        let Self {
598            chart,
599            axes,
600            boundary_style,
601            corner_names,
602            corner_label_style,
603            corner_label_offset,
604            corner_visibility,
605            draw_corner_names,
606            draw_grid,
607            draw_boundary,
608        } = self;
609        (
610            chart,
611            TernaryMesh {
612                axes,
613                boundary_style,
614                corner_names,
615                corner_label_style,
616                corner_label_offset,
617                corner_visibility,
618                draw_corner_names,
619                draw_grid,
620                draw_boundary,
621            },
622        )
623    }
624
625    fn draw_phase(
626        self,
627        phase: MeshPhase,
628        scale: u32,
629    ) -> Result<(), TernaryChartError<DB::ErrorType>> {
630        let prepared = prepare_axes(self.chart, &self.axes)?;
631        if phase.background() {
632            self.draw_background_phase(&prepared, scale)?;
633        }
634        if phase.foreground() {
635            self.draw_foreground_phase(&prepared, scale)?;
636        }
637        if phase.text() {
638            self.draw_text_phase(&prepared)?;
639        }
640        Ok(())
641    }
642    fn draw_background_phase(
643        &self,
644        prepared: &[PreparedAxis; 3],
645        scale: u32,
646    ) -> Result<(), TernaryChartError<DB::ErrorType>> {
647        // Background geometry is intentionally drawn before data series.
648        if self.draw_grid {
649            for axis in prepared {
650                let config = &self.axes[axis.axis.index()];
651                if config.visible && config.minor_grid {
652                    self.draw_grid(axis.axis, &axis.minor_grid, config.minor_grid_style, scale)?;
653                }
654            }
655            for axis in prepared {
656                let config = &self.axes[axis.axis.index()];
657                if config.visible && config.major_grid {
658                    self.draw_grid(axis.axis, &axis.major_grid, config.major_grid_style, scale)?;
659                }
660            }
661        }
662        Ok(())
663    }
664
665    fn draw_foreground_phase(
666        &self,
667        prepared: &[PreparedAxis; 3],
668        scale: u32,
669    ) -> Result<(), TernaryChartError<DB::ErrorType>> {
670        // Foreground geometry masks data that reaches the mathematical edge.
671        if self.draw_boundary {
672            self.draw_boundary(scale)?;
673        }
674        for axis in prepared {
675            let config = &self.axes[axis.axis.index()];
676            if config.visible && config.ticks {
677                self.draw_ticks(axis, &axis.minor, config.minor_tick, scale)?;
678            }
679        }
680        for axis in prepared {
681            let config = &self.axes[axis.axis.index()];
682            if config.visible && config.ticks {
683                self.draw_ticks(axis, &axis.major, config.major_tick, scale)?;
684            }
685        }
686        Ok(())
687    }
688
689    fn draw_boundary(&self, scale: u32) -> Result<(), TernaryChartError<DB::ErrorType>> {
690        let visible = self
691            .chart
692            .geometry
693            .visible_edges(self.chart.viewport, self.chart.tolerance)?;
694        let width = self
695            .boundary_style
696            .stroke_width
697            .saturating_mul(scale)
698            .max(1);
699        let complete = visible.len() == 3
700            && visible.iter().all(|edge| {
701                self.chart.tolerance.is_near_zero(edge.parameter_start)
702                    && self.chart.tolerance.is_close(edge.parameter_end, 1.0)
703            });
704        if complete {
705            let left_right = self
706                .chart
707                .geometry
708                .triangle_edge(crate::TriangleEdge::LeftRight);
709            let right_apex = self
710                .chart
711                .geometry
712                .triangle_edge(crate::TriangleEdge::RightApex);
713            let vertices = vec![
714                (left_right.start.x, left_right.start.y),
715                (left_right.end.x, left_right.end.y),
716                (right_apex.end.x, right_apex.end.y),
717            ];
718            self.chart.plotting_area().draw(&BoundaryElement::closed(
719                vertices,
720                self.boundary_style,
721                width,
722            ))?;
723        } else {
724            for edge in visible {
725                let segment = edge.segment;
726                // Viewport cuts are butt-ended strips, never rounded protrusions.
727                self.chart.plotting_area().draw(&BoundaryElement::open(
728                    vec![
729                        (segment.start.x, segment.start.y),
730                        (segment.end.x, segment.end.y),
731                    ],
732                    self.boundary_style,
733                    width,
734                ))?;
735            }
736        }
737        Ok(())
738    }
739    fn draw_grid(
740        &self,
741        axis: TernaryAxis,
742        ticks: &[PreparedTick],
743        style: ShapeStyle,
744        scale: u32,
745    ) -> Result<(), TernaryChartError<DB::ErrorType>> {
746        for tick in ticks {
747            if is_endpoint(tick.value, self.chart.tolerance) {
748                continue;
749            }
750            if let Some(segment) = self.chart.geometry.visible_component_isoline(
751                axis.component(),
752                tick.value,
753                self.chart.viewport,
754                self.chart.tolerance,
755            )? {
756                self.chart.plotting_area().draw(&PathElement::new(
757                    [
758                        (segment.start.x, segment.start.y),
759                        (segment.end.x, segment.end.y),
760                    ],
761                    scaled_style(style, scale),
762                ))?;
763            }
764        }
765        Ok(())
766    }
767    fn draw_ticks(
768        &self,
769        axis: &PreparedAxis,
770        ticks: &[PreparedTick],
771        style: TickStyle,
772        scale: u32,
773    ) -> Result<(), TernaryChartError<DB::ErrorType>> {
774        let Some(edge) = axis.edge else {
775            return Ok(());
776        };
777        for tick in ticks {
778            let normal = outward_normal(self.chart, tick.anchor);
779            let (start, end) =
780                tick_endpoints(normal, style.length.saturating_mul(scale), style.direction);
781            let element = EmptyElement::<_, DB>::at((tick.anchor.x, tick.anchor.y))
782                + PathElement::new([start, end], scaled_style(style.style, scale));
783            self.chart.plotting_area().draw(&element)?;
784        }
785        let _ = edge; // The edge proves physical ticks are never synthesized on a viewport side.
786        Ok(())
787    }
788
789    fn draw_text_phase(
790        &self,
791        prepared: &[PreparedAxis; 3],
792    ) -> Result<(), TernaryChartError<DB::ErrorType>> {
793        // Tick labels -> axis names -> corners. PNG geometry passes never reach here.
794        for axis in prepared {
795            let config = &self.axes[axis.axis.index()];
796            if config.visible && config.tick_labels {
797                self.draw_tick_labels(axis, config)?;
798            }
799        }
800        for axis in prepared {
801            let config = &self.axes[axis.axis.index()];
802            if config.visible {
803                self.draw_axis_name(axis, config)?;
804            }
805        }
806        if self.draw_corner_names && self.corner_visibility != CornerLabelVisibility::Hidden {
807            draw_corner_names(
808                self.chart,
809                &self.corner_names,
810                &self.corner_label_style,
811                self.corner_label_offset,
812                self.corner_visibility,
813            )?;
814        }
815        Ok(())
816    }
817    fn draw_tick_labels(
818        &self,
819        axis: &PreparedAxis,
820        config: &TernaryAxisConfig,
821    ) -> Result<(), TernaryChartError<DB::ErrorType>> {
822        if axis.edge.is_none() {
823            return Ok(());
824        }
825        for tick in &axis.major {
826            if !show_tick_label(
827                axis.axis,
828                tick.value,
829                config.endpoint_labels,
830                self.chart,
831                &self.corner_names,
832                self.corner_visibility,
833            ) {
834                continue;
835            }
836            let normal = outward_normal(self.chart, tick.anchor);
837            let offset = pixel_offset(normal, config.tick_label_offset);
838            let position = Pos::new(
839                if normal.0 < 0.0 {
840                    HPos::Right
841                } else if normal.0 > 0.0 {
842                    HPos::Left
843                } else {
844                    HPos::Center
845                },
846                if normal.1 < 0.0 {
847                    VPos::Bottom
848                } else {
849                    VPos::Top
850                },
851            );
852            let text = EmptyElement::<_, DB>::at((tick.anchor.x, tick.anchor.y))
853                + Text::new(
854                    config.label_format.format(tick.value),
855                    offset,
856                    config.tick_label_style.plotters_style().pos(position),
857                );
858            self.chart.plotting_area().draw(&text)?;
859        }
860        Ok(())
861    }
862    fn draw_axis_name(
863        &self,
864        axis: &PreparedAxis,
865        config: &TernaryAxisConfig,
866    ) -> Result<(), TernaryChartError<DB::ErrorType>> {
867        let Some(name) = &config.name else {
868            return Ok(());
869        };
870        let anchor = match config.name_position {
871            AxisNamePosition::Auto => {
872                if axis.edge.is_none() {
873                    return Ok(());
874                }
875                axis_name_anchor(self.chart.geometry, axis.axis.component())
876            }
877            AxisNamePosition::Logical(anchor) => anchor,
878            AxisNamePosition::Hidden => return Ok(()),
879        };
880        if !self.chart.viewport.contains(anchor, self.chart.tolerance)? {
881            return Ok(());
882        }
883        let edge = semantic_axis_edge(self.chart.geometry, axis.axis.component());
884        let layout = axis_name_layout(self.chart, edge, anchor, config.name_offset);
885        if layout.angle.abs() <= 1.0e-12 {
886            let text = EmptyElement::<_, DB>::at((anchor.x, anchor.y))
887                + Text::new(
888                    name.clone(),
889                    layout.offset,
890                    config
891                        .name_style
892                        .plotters_style()
893                        .pos(Pos::new(HPos::Center, VPos::Center)),
894                );
895            self.chart.plotting_area().draw(&text)?;
896        } else {
897            self.chart.plotting_area().draw(&RotatedText::new(
898                (anchor.x, anchor.y),
899                name.clone(),
900                config.name_style.clone(),
901                layout.angle,
902                layout.offset,
903            ))?;
904        }
905        Ok(())
906    }
907}
908
909#[derive(Clone, Copy)]
910enum MeshPhase {
911    Background,
912    Foreground,
913    Text,
914}
915impl MeshPhase {
916    const fn background(self) -> bool {
917        matches!(self, Self::Background)
918    }
919    const fn foreground(self) -> bool {
920        matches!(self, Self::Foreground)
921    }
922    const fn text(self) -> bool {
923        matches!(self, Self::Text)
924    }
925}
926
927/// An owned mesh configuration for explicit chart-layer compositing.
928///
929/// It contains styles and policies only. It never owns numerical series data,
930/// so drawing it with different Plotters backends or viewports cannot mutate or
931/// reconstruct a contour path.
932pub struct TernaryMesh {
933    axes: [TernaryAxisConfig; 3],
934    boundary_style: ShapeStyle,
935    corner_names: [Option<String>; 3],
936    corner_label_style: AxisTextStyle,
937    corner_label_offset: u32,
938    corner_visibility: CornerLabelVisibility,
939    draw_corner_names: bool,
940    draw_grid: bool,
941    draw_boundary: bool,
942}
943
944impl TernaryMesh {
945    fn bind<'chart, 'series, DB: DrawingBackend>(
946        &self,
947        chart: &'chart mut TernaryChart<'series, DB>,
948    ) -> TernaryMeshConfig<'chart, 'series, DB> {
949        TernaryMeshConfig {
950            chart,
951            axes: self.axes.clone(),
952            boundary_style: self.boundary_style,
953            corner_names: self.corner_names.clone(),
954            corner_label_style: self.corner_label_style.clone(),
955            corner_label_offset: self.corner_label_offset,
956            corner_visibility: self.corner_visibility,
957            draw_corner_names: self.draw_corner_names,
958            draw_grid: self.draw_grid,
959            draw_boundary: self.draw_boundary,
960        }
961    }
962
963    /// Draw minor and major grid geometry beneath data at native resolution.
964    pub fn draw_background<DB: DrawingBackend>(
965        &self,
966        chart: &mut TernaryChart<'_, DB>,
967    ) -> Result<(), TernaryChartError<DB::ErrorType>> {
968        self.bind(chart).draw_phase(MeshPhase::Background, 1)
969    }
970
971    /// Draw minor and major grid geometry beneath data with supersampled pixel styles.
972    pub fn draw_background_scaled<DB: DrawingBackend>(
973        &self,
974        chart: &mut TernaryChart<'_, DB>,
975        scale: u32,
976    ) -> Result<(), TernaryChartError<DB::ErrorType>> {
977        self.bind(chart)
978            .draw_phase(MeshPhase::Background, scale.max(1))
979    }
980
981    /// Draw the physical simplex frame and ticks above data at native resolution.
982    pub fn draw_foreground<DB: DrawingBackend>(
983        &self,
984        chart: &mut TernaryChart<'_, DB>,
985    ) -> Result<(), TernaryChartError<DB::ErrorType>> {
986        self.bind(chart).draw_phase(MeshPhase::Foreground, 1)
987    }
988
989    /// Draw the physical simplex frame and ticks above data with supersampled pixel styles.
990    pub fn draw_foreground_scaled<DB: DrawingBackend>(
991        &self,
992        chart: &mut TernaryChart<'_, DB>,
993        scale: u32,
994    ) -> Result<(), TernaryChartError<DB::ErrorType>> {
995        self.bind(chart)
996            .draw_phase(MeshPhase::Foreground, scale.max(1))
997    }
998
999    /// Draw tick labels, axis names, and corner names at final resolution.
1000    pub fn draw_text<DB: DrawingBackend>(
1001        &self,
1002        chart: &mut TernaryChart<'_, DB>,
1003    ) -> Result<(), TernaryChartError<DB::ErrorType>> {
1004        self.bind(chart).draw_phase(MeshPhase::Text, 1)
1005    }
1006}
1007#[derive(Clone, Copy)]
1008struct PreparedEdge {
1009    start: f64,
1010    end: f64,
1011}
1012#[derive(Clone, Copy)]
1013struct PreparedTick {
1014    value: f64,
1015    anchor: TernaryCartesian,
1016}
1017struct PreparedAxis {
1018    axis: TernaryAxis,
1019    edge: Option<PreparedEdge>,
1020    // Grid values remain available in full-range interior viewports even when
1021    // no original edge is visible. Physical ticks use only edge-visible values.
1022    major_grid: Vec<PreparedTick>,
1023    minor_grid: Vec<PreparedTick>,
1024    major: Vec<PreparedTick>,
1025    minor: Vec<PreparedTick>,
1026}
1027
1028fn prepare_axes<DB: DrawingBackend>(
1029    chart: &TernaryChart<'_, DB>,
1030    configs: &[TernaryAxisConfig; 3],
1031) -> Result<[PreparedAxis; 3], TernaryChartError<DB::ErrorType>> {
1032    let mut result = Vec::with_capacity(3);
1033    for axis in TernaryAxis::ALL {
1034        let config = &configs[axis.index()];
1035        let source = semantic_axis_edge(chart.geometry, axis.component());
1036        let edge = clip_segment_with_parameters(source, chart.viewport, chart.tolerance)?.map(
1037            |fragment| PreparedEdge {
1038                start: fragment.parameter_start,
1039                end: fragment.parameter_end,
1040            },
1041        );
1042        let range = match (config.range_mode, edge) {
1043            (TickRangeMode::FullCompositionRange, _) => Some((0.0, 1.0)),
1044            (TickRangeMode::VisibleRange, Some(edge)) => Some((edge.start, edge.end)),
1045            (TickRangeMode::VisibleRange, None) => None,
1046        };
1047        let major_values = match range {
1048            Some(range) => resolve_tick_values(&config.major_ticks, range, chart.tolerance)?,
1049            None => Vec::new(),
1050        };
1051        let minor_values = match (&config.minor_ticks, range) {
1052            (Some(spec), Some(range)) => resolve_tick_values(spec, range, chart.tolerance)?,
1053            _ => Vec::new(),
1054        };
1055        let minor_values: Vec<_> = minor_values
1056            .into_iter()
1057            .filter(|minor| {
1058                !major_values
1059                    .iter()
1060                    .any(|major| chart.tolerance.is_close(*major, *minor))
1061            })
1062            .collect();
1063        let major_grid = to_ticks(source, &major_values);
1064        let minor_grid = to_ticks(source, &minor_values);
1065        let edge_visible = |value: f64| match edge {
1066            Some(edge) => {
1067                value >= edge.start - chart.tolerance.absolute
1068                    && value <= edge.end + chart.tolerance.absolute
1069            }
1070            None => false,
1071        };
1072        let major = to_ticks(
1073            source,
1074            &major_values
1075                .iter()
1076                .copied()
1077                .filter(|value| edge_visible(*value))
1078                .collect::<Vec<_>>(),
1079        );
1080        let minor = to_ticks(
1081            source,
1082            &minor_values
1083                .iter()
1084                .copied()
1085                .filter(|value| edge_visible(*value))
1086                .collect::<Vec<_>>(),
1087        );
1088        result.push(PreparedAxis {
1089            axis,
1090            edge,
1091            major_grid,
1092            minor_grid,
1093            major,
1094            minor,
1095        });
1096    }
1097    match result.try_into() {
1098        Ok(axes) => Ok(axes),
1099        Err(_) => unreachable!("three semantic axes"),
1100    }
1101}
1102fn semantic_axis_edge(geometry: TernaryGeometry, component: Component) -> CartesianSegment {
1103    let [first, second] = component.others();
1104    CartesianSegment::new(geometry.vertex(first), geometry.vertex(second))
1105}
1106fn to_ticks(source: CartesianSegment, values: &[f64]) -> Vec<PreparedTick> {
1107    values
1108        .iter()
1109        .map(|&value| PreparedTick {
1110            value,
1111            anchor: source.point_at(value),
1112        })
1113        .collect()
1114}
1115
1116/// Backend-neutral tick resolution. Explicit values are sorted and deduplicated.
1117pub(crate) fn resolve_tick_values<E: std::error::Error + Send + Sync>(
1118    spec: &TickSpec,
1119    range: (f64, f64),
1120    tolerance: Tolerance,
1121) -> Result<Vec<f64>, TernaryChartError<E>> {
1122    let (low, high) = range;
1123    if !low.is_finite() || !high.is_finite() || low > high + tolerance.absolute {
1124        return Err(TernaryChartError::InvalidTickValue { value: low });
1125    }
1126    let mut values: Vec<f64> = match spec {
1127        TickSpec::Count(0) => return Err(TernaryChartError::InvalidTickCount { count: 0 }),
1128        TickSpec::Count(count) => (0..=*count)
1129            .map(|i| low + (high - low) * (i as f64 / *count as f64))
1130            .collect(),
1131        TickSpec::Step(step) => {
1132            if !step.is_finite()
1133                || *step <= 0.0
1134                || *step > 1.0
1135                || (1.0 / *step).ceil() as usize > MAX_TICK_INTERVALS
1136            {
1137                return Err(TernaryChartError::InvalidTickStep { value: *step });
1138            }
1139            let count = (1.0 / *step).floor() as usize;
1140            (0..=count)
1141                .map(|i| i as f64 * *step)
1142                .filter(|v| *v >= low - tolerance.absolute && *v <= high + tolerance.absolute)
1143                .collect()
1144        }
1145        TickSpec::Values(input) => {
1146            let mut values = Vec::new();
1147            for &value in input {
1148                if !value.is_finite()
1149                    || value < -tolerance.absolute
1150                    || value > 1.0 + tolerance.absolute
1151                {
1152                    return Err(TernaryChartError::InvalidTickValue { value });
1153                }
1154                if value >= low - tolerance.absolute && value <= high + tolerance.absolute {
1155                    values.push(snap_endpoint(value, tolerance));
1156                }
1157            }
1158            values
1159        }
1160    };
1161    for value in &mut values {
1162        *value = snap_endpoint(*value, tolerance);
1163    }
1164    values.sort_by(f64::total_cmp);
1165    values.dedup_by(|a, b| tolerance.is_close(*a, *b));
1166    Ok(values)
1167}
1168#[allow(dead_code)]
1169pub(crate) fn major_grid_values<E: std::error::Error + Send + Sync>(
1170    step: f64,
1171) -> Result<Vec<f64>, TernaryChartError<E>> {
1172    resolve_tick_values(&TickSpec::Step(step), (0.0, 1.0), Tolerance::default()).map(|values| {
1173        values
1174            .into_iter()
1175            .filter(|v| !is_endpoint(*v, Tolerance::default()))
1176            .collect()
1177    })
1178}
1179fn snap_endpoint(value: f64, tolerance: Tolerance) -> f64 {
1180    if tolerance.is_close(value, 0.0) {
1181        0.0
1182    } else if tolerance.is_close(value, 1.0) {
1183        1.0
1184    } else {
1185        value
1186    }
1187}
1188fn is_endpoint(value: f64, tolerance: Tolerance) -> bool {
1189    tolerance.is_close(value, 0.0) || tolerance.is_close(value, 1.0)
1190}
1191/// A filled, miter-limited strip around one physical simplex boundary path.
1192///
1193/// Unlike three independent stroked paths, each segment shares computed offset
1194/// vertices with its neighbours. The mathematical edge is the centreline: one
1195/// half of the visual frame lies inside the simplex and masks data drawn first.
1196struct BoundaryElement<Coord> {
1197    vertices: Vec<Coord>,
1198    style: ShapeStyle,
1199    width: u32,
1200    closed: bool,
1201}
1202
1203impl<Coord> BoundaryElement<Coord> {
1204    fn closed(vertices: Vec<Coord>, style: ShapeStyle, width: u32) -> Self {
1205        Self {
1206            vertices,
1207            style,
1208            width,
1209            closed: true,
1210        }
1211    }
1212
1213    fn open(vertices: Vec<Coord>, style: ShapeStyle, width: u32) -> Self {
1214        Self {
1215            vertices,
1216            style,
1217            width,
1218            closed: false,
1219        }
1220    }
1221}
1222
1223impl<'a, Coord> PointCollection<'a, Coord> for &'a BoundaryElement<Coord> {
1224    type Point = &'a Coord;
1225    type IntoIter = std::slice::Iter<'a, Coord>;
1226
1227    fn point_iter(self) -> Self::IntoIter {
1228        self.vertices.iter()
1229    }
1230}
1231
1232impl<Coord, DB: DrawingBackend> Drawable<DB> for BoundaryElement<Coord> {
1233    fn draw<I: Iterator<Item = BackendCoord>>(
1234        &self,
1235        points: I,
1236        backend: &mut DB,
1237        _: (u32, u32),
1238    ) -> Result<(), DrawingErrorKind<DB::ErrorType>> {
1239        let vertices: Vec<_> = points.collect();
1240        let fill = ShapeStyle::from(self.style.color).filled();
1241        for quad in boundary_quads(&vertices, self.width, self.closed) {
1242            backend.fill_polygon(quad, &fill)?;
1243        }
1244        Ok(())
1245    }
1246}
1247
1248/// Compute non-overlapping frame quads with shared miter vertices.
1249///
1250/// The miter is limited to four half-widths. A cropped fragment has butt caps;
1251/// a complete triangle is closed and therefore has no cap geometry.
1252fn boundary_quads(vertices: &[BackendCoord], width: u32, closed: bool) -> Vec<[BackendCoord; 4]> {
1253    let minimum = if closed { 3 } else { 2 };
1254    if vertices.len() < minimum || width == 0 {
1255        return Vec::new();
1256    }
1257    let half = f64::from(width) / 2.0;
1258    let count = vertices.len();
1259    let segment_count = if closed { count } else { count - 1 };
1260    let directions: Vec<_> = (0..segment_count)
1261        .map(|index| {
1262            let a = point_f64(vertices[index]);
1263            let b = point_f64(vertices[(index + 1) % count]);
1264            unit(subtract_point(b, a))
1265        })
1266        .collect();
1267    if directions.iter().any(|direction| direction.is_none()) {
1268        return Vec::new();
1269    }
1270    let directions: Vec<_> = directions.into_iter().flatten().collect();
1271    let mut left = Vec::with_capacity(count);
1272    let mut right = Vec::with_capacity(count);
1273    for index in 0..count {
1274        let point = point_f64(vertices[index]);
1275        let (previous, next) = if closed {
1276            (
1277                directions[(index + segment_count - 1) % segment_count],
1278                directions[index],
1279            )
1280        } else if index == 0 {
1281            (directions[0], directions[0])
1282        } else if index + 1 == count {
1283            (directions[segment_count - 1], directions[segment_count - 1])
1284        } else {
1285            (directions[index - 1], directions[index])
1286        };
1287        left.push(offset_join(point, previous, next, half));
1288        right.push(offset_join(point, negate(previous), negate(next), half));
1289    }
1290    (0..segment_count)
1291        .map(|index| {
1292            let next = (index + 1) % count;
1293            [
1294                round_point(left[index]),
1295                round_point(left[next]),
1296                round_point(right[next]),
1297                round_point(right[index]),
1298            ]
1299        })
1300        .collect()
1301}
1302
1303type FloatPoint = (f64, f64);
1304
1305fn point_f64((x, y): BackendCoord) -> FloatPoint {
1306    (f64::from(x), f64::from(y))
1307}
1308fn subtract_point((x, y): FloatPoint, (u, v): FloatPoint) -> FloatPoint {
1309    (x - u, y - v)
1310}
1311fn negate((x, y): FloatPoint) -> FloatPoint {
1312    (-x, -y)
1313}
1314fn cross_point((x, y): FloatPoint, (u, v): FloatPoint) -> f64 {
1315    x * v - y * u
1316}
1317fn unit((x, y): FloatPoint) -> Option<FloatPoint> {
1318    let length = (x * x + y * y).sqrt();
1319    (length > f64::EPSILON).then_some((x / length, y / length))
1320}
1321fn normal((x, y): FloatPoint) -> FloatPoint {
1322    (-y, x)
1323}
1324fn round_point((x, y): FloatPoint) -> BackendCoord {
1325    (x.round() as i32, y.round() as i32)
1326}
1327
1328fn offset_join(point: FloatPoint, previous: FloatPoint, next: FloatPoint, half: f64) -> FloatPoint {
1329    let a = normal(previous);
1330    let b = normal(next);
1331    let start = (point.0 + a.0 * half, point.1 + a.1 * half);
1332    let end = (point.0 + b.0 * half, point.1 + b.1 * half);
1333    let denominator = cross_point(previous, next);
1334    if denominator.abs() <= 1.0e-9 {
1335        return start;
1336    }
1337    let delta = subtract_point(end, start);
1338    let distance = cross_point(delta, next) / denominator;
1339    let candidate = (
1340        start.0 + previous.0 * distance,
1341        start.1 + previous.1 * distance,
1342    );
1343    let offset = subtract_point(candidate, point);
1344    let length = (offset.0 * offset.0 + offset.1 * offset.1).sqrt();
1345    let maximum = half * 4.0;
1346    if length > maximum && length > 0.0 {
1347        (
1348            point.0 + offset.0 * maximum / length,
1349            point.1 + offset.1 * maximum / length,
1350        )
1351    } else {
1352        candidate
1353    }
1354}
1355
1356fn scaled_style(style: ShapeStyle, scale: u32) -> ShapeStyle {
1357    style.stroke_width(style.stroke_width.saturating_mul(scale))
1358}
1359
1360fn show_tick_label<DB: DrawingBackend>(
1361    axis: TernaryAxis,
1362    value: f64,
1363    policy: EndpointLabelPolicy,
1364    chart: &TernaryChart<'_, DB>,
1365    corner_names: &[Option<String>; 3],
1366    corner_visibility: CornerLabelVisibility,
1367) -> bool {
1368    if !is_endpoint(value, chart.tolerance) {
1369        return policy != EndpointLabelPolicy::None;
1370    }
1371    let requested = match policy {
1372        EndpointLabelPolicy::Both | EndpointLabelPolicy::AutoAvoidDuplicates => true,
1373        EndpointLabelPolicy::MinimumOnly => chart.tolerance.is_close(value, 0.0),
1374        EndpointLabelPolicy::MaximumOnly => chart.tolerance.is_close(value, 1.0),
1375        EndpointLabelPolicy::InteriorOnly | EndpointLabelPolicy::None => false,
1376    };
1377    if !requested {
1378        return false;
1379    }
1380    let [first, second] = axis.component().others();
1381    let corner = if chart.tolerance.is_close(value, 0.0) {
1382        first
1383    } else {
1384        second
1385    };
1386    let named = corner_visibility != CornerLabelVisibility::Hidden
1387        && corner_names[corner.index()].is_some()
1388        && chart
1389            .viewport
1390            .contains(chart.geometry.vertex(corner), chart.tolerance)
1391            .unwrap_or(false);
1392    if named {
1393        return false;
1394    }
1395    // Stable A/B/C ownership avoids duplicate endpoint labels at every shared corner.
1396    TernaryAxis::ALL
1397        .into_iter()
1398        .filter(|candidate| *candidate != TernaryAxis::from_component(corner))
1399        .min()
1400        == Some(axis)
1401}
1402
1403fn draw_corner_names<DB: DrawingBackend>(
1404    chart: &TernaryChart<'_, DB>,
1405    names: &[Option<String>; 3],
1406    style: &AxisTextStyle,
1407    offset: u32,
1408    visibility: CornerLabelVisibility,
1409) -> Result<(), TernaryChartError<DB::ErrorType>> {
1410    for component in Component::ALL {
1411        let Some(name) = &names[component.index()] else {
1412            continue;
1413        };
1414        let vertex = chart.geometry.vertex(component);
1415        if visibility != CornerLabelVisibility::Always
1416            && !chart.viewport.contains(vertex, chart.tolerance)?
1417        {
1418            continue;
1419        }
1420        let layout = corner_label_layout(chart, component, offset);
1421        let text = EmptyElement::<_, DB>::at((vertex.x, vertex.y))
1422            + Text::new(
1423                name.clone(),
1424                layout.offset,
1425                style.plotters_style().pos(layout.position),
1426            );
1427        chart.plotting_area().draw(&text)?;
1428    }
1429    Ok(())
1430}
1431pub(crate) fn axis_name_anchor(
1432    geometry: TernaryGeometry,
1433    component: Component,
1434) -> TernaryCartesian {
1435    let [first, second] = component.others();
1436    midpoint(geometry.vertex(first), geometry.vertex(second))
1437}
1438fn midpoint(a: TernaryCartesian, b: TernaryCartesian) -> TernaryCartesian {
1439    TernaryCartesian::new((a.x + b.x) / 2.0, (a.y + b.y) / 2.0)
1440}
1441fn centroid(geometry: TernaryGeometry) -> TernaryCartesian {
1442    let [a, b, c] = geometry.vertices();
1443    TernaryCartesian::new((a.x + b.x + c.x) / 3.0, (a.y + b.y + c.y) / 3.0)
1444}
1445#[derive(Clone, Copy)]
1446struct LabelLayout {
1447    offset: (i32, i32),
1448    angle: f64,
1449    position: Pos,
1450}
1451fn pixel_offset(vector: (f64, f64), distance: u32) -> (i32, i32) {
1452    (
1453        (vector.0 * f64::from(distance)).round() as i32,
1454        (vector.1 * f64::from(distance)).round() as i32,
1455    )
1456}
1457fn outward_normal<DB: DrawingBackend>(
1458    chart: &TernaryChart<'_, DB>,
1459    anchor: TernaryCartesian,
1460) -> (f64, f64) {
1461    let c = centroid(chart.geometry);
1462    let cp = chart.plotting_area().map_coordinate(&(c.x, c.y));
1463    let ap = chart.plotting_area().map_coordinate(&(anchor.x, anchor.y));
1464    let dx = f64::from(ap.0 - cp.0);
1465    let dy = f64::from(ap.1 - cp.1);
1466    let len = dx.hypot(dy);
1467    if len <= f64::EPSILON {
1468        (0.0, -1.0)
1469    } else {
1470        (dx / len, dy / len)
1471    }
1472}
1473fn corner_label_layout<DB: DrawingBackend>(
1474    chart: &TernaryChart<'_, DB>,
1475    component: Component,
1476    distance: u32,
1477) -> LabelLayout {
1478    let vertex = chart.geometry.vertex(component);
1479    let normal = outward_normal(chart, vertex);
1480    let offset = pixel_offset(normal, distance);
1481    let position = Pos::new(
1482        if offset.0 < 0 {
1483            HPos::Right
1484        } else if offset.0 > 0 {
1485            HPos::Left
1486        } else {
1487            HPos::Center
1488        },
1489        if offset.1 < 0 {
1490            VPos::Bottom
1491        } else {
1492            VPos::Top
1493        },
1494    );
1495    LabelLayout {
1496        offset,
1497        angle: 0.0,
1498        position,
1499    }
1500}
1501fn axis_name_layout<DB: DrawingBackend>(
1502    chart: &TernaryChart<'_, DB>,
1503    edge: CartesianSegment,
1504    anchor: TernaryCartesian,
1505    distance: u32,
1506) -> LabelLayout {
1507    let first = chart
1508        .plotting_area()
1509        .map_coordinate(&(edge.start.x, edge.start.y));
1510    let second = chart
1511        .plotting_area()
1512        .map_coordinate(&(edge.end.x, edge.end.y));
1513    let (mut dx, mut dy) = (f64::from(second.0 - first.0), f64::from(second.1 - first.1));
1514    if dx < 0.0 || (dx.abs() <= f64::EPSILON && dy < 0.0) {
1515        dx = -dx;
1516        dy = -dy;
1517    }
1518    LabelLayout {
1519        offset: pixel_offset(outward_normal(chart, anchor), distance),
1520        angle: dy.atan2(dx),
1521        position: Pos::new(HPos::Center, VPos::Center),
1522    }
1523}
1524fn tick_endpoints(
1525    normal: (f64, f64),
1526    length: u32,
1527    direction: TickDirection,
1528) -> ((i32, i32), (i32, i32)) {
1529    let vector = |amount: f64| {
1530        (
1531            (normal.0 * amount).round() as i32,
1532            (normal.1 * amount).round() as i32,
1533        )
1534    };
1535    let length = f64::from(length);
1536    match direction {
1537        TickDirection::Outward => ((0, 0), vector(length)),
1538        TickDirection::Inward => (vector(-length), (0, 0)),
1539        TickDirection::Both => (vector(-length / 2.0), vector(length / 2.0)),
1540    }
1541}
1542
1543#[cfg(test)]
1544mod tests {
1545    use super::*;
1546    use crate::{EQUILATERAL_TRIANGLE_HEIGHT, TernaryViewport, TriangleOrientation, VertexOrder};
1547    #[test]
1548    fn count_step_and_values_are_deterministic() {
1549        let t = Tolerance::default();
1550        assert_eq!(
1551            resolve_tick_values::<std::io::Error>(&TickSpec::Count(4), (0.0, 1.0), t).unwrap(),
1552            vec![0.0, 0.25, 0.5, 0.75, 1.0]
1553        );
1554        assert_eq!(
1555            resolve_tick_values::<std::io::Error>(&TickSpec::Step(0.25), (0.0, 1.0), t).unwrap(),
1556            vec![0.0, 0.25, 0.5, 0.75, 1.0]
1557        );
1558        assert_eq!(
1559            resolve_tick_values::<std::io::Error>(
1560                &TickSpec::Values(vec![1.0, 0.5, 0.5 + 1e-13, 0.0]),
1561                (0.0, 1.0),
1562                t
1563            )
1564            .unwrap(),
1565            vec![0.0, 0.5, 1.0]
1566        );
1567    }
1568    #[test]
1569    fn invalid_ticks_are_errors() {
1570        let t = Tolerance::default();
1571        assert!(matches!(
1572            resolve_tick_values::<std::io::Error>(&TickSpec::Count(0), (0.0, 1.0), t),
1573            Err(TernaryChartError::InvalidTickCount { .. })
1574        ));
1575        for value in [0.0, -0.1, 1.1, f64::NAN] {
1576            assert!(matches!(
1577                resolve_tick_values::<std::io::Error>(&TickSpec::Step(value), (0.0, 1.0), t),
1578                Err(TernaryChartError::InvalidTickStep { .. })
1579            ));
1580        }
1581    }
1582    #[test]
1583    fn boundary_ring_uses_shared_miter_vertices_for_all_supported_widths() {
1584        let triangle = [(20, 140), (180, 140), (100, 1)];
1585        for width in [1, 3, 8, 16, 30] {
1586            let quads = boundary_quads(&triangle, width, true);
1587            assert_eq!(quads.len(), 3, "width {width}");
1588            for index in 0..3 {
1589                let next = (index + 1) % 3;
1590                assert_eq!(
1591                    quads[index][1], quads[next][0],
1592                    "left join at {index}, width {width}"
1593                );
1594                assert_eq!(
1595                    quads[index][2], quads[next][3],
1596                    "right join at {index}, width {width}"
1597                );
1598            }
1599        }
1600    }
1601
1602    #[test]
1603    fn cropped_boundary_strips_have_butt_caps() {
1604        let quads = boundary_quads(&[(20, 100), (180, 100)], 16, false);
1605        assert_eq!(quads.len(), 1);
1606        assert_eq!(quads[0][0].0, 20);
1607        assert_eq!(quads[0][3].0, 20);
1608        assert_eq!(quads[0][1].0, 180);
1609        assert_eq!(quads[0][2].0, 180);
1610    }
1611
1612    #[test]
1613    fn formatting_preserves_percent_and_unicode() {
1614        assert_eq!(
1615            AxisLabelFormat::Percentage { precision: 0 }.format(0.25),
1616            "25%"
1617        );
1618        assert_eq!(
1619            AxisLabelFormat::Custom(Arc::new(|v| format!("SiO\u{2082} {v:.1}"))).format(0.5),
1620            "SiO\u{2082} 0.5"
1621        );
1622    }
1623    #[test]
1624    fn semantic_edges_follow_custom_order() {
1625        let g = TernaryGeometry::new(
1626            TriangleOrientation::Up,
1627            VertexOrder::new(Component::C, Component::A, Component::B).unwrap(),
1628        );
1629        let edge = semantic_axis_edge(g, Component::A);
1630        assert_eq!(edge.start, g.vertex(Component::B));
1631        assert_eq!(edge.end, g.vertex(Component::C));
1632        assert_eq!(
1633            axis_name_anchor(g, Component::A),
1634            TernaryCartesian::new(0.25, EQUILATERAL_TRIANGLE_HEIGHT / 2.0)
1635        );
1636    }
1637    #[test]
1638    fn visible_edge_ranges_do_not_use_viewport_sides() {
1639        let g = TernaryGeometry::default();
1640        let v = TernaryViewport::new(0.3, 0.7, 0.15, 0.35).unwrap();
1641        let source = semantic_axis_edge(g, Component::A);
1642        assert!(
1643            clip_segment_with_parameters(source, v, Tolerance::default())
1644                .unwrap()
1645                .is_none()
1646        );
1647    }
1648}