Skip to main content

brep_construction/construction/
loft_guides.rs

1//! A loft between two sections along guide curves through their corners.
2//!
3//! Each wall is the patch its four edges bound: a side of the first section,
4//! the two guides from its ends, and the matching side of the last section,
5//! filled by the bilinearly blended Coons patch ([`crate::coons_bilinear`]).
6//! Where the two sides are straight, that patch is the surface ruled between
7//! the two guides at equal parameters. A side of no length (the last section
8//! closing on a point) makes its wall three-sided, closed on a pole. The walls
9//! and the two flat ends are faces of their own, joined into the solid they
10//! bound ([`crate::solid_from_sheets`]).
11//!
12//! [`loft_profile_brep_on_guide_chains`] takes any number of sections and
13//! guides that are chains of curves: the sections stand anywhere along the
14//! guides, and a wall is cut along its guides' joints, so a corner in a guide
15//! is an edge of the solid. (With rational sides or guides the Coons patch is
16//! the projective one, blended in homogeneous space; it still holds its four
17//! edges exactly.)
18use crate::{coons_bilinear, face_from_surface, face_from_surface_trimmed, make_plane, solid_from_sheets, BrepSolid, KernelRefusal, KernelStage, NurbsCurve, OrRefuse, Vec3};
19
20/// The prefix of every refusal of this operation.
21pub const LOFT_ON_GUIDES_REFUSAL: &str = "loftOnGuides";
22
23fn input(what: &'static str, message: String) -> KernelRefusal {
24    KernelRefusal::input(KernelStage::Collect, what, format!("{LOFT_ON_GUIDES_REFUSAL}: {message}"))
25}
26
27fn ends(curve: &NurbsCurve) -> Result<[Vec3; 2], KernelRefusal> {
28    let [t0, t1] = curve.domain().or_refuse(KernelStage::Collect, "loftOnGuides.domain")?;
29    Ok([curve.evaluate(t0).or_refuse(KernelStage::Collect, "loftOnGuides.end")?, curve.evaluate(t1).or_refuse(KernelStage::Collect, "loftOnGuides.end")?])
30}
31
32fn poles(curves: &[NurbsCurve]) -> Vec<Vec3> {
33    curves.iter().flat_map(|curve| &curve.control_points).map(|pole| Vec3::new(pole.x / pole.w, pole.y / pole.w, pole.z / pole.w)).collect()
34}
35
36/// The flat face inside the closed loop `section`, which must lie in a plane.
37fn flat_end(section: &[NurbsCurve], size: f64, which: &str) -> Result<BrepSolid, KernelRefusal> {
38    let points = poles(section);
39    let origin = points[0];
40    let far = |off: Option<Vec3>| {
41        points.iter().map(|point| point.sub(origin)).map(|arm| off.map_or(arm, |axis| arm.sub(axis.scale(arm.dot(axis))))).fold(Vec3::new(0.0, 0.0, 0.0), |best, arm| if arm.length() > best.length() { arm } else { best })
42    };
43    let flat = || input("section_plane", format!("the {which} section does not lie in a plane"));
44    let e1 = far(None).normalized().map_err(|_| flat())?;
45    let across = far(Some(e1));
46    if across.length() <= 1e-9 * size {
47        return Err(flat());
48    }
49    let e2 = across.normalized().map_err(|_| flat())?;
50    let normal = e1.cross(e2);
51    if points.iter().any(|point| point.sub(origin).dot(normal).abs() > 1e-9 * size) {
52        return Err(flat());
53    }
54    let reach = |axis: Vec3| points.iter().map(|point| point.sub(origin).dot(axis)).fold((0.0f64, 0.0f64), |(low, high), at| (low.min(at), high.max(at)));
55    let ((low1, high1), (low2, high2)) = (reach(e1), reach(e2));
56    let corner = origin.add(e1.scale(low1 - 0.5 * size)).add(e2.scale(low2 - 0.5 * size));
57    let plane = make_plane(corner, e1, e2, high1 - low1 + size, high2 - low2 + size).or_refuse(KernelStage::Collect, "loftOnGuides.plane")?;
58    face_from_surface_trimmed(&plane, &[section.to_vec()])
59}
60
61/// The wall standing on the straight side `side` between two guides that meet
62/// at one point: the surface ruled between the guides at equal parameters,
63/// closed on a pole where they meet. (The Coons patch of a straight side, two
64/// guides and a point is that ruled surface.)
65fn pointed_wall(side: &NurbsCurve, rail: &NurbsCurve, next: &NurbsCurve, k: usize, tolerance: f64) -> Result<crate::NurbsSurface, KernelRefusal> {
66    let [from, to] = ends(side)?;
67    let straight = poles(std::slice::from_ref(side)).iter().all(|point| point.sub(from).cross(to.sub(from)).length() <= tolerance * to.sub(from).length());
68    if !straight {
69        return Err(KernelRefusal::unsupported(KernelStage::Fragment, "pointed_wall_side", format!("{LOFT_ON_GUIDES_REFUSAL}: wall {k} closes on a point from a side that is not straight")));
70    }
71    if rail.degree != next.degree || rail.knots != next.knots {
72        return Err(KernelRefusal::unsupported(KernelStage::Fragment, "pointed_wall_guides", format!("{LOFT_ON_GUIDES_REFUSAL}: wall {k} closes on a point between guides of different degree or knots")));
73    }
74    let net = vec![rail.control_points.clone(), next.control_points.clone()];
75    crate::NurbsSurface::new(1, rail.degree, vec![0.0, 0.0, 1.0, 1.0], rail.knots.clone(), net).or_refuse(KernelStage::Fragment, "loftOnGuides.pointed_wall")
76}
77
78/// The solid lofted from the closed section `first` to the closed section
79/// `last` along `guides`.
80///
81/// The two sections have the same number of curves, each a closed loop run the
82/// same way round, curve `k` of the first matched with curve `k` of the last;
83/// each lies in a plane. `guides[k]` runs from the start of `first[k]` to the
84/// start of `last[k]` (given in either direction). A curve of `last` may have
85/// no length: where every one of them is the same point the loft closes on
86/// that point and has no last end.
87///
88/// Refuses sections of different counts, guides that do not join the matched
89/// corners, sections off a plane, and walls the Coons patch refuses.
90pub fn loft_profile_brep_on_guides(first: &[NurbsCurve], last: &[NurbsCurve], guides: &[NurbsCurve]) -> Result<BrepSolid, KernelRefusal> {
91    let count = first.len();
92    if count < 2 || last.len() != count || guides.len() != count {
93        return Err(input("counts", format!("the sections and the guides must be equally many, at least 2 (got {count}, {} and {})", last.len(), guides.len())));
94    }
95    let all = poles(&[first, last, guides].concat());
96    let size = all.iter().map(|point| point.sub(all[0]).length()).fold(0.0, f64::max);
97    let tolerance = 1e-9 * size;
98    let near = |a: Vec3, b: Vec3| a.sub(b).length() <= tolerance;
99    // each guide turned to run from the first section to the last
100    let mut rails = Vec::with_capacity(count);
101    for k in 0..count {
102        let ([foot, _], [head, _]) = (ends(&first[k])?, ends(&last[k])?);
103        let [from, to] = ends(&guides[k])?;
104        let rail = if near(from, foot) && near(to, head) {
105            guides[k].clone()
106        } else if near(to, foot) && near(from, head) {
107            guides[k].reversed().or_refuse(KernelStage::Collect, "loftOnGuides.reverse")?
108        } else {
109            return Err(input("guide_ends", format!("guide {k} does not join the start of curve {k} of the first section to that of the last")));
110        };
111        rails.push(rail);
112    }
113    let mut sheets = Vec::with_capacity(count + 2);
114    for k in 0..count {
115        let next = (k + 1) % count;
116        let far_side = last[k].reversed().or_refuse(KernelStage::Collect, "loftOnGuides.reverse")?;
117        let back = rails[k].reversed().or_refuse(KernelStage::Collect, "loftOnGuides.reverse")?;
118        let [head, head_next] = ends(&last[k])?;
119        let patch = if near(head, head_next) && poles(&last[k..=k]).iter().all(|point| near(*point, head)) {
120            pointed_wall(&first[k], &rails[k], &rails[next], k, tolerance)?
121        } else {
122            coons_bilinear([first[k].clone(), rails[next].clone(), far_side, back])
123                .map_err(|error| KernelRefusal::unsupported(KernelStage::Fragment, "wall", format!("{LOFT_ON_GUIDES_REFUSAL}: wall {k} has no Coons patch: {error:?}")))?
124        };
125        sheets.push(face_from_surface(&patch)?);
126    }
127    sheets.push(flat_end(first, size, "first")?);
128    let apex = ends(&last[0])?[0];
129    let pointed = poles(last).iter().all(|point| near(*point, apex));
130    if !pointed {
131        sheets.push(flat_end(last, size, "last")?);
132    }
133    // sewing reads each edge's place by projection, whose own error on a cubic is near 1e-8
134    solid_from_sheets(&sheets, (1e-8 * size).max(1e-7))
135}
136
137/// Where a point sits on a chain: the piece it is on and how far along the
138/// chain that is, counting each piece as one.
139#[derive(Clone, Copy)]
140pub struct Station {
141    along: f64,
142}
143
144/// The place on `chain` of `corner`, which must lie on it.
145fn station(chain: &[NurbsCurve], corner: Vec3, tolerance: f64, guide: usize, section: usize) -> Result<Station, KernelRefusal> {
146    let mut best: Option<(f64, f64)> = None;
147    for (index, piece) in chain.iter().enumerate() {
148        let [t0, t1] = piece.domain().or_refuse(KernelStage::Collect, "loftOnGuides.domain")?;
149        let foot = crate::project_point_to_curve(piece, corner).or_refuse(KernelStage::Classify, "loftOnGuides.project")?;
150        // an end of a piece is a joint: count it as the whole number it is
151        let [from, to] = ends(piece)?;
152        let along = if corner.sub(from).length() <= tolerance {
153            index as f64
154        } else if corner.sub(to).length() <= tolerance {
155            (index + 1) as f64
156        } else {
157            index as f64 + (foot.u - t0) / (t1 - t0)
158        };
159        if best.map_or(true, |(distance, _)| foot.distance < distance) {
160            best = Some((foot.distance, along));
161        }
162    }
163    match best {
164        Some((distance, along)) if distance <= tolerance => Ok(Station { along }),
165        Some((distance, _)) => Err(input("corner_off_guide", format!("the start of curve {guide} of section {section} is {distance:.3e} off guide {guide}"))),
166        None => Err(input("guide_empty", format!("guide {guide} has no curves"))),
167    }
168}
169
170/// The pieces of `chain` between the places `from` and `to` along it.
171fn between(chain: &[NurbsCurve], from: f64, to: f64) -> Result<Vec<NurbsCurve>, KernelRefusal> {
172    let stage = KernelStage::Collect;
173    let mut pieces = Vec::new();
174    for (index, piece) in chain.iter().enumerate() {
175        let (low, high) = (from.max(index as f64), to.min((index + 1) as f64));
176        if high - low <= 1e-12 {
177            continue;
178        }
179        let [t0, t1] = piece.domain().or_refuse(stage, "loftOnGuides.domain")?;
180        let at = |along: f64| t0 + (t1 - t0) * (along - index as f64);
181        let mut part = piece.clone();
182        if high < (index + 1) as f64 {
183            part = part.split(at(high)).or_refuse(stage, "loftOnGuides.cut")?.0;
184        }
185        if low > index as f64 {
186            part = part.split(at(low)).or_refuse(stage, "loftOnGuides.cut")?.1;
187        }
188        pieces.push(part);
189    }
190    Ok(pieces)
191}
192
193/// The solid lofted through the closed sections `sections` along `guides`,
194/// each guide a chain of curves.
195///
196/// Every section has the same number of curves, run the same way round, curve
197/// `k` of one matched with curve `k` of the next. `guides[k]` is a chain of
198/// curves that follow one another head to tail (the chain may be given from
199/// either end) and passes through the start of curve `k` of every section, in
200/// the sections' order. The sections may stand anywhere along the guides, at a
201/// joint of a chain or between two; what a guide has before the first section
202/// or after the last is not used. The first and last sections lie in planes
203/// and close the solid; the last may be curves of no length at one point, on
204/// which the loft then closes.
205///
206/// Between two sections each wall is the Coons patch of a side of each and the
207/// two guides between them, each guide taken as one curve with its pieces on
208/// equal stretches of the parameter. Where the guides have joints between two
209/// sections the wall is cut along them into one face for each piece, so a
210/// corner in a guide is an edge of the solid and no face has a crease; the two
211/// guides of a wall must then have equally many pieces between those sections.
212///
213/// Refuses, by name: counts that do not agree (`counts`), a section's corner
214/// off its guide (`corner_off_guide`), sections out of order along a guide
215/// (`stations_order`), two neighbouring guides with different numbers of
216/// pieces between two sections (`guide_pieces`), a chain whose curves do not
217/// meet (`guide_chain`), an end section off a plane (`section_plane`), a wall
218/// closing on a point from a side that is not straight (`pointed_wall_side`),
219/// and a wall the Coons patch refuses (`wall`).
220pub fn loft_profile_brep_on_guide_chains(sections: &[Vec<NurbsCurve>], guides: &[Vec<NurbsCurve>]) -> Result<BrepSolid, KernelRefusal> {
221    Ok(chains_with_walls(sections, guides)?.0)
222}
223
224/// Which wall a side face of a loft along guide chains is: the faces of the
225/// solid come one for each of these, in this order, and then the flat ends.
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub struct GuideLoftWall {
228    /// The curve of the first section the wall stands over.
229    pub side: usize,
230    /// The wall lies between sections `span` and `span + 1`.
231    pub span: usize,
232    /// The guide through the start of that curve, as the guides were given.
233    pub guide: usize,
234    /// The curve of that guide the wall runs along, as the chain was given.
235    pub piece: usize,
236}
237
238/// [`loft_profile_brep_on_guide_chains`] for sections and guides that are not
239/// yet matched: the guides in any order, and every section after the first
240/// starting at any of its corners and run either way round. The first section
241/// is taken as given; each guide is given to the corner of it that it passes
242/// through, and every later section is turned (and reversed if need be) until
243/// its corners lie on the guides of the first section's corners. A last section
244/// at one point is left as it is.
245///
246/// Returns the solid and, for its side faces in order, which wall each is.
247/// Refuses as the matched loft does, and by name a corner of the first section
248/// that no guide, or more than one, passes through (`guide_for_corner`) and a
249/// later section none of whose turns puts its corners on the guides
250/// (`section_off_guides`).
251pub fn loft_profile_brep_on_loose_guide_chains(sections: &[Vec<NurbsCurve>], guides: &[Vec<NurbsCurve>]) -> Result<(BrepSolid, Vec<GuideLoftWall>), KernelRefusal> {
252    let stage = KernelStage::Collect;
253    let count = guides.len();
254    if sections.len() < 2 || count < 2 || sections.iter().any(|section| section.len() != count) || guides.iter().any(Vec::is_empty) {
255        return Err(input("counts", format!("at least two sections are needed, each of as many curves as there are guides, at least 2, and no guide empty (got {} sections of {:?} curves and {count} guides)", sections.len(), sections.iter().map(Vec::len).collect::<Vec<_>>())));
256    }
257    let every: Vec<NurbsCurve> = sections.iter().flatten().chain(guides.iter().flatten()).cloned().collect();
258    let all = poles(&every);
259    let size = all.iter().map(|point| point.sub(all[0]).length()).fold(0.0, f64::max);
260    let tolerance = 1e-9 * size;
261    let on = |guide: usize, point: Vec3| -> Result<bool, KernelRefusal> {
262        for piece in &guides[guide] {
263            if crate::project_point_to_curve(piece, point).or_refuse(KernelStage::Classify, "loftOnGuides.project")?.distance <= tolerance {
264                return Ok(true);
265            }
266        }
267        Ok(false)
268    };
269    // the guide of each corner of the first section
270    let mut order = Vec::with_capacity(count);
271    for (k, curve) in sections[0].iter().enumerate() {
272        let corner = ends(curve)?[0];
273        let mut through = Vec::new();
274        for guide in 0..count {
275            if on(guide, corner)? {
276                through.push(guide);
277            }
278        }
279        match through[..] {
280            [guide] if !order.contains(&guide) => order.push(guide),
281            _ => return Err(input("guide_for_corner", format!("the start of curve {k} of the first section needs one guide of its own through it; the guides through it are {through:?}"))),
282        }
283    }
284    let mut matched = vec![sections[0].clone()];
285    for (index, section) in sections.iter().enumerate().skip(1) {
286        let points = poles(section);
287        if points.iter().all(|point| point.sub(points[0]).length() <= tolerance) {
288            matched.push(section.clone());
289            continue;
290        }
291        let backwards: Vec<NurbsCurve> = section.iter().rev().map(|curve| curve.reversed().or_refuse(stage, "loftOnGuides.reverse")).collect::<Result<_, _>>()?;
292        let mut fit = None;
293        'turns: for way in [section, &backwards] {
294            for turn in 0..count {
295                let mut fits = true;
296                for k in 0..count {
297                    if !on(order[k], ends(&way[(turn + k) % count])?[0])? {
298                        fits = false;
299                        break;
300                    }
301                }
302                if fits {
303                    fit = Some((0..count).map(|k| way[(turn + k) % count].clone()).collect::<Vec<_>>());
304                    break 'turns;
305                }
306            }
307        }
308        matched.push(fit.ok_or_else(|| input("section_off_guides", format!("section {index} cannot be turned so that each of its corners lies on the guide through the matching corner of the first section")))?);
309    }
310    let ordered: Vec<Vec<NurbsCurve>> = order.iter().map(|guide| guides[*guide].clone()).collect();
311    let (solid, walls) = chains_with_walls(&matched, &ordered)?;
312    Ok((solid, walls.into_iter().map(|wall| GuideLoftWall { guide: order[wall.guide], ..wall }).collect()))
313}
314
315fn chains_with_walls(sections: &[Vec<NurbsCurve>], guides: &[Vec<NurbsCurve>]) -> Result<(BrepSolid, Vec<GuideLoftWall>), KernelRefusal> {
316    let stage = KernelStage::Collect;
317    let count = guides.len();
318    if sections.len() < 2 || count < 2 || sections.iter().any(|section| section.len() != count) {
319        return Err(input("counts", format!("at least two sections are needed, each of as many curves as there are guides, at least 2 (got {} sections of {:?} curves and {count} guides)", sections.len(), sections.iter().map(Vec::len).collect::<Vec<_>>())));
320    }
321    let every: Vec<NurbsCurve> = sections.iter().flatten().chain(guides.iter().flatten()).cloned().collect();
322    let all = poles(&every);
323    let size = all.iter().map(|point| point.sub(all[0]).length()).fold(0.0, f64::max);
324    let tolerance = 1e-9 * size;
325    let near = |a: Vec3, b: Vec3| a.sub(b).length() <= tolerance;
326
327    // each chain run from the first section toward the last, and where each section meets it
328    let mut chains: Vec<Vec<NurbsCurve>> = Vec::with_capacity(count);
329    let mut turned = vec![false; count];
330    let mut stations: Vec<Vec<f64>> = Vec::with_capacity(count);
331    for (k, guide) in guides.iter().enumerate() {
332        for index in 1..guide.len() {
333            if !near(ends(&guide[index - 1])?[1], ends(&guide[index])?[0]) {
334                return Err(input("guide_chain", format!("curve {index} of guide {k} does not start where curve {} ends", index - 1)));
335            }
336        }
337        let place = |chain: &[NurbsCurve]| -> Result<Vec<f64>, KernelRefusal> {
338            sections.iter().enumerate().map(|(i, section)| Ok(station(chain, ends(&section[k])?[0], tolerance, k, i)?.along)).collect()
339        };
340        let mut chain = guide.clone();
341        let mut along = place(&chain)?;
342        if along[0] > along[along.len() - 1] {
343            chain = chain.iter().rev().map(|piece| piece.reversed().or_refuse(stage, "loftOnGuides.reverse")).collect::<Result<_, _>>()?;
344            along = place(&chain)?;
345            turned[k] = true;
346        }
347        if along.windows(2).any(|pair| pair[1] - pair[0] <= 1e-9) {
348            return Err(input("stations_order", format!("the sections do not follow one another along guide {k} (they meet it at {along:?} of its curves)")));
349        }
350        chains.push(chain);
351        stations.push(along);
352    }
353
354    let mut sheets = Vec::new();
355    let mut walls = Vec::new();
356    for span in 0..sections.len() - 1 {
357        let (foot, head) = (&sections[span], &sections[span + 1]);
358        let rails: Vec<Vec<NurbsCurve>> = (0..count).map(|k| between(&chains[k], stations[k][span], stations[k][span + 1])).collect::<Result<_, _>>()?;
359        for k in 0..count {
360            let next = (k + 1) % count;
361            let tiers = rails[k].len();
362            if rails[next].len() != tiers {
363                return Err(input("guide_pieces", format!("between sections {span} and {} guide {k} has {tiers} piece(s) and guide {next} has {}; the two guides of a wall need equally many", span + 1, rails[next].len())));
364            }
365            // each guide as one curve, piece j on the stretch from j to j + 1
366            let unit = vec![1.0; tiers];
367            let join = |pieces: &[NurbsCurve]| crate::curve_chain::join_curve_chain_on_spans(pieces, &unit).or_refuse(stage, "loftOnGuides.join");
368            let (rail, far_rail) = (join(&rails[k])?, join(&rails[next])?);
369            let [head_from, head_to] = ends(&head[k])?;
370            let pointed = near(head_from, head_to) && poles(&head[k..=k]).iter().all(|point| near(*point, head_from));
371            let patch = if pointed {
372                let family = crate::coons::compat::make_family_compatible(&[rail, far_rail], 1).or_refuse(KernelStage::Fragment, "loftOnGuides.compatible")?.0;
373                pointed_wall(&foot[k], &family[0], &family[1], k, tolerance)?
374            } else {
375                let far_side = head[k].reversed().or_refuse(stage, "loftOnGuides.reverse")?;
376                let back = rail.reversed().or_refuse(stage, "loftOnGuides.reverse")?;
377                coons_bilinear([foot[k].clone(), far_rail, far_side, back])
378                    .map_err(|error| KernelRefusal::unsupported(KernelStage::Fragment, "wall", format!("{LOFT_ON_GUIDES_REFUSAL}: wall {k} between sections {span} and {} has no Coons patch: {error:?}", span + 1)))?
379            };
380            // the guide's curves this wall runs along: the ones `between` kept a stretch of
381            let (from, to) = (stations[k][span], stations[k][span + 1]);
382            let pieces = (0..chains[k].len()).filter(|index| to.min((index + 1) as f64) - from.max(*index as f64) > 1e-12);
383            for (tier, piece) in split_at_joints(&patch, ends(&foot[k])?, ends(&rails[k][tiers - 1])?[1], tiers, tolerance)?.iter().zip(pieces) {
384                sheets.push(face_from_surface(tier)?);
385                walls.push(GuideLoftWall { side: k, span, guide: k, piece: if turned[k] { chains[k].len() - 1 - piece } else { piece } });
386            }
387        }
388    }
389    sheets.push(flat_end(&sections[0], size, "first")?);
390    let last = &sections[sections.len() - 1];
391    let apex = ends(&last[0])?[0];
392    if !poles(last).iter().all(|point| near(*point, apex)) {
393        sheets.push(flat_end(last, size, "last")?);
394    }
395    // sewing reads each edge's place by projection, whose own error on a cubic is near 1e-8
396    Ok((solid_from_sheets(&sheets, (1e-8 * size).max(1e-7))?, walls))
397}
398
399/// A wall's patch cut along its guides' joints into `tiers` faces' surfaces.
400/// `side` is the foot side's two ends and `up` the far end of the guide from
401/// the side's start: they tell which of the patch's two parameters runs along
402/// the guides. The joints are the patch's own knots at the whole `tiers`-ths of
403/// that parameter.
404fn split_at_joints(patch: &crate::NurbsSurface, side: [Vec3; 2], up: Vec3, tiers: usize, tolerance: f64) -> Result<Vec<crate::NurbsSurface>, KernelRefusal> {
405    if tiers == 1 {
406        return Ok(vec![patch.clone()]);
407    }
408    let stage = KernelStage::Fragment;
409    let [u0, u1] = patch.domain_u().or_refuse(stage, "loftOnGuides.domain")?;
410    let [v0, v1] = patch.domain_v().or_refuse(stage, "loftOnGuides.domain")?;
411    // the corner opposite the side's start along each parameter
412    let corners = [(u0, v0), (u1, v0), (u0, v1), (u1, v1)];
413    let mut origin = None;
414    for (u, v) in corners {
415        if patch.evaluate(u, v).or_refuse(stage, "loftOnGuides.corner")?.sub(side[0]).length() <= tolerance.max(1e-12) * 10.0 {
416            origin = Some((u, v));
417        }
418    }
419    let (ou, ov) = origin.ok_or_else(|| KernelRefusal::internal(stage, "wall_corner", format!("{LOFT_ON_GUIDES_REFUSAL}: the wall's patch does not start at its side's corner")))?;
420    let (other_u, other_v) = (if ou == u0 { u1 } else { u0 }, if ov == v0 { v1 } else { v0 });
421    let along_v = patch.evaluate(ou, other_v).or_refuse(stage, "loftOnGuides.corner")?.sub(up).length() <= patch.evaluate(other_u, ov).or_refuse(stage, "loftOnGuides.corner")?.sub(up).length();
422    let ([low, high], knots, degree) = if along_v { ([v0, v1], &patch.knots_v, patch.degree_v) } else { ([u0, u1], &patch.knots_u, patch.degree_u) };
423    let mut rest = patch.clone();
424    let mut parts = Vec::with_capacity(tiers);
425    for joint in 1..tiers {
426        let wanted = low + (high - low) * joint as f64 / tiers as f64;
427        let knot = knots.iter().copied().min_by(|a, b| (a - wanted).abs().partial_cmp(&(b - wanted).abs()).expect("finite knots")).expect("a knot");
428        let multiplicity = knots.iter().filter(|other| (**other - knot).abs() <= 1e-12).count();
429        if (knot - wanted).abs() > 1e-9 * (high - low) || multiplicity < degree {
430            return Err(KernelRefusal::internal(stage, "wall_joint", format!("{LOFT_ON_GUIDES_REFUSAL}: the wall's patch has no knot of full multiplicity at joint {joint} of {tiers}")));
431        }
432        let (before, after) = crate::split_surface(&rest, along_v, knot).or_refuse(stage, "loftOnGuides.split")?;
433        parts.push(before);
434        rest = after;
435    }
436    parts.push(rest);
437    Ok(parts)
438}
439