Skip to main content

brep_geometry/geometry/
bezier_triangle.rs

1//! Triangular (rational) Bézier surfaces (Golovanov 2020 §3.11) and their
2//! exact conversion to tensor-product NURBS patches.
3//!
4//! A degree-`n` patch has `(n+1)(n+2)/2` homogeneous control points
5//! `P_ijk = (w·p, w)`, `i + j + k = n`, and is evaluated at barycentric
6//! coordinates `(a, b, c)` by de Casteljau on the homogeneous points
7//! (3.11.7), then divided by the weight (3.11.9). Corner `P_n00` is at
8//! `(1, 0, 0)`, `P_0n0` at `(0, 1, 0)`, `P_00n` at `(0, 0, 1)`.
9//!
10//! The patch is an input form, not a face carrier: [`BezierTriangle::to_nurbs_quads`]
11//! re-expresses it exactly as three regular bidegree `(n, n)` patches (split
12//! at the centroid and edge midpoints, no collapsed side), and
13//! [`BezierTriangle::to_nurbs_collapsed`] as one patch with side `s = 0`
14//! collapsed to `P_n00`. Both use the polar form (blossom), so the tensor
15//! patches are the same rational function, not a fit.
16
17use crate::{NurbsCurve, NurbsSurface, Vec3, Vec4};
18
19/// Highest supported degree. The blossom and the binomial weights of the
20/// conversion stay well inside f64 range far beyond this; the bound keeps a
21/// malformed request from allocating a huge net.
22pub const MAX_TRIANGLE_DEGREE: usize = 24;
23
24/// Smallest admitted ratio of the least to the largest weight. Every point of
25/// the converted tensor nets is a convex combination of the control points'
26/// homogeneous values, so their weights stay at or above this ratio too.
27pub const MIN_WEIGHT_RATIO: f64 = 1e-9;
28
29/// Largest admitted Cartesian coordinate magnitude of a control point.
30pub const MAX_TRIANGLE_COORDINATE: f64 = 1e100;
31
32/// Why a triangle patch or one of its operations was refused.
33#[derive(Clone, Debug, PartialEq)]
34pub enum BezierTriangleRefusal {
35    /// Degree zero or above [`MAX_TRIANGLE_DEGREE`].
36    Degree { degree: usize },
37    /// The control net does not have `(n+1)(n+2)/2` points.
38    PointCount { degree: usize, expected: usize, found: usize },
39    /// A control point or weight that is not finite.
40    NonFinite { index: usize },
41    /// A control point farther than [`MAX_TRIANGLE_COORDINATE`] from the origin: the
42    /// derivative arithmetic would overflow.
43    Magnitude { index: usize },
44    /// A weight that is not positive: the rational patch would have a pole or
45    /// change sign inside the domain.
46    Weight { index: usize, weight: f64 },
47    /// The smallest weight is below [`MIN_WEIGHT_RATIO`] of the largest: the
48    /// converted tensor net could not hold it.
49    WeightRatio { min: f64, max: f64 },
50    /// The homogeneous weight vanishes or is negative at a point outside the
51    /// triangle (inside it every weight is a positive convex combination).
52    PoleOutside { a: f64, b: f64, c: f64, weight: f64 },
53    /// Barycentric coordinates that are not finite or do not sum to one.
54    Barycentric { a: f64, b: f64, c: f64 },
55    /// A direction whose barycentric components do not sum to zero.
56    Direction { da: f64, db: f64, dc: f64 },
57    /// The tensor patch builder refused the converted net.
58    Conversion { reason: String },
59}
60
61impl std::fmt::Display for BezierTriangleRefusal {
62    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        match self {
64            Self::Degree { degree } => write!(
65                formatter,
66                "bezier triangle: degree {degree} is outside 1..={MAX_TRIANGLE_DEGREE}"
67            ),
68            Self::PointCount { degree, expected, found } => write!(
69                formatter,
70                "bezier triangle: degree {degree} needs {expected} control points, found {found}"
71            ),
72            Self::Magnitude { index } => write!(
73                formatter,
74                "bezier triangle: control point {index} lies beyond {MAX_TRIANGLE_COORDINATE} from the origin"
75            ),
76            Self::NonFinite { index } => {
77                write!(formatter, "bezier triangle: control point {index} is not finite")
78            }
79            Self::WeightRatio { min, max } => write!(
80                formatter,
81                "bezier triangle: weights span {min}..{max}; the smallest must be at least {MIN_WEIGHT_RATIO} of the largest"
82            ),
83            Self::PoleOutside { a, b, c, weight } => write!(
84                formatter,
85                "bezier triangle: the rational patch has weight {weight} at ({a}, {b}, {c}) outside the triangle"
86            ),
87            Self::Weight { index, weight } => write!(
88                formatter,
89                "bezier triangle: control point {index} has weight {weight}; weights must be positive"
90            ),
91            Self::Barycentric { a, b, c } => write!(
92                formatter,
93                "bezier triangle: ({a}, {b}, {c}) are not barycentric coordinates (finite, summing to one)"
94            ),
95            Self::Direction { da, db, dc } => write!(
96                formatter,
97                "bezier triangle: direction ({da}, {db}, {dc}) does not sum to zero"
98            ),
99            Self::Conversion { reason } => {
100                write!(formatter, "bezier triangle: tensor conversion refused: {reason}")
101            }
102        }
103    }
104}
105
106impl std::error::Error for BezierTriangleRefusal {}
107
108/// Which side of the triangle: the side opposite the named corner.
109#[derive(Clone, Copy, Debug, PartialEq, Eq)]
110pub enum TriangleSide {
111    /// `a = 0`: from `P_0n0` (t = 0) to `P_00n` (t = 1).
112    OppositeA,
113    /// `b = 0`: from `P_00n` (t = 0) to `P_n00` (t = 1).
114    OppositeB,
115    /// `c = 0`: from `P_n00` (t = 0) to `P_0n0` (t = 1).
116    OppositeC,
117}
118
119/// One tensor patch of a conversion and the bilinear map from its `(s, t)`
120/// unit square into the triangle: barycentric corners `[Q00, Q10, Q01, Q11]`,
121/// `φ(s, t) = (1−s)(1−t)Q00 + s(1−t)Q10 + (1−s)t Q01 + st Q11`.
122#[derive(Clone, Debug)]
123pub struct TrianglePiece {
124    pub surface: NurbsSurface,
125    pub corners: [[f64; 3]; 4],
126}
127
128impl TrianglePiece {
129    /// The barycentric point of the triangle that `(s, t)` of this piece maps to.
130    pub fn barycentric(&self, s: f64, t: f64) -> [f64; 3] {
131        bilinear(&self.corners, s, t)
132    }
133}
134
135/// A (rational) triangular Bézier patch.
136#[derive(Clone, Debug)]
137pub struct BezierTriangle {
138    degree: usize,
139    /// Homogeneous points in [`BezierTriangle::index`] order.
140    points: Vec<Vec4>,
141}
142
143const BARYCENTRIC_SUM: f64 = 1e-12;
144
145impl BezierTriangle {
146    /// Number of control points of a degree-`n` patch.
147    pub fn point_count(degree: usize) -> usize {
148        (degree + 1) * (degree + 2) / 2
149    }
150
151    /// Storage index of `P_ijk` (`i = n − j − k`): rows of constant `k`, `j`
152    /// increasing inside a row.
153    pub fn index(degree: usize, j: usize, k: usize) -> usize {
154        debug_assert!(j + k <= degree);
155        k * (degree + 1) - k * k.saturating_sub(1) / 2 + j
156    }
157
158    /// A patch from homogeneous points `(w·p, w)` in [`BezierTriangle::index`] order.
159    pub fn new(degree: usize, points: Vec<Vec4>) -> Result<Self, BezierTriangleRefusal> {
160        if degree == 0 || degree > MAX_TRIANGLE_DEGREE {
161            return Err(BezierTriangleRefusal::Degree { degree });
162        }
163        let expected = Self::point_count(degree);
164        if points.len() != expected {
165            return Err(BezierTriangleRefusal::PointCount { degree, expected, found: points.len() });
166        }
167        for (index, point) in points.iter().enumerate() {
168            if !(point.x.is_finite() && point.y.is_finite() && point.z.is_finite() && point.w.is_finite()) {
169                return Err(BezierTriangleRefusal::NonFinite { index });
170            }
171            if !(point.w > 0.0) {
172                return Err(BezierTriangleRefusal::Weight { index, weight: point.w });
173            }
174            if [point.x, point.y, point.z].iter().any(|value| !((value / point.w).abs() <= MAX_TRIANGLE_COORDINATE)) {
175                return Err(BezierTriangleRefusal::Magnitude { index });
176            }
177        }
178        // Normalise the homogeneous scale (geometry unchanged) so the largest
179        // weight is one: the tensor constructors bound weights absolutely.
180        let max = points.iter().map(|point| point.w).fold(0.0, f64::max);
181        let min = points.iter().map(|point| point.w).fold(f64::INFINITY, f64::min);
182        if min < MIN_WEIGHT_RATIO * max {
183            return Err(BezierTriangleRefusal::WeightRatio { min, max });
184        }
185        // Divide (not multiply by 1/max, which overflows for a subnormal max).
186        let points: Vec<Vec4> = points
187            .into_iter()
188            .map(|point| Vec4 { x: point.x / max, y: point.y / max, z: point.z / max, w: point.w / max })
189            .collect();
190        if let Some(index) = points.iter().position(|point| !(point.x.is_finite() && point.y.is_finite() && point.z.is_finite())) {
191            return Err(BezierTriangleRefusal::NonFinite { index });
192        }
193        Ok(Self { degree, points })
194    }
195
196    /// A polynomial patch (all weights one) from Cartesian points.
197    pub fn from_points(degree: usize, points: &[Vec3]) -> Result<Self, BezierTriangleRefusal> {
198        Self::new(degree, points.iter().map(|point| Vec4::from_point(*point, 1.0)).collect())
199    }
200
201    pub fn degree(&self) -> usize {
202        self.degree
203    }
204
205    /// Homogeneous control points in [`BezierTriangle::index`] order.
206    pub fn points(&self) -> &[Vec4] {
207        &self.points
208    }
209
210    /// Homogeneous control point `P_ijk`, `i = n − j − k`.
211    pub fn control(&self, j: usize, k: usize) -> Vec4 {
212        self.points[Self::index(self.degree, j, k)]
213    }
214
215    /// The homogeneous polar form `R(x_1, …, x_n)`: de Casteljau with argument
216    /// `x_m` at level `m`. Symmetric and linear in each argument (arguments
217    /// are barycentric triples; points sum to one, directions to zero).
218    /// `args.len()` must equal the degree.
219    pub fn blossom_homogeneous(&self, args: &[[f64; 3]]) -> Vec4 {
220        assert_eq!(args.len(), self.degree, "blossom needs one argument per degree");
221        let n = self.degree;
222        let mut level = self.points.clone();
223        for (m, arg) in args.iter().enumerate() {
224            let size = n - m - 1;
225            let mut next = Vec::with_capacity(Self::point_count(size));
226            for k in 0..=size {
227                for j in 0..=size - k {
228                    // Points of the previous level (degree size + 1):
229                    // i+1 (same j, k), j+1, k+1.
230                    let pa = level[Self::index(size + 1, j, k)];
231                    let pb = level[Self::index(size + 1, j + 1, k)];
232                    let pc = level[Self::index(size + 1, j, k + 1)];
233                    next.push(pa.scale(arg[0]).add(pb.scale(arg[1])).add(pc.scale(arg[2])));
234                }
235            }
236            level = next;
237        }
238        level[0]
239    }
240
241    fn check_barycentric(a: f64, b: f64, c: f64) -> Result<(), BezierTriangleRefusal> {
242        if !(a.is_finite() && b.is_finite() && c.is_finite()) || (a + b + c - 1.0).abs() > BARYCENTRIC_SUM {
243            return Err(BezierTriangleRefusal::Barycentric { a, b, c });
244        }
245        Ok(())
246    }
247
248    fn check_weight(h: Vec4, a: f64, b: f64, c: f64) -> Result<(), BezierTriangleRefusal> {
249        if !(h.w > 0.0) {
250            return Err(BezierTriangleRefusal::PoleOutside { a, b, c, weight: h.w });
251        }
252        Ok(())
253    }
254
255    /// Homogeneous point at barycentric `(a, b, c)` (3.11.7).
256    pub fn evaluate_homogeneous(&self, a: f64, b: f64, c: f64) -> Result<Vec4, BezierTriangleRefusal> {
257        Self::check_barycentric(a, b, c)?;
258        Ok(self.blossom_homogeneous(&vec![[a, b, c]; self.degree]))
259    }
260
261    /// Point at barycentric `(a, b, c)`.
262    pub fn evaluate(&self, a: f64, b: f64, c: f64) -> Result<Vec3, BezierTriangleRefusal> {
263        let h = self.evaluate_homogeneous(a, b, c)?;
264        Self::check_weight(h, a, b, c)?;
265        Ok(project(h))
266    }
267
268    /// Point and directional derivative along the barycentric direction
269    /// `(da, db, dc)` (components summing to zero), e.g. `(-1, 1, 0)` is
270    /// `∂/∂b` with `c` held. The homogeneous derivative is
271    /// `n·R(d, x, …, x)`, then the quotient rule.
272    pub fn derivative(
273        &self,
274        a: f64,
275        b: f64,
276        c: f64,
277        direction: [f64; 3],
278    ) -> Result<(Vec3, Vec3), BezierTriangleRefusal> {
279        Self::check_barycentric(a, b, c)?;
280        let [da, db, dc] = direction;
281        let scale = da.abs().max(db.abs()).max(dc.abs()).max(1.0);
282        if !(da.is_finite() && db.is_finite() && dc.is_finite()) || (da + db + dc).abs() > BARYCENTRIC_SUM * scale {
283            return Err(BezierTriangleRefusal::Direction { da, db, dc });
284        }
285        let n = self.degree;
286        let mut args = vec![[a, b, c]; n];
287        let h = self.blossom_homogeneous(&args);
288        args[0] = direction;
289        let dh = self.blossom_homogeneous(&args).scale(n as f64);
290        Self::check_weight(h, a, b, c)?;
291        let point = project(h);
292        let derivative = Vec3::new(
293            (dh.x - point.x * dh.w) / h.w,
294            (dh.y - point.y * dh.w) / h.w,
295            (dh.z - point.z * dh.w) / h.w,
296        );
297        Ok((point, derivative))
298    }
299
300    /// The boundary row on `side` as a rational Bézier curve on `[0, 1]`.
301    pub fn side_curve(&self, side: TriangleSide) -> Result<NurbsCurve, BezierTriangleRefusal> {
302        let n = self.degree;
303        let row: Vec<Vec4> = (0..=n)
304            .map(|step| match side {
305                // a = 0: j + k = n, from (j = n, k = 0) to (j = 0, k = n).
306                TriangleSide::OppositeA => self.control(n - step, step),
307                // b = 0: j = 0, from k = n to k = 0.
308                TriangleSide::OppositeB => self.control(0, n - step),
309                // c = 0: k = 0, from j = 0 to j = n.
310                TriangleSide::OppositeC => self.control(step, 0),
311            })
312            .collect();
313        NurbsCurve::new(n, bezier_knots(n), row).map_err(|reason| BezierTriangleRefusal::Conversion { reason })
314    }
315
316    /// The same patch at degree `n + 1` (3.11.8):
317    /// `P*_ijk = (i·P_{i−1,j,k} + j·P_{i,j−1,k} + k·P_{i,j,k−1}) / (n + 1)`.
318    pub fn elevate(&self) -> Result<Self, BezierTriangleRefusal> {
319        let n = self.degree;
320        let up = n + 1;
321        let mut points = Vec::with_capacity(Self::point_count(up));
322        for k in 0..=up {
323            for j in 0..=up - k {
324                let i = up - j - k;
325                let mut sum = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
326                if i > 0 {
327                    sum = sum.add(self.control(j, k).scale(i as f64));
328                }
329                if j > 0 {
330                    sum = sum.add(self.control(j - 1, k).scale(j as f64));
331                }
332                if k > 0 {
333                    sum = sum.add(self.control(j, k - 1).scale(k as f64));
334                }
335                points.push(sum.scale(1.0 / up as f64));
336            }
337        }
338        Self::new(up, points)
339    }
340
341    /// The exact bidegree `(n, n)` tensor patch of the triangle composed with
342    /// the bilinear map of `corners` (`[Q00, Q10, Q01, Q11]`, barycentric).
343    /// Control point `(k, l)` is the symmetrized tensor blossom at
344    /// `(1^k 0^(n−k); 1^l 0^(n−l))`: a hypergeometric average over how many
345    /// `s = 1` slots pair with `t = 1` slots.
346    pub fn compose_bilinear(&self, corners: [[f64; 3]; 4]) -> Result<TrianglePiece, BezierTriangleRefusal> {
347        let n = self.degree;
348        let [q00, q10, q01, q11] = corners;
349        let mut rows = Vec::with_capacity(n + 1);
350        for k in 0..=n {
351            let mut row = Vec::with_capacity(n + 1);
352            for l in 0..=n {
353                let mut sum = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
354                let low = (k + l).saturating_sub(n);
355                for m in low..=k.min(l) {
356                    let probability =
357                        binomial(k, m) * binomial(n - k, l - m) / binomial(n, l);
358                    let mut args = Vec::with_capacity(n);
359                    args.extend(std::iter::repeat(q11).take(m));
360                    args.extend(std::iter::repeat(q10).take(k - m));
361                    args.extend(std::iter::repeat(q01).take(l - m));
362                    args.extend(std::iter::repeat(q00).take(n + m - k - l));
363                    sum = sum.add(self.blossom_homogeneous(&args).scale(probability));
364                }
365                row.push(sum);
366            }
367            rows.push(row);
368        }
369        let surface = NurbsSurface::new(n, n, bezier_knots(n), bezier_knots(n), rows)
370            .map_err(|reason| BezierTriangleRefusal::Conversion { reason })?;
371        Ok(TrianglePiece { surface, corners })
372    }
373
374    /// The exact conversion into three regular `(n, n)` patches, one per
375    /// corner: piece `v` spans corner `V_v`, the midpoints of its two sides
376    /// and the centroid, with `s` running toward the next corner's side
377    /// midpoint and `t` toward the previous one's (each piece keeps the
378    /// triangle's orientation). Adjacent pieces share their common side
379    /// exactly: it is the image of one straight domain segment.
380    pub fn to_nurbs_quads(&self) -> Result<[TrianglePiece; 3], BezierTriangleRefusal> {
381        let vertex = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
382        let midpoint = |p: usize, q: usize| -> [f64; 3] {
383            let mut m = [0.0; 3];
384            m[p] = 0.5;
385            m[q] = 0.5;
386            m
387        };
388        let third = 1.0 / 3.0;
389        let centroid = [third, third, third];
390        let piece = |v: usize| -> Result<TrianglePiece, BezierTriangleRefusal> {
391            let next = (v + 1) % 3;
392            let previous = (v + 2) % 3;
393            self.compose_bilinear([vertex[v], midpoint(v, next), midpoint(previous, v), centroid])
394        };
395        Ok([piece(0)?, piece(1)?, piece(2)?])
396    }
397
398    /// The exact conversion into one `(n, n)` patch through
399    /// `(s, t) ↦ (1 − s, s(1 − t), s t)`: side `s = 0` is collapsed to the
400    /// corner `P_n00` (a pole), `s = 1` is the side `a = 0`.
401    pub fn to_nurbs_collapsed(&self) -> Result<TrianglePiece, BezierTriangleRefusal> {
402        let corner = [1.0, 0.0, 0.0];
403        self.compose_bilinear([corner, [0.0, 1.0, 0.0], corner, [0.0, 0.0, 1.0]])
404    }
405}
406
407fn project(h: Vec4) -> Vec3 {
408    Vec3::new(h.x / h.w, h.y / h.w, h.z / h.w)
409}
410
411fn bilinear(corners: &[[f64; 3]; 4], s: f64, t: f64) -> [f64; 3] {
412    let [q00, q10, q01, q11] = corners;
413    let mut out = [0.0; 3];
414    for axis in 0..3 {
415        out[axis] = (1.0 - s) * (1.0 - t) * q00[axis]
416            + s * (1.0 - t) * q10[axis]
417            + (1.0 - s) * t * q01[axis]
418            + s * t * q11[axis];
419    }
420    out
421}
422
423fn bezier_knots(degree: usize) -> Vec<f64> {
424    let mut knots = vec![0.0; degree + 1];
425    knots.extend(std::iter::repeat(1.0).take(degree + 1));
426    knots
427}
428
429fn binomial(n: usize, k: usize) -> f64 {
430    if k > n {
431        return 0.0;
432    }
433    let k = k.min(n - k);
434    let mut value = 1.0;
435    for step in 0..k {
436        value = value * (n - step) as f64 / (step + 1) as f64;
437    }
438    value
439}
440