Skip to main content

opensubdiv_rs/sdc/
crease.rs

1//! Semi-sharp creasing support (port of `opensubdiv/sdc/crease.{h,cpp}`).
2
3use super::options::{CreasingMethod, Options};
4
5/// Sharpness of a completely smooth edge or vertex (`Sdc::Crease::SHARPNESS_SMOOTH`).
6pub const SHARPNESS_SMOOTH: f32 = 0.0;
7
8/// Sharpness of an infinitely sharp edge or vertex (`Sdc::Crease::SHARPNESS_INFINITE`).
9///
10/// As in OpenSubdiv, `10.0` is the canonical "infinite" sharpness value: an
11/// infinitely sharp feature never decays under subdivision.
12pub const SHARPNESS_INFINITE: f32 = 10.0;
13
14/// The subdivision *rule* in effect at a vertex, derived from the sharpness
15/// of the vertex and of its incident edges (`Sdc::Crease::Rule`).
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub enum Rule {
18    /// The rule has not been determined yet.
19    Unknown,
20    /// No sharp features: the full smooth mask applies.
21    Smooth,
22    /// Exactly one sharp edge and a smooth vertex: interpolated like Smooth,
23    /// but the limit neighborhood is only C1.
24    Dart,
25    /// Exactly two sharp edges (or a boundary): the crease mask applies.
26    Crease,
27    /// A sharp vertex, or three or more sharp edges: the vertex is pinned.
28    Corner,
29}
30
31/// Types, constants and queries related to semi-sharp creasing
32/// (`Sdc::Crease`).
33///
34/// All sharpness values are clamped to the range `[SHARPNESS_SMOOTH,
35/// SHARPNESS_INFINITE]`, i.e. `[0.0, 10.0]`.
36#[derive(Debug, Clone, Copy)]
37pub struct Crease {
38    options: Options,
39}
40
41impl Crease {
42    /// Create the creasing queries for the given subdivision `options`.
43    pub fn new(options: Options) -> Self {
44        Self { options }
45    }
46
47    /// Is the given sharpness considered sharp (greater than smooth)?
48    pub fn is_sharp(sharpness: f32) -> bool {
49        sharpness > SHARPNESS_SMOOTH
50    }
51
52    /// Is the given sharpness smooth?
53    pub fn is_smooth(sharpness: f32) -> bool {
54        sharpness <= SHARPNESS_SMOOTH
55    }
56
57    /// Is the given sharpness semi-sharp, i.e. sharp but not infinitely so?
58    pub fn is_semi_sharp(sharpness: f32) -> bool {
59        (SHARPNESS_SMOOTH < sharpness) && (sharpness < SHARPNESS_INFINITE)
60    }
61
62    /// Is the given sharpness infinitely sharp?
63    pub fn is_infinite(sharpness: f32) -> bool {
64        sharpness >= SHARPNESS_INFINITE
65    }
66
67    /// Clamp an arbitrary user-provided sharpness into the valid range.
68    pub fn clamp(sharpness: f32) -> f32 {
69        sharpness.clamp(SHARPNESS_SMOOTH, SHARPNESS_INFINITE)
70    }
71
72    fn is_uniform(&self) -> bool {
73        self.options.creasing_method == CreasingMethod::Uniform
74    }
75
76    fn decrement_sharpness(sharpness: f32) -> f32 {
77        if Self::is_infinite(sharpness) {
78            SHARPNESS_INFINITE
79        } else if sharpness > 1.0 {
80            sharpness - 1.0
81        } else {
82            SHARPNESS_SMOOTH
83        }
84    }
85
86    /// Sharpness of the child of a vertex with the given sharpness
87    /// (`Sdc::Crease::SubdivideVertexSharpness`). Both the `Uniform` and
88    /// `Chaikin` methods simply decrement vertex sharpness.
89    pub fn subdivide_vertex_sharpness(&self, sharpness: f32) -> f32 {
90        Self::decrement_sharpness(sharpness)
91    }
92
93    /// Uniform subdivision of an edge sharpness value
94    /// (`Sdc::Crease::SubdivideUniformSharpness`).
95    pub fn subdivide_uniform_sharpness(&self, sharpness: f32) -> f32 {
96        Self::decrement_sharpness(sharpness)
97    }
98
99    /// Sharpness of the child (half) of an edge nearest the given end vertex
100    /// (`Sdc::Crease::SubdivideEdgeSharpnessAtVertex`).
101    ///
102    /// * `edge_sharpness` — sharpness of the parent edge,
103    /// * `incident_edge_sharpness` — sharpness of *all* edges incident the
104    ///   end vertex (including the parent edge itself, whose exact value must
105    ///   appear in the slice for the Chaikin average to exclude it).
106    pub fn subdivide_edge_sharpness_at_vertex(
107        &self,
108        edge_sharpness: f32,
109        incident_edge_sharpness: &[f32],
110    ) -> f32 {
111        if self.is_uniform() || incident_edge_sharpness.len() < 2 {
112            return Self::decrement_sharpness(edge_sharpness);
113        }
114        if Self::is_infinite(edge_sharpness) {
115            return SHARPNESS_INFINITE;
116        }
117        if Self::is_smooth(edge_sharpness) {
118            return SHARPNESS_SMOOTH;
119        }
120
121        // Chaikin creasing: blend the edge's sharpness with the average
122        // sharpness of the *other* semi-sharp edges around the shared vertex
123        // (3/4 self + 1/4 neighbor average), then decrement. Infinitely sharp
124        // neighbors (boundary edges, infinite creases, non-manifold edges) do
125        // not take part in the average; without semi-sharp neighbors the
126        // sharpness is simply decremented.
127        let mut sharp_sum = 0.0f32;
128        let mut sharp_count = 0u32;
129        for &s in incident_edge_sharpness {
130            if Self::is_semi_sharp(s) {
131                sharp_sum += s;
132                sharp_count += 1;
133            }
134        }
135
136        let blended = if sharp_count > 1 {
137            // Exclude the subject edge itself from the neighbor average:
138            let avg = (sharp_sum - edge_sharpness) / (sharp_count - 1) as f32;
139            0.75 * edge_sharpness + 0.25 * avg
140        } else {
141            edge_sharpness
142        };
143        (blended - 1.0).max(SHARPNESS_SMOOTH)
144    }
145
146    /// Determine the [`Rule`] at a vertex from its own sharpness and the
147    /// number of sharp edges incident to it
148    /// (`Sdc::Crease::DetermineVertexVertexRule`).
149    pub fn determine_vertex_vertex_rule(
150        &self,
151        vertex_sharpness: f32,
152        sharp_edge_count: usize,
153    ) -> Rule {
154        if Self::is_sharp(vertex_sharpness) {
155            return Rule::Corner;
156        }
157        match sharp_edge_count {
158            0 => Rule::Smooth,
159            1 => Rule::Dart,
160            2 => Rule::Crease,
161            _ => Rule::Corner,
162        }
163    }
164
165    /// Transitional weight for blending the mask of the parent rule with the
166    /// mask of the child rule when semi-sharp features decay across a
167    /// refinement step (`Sdc::Crease::ComputeFractionalWeightAtVertex`).
168    ///
169    /// The result is in `[0, 1]`: `1` means the parent rule fully applies,
170    /// `0` means the child rule fully applies. Matching OpenSubdiv, the
171    /// weight is the average fractional sharpness of the *transitional*
172    /// features — features that are sharp in the parent but smooth in the
173    /// child.
174    pub fn compute_fractional_weight_at_vertex(
175        &self,
176        vertex_sharpness: f32,
177        child_vertex_sharpness: f32,
178        incident_edge_sharpness: &[f32],
179        child_edge_sharpness: &[f32],
180    ) -> f32 {
181        debug_assert_eq!(incident_edge_sharpness.len(), child_edge_sharpness.len());
182
183        let mut weight_sum = 0.0f32;
184        let mut count = 0u32;
185
186        if Self::is_sharp(vertex_sharpness) && Self::is_smooth(child_vertex_sharpness) {
187            weight_sum += vertex_sharpness.min(1.0);
188            count += 1;
189        }
190        for (&s, &cs) in incident_edge_sharpness.iter().zip(child_edge_sharpness) {
191            if Self::is_sharp(s) && Self::is_smooth(cs) {
192                weight_sum += s.min(1.0);
193                count += 1;
194            }
195        }
196        if count == 0 {
197            1.0
198        } else {
199            weight_sum / count as f32
200        }
201    }
202
203    /// Sharpen a boundary edge or boundary vertex according to the
204    /// vertex-boundary-interpolation option. Returns the effective sharpness.
205    pub(crate) fn sharpen_boundary_edge(&self, sharpness: f32) -> f32 {
206        use super::options::VtxBoundaryInterpolation::*;
207        match self.options.vtx_boundary_interpolation {
208            None => sharpness,
209            EdgeOnly | EdgeAndCorner => SHARPNESS_INFINITE,
210        }
211    }
212
213    pub(crate) fn sharpen_boundary_corner_vertex(&self, sharpness: f32) -> f32 {
214        use super::options::VtxBoundaryInterpolation::*;
215        match self.options.vtx_boundary_interpolation {
216            None | EdgeOnly => sharpness,
217            EdgeAndCorner => SHARPNESS_INFINITE,
218        }
219    }
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225
226    #[test]
227    fn uniform_subdivision_decrements() {
228        let c = Crease::new(Options::default());
229        assert_eq!(c.subdivide_vertex_sharpness(2.5), 1.5);
230        assert_eq!(c.subdivide_vertex_sharpness(0.5), 0.0);
231        assert_eq!(
232            c.subdivide_vertex_sharpness(SHARPNESS_INFINITE),
233            SHARPNESS_INFINITE
234        );
235    }
236
237    #[test]
238    fn chaikin_averages_neighbors() {
239        let opts = Options::default().with_creasing_method(CreasingMethod::Chaikin);
240        let c = Crease::new(opts);
241        // Edge of sharpness 2 meeting one other sharp edge (sharpness 4) and
242        // two smooth edges: 0.75*2 + 0.25*4 - 1 = 1.5
243        let s = c.subdivide_edge_sharpness_at_vertex(2.0, &[2.0, 4.0, 0.0, 0.0]);
244        assert!((s - 1.5).abs() < 1e-6);
245    }
246
247    #[test]
248    fn chaikin_ignores_infinitely_sharp_neighbors() {
249        let opts = Options::default().with_creasing_method(CreasingMethod::Chaikin);
250        let c = Crease::new(opts);
251        // Edge of sharpness 2 at a boundary vertex whose two other edges are
252        // infinitely sharp boundary edges: no semi-sharp neighbor, so the
253        // sharpness is simply decremented (2 - 1 = 1), as in OpenSubdiv.
254        let s = c.subdivide_edge_sharpness_at_vertex(
255            2.0,
256            &[2.0, SHARPNESS_INFINITE, SHARPNESS_INFINITE],
257        );
258        assert!((s - 1.0).abs() < 1e-6);
259        // Infinite neighbors are skipped, semi-sharp ones still average:
260        // 0.75*2 + 0.25*4 - 1 = 1.5
261        let s = c.subdivide_edge_sharpness_at_vertex(
262            2.0,
263            &[2.0, SHARPNESS_INFINITE, 4.0, 0.0, SHARPNESS_INFINITE],
264        );
265        assert!((s - 1.5).abs() < 1e-6);
266    }
267
268    #[test]
269    fn rules() {
270        let c = Crease::new(Options::default());
271        assert_eq!(c.determine_vertex_vertex_rule(0.0, 0), Rule::Smooth);
272        assert_eq!(c.determine_vertex_vertex_rule(0.0, 1), Rule::Dart);
273        assert_eq!(c.determine_vertex_vertex_rule(0.0, 2), Rule::Crease);
274        assert_eq!(c.determine_vertex_vertex_rule(0.0, 3), Rule::Corner);
275        assert_eq!(c.determine_vertex_vertex_rule(1.0, 0), Rule::Corner);
276    }
277
278    #[test]
279    fn fractional_weight() {
280        let c = Crease::new(Options::default());
281        // A single semi-sharp crease (two edges of sharpness 0.5) decaying to
282        // smooth: fractional weight is 0.5.
283        let w = c.compute_fractional_weight_at_vertex(0.0, 0.0, &[0.5, 0.5, 0.0], &[0.0, 0.0, 0.0]);
284        assert!((w - 0.5).abs() < 1e-6);
285    }
286}