1use crate::surface::{KnotDirection, KnotRefinementRefusal};
32use crate::{KnotVector, NurbsSurface, Vec3, Vec4};
33
34pub const MAX_DEFORM_POLES: usize = 4096;
38pub const MAX_DEFORM_DEGREE: usize = 9;
40pub const MAX_DEFORM_PICKS: usize = 64;
42pub const MAX_DEFORM_CONDITION: f64 = 1e12;
45const DEPENDENCE_FRACTION: f64 = 1e-10;
48pub const MAX_DEFORM_DISPLACEMENT_RATIO: f64 = 1.0;
51const MEMBRANE_WEIGHT: f64 = 1e-2;
54const SIZE_WEIGHT: f64 = 1e-6;
55pub const MAX_DEFORM_AMPLIFICATION: f64 = 25.0;
59const ROUND_OFF: f64 = 1e-14;
61const FOLD_SAMPLES_PER_SPAN: usize = 6;
63
64#[derive(Clone, Copy, Debug)]
66pub struct DeformPick {
67 pub u: f64,
68 pub v: f64,
69 pub target: Vec3,
71 pub normal: Option<Vec3>,
73}
74
75#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
77pub enum EdgeHold {
78 #[default]
80 Free,
81 Position,
83 Tangent,
86}
87
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub enum DeformSide {
91 UMin,
92 UMax,
93 VMin,
94 VMax,
95}
96
97const SIDES: [DeformSide; 4] = [DeformSide::UMin, DeformSide::UMax, DeformSide::VMin, DeformSide::VMax];
98
99#[derive(Clone, Debug)]
100pub struct DeformSpec {
101 pub picks: Vec<DeformPick>,
102 pub hold: [EdgeHold; 4],
104 pub min_degree: usize,
107 pub split_spans: [usize; 2],
110 pub split_window: Option<[f64; 4]>,
114}
115
116impl Default for DeformSpec {
117 fn default() -> Self {
118 Self { picks: Vec::new(), hold: [EdgeHold::Free; 4], min_degree: 3, split_spans: [1, 1], split_window: None }
119 }
120}
121
122#[derive(Clone, Debug)]
124pub struct DeformResult {
125 pub surface: NurbsSurface,
126 pub net: (usize, usize),
128 pub free_poles: usize,
130 pub max_pick_error: f64,
133 pub max_normal_error: f64,
136 pub max_pole_shift: f64,
138 pub condition: f64,
140}
141
142#[derive(Clone, Debug, PartialEq)]
143pub enum DeformRefusal {
144 InvalidSurface(String),
145 InvalidWeights { row: usize, column: usize },
147 UnclampedKnots { direction: KnotDirection },
150 NoPicks,
151 TooManyPicks { count: usize, limit: usize },
152 NetTooLarge { poles: usize, limit: usize },
153 InvalidSpec(String),
155 InvalidPick { index: usize, reason: String },
158 DuplicatePicks { first: usize, second: usize },
160 PickOnHeldRegion { index: usize },
163 DependentConstraints { index: usize },
167 IllConditioned { estimate: f64, limit: f64 },
168 DisplacementTooLarge { index: usize, displacement: f64, limit: f64 },
169 ClosedDirectionNotHeld { direction: KnotDirection },
172 CollapsedSideNotHeld { side: DeformSide },
175 Folded { u: f64, v: f64 },
177 Amplified { ratio: f64, limit: f64 },
182 InvalidTie { tie: usize, reason: String },
185 EdgeRowsDisagree { tie: usize, gap: f64 },
188 EdgeNotUniformlyTangent { tie: usize, reason: String },
192 DependentTie { tie: usize },
194 TooManyConstraints { rows: usize, limit: usize },
196 EdgeFoldedThrough { tie: usize, t: f64 },
199 Refinement(KnotRefinementRefusal),
200}
201
202impl std::fmt::Display for DeformRefusal {
203 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
204 write!(f, "deform surface: {self:?}")
205 }
206}
207
208impl std::error::Error for DeformRefusal {}
209
210pub fn deform_surface(surface: &NurbsSurface, spec: &DeformSpec) -> Result<DeformResult, DeformRefusal> {
212 deform_surface_where(surface, spec, &|_: PoleSupport| true)
213}
214
215#[derive(Clone, Copy, Debug, PartialEq)]
217pub struct PoleSupport {
218 pub bounds: [f64; 4],
221 pub vanishing: [usize; 4],
227}
228
229pub fn deform_surface_where(
237 surface: &NurbsSurface,
238 spec: &DeformSpec,
239 may_move: &dyn Fn(PoleSupport) -> bool,
240) -> Result<DeformResult, DeformRefusal> {
241 surface.domain_u().map_err(DeformRefusal::InvalidSurface)?;
242 for (row, line) in surface.control_points.iter().enumerate() {
243 for (column, pole) in line.iter().enumerate() {
244 if !(pole.w.is_finite() && pole.w > 0.0) || ![pole.x, pole.y, pole.z].iter().all(|c| c.is_finite()) {
245 return Err(DeformRefusal::InvalidWeights { row, column });
246 }
247 }
248 }
249 if spec.min_degree < 2 || spec.min_degree > MAX_DEFORM_DEGREE || spec.split_spans.contains(&0) {
250 return Err(DeformRefusal::InvalidSpec(format!(
251 "min_degree {} (2 to {MAX_DEFORM_DEGREE}) and split_spans {:?} (at least 1)",
252 spec.min_degree, spec.split_spans
253 )));
254 }
255 if spec.picks.is_empty() {
256 return Err(DeformRefusal::NoPicks);
257 }
258 if spec.picks.len() > MAX_DEFORM_PICKS {
259 return Err(DeformRefusal::TooManyPicks { count: spec.picks.len(), limit: MAX_DEFORM_PICKS });
260 }
261 for direction in [KnotDirection::U, KnotDirection::V] {
262 let (degree, knots) = knots_of(surface, direction);
263 let n = knots.len();
264 if knots[..=degree].iter().any(|&k| k != knots[degree])
265 || knots[n - 1 - degree..].iter().any(|&k| k != knots[n - 1])
266 {
267 return Err(DeformRefusal::UnclampedKnots { direction });
268 }
269 }
270 let [u0, u1] = surface.domain_u().map_err(DeformRefusal::InvalidSurface)?;
271 let [v0, v1] = surface.domain_v().map_err(DeformRefusal::InvalidSurface)?;
272 for (index, pick) in spec.picks.iter().enumerate() {
273 let finite = [pick.u, pick.v, pick.target.x, pick.target.y, pick.target.z].iter().all(|c| c.is_finite());
274 if !finite {
275 return Err(DeformRefusal::InvalidPick { index, reason: "non-finite parameter or target".into() });
276 }
277 if pick.u < u0 || pick.u > u1 || pick.v < v0 || pick.v > v1 {
278 return Err(DeformRefusal::InvalidPick {
279 index,
280 reason: format!("({}, {}) outside the domain [{u0}, {u1}] x [{v0}, {v1}]", pick.u, pick.v),
281 });
282 }
283 if let Some(normal) = pick.normal {
284 let length = normal.length();
285 if !length.is_finite() || length <= f64::MIN_POSITIVE.sqrt() {
286 return Err(DeformRefusal::InvalidPick { index, reason: "zero or non-finite normal".into() });
287 }
288 }
289 }
290 let (du, dv) = ((u1 - u0).max(f64::MIN_POSITIVE), (v1 - v0).max(f64::MIN_POSITIVE));
291 for first in 0..spec.picks.len() {
292 for second in first + 1..spec.picks.len() {
293 let (a, b) = (spec.picks[first], spec.picks[second]);
294 if ((a.u - b.u) / du).abs() <= 1e-9 && ((a.v - b.v) / dv).abs() <= 1e-9 {
295 return Err(DeformRefusal::DuplicatePicks { first, second });
296 }
297 }
298 }
299 let base = prepare_base(surface, spec)?;
300 let rows = base.control_points.len();
301 let columns = base.control_points[0].len();
302
303 let depth = |hold: EdgeHold| match hold {
305 EdgeHold::Free => 0,
306 EdgeHold::Position => 1,
307 EdgeHold::Tangent => 2,
308 };
309 let (i_lo, i_hi) = (depth(spec.hold[0]), rows.saturating_sub(depth(spec.hold[1])));
310 let (j_lo, j_hi) = (depth(spec.hold[2]), columns.saturating_sub(depth(spec.hold[3])));
311 let mut free_index = vec![vec![usize::MAX; columns]; rows];
312 let mut free = Vec::new();
313 let (pu, pv) = (base.degree_u, base.degree_v);
314 for i in i_lo..i_hi.max(i_lo) {
315 for j in j_lo..j_hi.max(j_lo) {
316 let (ku, kv) = (&base.knots_u[i..=i + pu + 1], &base.knots_v[j..=j + pv + 1]);
317 let order = |local: &[f64], end: f64, degree: usize| (degree + 1).saturating_sub(local.iter().filter(|&&k| k == end).count());
318 let support = PoleSupport {
319 bounds: [ku[0], ku[pu + 1], kv[0], kv[pv + 1]],
320 vanishing: [order(ku, ku[0], pu), order(ku, ku[pu + 1], pu), order(kv, kv[0], pv), order(kv, kv[pv + 1], pv)],
321 };
322 if may_move(support) {
323 free_index[i][j] = free.len();
324 free.push((i, j));
325 }
326 }
327 }
328 let row_free = |i: usize| (0..columns).any(|j| free_index[i][j] != usize::MAX);
332 let column_free = |j: usize| (0..rows).any(|i| free_index[i][j] != usize::MAX);
333 let (closed_u, closed_v) = base.closed_directions().map_err(DeformRefusal::InvalidSurface)?;
334 if closed_u && [0, 1, rows - 2, rows - 1].into_iter().any(row_free) {
335 return Err(DeformRefusal::ClosedDirectionNotHeld { direction: KnotDirection::U });
336 }
337 if closed_v && [0, 1, columns - 2, columns - 1].into_iter().any(column_free) {
338 return Err(DeformRefusal::ClosedDirectionNotHeld { direction: KnotDirection::V });
339 }
340 for side in SIDES {
341 let near = match side {
342 DeformSide::UMin => row_free(0) || row_free(1),
343 DeformSide::UMax => row_free(rows - 1) || row_free(rows - 2),
344 DeformSide::VMin => column_free(0) || column_free(1),
345 DeformSide::VMax => column_free(columns - 1) || column_free(columns - 2),
346 };
347 if near && side_collapsed(&base, side) {
348 return Err(DeformRefusal::CollapsedSideNotHeld { side });
349 }
350 }
351
352 let diagonal = net_diagonal(&base);
354 let displacement_limit = MAX_DEFORM_DISPLACEMENT_RATIO * diagonal;
355 let mut constraints: Vec<Constraint> = Vec::new();
356 let mut requested = 0.0f64;
357 pick_constraints(&base, &spec.picks, &free_index, 0, 0, displacement_limit, &mut constraints, &mut requested)?;
358
359 let (displacements, condition) = if constraints.iter().all(|c| c.rhs == 0.0) {
361 (vec![0.0; 3 * free.len()], 1.0)
362 } else {
363 let energy = BandedEnergy::build(&base, &free, &free_index)?;
364 solve(&energy, &constraints)?
365 };
366
367 let mut net = base.control_points.clone();
369 let mut max_pole_shift = 0.0f64;
370 for (f, &(i, j)) in free.iter().enumerate() {
371 let d = Vec3::new(displacements[3 * f], displacements[3 * f + 1], displacements[3 * f + 2]);
372 if d.x == 0.0 && d.y == 0.0 && d.z == 0.0 {
373 continue;
374 }
375 let pole = net[i][j];
376 net[i][j] = Vec4 { x: pole.x + d.x * pole.w, y: pole.y + d.y * pole.w, z: pole.z + d.z * pole.w, w: pole.w };
377 max_pole_shift = max_pole_shift.max(d.length());
378 }
379 let deformed = NurbsSurface::new(base.degree_u, base.degree_v, base.knots_u.clone(), base.knots_v.clone(), net)
380 .map_err(DeformRefusal::InvalidSurface)?;
381
382 if max_pole_shift > MAX_DEFORM_AMPLIFICATION * requested {
383 return Err(DeformRefusal::Amplified {
384 ratio: max_pole_shift / requested.max(f64::MIN_POSITIVE),
385 limit: MAX_DEFORM_AMPLIFICATION,
386 });
387 }
388 check_fold(&base, &deformed)?;
389 let mut max_pick_error = 0.0f64;
390 let mut max_normal_error = 0.0f64;
391 for pick in &spec.picks {
392 let point = deformed.evaluate(pick.u, pick.v).map_err(DeformRefusal::InvalidSurface)?;
393 max_pick_error = max_pick_error.max(point.sub(pick.target).length());
394 if let Some(normal) = pick.normal {
395 let (_, su, sv) = deformed.deriv1(pick.u, pick.v).map_err(DeformRefusal::InvalidSurface)?;
396 let n = su.cross(sv);
397 let sine = n.cross(normal).length() / (n.length() * normal.length()).max(f64::MIN_POSITIVE);
398 max_normal_error = max_normal_error.max(sine.min(1.0).asin());
399 }
400 }
401 Ok(DeformResult {
402 surface: deformed,
403 net: (rows, columns),
404 free_poles: free.len(),
405 max_pick_error,
406 max_normal_error,
407 max_pole_shift,
408 condition,
409 })
410}
411
412pub(crate) fn prepare_base(surface: &NurbsSurface, spec: &DeformSpec) -> Result<NurbsSurface, DeformRefusal> {
417 surface.domain_u().map_err(DeformRefusal::InvalidSurface)?;
418 for (row, line) in surface.control_points.iter().enumerate() {
419 for (column, pole) in line.iter().enumerate() {
420 if !(pole.w.is_finite() && pole.w > 0.0) || ![pole.x, pole.y, pole.z].iter().all(|c| c.is_finite()) {
421 return Err(DeformRefusal::InvalidWeights { row, column });
422 }
423 }
424 }
425 if spec.min_degree < 2 || spec.min_degree > MAX_DEFORM_DEGREE || spec.split_spans.contains(&0) {
426 return Err(DeformRefusal::InvalidSpec(format!(
427 "min_degree {} (2 to {MAX_DEFORM_DEGREE}) and split_spans {:?} (at least 1)",
428 spec.min_degree, spec.split_spans
429 )));
430 }
431 for direction in [KnotDirection::U, KnotDirection::V] {
432 let (degree, knots) = knots_of(surface, direction);
433 let n = knots.len();
434 if knots[..=degree].iter().any(|&k| k != knots[degree])
435 || knots[n - 1 - degree..].iter().any(|&k| k != knots[n - 1])
436 {
437 return Err(DeformRefusal::UnclampedKnots { direction });
438 }
439 }
440 let mut predicted = 1usize;
445 for (axis, direction) in [KnotDirection::U, KnotDirection::V].into_iter().enumerate() {
446 let (degree, knots) = knots_of(surface, direction);
447 let spans = knots.windows(2).filter(|pair| pair[1] > pair[0]).count();
448 let split = knots.windows(2).filter(|pair| pair[1] > pair[0] && in_window(spec, axis, pair)).count();
449 let count = knots.len() - degree - 1;
450 let raise = spec.min_degree.saturating_sub(degree);
451 let lines = raise
452 .checked_mul(spans)
453 .and_then(|extra| extra.checked_add(count))
454 .and_then(|lines| (spec.split_spans[axis] - 1).checked_mul(split).and_then(|extra| lines.checked_add(extra)));
455 predicted = match lines.and_then(|lines| predicted.checked_mul(lines)) {
456 Some(value) if value <= MAX_DEFORM_POLES => value,
457 _ => return Err(DeformRefusal::NetTooLarge { poles: usize::MAX, limit: MAX_DEFORM_POLES }),
458 };
459 }
460
461 let mut base = surface.clone();
463 for direction in [KnotDirection::U, KnotDirection::V] {
464 let (degree, _) = knots_of(&base, direction);
465 if degree < spec.min_degree {
466 base = base.elevate_degree(direction, spec.min_degree).map_err(DeformRefusal::InvalidSurface)?;
467 }
468 let pieces = spec.split_spans[match direction {
469 KnotDirection::U => 0,
470 KnotDirection::V => 1,
471 }];
472 if pieces > 1 {
473 let axis = match direction {
474 KnotDirection::U => 0,
475 KnotDirection::V => 1,
476 };
477 let (_, knots) = knots_of(&base, direction);
478 let mut inserts = Vec::new();
479 for pair in knots.windows(2) {
480 if pair[1] > pair[0] && in_window(spec, axis, pair) {
481 for k in 1..pieces {
482 inserts.push(pair[0] + (pair[1] - pair[0]) * k as f64 / pieces as f64);
483 }
484 }
485 }
486 base = base.refine_knots(direction, &inserts).map_err(DeformRefusal::Refinement)?;
487 }
488 }
489 let (rows, columns) = (base.control_points.len(), base.control_points[0].len());
490 if rows * columns > MAX_DEFORM_POLES {
491 return Err(DeformRefusal::NetTooLarge { poles: rows * columns, limit: MAX_DEFORM_POLES });
492 }
493 Ok(base)
494}
495
496#[allow(clippy::too_many_arguments)]
500fn pick_constraints(
501 base: &NurbsSurface,
502 picks: &[DeformPick],
503 free_index: &[Vec<usize>],
504 offset: usize,
505 first_pick: usize,
506 displacement_limit: f64,
507 constraints: &mut Vec<Constraint>,
508 requested: &mut f64,
509) -> Result<(), DeformRefusal> {
510 let diagonal = net_diagonal(base);
511 for (local_index, pick) in picks.iter().enumerate() {
512 let index = first_pick + local_index;
513 let local = RationalBasis::at(base, pick.u, pick.v).map_err(DeformRefusal::InvalidSurface)?;
514 let delta = pick.target.sub(local.point);
515 let displacement = delta.length();
516 if !(displacement <= displacement_limit) {
517 return Err(DeformRefusal::DisplacementTooLarge { index, displacement, limit: displacement_limit });
518 }
519 *requested = requested.max(displacement);
520 if let Some(normal) = pick.normal {
521 let current = local.du.cross(local.dv);
522 let sine = current.cross(normal).length() / (current.length() * normal.length()).max(f64::MIN_POSITIVE);
523 *requested = requested.max(sine.min(1.0).asin() * diagonal);
524 }
525 for axis in 0..3 {
530 let terms: Vec<(usize, f64)> =
531 local.terms(free_index, |r, _, _| r, axis).into_iter().map(|(i, c)| (i + 3 * offset, c)).collect();
532 let scale = local.cartesian.iter().map(|p| component(*p, axis).abs()).fold(0.0, f64::max);
533 push_constraint(constraints, index, terms, component(delta, axis), scale, 1.0)?;
534 }
535 if let Some(normal) = pick.normal {
536 let normal = normal.normalized().map_err(DeformRefusal::InvalidSurface)?;
537 for partial in [Partial::U, Partial::V] {
538 let mut terms = Vec::new();
539 let mut rhs = 0.0;
540 let mut whole_reach = 0.0f64;
541 let mut round_off_scale = 0.0f64;
542 for (k, (ru, rv)) in local.partials.iter().enumerate() {
543 let r = match partial {
544 Partial::U => *ru,
545 Partial::V => *rv,
546 };
547 whole_reach = whole_reach.max(r.abs());
548 round_off_scale += (r * local.cartesian[k].dot(normal)).abs();
549 let (i, j) = local.poles[k];
550 rhs -= r * local.cartesian[k].dot(normal);
551 let f = free_index[i][j];
552 if f != usize::MAX && r != 0.0 {
553 for axis in 0..3 {
554 terms.push((3 * (offset + f) + axis, r * component(normal, axis)));
555 }
556 }
557 }
558 push_constraint(constraints, index, terms, rhs, round_off_scale, whole_reach)?;
559 }
560 }
561 }
562 Ok(())
563}
564
565fn in_window(spec: &DeformSpec, axis: usize, pair: &[f64]) -> bool {
567 match spec.split_window {
568 None => true,
569 Some(window) => {
570 let (lo, hi) = (window[2 * axis], window[2 * axis + 1]);
571 pair[1] > lo && pair[0] < hi
572 }
573 }
574}
575
576fn knots_of(surface: &NurbsSurface, direction: KnotDirection) -> (usize, &Vec<f64>) {
577 match direction {
578 KnotDirection::U => (surface.degree_u, &surface.knots_u),
579 KnotDirection::V => (surface.degree_v, &surface.knots_v),
580 }
581}
582
583fn component(v: Vec3, axis: usize) -> f64 {
584 match axis {
585 0 => v.x,
586 1 => v.y,
587 _ => v.z,
588 }
589}
590
591fn cartesian(pole: Vec4) -> Vec3 {
592 Vec3::new(pole.x / pole.w, pole.y / pole.w, pole.z / pole.w)
593}
594
595fn side_collapsed(surface: &NurbsSurface, side: DeformSide) -> bool {
596 let rows = surface.control_points.len();
597 let columns = surface.control_points[0].len();
598 let line: Vec<Vec3> = match side {
599 DeformSide::UMin => surface.control_points[0].iter().copied().map(cartesian).collect(),
600 DeformSide::UMax => surface.control_points[rows - 1].iter().copied().map(cartesian).collect(),
601 DeformSide::VMin => surface.control_points.iter().map(|row| cartesian(row[0])).collect(),
602 DeformSide::VMax => surface.control_points.iter().map(|row| cartesian(row[columns - 1])).collect(),
603 };
604 let scale = net_diagonal(surface).max(f64::MIN_POSITIVE);
605 line.iter().all(|p| p.sub(line[0]).length() <= 1e-12 * scale)
606}
607
608fn net_diagonal(surface: &NurbsSurface) -> f64 {
609 let mut lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
610 let mut hi = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
611 for pole in surface.control_points.iter().flatten() {
612 let p = cartesian(*pole);
613 lo = Vec3::new(lo.x.min(p.x), lo.y.min(p.y), lo.z.min(p.z));
614 hi = Vec3::new(hi.x.max(p.x), hi.y.max(p.y), hi.z.max(p.z));
615 }
616 hi.sub(lo).length()
617}
618
619#[derive(Clone, Copy)]
620enum Partial {
621 U,
622 V,
623}
624
625struct RationalBasis {
629 poles: Vec<(usize, usize)>,
630 values: Vec<f64>,
631 partials: Vec<(f64, f64)>,
632 cartesian: Vec<Vec3>,
633 point: Vec3,
634 du: Vec3,
635 dv: Vec3,
636}
637
638impl RationalBasis {
639 fn at(surface: &NurbsSurface, u: f64, v: f64) -> Result<Self, String> {
640 let ku = KnotVector::new(surface.knots_u.clone(), surface.degree_u)?;
641 let kv = KnotVector::new(surface.knots_v.clone(), surface.degree_v)?;
642 let (u, v) = (ku.clamp_param(u), kv.clamp_param(v));
643 let (su, sv) = (ku.find_span(u), kv.find_span(v));
644 let nu = ku.basis_derivatives(su, u, 1);
645 let nv = kv.basis_derivatives(sv, v, 1);
646 let (pu, pv) = (surface.degree_u, surface.degree_v);
647 let (mut w, mut wu, mut wv) = (0.0, 0.0, 0.0);
648 for a in 0..=pu {
649 for b in 0..=pv {
650 let weight = surface.control_points[su - pu + a][sv - pv + b].w;
651 w += nu[0][a] * nv[0][b] * weight;
652 wu += nu[1][a] * nv[0][b] * weight;
653 wv += nu[0][a] * nv[1][b] * weight;
654 }
655 }
656 if !(w > 0.0) {
657 return Err(format!("deform: rational denominator {w} at ({u}, {v})"));
658 }
659 let mut basis = Self {
660 poles: Vec::new(),
661 values: Vec::new(),
662 partials: Vec::new(),
663 cartesian: Vec::new(),
664 point: Vec3::default(),
665 du: Vec3::default(),
666 dv: Vec3::default(),
667 };
668 for a in 0..=pu {
669 for b in 0..=pv {
670 let (i, j) = (su - pu + a, sv - pv + b);
671 let pole = surface.control_points[i][j];
672 let n = nu[0][a] * nv[0][b] * pole.w;
673 let r = n / w;
674 let ru = (nu[1][a] * nv[0][b] * pole.w * w - n * wu) / (w * w);
675 let rv = (nu[0][a] * nv[1][b] * pole.w * w - n * wv) / (w * w);
676 let p = cartesian(pole);
677 basis.point = basis.point.add(p.scale(r));
678 basis.du = basis.du.add(p.scale(ru));
679 basis.dv = basis.dv.add(p.scale(rv));
680 basis.poles.push((i, j));
681 basis.values.push(r);
682 basis.partials.push((ru, rv));
683 basis.cartesian.push(p);
684 }
685 }
686 Ok(basis)
687 }
688
689 fn terms(
691 &self,
692 free_index: &[Vec<usize>],
693 coefficient: impl Fn(f64, f64, f64) -> f64,
694 axis: usize,
695 ) -> Vec<(usize, f64)> {
696 let mut out = Vec::new();
697 for (k, &(i, j)) in self.poles.iter().enumerate() {
698 let f = free_index[i][j];
699 let c = coefficient(self.values[k], self.partials[k].0, self.partials[k].1);
700 if f != usize::MAX && c != 0.0 {
701 out.push((3 * f + axis, c));
702 }
703 }
704 out
705 }
706}
707
708struct Constraint {
711 pick: usize,
712 tie: Option<usize>,
714 terms: Vec<(usize, f64)>,
715 rhs: f64,
716}
717
718fn push_constraint(
727 constraints: &mut Vec<Constraint>,
728 pick: usize,
729 terms: Vec<(usize, f64)>,
730 rhs: f64,
731 scale: f64,
732 whole_reach: f64,
733) -> Result<(), DeformRefusal> {
734 let rhs = if rhs.abs() <= ROUND_OFF * scale { 0.0 } else { rhs };
737 let reach = terms.iter().map(|(_, c)| c.abs()).fold(0.0, f64::max);
738 if !(reach > 1e-12 * whole_reach) {
739 if rhs == 0.0 {
740 return Ok(());
741 }
742 return Err(DeformRefusal::PickOnHeldRegion { index: pick });
743 }
744 let norm = terms.iter().map(|(_, c)| c * c).sum::<f64>().sqrt();
745 let terms = terms.into_iter().map(|(index, c)| (index, c / norm)).collect();
746 constraints.push(Constraint { pick, tie: None, terms, rhs: rhs / norm });
747 Ok(())
748}
749
750struct BandedEnergy {
756 n: usize,
757 bandwidth: usize,
758 factor: Vec<Vec<f64>>,
760}
761
762impl BandedEnergy {
763 fn build(surface: &NurbsSurface, free: &[(usize, usize)], free_index: &[Vec<usize>]) -> Result<Self, DeformRefusal> {
764 let gu = gram(&surface.knots_u, surface.degree_u);
765 let gv = gram(&surface.knots_v, surface.degree_v);
766 let (pu, pv) = (surface.degree_u, surface.degree_v);
767 let rows = surface.control_points.len();
768 let columns = surface.control_points[0].len();
769 let n = free.len();
770 let mut bandwidth = 0;
771 for (k, &(i, j)) in free.iter().enumerate() {
772 for i2 in i.saturating_sub(pu)..=(i + pu).min(rows - 1) {
773 for j2 in j.saturating_sub(pv)..=(j + pv).min(columns - 1) {
774 let f = free_index[i2][j2];
775 if f != usize::MAX && f <= k {
776 bandwidth = bandwidth.max(k - f);
777 }
778 }
779 }
780 }
781 let mut band = vec![vec![0.0; bandwidth + 1]; n];
782 for (k, &(i, j)) in free.iter().enumerate() {
783 for i2 in i.saturating_sub(pu)..=(i + pu).min(rows - 1) {
784 for j2 in j.saturating_sub(pv)..=(j + pv).min(columns - 1) {
785 let f = free_index[i2][j2];
786 if f == usize::MAX || f > k {
787 continue;
788 }
789 let (a, b) = (gu.at(i, i2), gv.at(j, j2));
790 let value = a[2] * b[0]
791 + 2.0 * a[1] * b[1]
792 + a[0] * b[2]
793 + MEMBRANE_WEIGHT * (a[1] * b[0] + a[0] * b[1])
794 + SIZE_WEIGHT * a[0] * b[0];
795 band[k][k - f] = value;
796 }
797 }
798 }
799 for i in 0..n {
801 let lo = i.saturating_sub(bandwidth);
802 for j in lo..=i {
803 let mut sum = band[i][i - j];
804 let t_lo = lo.max(j.saturating_sub(bandwidth));
805 for t in t_lo..j {
806 sum -= band[i][i - t] * band[j][j - t];
807 }
808 if i == j {
809 if !(sum > 0.0) {
810 return Err(DeformRefusal::IllConditioned { estimate: f64::INFINITY, limit: MAX_DEFORM_CONDITION });
811 }
812 band[i][0] = sum.sqrt();
813 } else {
814 band[i][i - j] = sum / band[j][0];
815 }
816 }
817 }
818 Ok(Self { n, bandwidth, factor: band })
819 }
820
821 fn solve(&self, b: &mut [f64]) {
823 let (n, w, l) = (self.n, self.bandwidth, &self.factor);
824 for i in 0..n {
825 let mut sum = b[i];
826 for t in i.saturating_sub(w)..i {
827 sum -= l[i][i - t] * b[t];
828 }
829 b[i] = sum / l[i][0];
830 }
831 for i in (0..n).rev() {
832 let mut sum = b[i];
833 for t in i + 1..(i + w + 1).min(n) {
834 sum -= l[t][t - i] * b[t];
835 }
836 b[i] = sum / l[i][0];
837 }
838 }
839}
840
841fn solve(energy: &BandedEnergy, constraints: &[Constraint]) -> Result<(Vec<f64>, f64), DeformRefusal> {
845 solve_blocks(&[(energy, 0)], energy.n, constraints)
846}
847
848fn solve_blocks(
854 blocks: &[(&BandedEnergy, usize)],
855 total: usize,
856 constraints: &[Constraint],
857) -> Result<(Vec<f64>, f64), DeformRefusal> {
858 let n = total;
859 let m = constraints.len();
860 let mut columns: Vec<Vec<f64>> = Vec::with_capacity(m);
862 for constraint in constraints {
863 let mut y = vec![0.0; 3 * n];
864 for &(energy, offset) in blocks {
865 for axis in 0..3 {
866 let mut rhs = vec![0.0; energy.n];
867 let mut any = false;
868 for &(index, c) in &constraint.terms {
869 let point = index / 3;
870 if index % 3 == axis && point >= offset && point < offset + energy.n {
871 rhs[point - offset] += c;
872 any = true;
873 }
874 }
875 if any {
876 energy.solve(&mut rhs);
877 for (f, value) in rhs.into_iter().enumerate() {
878 y[3 * (offset + f) + axis] = value;
879 }
880 }
881 }
882 }
883 columns.push(y);
884 }
885 let mut schur = vec![vec![0.0; m]; m];
886 for r in 0..m {
887 for s in 0..=r {
888 let value: f64 = constraints[s].terms.iter().map(|&(index, c)| c * columns[r][index]).sum();
889 schur[r][s] = value;
890 schur[s][r] = value;
891 }
892 }
893 let diagonal: Vec<f64> = (0..m).map(|r| schur[r][r]).collect();
895 let mut factor = vec![vec![0.0; m]; m];
896 let (mut largest, mut smallest) = (0.0f64, f64::INFINITY);
897 for i in 0..m {
898 for j in 0..=i {
899 let mut sum = schur[i][j];
900 for t in 0..j {
901 sum -= factor[i][t] * factor[j][t];
902 }
903 if i == j {
904 if !(sum > DEPENDENCE_FRACTION * diagonal[i]) {
905 return Err(match constraints[i].tie {
906 Some(tie) => DeformRefusal::DependentTie { tie },
907 None => DeformRefusal::DependentConstraints { index: constraints[i].pick },
908 });
909 }
910 factor[i][i] = sum.sqrt();
911 largest = largest.max(factor[i][i]);
912 smallest = smallest.min(factor[i][i]);
913 } else {
914 factor[i][j] = sum / factor[j][j];
915 }
916 }
917 }
918 let condition = (largest / smallest).powi(2);
919 if !(condition <= MAX_DEFORM_CONDITION) {
920 return Err(DeformRefusal::IllConditioned { estimate: condition, limit: MAX_DEFORM_CONDITION });
921 }
922 let mut lambda: Vec<f64> = constraints.iter().map(|c| c.rhs).collect();
923 for i in 0..m {
924 let mut sum = lambda[i];
925 for t in 0..i {
926 sum -= factor[i][t] * lambda[t];
927 }
928 lambda[i] = sum / factor[i][i];
929 }
930 for i in (0..m).rev() {
931 let mut sum = lambda[i];
932 for t in i + 1..m {
933 sum -= factor[t][i] * lambda[t];
934 }
935 lambda[i] = sum / factor[i][i];
936 }
937 let mut x = vec![0.0; 3 * n];
938 for (r, column) in columns.iter().enumerate() {
939 if lambda[r] != 0.0 {
940 for (value, y) in x.iter_mut().zip(column) {
941 *value += lambda[r] * y;
942 }
943 }
944 }
945 Ok((x, condition))
946}
947
948struct Gram {
952 entries: Vec<Vec<[f64; 3]>>,
954 degree: usize,
955}
956
957impl Gram {
958 fn at(&self, i: usize, j: usize) -> [f64; 3] {
959 let d = j + self.degree - i;
960 self.entries[i][d]
961 }
962}
963
964fn gram(knots: &[f64], degree: usize) -> Gram {
965 let count = knots.len() - degree - 1;
966 let start = knots[degree];
967 let length = (knots[count] - start).max(f64::MIN_POSITIVE);
968 let mut entries = vec![vec![[0.0; 3]; 2 * degree + 1]; count];
969 let (nodes, weights) = gauss_legendre(degree + 1);
970 let vector = KnotVector::new(knots.to_vec(), degree).expect("validated knots");
971 let order = 2.min(degree);
972 for span in degree..count {
973 let (a, b) = (knots[span], knots[span + 1]);
974 if b <= a {
975 continue;
976 }
977 for (node, weight) in nodes.iter().zip(&weights) {
978 let t = 0.5 * (a + b) + 0.5 * (b - a) * node;
979 let w = weight * 0.5 * (b - a) / length;
980 let ders = vector.basis_derivatives(span, t, order);
981 for x in 0..=degree {
982 for y in 0..=degree {
983 let (i, j) = (span - degree + x, span - degree + y);
984 let d = j + degree - i;
985 for k in 0..=order {
986 let scale = length.powi(2 * k as i32);
988 entries[i][d][k] += w * scale * ders[k][x] * ders[k][y];
989 }
990 }
991 }
992 }
993 }
994 Gram { entries, degree }
995}
996
997fn gauss_legendre(n: usize) -> (Vec<f64>, Vec<f64>) {
999 let mut nodes = vec![0.0; n];
1000 let mut weights = vec![0.0; n];
1001 for i in 0..n {
1002 let mut x = (std::f64::consts::PI * (i as f64 + 0.75) / (n as f64 + 0.5)).cos();
1003 let mut derivative = 1.0;
1004 for _ in 0..100 {
1005 let (mut p0, mut p1) = (1.0, x);
1006 for k in 2..=n {
1007 let p2 = ((2 * k - 1) as f64 * x * p1 - (k - 1) as f64 * p0) / k as f64;
1008 p0 = p1;
1009 p1 = p2;
1010 }
1011 derivative = n as f64 * (x * p1 - p0) / (x * x - 1.0);
1013 let step = p1 / derivative;
1014 x -= step;
1015 if step.abs() < 1e-16 {
1016 break;
1017 }
1018 }
1019 nodes[i] = x;
1020 weights[i] = 2.0 / ((1.0 - x * x) * derivative * derivative);
1021 }
1022 (nodes, weights)
1023}
1024
1025fn check_fold(base: &NurbsSurface, deformed: &NurbsSurface) -> Result<(), DeformRefusal> {
1028 let grid = |knots: &[f64]| {
1029 let mut out: Vec<f64> = Vec::new();
1030 for pair in knots.windows(2) {
1031 if pair[1] > pair[0] {
1032 for k in 0..=FOLD_SAMPLES_PER_SPAN {
1033 out.push(pair[0] + (pair[1] - pair[0]) * k as f64 / FOLD_SAMPLES_PER_SPAN as f64);
1034 }
1035 }
1036 }
1037 out.dedup();
1038 out
1039 };
1040 let scale = net_diagonal(base).max(f64::MIN_POSITIVE);
1043 let length = |knots: &[f64], degree: usize| knots[knots.len() - 1 - degree] - knots[degree];
1044 let (lu, lv) = (length(&base.knots_u, base.degree_u), length(&base.knots_v, base.degree_v));
1045 let floor = 1e-12 * scale;
1050 for &u in &grid(&base.knots_u) {
1051 for &v in &grid(&base.knots_v) {
1052 let before = RationalBasis::at(base, u, v).map_err(DeformRefusal::InvalidSurface)?;
1053 let after = RationalBasis::at(deformed, u, v).map_err(DeformRefusal::InvalidSurface)?;
1054 let (du0, dv0) = (before.du.scale(lu), before.dv.scale(lv));
1055 let (du1, dv1) = (after.du.scale(lu), after.dv.scale(lv));
1056 let (n0, n1) = (du0.cross(dv0), du1.cross(dv1));
1057 if !(du0.length() > floor && dv0.length() > floor && n0.length() > 1e-9 * du0.length() * dv0.length()) {
1058 continue;
1059 }
1060 let regular = n1.length() > 1e-9 * du1.length() * dv1.length();
1061 if !(regular && n1.dot(n0) > 1e-9 * n1.length() * n0.length()) {
1062 return Err(DeformRefusal::Folded { u, v });
1063 }
1064 }
1065 }
1066 Ok(())
1067}
1068
1069#[path = "deform/tied.rs"]
1070mod tied;
1071pub use tied::{deform_surfaces_tied, SurfaceTie, TieContinuity, TiedResult, TiedSurface, MAX_TIED_POLES, MAX_TIED_ROWS};