1use crate::{NurbsCurve, NurbsSurface, Vec3, Vec4};
18
19pub const MAX_TRIANGLE_DEGREE: usize = 24;
23
24pub const MIN_WEIGHT_RATIO: f64 = 1e-9;
28
29pub const MAX_TRIANGLE_COORDINATE: f64 = 1e100;
31
32#[derive(Clone, Debug, PartialEq)]
34pub enum BezierTriangleRefusal {
35 Degree { degree: usize },
37 PointCount { degree: usize, expected: usize, found: usize },
39 NonFinite { index: usize },
41 Magnitude { index: usize },
44 Weight { index: usize, weight: f64 },
47 WeightRatio { min: f64, max: f64 },
50 PoleOutside { a: f64, b: f64, c: f64, weight: f64 },
53 Barycentric { a: f64, b: f64, c: f64 },
55 Direction { da: f64, db: f64, dc: f64 },
57 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
110pub enum TriangleSide {
111 OppositeA,
113 OppositeB,
115 OppositeC,
117}
118
119#[derive(Clone, Debug)]
123pub struct TrianglePiece {
124 pub surface: NurbsSurface,
125 pub corners: [[f64; 3]; 4],
126}
127
128impl TrianglePiece {
129 pub fn barycentric(&self, s: f64, t: f64) -> [f64; 3] {
131 bilinear(&self.corners, s, t)
132 }
133}
134
135#[derive(Clone, Debug)]
137pub struct BezierTriangle {
138 degree: usize,
139 points: Vec<Vec4>,
141}
142
143const BARYCENTRIC_SUM: f64 = 1e-12;
144
145impl BezierTriangle {
146 pub fn point_count(degree: usize) -> usize {
148 (degree + 1) * (degree + 2) / 2
149 }
150
151 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 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 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 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 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 pub fn points(&self) -> &[Vec4] {
207 &self.points
208 }
209
210 pub fn control(&self, j: usize, k: usize) -> Vec4 {
212 self.points[Self::index(self.degree, j, k)]
213 }
214
215 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 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 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 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 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 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 TriangleSide::OppositeA => self.control(n - step, step),
307 TriangleSide::OppositeB => self.control(0, n - step),
309 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 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 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 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 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