1use std::collections::HashSet;
30
31use crate::{NurbsSurface, Vec3, Vec4};
32
33pub const MAX_T_MESH_LINES: usize = 512;
36
37pub const MIN_T_SPLINE_WEIGHT_RATIO: f64 = 1e-9;
41
42pub const MIN_KNOT_SPAN: f64 = 1e-9;
47
48pub const MAX_T_SPLINE_VALUE: f64 = 1e100;
51
52#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub enum TMeshSegment {
55 Horizontal { j: usize, i0: usize, i1: usize },
57 Vertical { i: usize, j0: usize, j1: usize },
59}
60
61#[derive(Clone, Debug, PartialEq)]
63pub enum TSplineRefusal {
64 Degree { direction: char, degree: usize },
66 Knots { direction: char, index: usize },
68 KnotSpan { direction: char, index: usize, span: f64 },
71 NotClamped { direction: char },
73 Multiplicity { direction: char, value: f64 },
75 Extent { direction: char, lines: usize },
77 Segment { segment: TMeshSegment },
79 Dangling { i: usize, j: usize },
81 Corner { i: usize, j: usize },
83 Ray { i: usize, j: usize },
85 NotAnalysisSuitable { horizontal: (usize, usize), vertical: (usize, usize) },
87 PointCount { expected: usize, found: usize },
89 NonFinite { index: usize },
91 Magnitude { index: usize },
94 Weight { index: usize, weight: f64 },
96 WeightRatio { min: f64, max: f64 },
98 Parameter { u: f64, v: f64 },
100 Conversion { reason: String },
102}
103
104impl std::fmt::Display for TSplineRefusal {
105 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106 match self {
107 Self::Degree { direction, degree } => {
108 write!(f, "t-spline: degree {degree} in {direction}; only odd degrees 1, 3, 5 are supported")
109 }
110 Self::Knots { direction, index } => {
111 write!(f, "t-spline: {direction} knot {index} is not finite, beyond {MAX_T_SPLINE_VALUE}, or decreases")
112 }
113 Self::KnotSpan { direction, index, span } => write!(
114 f,
115 "t-spline: {direction} knots {index} and {} are {span} apart; distinct knots must be more than {MIN_KNOT_SPAN} apart",
116 index + 1
117 ),
118 Self::NotClamped { direction } => write!(
119 f,
120 "t-spline: the {direction} knots must repeat their end values degree + 1 times with a nonzero span between"
121 ),
122 Self::Multiplicity { direction, value } => {
123 write!(f, "t-spline: interior {direction} knot {value} repeats more than the degree")
124 }
125 Self::Extent { direction, lines } => write!(
126 f,
127 "t-spline: {lines} {direction} index lines is outside the supported range (at most {MAX_T_MESH_LINES})"
128 ),
129 Self::Segment { segment } => write!(f, "t-spline: segment {segment:?} is empty or outside the index range"),
130 Self::Dangling { i, j } => {
131 write!(f, "t-spline: an edge ends at ({i}, {j}) without meeting a perpendicular edge")
132 }
133 Self::Corner { i, j } => {
134 write!(f, "t-spline: interior L corner at ({i}, {j}); every T-mesh face must be a rectangle")
135 }
136 Self::Ray { i, j } => write!(f, "t-spline: the knot ray from anchor ({i}, {j}) left the mesh"),
137 Self::NotAnalysisSuitable { horizontal, vertical } => write!(
138 f,
139 "t-spline: not analysis-suitable: the extension of the horizontal T-junction {horizontal:?} meets \
140 that of the vertical T-junction {vertical:?}"
141 ),
142 Self::PointCount { expected, found } => {
143 write!(f, "t-spline: the mesh has {expected} anchors, {found} control points were given")
144 }
145 Self::NonFinite { index } => write!(f, "t-spline: control point {index} is not finite"),
146 Self::Magnitude { index } => {
147 write!(f, "t-spline: control point {index} lies beyond {MAX_T_SPLINE_VALUE} from the origin")
148 }
149 Self::Weight { index, weight } => {
150 write!(f, "t-spline: control point {index} has weight {weight}; weights must be positive")
151 }
152 Self::WeightRatio { min, max } => write!(
153 f,
154 "t-spline: weights span {min}..{max}; the smallest must be at least {MIN_T_SPLINE_WEIGHT_RATIO} of the largest"
155 ),
156 Self::Parameter { u, v } => write!(f, "t-spline: ({u}, {v}) is outside the domain"),
157 Self::Conversion { reason } => write!(f, "t-spline: tensor conversion refused: {reason}"),
158 }
159 }
160}
161
162impl std::error::Error for TSplineRefusal {}
163
164#[derive(Clone, Debug, PartialEq, Eq)]
167pub struct TAnchor {
168 pub i: usize,
169 pub j: usize,
170 pub lines_u: Vec<usize>,
171 pub lines_v: Vec<usize>,
172}
173
174#[derive(Clone, Debug)]
176pub struct TMesh {
177 degree_u: usize,
178 degree_v: usize,
179 knots_u: Vec<f64>,
180 knots_v: Vec<f64>,
181 horizontal: HashSet<(usize, usize)>,
183 vertical: HashSet<(usize, usize)>,
185 anchors: Vec<TAnchor>,
186}
187
188fn check_knots(direction: char, degree: usize, knots: &[f64]) -> Result<(), TSplineRefusal> {
189 if degree % 2 == 0 || degree > 5 {
190 return Err(TSplineRefusal::Degree { direction, degree });
191 }
192 let lines = knots.len();
193 if lines < 2 * degree + 2 || lines > MAX_T_MESH_LINES {
194 return Err(TSplineRefusal::Extent { direction, lines });
195 }
196 for (index, pair) in knots.windows(2).enumerate() {
197 if !(pair[0].abs() <= MAX_T_SPLINE_VALUE && pair[1].abs() <= MAX_T_SPLINE_VALUE) || pair[1] < pair[0] {
198 return Err(TSplineRefusal::Knots { direction, index: index + 1 });
199 }
200 let span = pair[1] - pair[0];
201 if span > 0.0 && span <= MIN_KNOT_SPAN {
204 return Err(TSplineRefusal::KnotSpan { direction, index, span });
205 }
206 }
207 let last = lines - 1;
208 if knots[0] != knots[degree] || knots[last - degree] != knots[last] || !(knots[degree] < knots[last - degree]) {
209 return Err(TSplineRefusal::NotClamped { direction });
210 }
211 if knots[degree + 1] == knots[0] || knots[last - degree - 1] == knots[last] {
212 return Err(TSplineRefusal::NotClamped { direction });
213 }
214 let mut start = degree + 1;
215 while start < last - degree {
216 let mut end = start;
217 while end + 1 < last - degree && knots[end + 1] == knots[start] {
218 end += 1;
219 }
220 let interior_run = end - start + 1;
221 if interior_run > degree {
222 return Err(TSplineRefusal::Multiplicity { direction, value: knots[start] });
223 }
224 start = end + 1;
225 }
226 Ok(())
227}
228
229impl TMesh {
230 pub fn new(
234 degree_u: usize,
235 degree_v: usize,
236 knots_u: Vec<f64>,
237 knots_v: Vec<f64>,
238 segments: &[TMeshSegment],
239 ) -> Result<Self, TSplineRefusal> {
240 check_knots('u', degree_u, &knots_u)?;
241 check_knots('v', degree_v, &knots_v)?;
242 let (mu, mv) = (knots_u.len() - 1, knots_v.len() - 1);
243 let mut horizontal = HashSet::new();
244 let mut vertical = HashSet::new();
245 for segment in segments {
246 match *segment {
247 TMeshSegment::Horizontal { j, i0, i1 } => {
248 if !(i0 < i1 && i1 <= mu && j <= mv) {
249 return Err(TSplineRefusal::Segment { segment: *segment });
250 }
251 horizontal.extend((i0..i1).map(|i| (i, j)));
252 }
253 TMeshSegment::Vertical { i, j0, j1 } => {
254 if !(j0 < j1 && j1 <= mv && i <= mu) {
255 return Err(TSplineRefusal::Segment { segment: *segment });
256 }
257 vertical.extend((j0..j1).map(|j| (i, j)));
258 }
259 }
260 }
261 for j in (0..=degree_v).chain(mv - degree_v..=mv) {
263 horizontal.extend((0..mu).map(|i| (i, j)));
264 }
265 for i in (0..=degree_u).chain(mu - degree_u..=mu) {
266 vertical.extend((0..mv).map(|j| (i, j)));
267 }
268 let mut mesh = Self { degree_u, degree_v, knots_u, knots_v, horizontal, vertical, anchors: Vec::new() };
269 mesh.check_faces()?;
270 mesh.check_analysis_suitable()?;
271 mesh.anchors = mesh.cast_anchors()?;
272 Ok(mesh)
273 }
274
275 pub fn degree_u(&self) -> usize {
276 self.degree_u
277 }
278
279 pub fn degree_v(&self) -> usize {
280 self.degree_v
281 }
282
283 pub fn knots_u(&self) -> &[f64] {
284 &self.knots_u
285 }
286
287 pub fn knots_v(&self) -> &[f64] {
288 &self.knots_v
289 }
290
291 pub fn anchors(&self) -> &[TAnchor] {
293 &self.anchors
294 }
295
296 pub fn domain(&self) -> ([f64; 2], [f64; 2]) {
298 let (mu, mv) = (self.knots_u.len() - 1, self.knots_v.len() - 1);
299 (
300 [self.knots_u[self.degree_u], self.knots_u[mu - self.degree_u]],
301 [self.knots_v[self.degree_v], self.knots_v[mv - self.degree_v]],
302 )
303 }
304
305 fn arms(&self, i: usize, j: usize) -> (bool, bool, bool, bool) {
307 (
308 i > 0 && self.horizontal.contains(&(i - 1, j)),
309 self.horizontal.contains(&(i, j)),
310 j > 0 && self.vertical.contains(&(i, j - 1)),
311 self.vertical.contains(&(i, j)),
312 )
313 }
314
315 fn touches_vertical(&self, i: usize, j: usize) -> bool {
317 let (_, _, down, up) = self.arms(i, j);
318 down || up
319 }
320
321 fn touches_horizontal(&self, i: usize, j: usize) -> bool {
322 let (left, right, _, _) = self.arms(i, j);
323 left || right
324 }
325
326 fn check_faces(&self) -> Result<(), TSplineRefusal> {
327 let (mu, mv) = (self.knots_u.len() - 1, self.knots_v.len() - 1);
328 for j in 1..mv {
329 for i in 1..mu {
330 let (left, right, down, up) = self.arms(i, j);
331 let count = [left, right, down, up].iter().filter(|arm| **arm).count();
332 match count {
333 0 | 4 | 3 => {}
334 1 => return Err(TSplineRefusal::Dangling { i, j }),
335 2 if (left && right) || (down && up) => {}
336 _ => return Err(TSplineRefusal::Corner { i, j }),
337 }
338 }
339 }
340 Ok(())
341 }
342
343 fn ray(&self, i: usize, j: usize, along_u: bool, forward: bool, count: usize) -> Vec<usize> {
346 let (mu, mv) = (self.knots_u.len() - 1, self.knots_v.len() - 1);
347 let mut hits = Vec::with_capacity(count);
348 let mut position = if along_u { i } else { j };
349 let limit = if along_u { mu } else { mv };
350 while hits.len() < count {
351 if forward {
352 if position == limit {
353 break;
354 }
355 position += 1;
356 } else {
357 if position == 0 {
358 break;
359 }
360 position -= 1;
361 }
362 let hit = if along_u { self.touches_vertical(position, j) } else { self.touches_horizontal(i, position) };
363 if hit {
364 hits.push(position);
365 }
366 }
367 hits
368 }
369
370 fn extension(&self, i: usize, j: usize, along_u: bool, missing_forward: bool) -> (usize, usize) {
372 let degree = if along_u { self.degree_u } else { self.degree_v };
373 let at = if along_u { i } else { j };
374 let face = self.ray(i, j, along_u, missing_forward, (degree + 1) / 2);
375 let edge = self.ray(i, j, along_u, !missing_forward, (degree - 1) / 2);
376 let far = |hits: &Vec<usize>| hits.last().copied().unwrap_or(at);
377 let (a, b) = (far(&face), far(&edge));
378 (a.min(b), a.max(b))
379 }
380
381 fn check_analysis_suitable(&self) -> Result<(), TSplineRefusal> {
382 let (mu, mv) = (self.knots_u.len() - 1, self.knots_v.len() - 1);
383 let mut horizontal = Vec::new();
385 let mut vertical = Vec::new();
386 for j in 1..mv {
387 for i in 1..mu {
388 let (left, right, down, up) = self.arms(i, j);
389 if [left, right, down, up].iter().filter(|arm| **arm).count() != 3 {
390 continue;
391 }
392 if !left || !right {
393 horizontal.push(((i, j), self.extension(i, j, true, !right)));
395 } else {
396 vertical.push(((i, j), self.extension(i, j, false, !up)));
397 }
398 }
399 }
400 for &((hi, hj), (i0, i1)) in &horizontal {
401 for &((vi, vj), (j0, j1)) in &vertical {
402 if i0 <= vi && vi <= i1 && j0 <= hj && hj <= j1 {
403 return Err(TSplineRefusal::NotAnalysisSuitable { horizontal: (hi, hj), vertical: (vi, vj) });
404 }
405 }
406 }
407 Ok(())
408 }
409
410 fn cast_anchors(&self) -> Result<Vec<TAnchor>, TSplineRefusal> {
411 let (mu, mv) = (self.knots_u.len() - 1, self.knots_v.len() - 1);
412 let (hu, hv) = ((self.degree_u + 1) / 2, (self.degree_v + 1) / 2);
413 let mut anchors = Vec::new();
414 for j in hv..=mv - hv {
415 for i in hu..=mu - hu {
416 if !(self.touches_horizontal(i, j) && self.touches_vertical(i, j)) {
417 continue;
418 }
419 let lines = |along_u: bool, half: usize| -> Result<Vec<usize>, TSplineRefusal> {
420 let mut before = self.ray(i, j, along_u, false, half);
421 let after = self.ray(i, j, along_u, true, half);
422 if before.len() < half || after.len() < half {
423 return Err(TSplineRefusal::Ray { i, j });
424 }
425 before.reverse();
426 before.push(if along_u { i } else { j });
427 before.extend(after);
428 Ok(before)
429 };
430 anchors.push(TAnchor { i, j, lines_u: lines(true, hu)?, lines_v: lines(false, hv)? });
431 }
432 }
433 Ok(anchors)
434 }
435}
436
437fn single_basis(knots: &[f64], t: f64, end: f64) -> f64 {
440 let degree = knots.len() - 2;
441 let mut values: Vec<f64> = knots
442 .windows(2)
443 .map(|w| {
444 let inside = (w[0] <= t && t < w[1]) || (t == end && w[1] == end && w[0] < w[1]);
445 if inside { 1.0 } else { 0.0 }
446 })
447 .collect();
448 for p in 1..=degree {
449 for r in 0..values.len() - 1 {
450 let mut value = 0.0;
451 let left = knots[r + p] - knots[r];
452 if left > 0.0 {
453 value += (t - knots[r]) / left * values[r];
454 }
455 let right = knots[r + p + 1] - knots[r + 1];
456 if right > 0.0 {
457 value += (knots[r + p + 1] - t) / right * values[r + 1];
458 }
459 values[r] = value;
460 }
461 values.pop();
462 }
463 values[0]
464}
465
466fn refine_onto_global(knots: &[f64], degree: usize, lines: &[usize]) -> (usize, Vec<f64>) {
470 let first = lines[0];
471 let last = *lines.last().unwrap();
472 let mut present: Vec<usize> = lines.to_vec();
473 let mut coefficients = vec![1.0];
474 for g in first + 1..last {
475 if present.contains(&g) {
476 continue;
477 }
478 let t = knots[g];
479 let position = present.iter().position(|&index| index > g).unwrap();
480 let values: Vec<f64> = present.iter().map(|&index| knots[index]).collect();
481 let k = position - 1;
482 let n = coefficients.len();
483 let mut next = Vec::with_capacity(n + 1);
484 for j in 0..=n {
485 let alpha = if j + degree <= k {
486 1.0
487 } else if j >= k + 1 {
488 0.0
489 } else {
490 let span = values[j + degree] - values[j];
491 if span > 0.0 { (t - values[j]) / span } else { 0.0 }
492 };
493 let current = if j < n { coefficients[j] } else { 0.0 };
494 let previous = if j > 0 { coefficients[j - 1] } else { 0.0 };
495 next.push(alpha * current + (1.0 - alpha) * previous);
496 }
497 coefficients = next;
498 present.insert(position, g);
499 }
500 (first, coefficients)
501}
502
503#[derive(Clone, Debug)]
505pub struct TSpline {
506 mesh: TMesh,
507 points: Vec<Vec4>,
509}
510
511impl TSpline {
512 pub fn new(mesh: TMesh, points: Vec<Vec4>) -> Result<Self, TSplineRefusal> {
514 let expected = mesh.anchors.len();
515 if points.len() != expected {
516 return Err(TSplineRefusal::PointCount { expected, found: points.len() });
517 }
518 for (index, point) in points.iter().enumerate() {
519 if !(point.x.is_finite() && point.y.is_finite() && point.z.is_finite() && point.w.is_finite()) {
520 return Err(TSplineRefusal::NonFinite { index });
521 }
522 if !(point.w > 0.0) {
523 return Err(TSplineRefusal::Weight { index, weight: point.w });
524 }
525 if [point.x, point.y, point.z].iter().any(|value| !((value / point.w).abs() <= MAX_T_SPLINE_VALUE)) {
526 return Err(TSplineRefusal::Magnitude { index });
527 }
528 }
529 let max = points.iter().map(|point| point.w).fold(0.0, f64::max);
530 let min = points.iter().map(|point| point.w).fold(f64::INFINITY, f64::min);
531 if min < MIN_T_SPLINE_WEIGHT_RATIO * max {
532 return Err(TSplineRefusal::WeightRatio { min, max });
533 }
534 let points: Vec<Vec4> = points
536 .into_iter()
537 .map(|point| Vec4 { x: point.x / max, y: point.y / max, z: point.z / max, w: point.w / max })
538 .collect();
539 if let Some(index) = points.iter().position(|point| !(point.x.is_finite() && point.y.is_finite() && point.z.is_finite())) {
540 return Err(TSplineRefusal::NonFinite { index });
541 }
542 Ok(Self { mesh, points })
543 }
544
545 pub fn from_points(mesh: TMesh, points: &[Vec3]) -> Result<Self, TSplineRefusal> {
547 Self::new(mesh, points.iter().map(|point| Vec4::from_point(*point, 1.0)).collect())
548 }
549
550 pub fn mesh(&self) -> &TMesh {
551 &self.mesh
552 }
553
554 pub fn points(&self) -> &[Vec4] {
555 &self.points
556 }
557
558 fn check_parameter(&self, u: f64, v: f64) -> Result<(), TSplineRefusal> {
559 let ([u0, u1], [v0, v1]) = self.mesh.domain();
560 if !(u0 <= u && u <= u1 && v0 <= v && v <= v1) {
561 return Err(TSplineRefusal::Parameter { u, v });
562 }
563 Ok(())
564 }
565
566 pub fn blending(&self, index: usize, u: f64, v: f64) -> Result<f64, TSplineRefusal> {
568 self.check_parameter(u, v)?;
569 Ok(self.blending_unchecked(index, u, v))
570 }
571
572 fn blending_unchecked(&self, index: usize, u: f64, v: f64) -> f64 {
573 let anchor = &self.mesh.anchors[index];
574 let ([_, u1], [_, v1]) = self.mesh.domain();
575 let ku: Vec<f64> = anchor.lines_u.iter().map(|&line| self.mesh.knots_u[line]).collect();
576 let kv: Vec<f64> = anchor.lines_v.iter().map(|&line| self.mesh.knots_v[line]).collect();
577 single_basis(&ku, u, u1) * single_basis(&kv, v, v1)
578 }
579
580 pub fn evaluate_homogeneous(&self, u: f64, v: f64) -> Result<Vec4, TSplineRefusal> {
582 self.check_parameter(u, v)?;
583 let mut sum = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
584 for (index, point) in self.points.iter().enumerate() {
585 let value = self.blending_unchecked(index, u, v);
586 if value != 0.0 {
587 sum = sum.add(point.scale(value));
588 }
589 }
590 Ok(sum)
591 }
592
593 pub fn evaluate(&self, u: f64, v: f64) -> Result<Vec3, TSplineRefusal> {
595 let h = self.evaluate_homogeneous(u, v)?;
596 if !(h.w > 0.0) {
597 return Err(TSplineRefusal::Parameter { u, v });
600 }
601 Ok(Vec3::new(h.x / h.w, h.y / h.w, h.z / h.w))
602 }
603
604 pub fn to_nurbs(&self) -> Result<NurbsSurface, TSplineRefusal> {
607 let mesh = &self.mesh;
608 let (du, dv) = (mesh.degree_u, mesh.degree_v);
609 let count_u = mesh.knots_u.len() - du - 1;
610 let count_v = mesh.knots_v.len() - dv - 1;
611 let zero = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
612 let mut net = vec![vec![zero; count_v]; count_u];
613 for (anchor, point) in mesh.anchors.iter().zip(&self.points) {
614 let (first_u, alpha) = refine_onto_global(&mesh.knots_u, du, &anchor.lines_u);
615 let (first_v, beta) = refine_onto_global(&mesh.knots_v, dv, &anchor.lines_v);
616 for (a, alpha) in alpha.iter().enumerate() {
617 if *alpha == 0.0 {
618 continue;
619 }
620 for (b, beta) in beta.iter().enumerate() {
621 let cell = &mut net[first_u + a][first_v + b];
622 *cell = cell.add(point.scale(alpha * beta));
623 }
624 }
625 }
626 NurbsSurface::new(du, dv, mesh.knots_u.clone(), mesh.knots_v.clone(), net)
627 .map_err(|reason| TSplineRefusal::Conversion { reason })
628 }
629}
630