Skip to main content

ternary_contours/contour/
options.rs

1use crate::interpolation::BinaryExtrapolation;
2
3use super::ContourError;
4
5pub use crate::interpolation::{CubicAlphaMethod, CubicBoundaryPolicy};
6
7/// Bounds for adaptive cubic topology extraction in barycentric coordinates.
8#[derive(Clone, Copy, Debug, PartialEq)]
9pub struct AdaptiveContourOptions {
10    /// Scalar equality tolerance used while classifying a level.
11    pub value_tolerance: f64,
12    /// Composition-space endpoint cleanup tolerance.
13    pub geometry_tolerance: f64,
14    /// Maximum recursive microtriangle depth, in `1..=10`.
15    pub max_depth: u8,
16    /// Maximum sampled field disagreement allowed before further refinement.
17    pub flatness_tolerance: f64,
18}
19impl Default for AdaptiveContourOptions {
20    fn default() -> Self {
21        Self {
22            value_tolerance: 1.0e-10,
23            geometry_tolerance: 1.0e-7,
24            max_depth: 5,
25            flatness_tolerance: 1.0e-5,
26        }
27    }
28}
29impl AdaptiveContourOptions {
30    pub(crate) fn validate(self) -> Result<(), ContourError> {
31        if !self.value_tolerance.is_finite()
32            || self.value_tolerance <= 0.0
33            || !self.geometry_tolerance.is_finite()
34            || self.geometry_tolerance <= 0.0
35        {
36            return Err(ContourError::InvalidTolerance {
37                value_tolerance: self.value_tolerance,
38                geometry_tolerance: self.geometry_tolerance,
39            });
40        }
41        if self.max_depth == 0
42            || self.max_depth > 10
43            || !self.flatness_tolerance.is_finite()
44            || self.flatness_tolerance <= 0.0
45        {
46            return Err(ContourError::InvalidAdaptiveOptions {
47                max_depth: self.max_depth,
48                flatness_tolerance: self.flatness_tolerance,
49            });
50        }
51        Ok(())
52    }
53}
54
55/// Equal-arclength redistribution and implicit-level projection settings.
56///
57/// Lengths are measured in the canonical equilateral logical plane, not pixels.
58#[derive(Clone, Copy, Debug, PartialEq)]
59pub struct ContourRegularization {
60    /// Target logical spacing between redistributed path points.
61    pub spacing: f64,
62    /// Number of redistribution/project passes; zero still performs one pass.
63    pub redistribution_passes: usize,
64    /// Accepted absolute level residual after projection.
65    pub projection_tolerance: f64,
66    /// Maximum damped normal/Newton iterations for one point.
67    pub max_projection_iterations: usize,
68    /// Maximum semantic `(a,b)` correction length per iteration.
69    pub max_normal_step: f64,
70}
71impl Default for ContourRegularization {
72    fn default() -> Self {
73        Self {
74            spacing: 0.0125,
75            redistribution_passes: 2,
76            projection_tolerance: 1.0e-9,
77            max_projection_iterations: 16,
78            max_normal_step: 0.05,
79        }
80    }
81}
82impl ContourRegularization {
83    pub(crate) fn validate(self) -> Result<(), ContourError> {
84        if !self.spacing.is_finite() || self.spacing <= 0.0 {
85            return Err(ContourError::InvalidRegularizationSpacing {
86                spacing: self.spacing,
87            });
88        }
89        if !self.projection_tolerance.is_finite()
90            || self.projection_tolerance <= 0.0
91            || self.max_projection_iterations == 0
92            || !self.max_normal_step.is_finite()
93            || self.max_normal_step <= 0.0
94        {
95            return Err(ContourError::InvalidProjectionOptions {
96                tolerance: self.projection_tolerance,
97                iterations: self.max_projection_iterations,
98                max_step: self.max_normal_step,
99            });
100        }
101        Ok(())
102    }
103}
104
105/// Cubic-alpha construction policy.
106#[derive(Clone, Copy, Debug, PartialEq)]
107pub struct CubicAlphaOptions {
108    /// The `spline1d` method used on each regular lattice line.
109    pub method: CubicAlphaMethod,
110    /// Policy for two-sample boundary lines.
111    pub boundary_policy: CubicBoundaryPolicy,
112    /// Interior continuation of the shared directed edge intervals.
113    pub extrapolation: BinaryExtrapolation,
114    /// Bounded adaptive topology options.
115    pub adaptive: AdaptiveContourOptions,
116    /// Optional equal-arclength regularization after topology extraction.
117    pub regularization: Option<ContourRegularization>,
118}
119impl Default for CubicAlphaOptions {
120    fn default() -> Self {
121        Self {
122            method: CubicAlphaMethod::Steffen,
123            boundary_policy: CubicBoundaryPolicy::LinearFallback,
124            extrapolation: BinaryExtrapolation::Muggianu,
125            adaptive: AdaptiveContourOptions::default(),
126            regularization: Some(ContourRegularization::default()),
127        }
128    }
129}
130
131/// Scalar interpolation model used for contour construction.
132#[derive(Clone, Copy, Debug, PartialEq)]
133#[non_exhaustive]
134pub enum ContourInterpolation {
135    /// Exact piecewise-affine interpolation within each elementary triangle.
136    Linear,
137    /// Edge-derived cubic-alpha interpolation; requires the `cubic-alpha` feature.
138    CubicAlpha(CubicAlphaOptions),
139}
140
141/// Shared options for one [`super::ContourSet`] computation.
142#[derive(Clone, Copy, Debug, PartialEq)]
143pub struct ContourOptions {
144    /// Linear or cubic-alpha scalar model.
145    pub interpolation: ContourInterpolation,
146    /// Finite positive scalar equality tolerance.
147    pub value_tolerance: f64,
148    /// Finite positive composition-space cleanup tolerance.
149    pub geometry_tolerance: f64,
150    /// Optional regularization after path extraction.
151    pub regularization: Option<ContourRegularization>,
152}
153impl ContourOptions {
154    /// Construct the always-available piecewise-linear baseline.
155    pub const fn linear() -> Self {
156        Self {
157            interpolation: ContourInterpolation::Linear,
158            value_tolerance: 1.0e-10,
159            geometry_tolerance: 1.0e-8,
160            regularization: None,
161        }
162    }
163    /// Construct cubic-alpha options from one cubic configuration.
164    pub const fn cubic_alpha(options: CubicAlphaOptions) -> Self {
165        Self {
166            interpolation: ContourInterpolation::CubicAlpha(options),
167            value_tolerance: options.adaptive.value_tolerance,
168            geometry_tolerance: options.adaptive.geometry_tolerance,
169            regularization: options.regularization,
170        }
171    }
172    /// Replace the post-extraction regularization policy.
173    pub const fn regularization(mut self, options: Option<ContourRegularization>) -> Self {
174        self.regularization = options;
175        self
176    }
177    pub(crate) fn validate(self) -> Result<(), ContourError> {
178        if !self.value_tolerance.is_finite()
179            || self.value_tolerance <= 0.0
180            || !self.geometry_tolerance.is_finite()
181            || self.geometry_tolerance <= 0.0
182        {
183            return Err(ContourError::InvalidTolerance {
184                value_tolerance: self.value_tolerance,
185                geometry_tolerance: self.geometry_tolerance,
186            });
187        }
188        if let ContourInterpolation::CubicAlpha(options) = self.interpolation {
189            options.adaptive.validate()?;
190        }
191        if let Some(regularization) = self.regularization {
192            regularization.validate()?;
193        }
194        Ok(())
195    }
196}
197impl Default for ContourOptions {
198    fn default() -> Self {
199        Self::linear()
200    }
201}
202
203/// Diagnostics from cubic field preparation, refinement, and projection.
204#[derive(Clone, Debug, Default, PartialEq)]
205pub struct CubicContourDiagnostics {
206    /// Number of regular-grid edges assigned a cubic alpha interval.
207    pub cubic_edges: usize,
208    /// Number of two-sample edges using the configured linear fallback.
209    pub linear_fallback_edges: usize,
210    /// Number of recursively refined microtriangles.
211    pub refined_triangles: usize,
212    /// Number of cells that reached the configured depth while still non-flat.
213    pub maximum_depth_hits: usize,
214    /// Number of failed projection attempts observed before returning an error.
215    pub projection_failures: usize,
216}