Skip to main content

brep_geometry/geometry/
deform.rs

1//! Constrained deformation of one NURBS surface by its control net
2//! (Golovanov 2020 §3.16, the deformable surface (3.16.3): a vector field of
3//! deviations on a rectangular net added to a base surface).
4//!
5//! Here the deviation field is spanned by the base surface's OWN rational
6//! basis: every free control point `P_ij` moves by `D_ij` with its weight held,
7//! so the deformed surface `Σ R_ij (P_ij + D_ij)` is again an exact NURBS
8//! surface on the same knots and weights, and the change at any parameter is
9//! linear in the `D_ij`. The `D_ij` minimise a thin-plate bending energy of the
10//! displacement (plus a small membrane and size term so the system is definite)
11//! subject to hard linear constraints:
12//!
13//! - a pick `(u, v) -> target`: the surface passes through `target` at `(u, v)`;
14//! - an optional pick normal `n`: both first partials at `(u, v)` are
15//!   perpendicular to `n` (two linear rows, coupling x, y and z);
16//! - held edges: the first row of control points on that side is fixed
17//!   (position), or the first two (position and cross-boundary tangent).
18//!
19//! It is ONE constrained quadratic programme, solved exactly by the Schur
20//! complement of the banded energy matrix — not a tessellation deformed and
21//! refitted. Before the solve the surface may be degree-elevated and its spans
22//! split (exact operations, `surface/refine.rs`) to give the net room.
23//!
24//! Every way the problem can be ill-posed is refused by name
25//! ([`DeformRefusal`]): duplicate or dependent picks, picks the held rows leave
26//! no freedom for, a net or pick count over the bounds, a constraint system too
27//! ill-conditioned to trust, a displacement out of proportion to the surface,
28//! invalid weights, a seam or collapsed row left free, and a result whose
29//! normal turns over anywhere on a sampling grid (a fold).
30
31use crate::surface::{KnotDirection, KnotRefinementRefusal};
32use crate::{KnotVector, NurbsSurface, Vec3, Vec4};
33
34/// Largest control net the solver accepts after elevation and refinement.
35/// The banded factorisation costs `free · bandwidth²` with a bandwidth of about
36/// `degree_u · columns`; at this bound a solve stays well under a second.
37pub const MAX_DEFORM_POLES: usize = 4096;
38/// Highest degree the solver elevates to.
39pub const MAX_DEFORM_DEGREE: usize = 9;
40/// Most picks one deformation takes.
41pub const MAX_DEFORM_PICKS: usize = 64;
42/// Largest accepted condition estimate of the constraint system (the squared
43/// ratio of the largest to the smallest Cholesky pivot of its Schur complement).
44pub const MAX_DEFORM_CONDITION: f64 = 1e12;
45/// A constraint whose Schur pivot keeps less than this fraction of its own
46/// diagonal is (numerically) implied by the constraints before it.
47const DEPENDENCE_FRACTION: f64 = 1e-10;
48/// Largest pick displacement, as a multiple of the control net's bounding-box
49/// diagonal.
50pub const MAX_DEFORM_DISPLACEMENT_RATIO: f64 = 1.0;
51/// Thin-plate weight 1; the membrane and size terms that make the energy
52/// definite even with no held edge (rigid motion then costs only these).
53const MEMBRANE_WEIGHT: f64 = 1e-2;
54const SIZE_WEIGHT: f64 = 1e-6;
55/// Largest accepted ratio of the furthest control point move to the largest
56/// change asked for (a pick's offset, or a normal pick's tilt times the net's
57/// diagonal).
58pub const MAX_DEFORM_AMPLIFICATION: f64 = 25.0;
59/// Relative size below which a requested change is evaluation round-off.
60const ROUND_OFF: f64 = 1e-14;
61/// Samples per knot span (each direction) of the fold check.
62const FOLD_SAMPLES_PER_SPAN: usize = 6;
63
64/// One interpolation pick.
65#[derive(Clone, Copy, Debug)]
66pub struct DeformPick {
67    pub u: f64,
68    pub v: f64,
69    /// Where the surface must pass at `(u, v)`.
70    pub target: Vec3,
71    /// When given, the surface normal at `(u, v)` must be parallel to it.
72    pub normal: Option<Vec3>,
73}
74
75/// What a boundary side keeps.
76#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
77pub enum EdgeHold {
78    /// The side's rows move freely.
79    #[default]
80    Free,
81    /// The boundary row of control points is fixed: the edge curve is kept.
82    Position,
83    /// The first two rows are fixed: the edge curve and the cross-boundary
84    /// tangent (so G1 with a neighbour across that edge) are kept.
85    Tangent,
86}
87
88/// The four sides, in the order [`DeformSpec::hold`] lists them.
89#[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    /// Held sides: `[u_min, u_max, v_min, v_max]`.
103    pub hold: [EdgeHold; 4],
104    /// Each direction is elevated (exactly) to at least this degree first;
105    /// at least 2 (a bilinear net has no bending to minimise). Default 3.
106    pub min_degree: usize,
107    /// Each non-empty knot span is split into this many equal spans in u and
108    /// v first (1 = no split). Default `[1, 1]`.
109    pub split_spans: [usize; 2],
110    /// When given, `[u0, u1, v0, v1]`: only knot spans that overlap this
111    /// parameter box are split (a face's box on a larger carrier), so the
112    /// pole bound is spent where the deformation is.
113    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/// A deformed surface and what the solve measured.
123#[derive(Clone, Debug)]
124pub struct DeformResult {
125    pub surface: NurbsSurface,
126    /// Control rows and columns of the result.
127    pub net: (usize, usize),
128    /// Control points the solve could move.
129    pub free_poles: usize,
130    /// Largest pick distance of the result, read back through
131    /// `NurbsSurface::evaluate` (not the solver's residual).
132    pub max_pick_error: f64,
133    /// Largest normal-pick angle (radians) of the result, read back through
134    /// `NurbsSurface::deriv1`.
135    pub max_normal_error: f64,
136    /// Largest control point move.
137    pub max_pole_shift: f64,
138    /// Condition estimate of the constraint system.
139    pub condition: f64,
140}
141
142#[derive(Clone, Debug, PartialEq)]
143pub enum DeformRefusal {
144    InvalidSurface(String),
145    /// A weight is not finite and positive.
146    InvalidWeights { row: usize, column: usize },
147    /// Held rows need clamped ends: an unclamped side's boundary curve is not
148    /// its first row.
149    UnclampedKnots { direction: KnotDirection },
150    NoPicks,
151    TooManyPicks { count: usize, limit: usize },
152    NetTooLarge { poles: usize, limit: usize },
153    /// `min_degree` below 2 or a split count of 0.
154    InvalidSpec(String),
155    /// A pick parameter outside the domain, or a non-finite target or normal,
156    /// or a zero normal.
157    InvalidPick { index: usize, reason: String },
158    /// Two picks at the same parameters.
159    DuplicatePicks { first: usize, second: usize },
160    /// The pick asks for a change where every control point that reaches it
161    /// is held.
162    PickOnHeldRegion { index: usize },
163    /// The pick's constraints are implied by (or contradict) earlier ones on
164    /// this net: picks too close for the net to separate, or more than its
165    /// free control points can meet. Split spans to give it room.
166    DependentConstraints { index: usize },
167    IllConditioned { estimate: f64, limit: f64 },
168    DisplacementTooLarge { index: usize, displacement: f64, limit: f64 },
169    /// A closed (seam) direction needs both seam sides held with their
170    /// tangents, or the seam opens (free) or creases (position only).
171    ClosedDirectionNotHeld { direction: KnotDirection },
172    /// A side whose boundary row is collapsed to one point (a pole) must be
173    /// held with its tangent, or the pole splits or kinks.
174    CollapsedSideNotHeld { side: DeformSide },
175    /// The result's normal turns over (or vanishes) at `(u, v)`.
176    Folded { u: f64, v: f64 },
177    /// The net had to move a control point `ratio` times further than the
178    /// largest change asked for: the picks ask for more bending than the free
179    /// region can give smoothly (a pick right next to a held edge, or picks
180    /// pulling hard against each other). Split spans or move the pick.
181    Amplified { ratio: f64, limit: f64 },
182    /// Shell deformation: a tie between two surfaces is malformed (an index
183    /// out of range, a surface tied to itself on one side).
184    InvalidTie { tie: usize, reason: String },
185    /// The two boundary rows a tie joins do not coincide after the exact
186    /// elevation and knot merging that make them comparable.
187    EdgeRowsDisagree { tie: usize, gap: f64 },
188    /// A shared edge that is smooth (G1) in the base but whose rows cannot
189    /// keep it so by the linear frozen-ratio rows (a ratio that varies along
190    /// the edge, or rational rows): refused rather than creased.
191    EdgeNotUniformlyTangent { tie: usize, reason: String },
192    /// A tie's rows are implied by (or contradict) the other constraints.
193    DependentTie { tie: usize },
194    /// A tied system with more constraint rows than its bound.
195    TooManyConstraints { rows: usize, limit: usize },
196    /// Two surfaces meeting at a sharp shared edge have swung through each
197    /// other there (the dihedral turned over) at edge parameter `t`.
198    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
210/// Deform `surface` as `spec` asks. The input is never changed.
211pub fn deform_surface(surface: &NurbsSurface, spec: &DeformSpec) -> Result<DeformResult, DeformRefusal> {
212    deform_surface_where(surface, spec, &|_: PoleSupport| true)
213}
214
215/// One control point's support, as [`deform_surface_where`] shows it.
216#[derive(Clone, Copy, Debug, PartialEq)]
217pub struct PoleSupport {
218    /// The closed parameter box `[u0, u1, v0, v1]` (knots `t_i ..= t_(i+p+1)`
219    /// each way) outside which the pole's basis function is zero.
220    pub bounds: [f64; 4],
221    /// The order to which the basis function vanishes at each side
222    /// `[u0, u1, v0, v1]`: `p + 1 - m`, `m` the multiplicity of that end knot
223    /// among the pole's own `p + 2` knots. Order 1: the value is zero there;
224    /// order 2: the value and the first derivative across the side; and so on.
225    /// Moving the pole changes nothing on that side below that order.
226    pub vanishing: [usize; 4],
227}
228
229/// [`deform_surface`] where, besides the held sides, a control point may move
230/// only when `may_move` accepts its support. A point of the surface depends
231/// only on the poles whose supports contain it (and on a support's side only
232/// to the side's vanishing order), so holding every pole whose support meets a
233/// region keeps the surface identical there to every order, and admitting one
234/// that only touches the region on a side of vanishing order 2 keeps the
235/// surface's points and tangent planes there.
236pub 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    // Free poles: everything outside the held rows.
304    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    // Read off the free set (held sides and `may_move` together): a seam's
329    // two rows each side, and a collapsed side's two rows, must all be held,
330    // or the seam opens or creases and the pole splits or kinks.
331    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    // Constraints, and the displacement bound.
353    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    // Nothing asks for a change: the (elevated, split) base comes back as it is.
360    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    // The deformed net: weights held, Cartesian points moved.
368    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
412/// Check a surface and the spec's room parameters, then elevate and split it
413/// (both exact) as the spec asks, refusing a net over the pole bound before
414/// building it. The result is the deformation's base: the same surface on a
415/// finer net.
416pub(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    // The net size elevation and splitting will give, predicted (with checked
441    // arithmetic) before anything is allocated: elevating a direction to
442    // degree q adds (q - p) poles per non-empty span, splitting each
443    // span into k adds (k - 1) per span.
444    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    // Room: elevate, then split spans (both exact).
462    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/// The constraint rows of one surface's picks, its unknowns at `offset`
497/// (control points) in the stacked vector; refusals name picks from
498/// `first_pick` on. `requested` gathers the largest change asked for.
499#[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        // Σ R = 1: the whole reach of a position row is 1. The round-off of
526        // one coordinate of a point read back from the surface is relative
527        // to that coordinate of the poles that make it (Σ R_k P_k[c], R >= 0),
528        // not to the point's distance from the origin.
529        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
565/// Does the knot span `pair` overlap the split window in `axis` (0 = u)?
566fn 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
625/// The rational basis `R_ij` and its first partials at one parameter pair,
626/// over the `(degree_u + 1)(degree_v + 1)` poles that reach it, and the
627/// surface point and partials they give.
628struct 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    /// The sparse row `Σ coefficient(R, R_u, R_v) D_ij[axis]` over the free poles.
690    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
708/// One linear constraint `Σ coefficient · x[index] = rhs` on the stacked
709/// displacement vector `x = (D_0.x, D_0.y, D_0.z, D_1.x, ...)`.
710struct Constraint {
711    pick: usize,
712    /// A tie row's tie (shell deformation), named by a dependence refusal.
713    tie: Option<usize>,
714    terms: Vec<(usize, f64)>,
715    rhs: f64,
716}
717
718/// Add a constraint, or drop it when no free pole reaches it and it already
719/// holds (a pick on a held edge at its current place); refuse it when no free
720/// pole reaches it and it asks for a change. "Reaches" is relative to
721/// `whole_reach`, the row's largest coefficient over every pole held or free,
722/// so a parameterisation's scale (a derivative row's coefficients go as
723/// 1 / domain length) does not decide it. The kept row is scaled to unit
724/// length, so the Schur complement's conditioning is the geometry's, not the
725/// mix of position and derivative units.
726fn 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    // A change within round-off of the evaluation (a pick read back from the
735    // surface itself) is no change: the input comes back exactly.
736    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
750/// The thin-plate energy of the displacement on the free poles, one banded
751/// symmetric matrix shared by x, y and z:
752/// `H = G2u⊗G0v + 2 G1u⊗G1v + G0u⊗G2v + μ (G1u⊗G0v + G0u⊗G1v) + ε G0u⊗G0v`,
753/// `Gk` the Gram matrix of the k-th derivatives of the (polynomial) B-spline
754/// basis over the domain mapped to [0, 1]. Stored as its lower band.
755struct BandedEnergy {
756    n: usize,
757    bandwidth: usize,
758    /// `factor[k][d]` = L[k][k - d] after `build` (Cholesky factor).
759    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        // Banded Cholesky in place.
800        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    /// Solve `H y = b` in place.
822    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
841/// Minimise `½ xᵀ (I₃ ⊗ H) x` subject to `A x = b`: `x = H⁻¹ Aᵀ λ`,
842/// `(A H⁻¹ Aᵀ) λ = b`, the Schur complement factored by Cholesky with each
843/// pivot checked for dependence and the pivots' spread for conditioning.
844fn solve(energy: &BandedEnergy, constraints: &[Constraint]) -> Result<(Vec<f64>, f64), DeformRefusal> {
845    solve_blocks(&[(energy, 0)], energy.n, constraints)
846}
847
848/// [`solve`] over several surfaces at once: `blocks` are their energies and
849/// the offset (in control points) of each one's unknowns in the stacked
850/// vector of `total` points. The energy is block diagonal (each surface's own
851/// bending), so `H⁻¹` is one banded solve per block; the constraint rows may
852/// couple blocks (ties along shared edges).
853fn 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    // Y_r = (I₃ ⊗ H)⁻¹ a_r, one banded solve per block and axis the row touches.
861    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    // Cholesky with a dependence test on each pivot.
894    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
948/// Gram matrices `∫ N_i^(k) N_j^(k)`, k = 0, 1, 2, of one direction's
949/// B-spline basis over the domain mapped to [0, 1], by Gauss–Legendre on each
950/// span (degree + 1 points: exact for the degree-2p products).
951struct Gram {
952    /// `entries[i][d]` for `j = i + d - degree`, `d` in `0..=2 degree`.
953    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                        // d/ds = length · d/du on the unit parameter s.
987                        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
997/// Gauss–Legendre nodes and weights on [-1, 1] (Newton on P_n).
998fn 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            // n >= 1: p1 = P_n(x), p0 = P_(n-1)(x).
1012            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
1025/// Refuse a result whose normal turns over against the base surface's (at the
1026/// same parameters) or vanishes, on a grid of every knot span.
1027fn 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    // Partials on the unit parameter square, so neither the knot values'
1041    // scale nor the model's decides what counts as a vanishing normal.
1042    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    // A sample is skipped only where the BASE has no normal: a partial that
1046    // vanishes against the model's size (a pole) or two partials parallel to
1047    // 1e-9 of their own lengths. A thin surface (one partial tiny but
1048    // regular) is still checked.
1049    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};