Skip to main content

brep_construction/construction/
solid_sweep_notch.rs

1//! A convex workpiece less a sweep that crosses one of its faces' planes and
2//! no other, built directly: the sweep's faces on the workpiece's side of that
3//! plane, turned inside out, and the face itself with the sweep's section in
4//! its plane as a hole. No general boolean: the sweep's faces are read, split
5//! only along a knot line that lies in the plane, and sewn to the face by the
6//! edges they already share.
7//!
8//! What makes it exact (each tested, else `None` and the caller cuts the sweep
9//! by the boolean):
10//! - the workpiece is convex with planar faces (every vertex on the inner side
11//!   of every face's plane; each face a parallelogram of a 1×1 net);
12//! - exactly one plane F has sweep control points outside it; the sweep's kept
13//!   faces lie strictly inside every other plane (their control points, which
14//!   hold them, by the hull property), so their section in F lies inside F;
15//! - each sweep face lies wholly on one side of F (its control points), or is
16//!   split along a full-multiplicity knot row lying in F, whose two sides each
17//!   lie on one side;
18//! - the edges the kept faces use once lie in F and close into one loop that
19//!   is shown simple (`section_is_simple`); that loop is the sweep's section in
20//!   F, a hole in F's face;
21//! - the result validates.
22
23use crate::topology::{BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord};
24use crate::{NurbsCurve, NurbsSurface, Vec3, Vec4};
25use std::collections::{HashMap, HashSet};
26
27/// The switch for [`notch_less`] (default on; `=0` answers None).
28pub fn notch_less_on() -> bool {
29    crate::switch!("BREP_SWEEP_NOTCH", true)
30}
31
32/// The workpiece less the sweep, built directly where the sweep crosses one
33/// face plane of a convex workpiece (module docs); `None` elsewhere, or with
34/// `BREP_SWEEP_NOTCH=0`.
35pub fn notch_less(workpiece: &BrepSolid, sweep: &BrepSolid) -> Option<BrepSolid> {
36    if !notch_less_on() {
37        return None;
38    }
39    // A decline below that names no reason reads as this one.
40    DECLINED.with(|cell| cell.set("declined without a stated reason"));
41    build(workpiece, sweep)
42}
43
44thread_local! {
45    /// The last decline's reason, for a reader that asks why (the tests).
46    static DECLINED: std::cell::Cell<&'static str> = const { std::cell::Cell::new("") };
47}
48
49/// Decline, saying why ([`last_decline`]).
50fn declined<T>(why: &'static str) -> Option<T> {
51    DECLINED.with(|cell| cell.set(why));
52    None
53}
54
55/// Why the last [`notch_less`] on this thread declined, if it said.
56pub fn last_decline() -> &'static str {
57    DECLINED.with(|cell| cell.get())
58}
59
60struct Plane {
61    point: Vec3,
62    normal: Vec3,
63}
64
65impl Plane {
66    fn height(&self, x: Vec3) -> f64 {
67        x.sub(self.point).dot(self.normal)
68    }
69}
70
71fn point(p: &Vec4) -> Option<Vec3> {
72    (p.w > 0.0 && p.w.is_finite()).then(|| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w))
73}
74
75/// A planar face's plane (outward) and its parallelogram chart, if it is one.
76fn face_plane(face: &FaceRecord) -> Option<(Plane, [Vec3; 3], [f64; 4])> {
77    let surface = &face.surface;
78    if surface.degree_u != 1 || surface.degree_v != 1 || surface.control_points.len() != 2 || surface.control_points[0].len() != 2 {
79        return None;
80    }
81    // Equal weights: a bilinear net of a parallelogram is then affine in its
82    // parameters (unequal ones bend the parametrisation, not the plane).
83    let w = surface.control_points[0][0].w;
84    if surface.control_points.iter().flatten().any(|p| p.w != w) {
85        return None;
86    }
87    let [u0, u1] = surface.domain_u().ok()?;
88    let [v0, v1] = surface.domain_v().ok()?;
89    let p00 = surface.evaluate(u0, v0).ok()?;
90    let p10 = surface.evaluate(u1, v0).ok()?;
91    let p01 = surface.evaluate(u0, v1).ok()?;
92    let p11 = surface.evaluate(u1, v1).ok()?;
93    let (eu, ev) = (p10.sub(p00), p01.sub(p00));
94    let size = eu.length().max(ev.length());
95    if p11.sub(p10.add(ev)).length() > 1e-12 * size.max(1.0) {
96        return None;
97    }
98    let normal = eu.cross(ev).normalized().ok()?;
99    let normal = if face.same_sense { normal } else { normal.scale(-1.0) };
100    Some((Plane { point: p00, normal }, [p00, eu, ev], [u0, u1, v0, v1]))
101}
102
103/// A world point of a parallelogram face's plane to its parameters.
104fn chart_uv(chart: &[Vec3; 3], domain: &[f64; 4], x: Vec3) -> [f64; 2] {
105    let [p00, eu, ev] = *chart;
106    let d = x.sub(p00);
107    let (a, b, c) = (eu.dot(eu), eu.dot(ev), ev.dot(ev));
108    let (e, f) = (eu.dot(d), ev.dot(d));
109    let det = a * c - b * b;
110    let (alpha, beta) = ((c * e - b * f) / det, (a * f - b * e) / det);
111    [domain[0] + alpha * (domain[1] - domain[0]), domain[2] + beta * (domain[3] - domain[2])]
112}
113
114/// A curve's control points' heights over a plane.
115fn curve_heights(curve: &NurbsCurve, plane: &Plane) -> Option<Vec<f64>> {
116    curve.control_points.iter().map(|p| point(p).map(|x| plane.height(x))).collect()
117}
118
119/// The first way a body's curves or surfaces are malformed, if any: a net not
120/// rectangular, a degree at or past its points' count, knots that do not fit
121/// (count, finite, non-decreasing).
122fn malformed(body: &BrepSolid) -> Option<&'static str> {
123    let knots_fit = |knots: &[f64], count: usize, degree: usize| {
124        degree < count && knots.len() == count + degree + 1 && knots.iter().all(|k| k.is_finite()) && knots.windows(2).all(|w| w[0] <= w[1])
125    };
126    let curve_fits = |c: &NurbsCurve| knots_fit(&c.knots, c.control_points.len(), c.degree);
127    for face in body.shells.iter().flat_map(|s| &s.faces) {
128        let net = &face.surface.control_points;
129        if net.is_empty() || net.iter().any(|row| row.is_empty() || row.len() != net[0].len()) {
130            return Some("a face's net is not rectangular");
131        }
132        if !knots_fit(&face.surface.knots_u, net.len(), face.surface.degree_u) || !knots_fit(&face.surface.knots_v, net[0].len(), face.surface.degree_v) {
133            return Some("a face's knots do not fit its net");
134        }
135        if face.loops.iter().flat_map(|l| &l.coedges).any(|c| !curve_fits(&c.pcurve)) {
136            return Some("a pcurve's knots do not fit its points");
137        }
138    }
139    if body.edges.iter().any(|e| !curve_fits(&e.curve)) {
140        return Some("an edge curve's knots do not fit its points");
141    }
142    None
143}
144
145/// One kept sweep face: its surface (maybe one side of a split) and loop.
146struct Kept {
147    surface: NurbsSurface,
148    same_sense: bool,
149    coedges: Vec<CoedgeRecord>,
150}
151
152/// The new edge along a split line: (curve, start vertex, end vertex).
153struct IsoEdge {
154    id: u64,
155    curve: NurbsCurve,
156    start: u64,
157    end: u64,
158}
159
160fn build(workpiece: &BrepSolid, sweep: &BrepSolid) -> Option<BrepSolid> {
161    if workpiece.kind != crate::BodyKind::Solid || sweep.kind != crate::BodyKind::Solid {
162        return declined("the workpiece and the sweep must be solids");
163    }
164    if workpiece.shells.len() != 1 || sweep.shells.len() != 1 || workpiece.shells[0].faces.iter().any(|f| f.loops.len() != 1) {
165        return declined("one shell each, the workpiece's faces one loop each");
166    }
167    // Both bodies well formed in every curve and surface they hold, so that
168    // nothing below reads past an array or sums a degree into an overflow.
169    for body in [workpiece, sweep] {
170        if let Some(why) = malformed(body) {
171            return declined(why);
172        }
173    }
174    // --- The workpiece: convex, planar.
175    let mut planes = Vec::new();
176    for face in &workpiece.shells[0].faces {
177        let Some(plane) = face_plane(face) else { return declined("a workpiece face is not a parallelogram of equal weights") };
178        planes.push(plane);
179    }
180    // The tolerance: of the workpiece's extent (what is kept of the sweep lies
181    // inside it; what lies outside, however far, does not widen it), and the
182    // rounding of a height read that far from the origin.
183    let (lo, hi) = workpiece.vertices.iter().fold(
184        (Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY)),
185        |(lo, hi), v| (Vec3::new(lo.x.min(v.point.x), lo.y.min(v.point.y), lo.z.min(v.point.z)), Vec3::new(hi.x.max(v.point.x), hi.y.max(v.point.y), hi.z.max(v.point.z))),
186    );
187    let extent = hi.sub(lo).length();
188    let reach = lo.x.abs().max(lo.y.abs()).max(lo.z.abs()).max(hi.x.abs()).max(hi.y.abs()).max(hi.z.abs());
189    if !(extent.is_finite() && extent > 0.0) {
190        return declined("no extent");
191    }
192    let tol = 1e-9 * extent + 8.0 * f64::EPSILON * reach;
193    for (plane, _, _) in &planes {
194        if workpiece.vertices.iter().any(|v| plane.height(v.point) > tol) {
195            return declined("the workpiece is not convex");
196        }
197    }
198    // --- The one plane the sweep crosses.
199    let sweep_points: Vec<Vec3> = sweep.shells[0]
200        .faces
201        .iter()
202        .flat_map(|f| f.surface.control_points.iter().flatten())
203        .map(point)
204        .collect::<Option<_>>()?;
205    let outside: Vec<usize> = (0..planes.len()).filter(|&j| sweep_points.iter().any(|&x| planes[j].0.height(x) > tol)).collect();
206    let [cut] = outside.as_slice() else { return declined(if outside.is_empty() { "the sweep crosses no face plane" } else { "the sweep crosses more than one face plane" }) };
207    let cut = *cut;
208    let plane = &planes[cut].0;
209    // --- The sweep's faces on the inner side of the plane.
210    let mut kept: Vec<Kept> = Vec::new();
211    let mut iso_edges: Vec<IsoEdge> = Vec::new();
212    // Ids are renumbered past the workpiece's: room for that, or declined.
213    const ROOM: u64 = u64::MAX / 8;
214    let sweep_ids = sweep
215        .vertices
216        .iter()
217        .map(|v| v.id)
218        .chain(sweep.edges.iter().flat_map(|e| [e.id, e.start_vertex_id, e.end_vertex_id]))
219        .chain(sweep.shells.iter().flat_map(|s| s.faces.iter().flat_map(|f| f.loops.iter().flat_map(|l| l.coedges.iter().map(|c| c.edge_id)))))
220        .max()
221        .unwrap_or(0);
222    if sweep_ids >= ROOM {
223        return declined("the sweep's ids leave no room to renumber");
224    }
225    let mut next_id = sweep_ids + 1;
226    let edge_of: HashMap<u64, &EdgeRecord> = sweep.edges.iter().map(|e| (e.id, e)).collect();
227    for face in &sweep.shells[0].faces {
228        if face.loops.len() != 1 {
229            return declined("a sweep face has more than one loop");
230        }
231        let heights: Vec<Vec<f64>> = face.surface.control_points.iter().map(|row| row.iter().map(|p| point(p).map(|x| plane.height(x))).collect::<Option<Vec<_>>>()).collect::<Option<_>>()?;
232        let all = heights.iter().flatten();
233        if all.clone().all(|&h| h <= tol) {
234            kept.push(Kept { surface: face.surface.clone(), same_sense: face.same_sense, coedges: face.loops[0].coedges.clone() });
235            continue;
236        }
237        if all.clone().all(|&h| h >= -tol) {
238            continue;
239        }
240        let Some((surface, coedges)) = split_face(face, &heights, tol, &edge_of, &mut next_id, &mut iso_edges) else {
241            return declined("a sweep face crossing the plane has no knot row in it to split along");
242        };
243        kept.push(Kept { surface, same_sense: face.same_sense, coedges });
244    }
245    if kept.is_empty() {
246        return declined("nothing of the sweep lies inside the workpiece");
247    }
248    // A kept face meets the plane only along its boundary: its net's interior
249    // points strictly inside (an interior point of the surface weighs at least
250    // one of them, positively). A face lying in the plane, or touching it
251    // inside, is not one the hole accounts for.
252    for k in &kept {
253        let net = &k.surface.control_points;
254        if net.len() < 3 || net[0].len() < 3 {
255            return declined("a kept face's net has no interior");
256        }
257        let interior = net[1..net.len() - 1].iter().flat_map(|row| &row[1..row.len() - 1]);
258        if interior.clone().any(|p| point(p).is_none_or(|x| plane.height(x) >= -tol)) {
259            return declined("a kept face reaches the plane inside its boundary");
260        }
261    }
262    // Kept faces strictly inside every other plane (by their control points).
263    for (j, (other, _, _)) in planes.iter().enumerate() {
264        if j == cut {
265            continue;
266        }
267        if kept.iter().flat_map(|k| k.surface.control_points.iter().flatten()).any(|p| point(p).is_none_or(|x| other.height(x) >= -tol)) {
268            return declined("a kept face reaches another face plane of the workpiece");
269        }
270    }
271    // --- The hole: edges the kept faces use once, in the plane, closed into one loop.
272    let iso_of: HashMap<u64, &IsoEdge> = iso_edges.iter().map(|e| (e.id, e)).collect();
273    let mut uses: HashMap<u64, Vec<bool>> = HashMap::new();
274    for k in &kept {
275        for c in &k.coedges {
276            uses.entry(c.edge_id).or_default().push(c.forward);
277        }
278    }
279    let degenerate = |id: u64| edge_of.get(&id).is_some_and(|e| e.degenerate);
280    let mut hole: Vec<(u64, bool)> = Vec::new();
281    for (&id, list) in &uses {
282        if degenerate(id) {
283            continue;
284        }
285        match list.as_slice() {
286            [_, _] => {}
287            [forward] => {
288                let curve = match (edge_of.get(&id), iso_of.get(&id)) {
289                    (Some(e), _) => &e.curve,
290                    (None, Some(iso)) => &iso.curve,
291                    _ => return declined("a hole edge is neither the sweep's nor a split's"),
292                };
293                if curve_heights(curve, plane)?.iter().any(|h| h.abs() > tol) {
294                    return declined("an edge the kept faces use once does not lie in the plane");
295                }
296                hole.push((id, *forward));
297            }
298            _ => return declined("a kept edge is used more than twice"),
299        }
300    }
301    let ends = |id: u64| -> Option<(u64, u64)> {
302        match (edge_of.get(&id), iso_of.get(&id)) {
303            (Some(e), _) => Some((e.start_vertex_id, e.end_vertex_id)),
304            (None, Some(iso)) => Some((iso.start, iso.end)),
305            _ => None,
306        }
307    };
308    let curve_of = |id: u64| -> Option<&NurbsCurve> {
309        match (edge_of.get(&id), iso_of.get(&id)) {
310            (Some(e), _) => Some(&e.curve),
311            (None, Some(iso)) => Some(&iso.curve),
312            _ => None,
313        }
314    };
315    // The hole uses each edge as the kept face did before it is turned.
316    let mut by_start: HashMap<u64, (u64, bool, u64)> = HashMap::new();
317    for &(id, forward) in &hole {
318        let (a, b) = ends(id)?;
319        let (from, to) = if forward { (a, b) } else { (b, a) };
320        if by_start.insert(from, (id, forward, to)).is_some() {
321            return declined("the hole's edges branch at a vertex");
322        }
323    }
324    let first = *hole.iter().map(|(id, _)| id).min()?;
325    let (start_vertex, _) = {
326        let (a, b) = ends(first)?;
327        let forward = hole.iter().find(|(id, _)| *id == first)?.1;
328        if forward { (a, b) } else { (b, a) }
329    };
330    let mut ring: Vec<(u64, bool)> = Vec::new();
331    let mut at = start_vertex;
332    for _ in 0..hole.len() {
333        let &(id, forward, to) = by_start.get(&at)?;
334        ring.push((id, forward));
335        at = to;
336    }
337    if at != start_vertex || ring.len() != hole.len() {
338        return declined("the hole's edges do not close into one loop");
339    }
340    // Nothing else kept meets the plane: an edge not in the hole stays
341    // strictly inside but at its ends, and an end (or a degenerate edge's
342    // point) in the plane is one of the hole's vertices.
343    let hole_vertices: HashSet<u64> = ring.iter().filter_map(|&(id, _)| ends(id)).flat_map(|(a, b)| [a, b]).collect();
344    let vertex_at: HashMap<u64, Vec3> = sweep.vertices.iter().map(|v| (v.id, v.point)).collect();
345    let in_hole: HashSet<u64> = ring.iter().map(|&(id, _)| id).collect();
346    for id in uses.keys() {
347        if in_hole.contains(id) {
348            continue;
349        }
350        let Some(edge) = edge_of.get(id) else { return declined("a kept edge is not the sweep's") };
351        let heights = curve_heights(&edge.curve, plane)?;
352        let n = heights.len();
353        if n < 2 {
354            return declined("a kept edge's curve has one point");
355        }
356        if !edge.degenerate && heights[1..n - 1].iter().any(|&h| h >= -tol) {
357            return declined("a kept edge reaches the plane outside the hole");
358        }
359        for vertex in [edge.start_vertex_id, edge.end_vertex_id] {
360            let at = vertex_at.get(&vertex)?;
361            if plane.height(*at) >= -tol && !hole_vertices.contains(&vertex) {
362                return declined("a kept edge reaches the plane outside the hole");
363            }
364        }
365    }
366    let ring_curves: Vec<NurbsCurve> = ring
367        .iter()
368        .map(|&(id, forward)| {
369            let curve = curve_of(id)?.clone();
370            if forward { Some(curve) } else { curve.reversed().ok() }
371        })
372        .collect::<Option<_>>()?;
373    if !crate::solid_sweep::section_is_simple(&ring_curves, plane.normal, extent) {
374        return declined("the hole's loop is not shown simple");
375    }
376    // --- Assemble: the workpiece, its cut face with the hole; the kept faces turned.
377    let offset = workpiece
378        .vertices
379        .iter()
380        .map(|v| v.id)
381        .chain(workpiece.edges.iter().map(|e| e.id))
382        .chain(workpiece.shells.iter().flat_map(|s| std::iter::once(s.id).chain(s.faces.iter().flat_map(|f| std::iter::once(f.id).chain(f.loops.iter().flat_map(|l| std::iter::once(l.id).chain(l.coedges.iter().map(|c| c.id))))))))
383        .chain(std::iter::once(workpiece.id))
384        .max()?;
385    if offset >= ROOM {
386        return declined("the workpiece's ids leave no room to renumber");
387    }
388    let offset = offset + 1;
389    let mut fresh = offset + next_id + 1;
390    let mut new_id = || {
391        fresh += 1;
392        fresh
393    };
394    let (_, chart, domain) = &planes[cut];
395    let mut hole_coedges = Vec::with_capacity(ring.len());
396    for (&(id, forward), curve) in ring.iter().zip(&ring_curves) {
397        let points: Vec<Vec4> = curve
398            .control_points
399            .iter()
400            .map(|p| {
401                let x = point(p)?;
402                let [u, v] = chart_uv(chart, domain, x);
403                Some(Vec4 { x: u * p.w, y: v * p.w, z: 0.0, w: p.w })
404            })
405            .collect::<Option<_>>()?;
406        let pcurve = NurbsCurve::new(curve.degree, curve.knots.clone(), points).ok()?;
407        hole_coedges.push(CoedgeRecord { id: new_id(), edge_id: id + offset, forward, pcurve });
408    }
409    let mut faces = Vec::new();
410    for (j, face) in workpiece.shells[0].faces.iter().enumerate() {
411        let mut face = face.clone();
412        if j == cut {
413            face.loops.push(LoopRecord { id: new_id(), coedges: hole_coedges.clone() });
414        }
415        faces.push(face);
416    }
417    let mut used_edges: HashSet<u64> = HashSet::new();
418    for k in &kept {
419        let mut coedges = Vec::with_capacity(k.coedges.len());
420        for c in k.coedges.iter().rev() {
421            used_edges.insert(c.edge_id);
422            coedges.push(CoedgeRecord { id: new_id(), edge_id: c.edge_id + offset, forward: !c.forward, pcurve: c.pcurve.reversed().ok()? });
423        }
424        faces.push(FaceRecord { id: new_id(), surface: k.surface.clone(), same_sense: !k.same_sense, loops: vec![LoopRecord { id: new_id(), coedges }], name: None });
425    }
426    let mut edges = workpiece.edges.clone();
427    let mut used_vertices: HashSet<u64> = HashSet::new();
428    for e in &sweep.edges {
429        if used_edges.contains(&e.id) {
430            used_vertices.insert(e.start_vertex_id);
431            used_vertices.insert(e.end_vertex_id);
432            let mut e = e.clone();
433            e.id += offset;
434            e.start_vertex_id += offset;
435            e.end_vertex_id += offset;
436            edges.push(e);
437        }
438    }
439    for iso in &iso_edges {
440        let [t0, t1] = iso.curve.domain().ok()?;
441        used_vertices.insert(iso.start);
442        used_vertices.insert(iso.end);
443        edges.push(EdgeRecord { id: iso.id + offset, curve: iso.curve.clone(), t0, t1, start_vertex_id: iso.start + offset, end_vertex_id: iso.end + offset, degenerate: false, name: None });
444    }
445    let mut vertices = workpiece.vertices.clone();
446    for v in &sweep.vertices {
447        if used_vertices.contains(&v.id) {
448            vertices.push(VertexRecord { id: v.id + offset, point: v.point });
449        }
450    }
451    let holes = faces.iter().map(|f| f.loops.len().saturating_sub(1)).sum::<usize>() as i64;
452    let euler = vertices.len() as i64 - edges.iter().filter(|e| !e.degenerate).count() as i64 + faces.len() as i64 - holes;
453    let body = BrepSolid {
454        mass_properties_cache: Default::default(),
455        cells: Default::default(),
456        id: new_id(),
457        vertices,
458        edges,
459        shells: vec![ShellRecord { id: new_id(), faces }],
460        genus: (2 - euler) / 2,
461        kind: workpiece.kind,
462    };
463    body.validate().is_empty().then_some(body)
464}
465
466/// One side of a sweep face split along a full-multiplicity knot row (u or v)
467/// lying in the plane, the side on the plane's inner side; its loop: the
468/// coedges on that side (a degenerate edge across the line cut to its side),
469/// and a new edge along the line closing the gap. None where the face does
470/// not split so.
471fn split_face(
472    face: &FaceRecord,
473    heights: &[Vec<f64>],
474    tol: f64,
475    edge_of: &HashMap<u64, &EdgeRecord>,
476    next_id: &mut u64,
477    iso_edges: &mut Vec<IsoEdge>,
478) -> Option<(NurbsSurface, Vec<CoedgeRecord>)> {
479    let surface = &face.surface;
480    for along_u in [true, false] {
481        // Index rows (u) or columns (v) uniformly.
482        let (degree, knots, count) = if along_u {
483            (surface.degree_u, &surface.knots_u, surface.control_points.len())
484        } else {
485            (surface.degree_v, &surface.knots_v, surface.control_points[0].len())
486        };
487        let line = |r: usize| -> Vec<f64> {
488            if along_u { heights[r].clone() } else { heights.iter().map(|row| row[r]).collect() }
489        };
490        for r in 1..count.saturating_sub(1) {
491            // Row r interpolates: knots r+1 ..= r+degree all one value.
492            if r + degree + 1 >= knots.len() || r < degree {
493                continue;
494            }
495            let k = knots[r + 1];
496            if !knots[r + 1..=r + degree].iter().all(|&x| x == k) || knots[r] == k || knots[r + degree + 1] == k {
497                continue;
498            }
499            if line(r).iter().any(|h| h.abs() > tol) {
500                continue;
501            }
502            let below = |range: std::ops::Range<usize>| range.flat_map(|i| line(i)).all(|h| h <= tol);
503            let above = |range: std::ops::Range<usize>| range.flat_map(|i| line(i)).all(|h| h >= -tol);
504            let keep_high = if below(r..count) && above(0..r + 1) {
505                true
506            } else if below(0..r + 1) && above(r..count) {
507                false
508            } else {
509                continue;
510            };
511            // The kept side's surface, its domain the original's part.
512            let (kept_knots, range): (Vec<f64>, std::ops::Range<usize>) = if keep_high {
513                (std::iter::repeat_n(k, degree + 1).chain(knots[r + degree + 1..].iter().copied()).collect(), r..count)
514            } else {
515                (knots[..r + 1].iter().copied().chain(std::iter::repeat_n(k, degree + 1)).collect(), 0..r + 1)
516            };
517            let net: Vec<Vec<Vec4>> = if along_u {
518                surface.control_points[range.clone()].to_vec()
519            } else {
520                surface.control_points.iter().map(|row| row[range.clone()].to_vec()).collect()
521            };
522            let kept_surface = if along_u {
523                NurbsSurface::new(surface.degree_u, surface.degree_v, kept_knots, surface.knots_v.clone(), net).ok()?
524            } else {
525                NurbsSurface::new(surface.degree_u, surface.degree_v, surface.knots_u.clone(), kept_knots, net).ok()?
526            };
527            // The line as a curve: row r over the other parameter.
528            let (other_degree, other_knots) = if along_u { (surface.degree_v, surface.knots_v.clone()) } else { (surface.degree_u, surface.knots_u.clone()) };
529            let row: Vec<Vec4> = if along_u { surface.control_points[r].clone() } else { surface.control_points.iter().map(|row| row[r]).collect() };
530            let iso = NurbsCurve::new(other_degree, other_knots, row).ok()?;
531            let [s0, s1] = iso.domain().ok()?;
532            // The coordinate across the line (u for a row), and along it.
533            let across = |p: &Vec4| if along_u { p.x / p.w } else { p.y / p.w };
534            let side = |x: f64| if keep_high { x >= k - 1e-12 } else { x <= k + 1e-12 };
535            let mut kept_coedges: Vec<CoedgeRecord> = Vec::new();
536            let mut cut_any = false;
537            for c in &face.loops[0].coedges {
538                let xs: Vec<f64> = c.pcurve.control_points.iter().map(across).collect();
539                if xs.iter().all(|&x| side(x)) {
540                    kept_coedges.push(c.clone());
541                } else if xs.iter().any(|&x| side(x)) {
542                    // Across the line: only a degenerate edge, a straight pcurve, is cut.
543                    let edge = edge_of.get(&c.edge_id)?;
544                    if !edge.degenerate || c.pcurve.degree != 1 || c.pcurve.control_points.len() != 2 {
545                        return None;
546                    }
547                    let clamp = |p: Vec4| -> Vec4 {
548                        let (u, v) = (p.x / p.w, p.y / p.w);
549                        let (u, v) = if along_u { (if side(u) { u } else { k }, v) } else { (u, if side(v) { v } else { k }) };
550                        Vec4 { x: u, y: v, z: 0.0, w: 1.0 }
551                    };
552                    let points = vec![clamp(c.pcurve.control_points[0]), clamp(c.pcurve.control_points[1])];
553                    let pcurve = NurbsCurve::new(1, c.pcurve.knots.clone(), points).ok()?;
554                    kept_coedges.push(CoedgeRecord { id: c.id, edge_id: c.edge_id, forward: c.forward, pcurve });
555                    cut_any = true;
556                }
557            }
558            let _ = cut_any;
559            // The gap: the one place the loop does not join, closed along the line.
560            let uv_end = |c: &CoedgeRecord| -> Option<[f64; 2]> {
561                let [_, d1] = c.pcurve.domain().ok()?;
562                let p = c.pcurve.evaluate(d1).ok()?;
563                Some([p.x, p.y])
564            };
565            let uv_start = |c: &CoedgeRecord| -> Option<[f64; 2]> {
566                let [d0, _] = c.pcurve.domain().ok()?;
567                let p = c.pcurve.evaluate(d0).ok()?;
568                Some([p.x, p.y])
569            };
570            let n = kept_coedges.len();
571            if n == 0 {
572                return None;
573            }
574            let mut gaps = Vec::new();
575            for i in 0..n {
576                let (a, b) = (uv_end(&kept_coedges[i])?, uv_start(&kept_coedges[(i + 1) % n])?);
577                if (a[0] - b[0]).hypot(a[1] - b[1]) > 1e-9 {
578                    gaps.push(i);
579                }
580            }
581            let [gap] = gaps.as_slice() else { return None };
582            let gap = *gap;
583            let (a, b) = (uv_end(&kept_coedges[gap])?, uv_start(&kept_coedges[(gap + 1) % n])?);
584            let along = |p: [f64; 2]| if along_u { p[1] } else { p[0] };
585            let (from, to) = (along(a), along(b));
586            // The gap spans the whole line, end to end.
587            let forward = if (from - s0).abs() < 1e-9 && (to - s1).abs() < 1e-9 {
588                true
589            } else if (from - s1).abs() < 1e-9 && (to - s0).abs() < 1e-9 {
590                false
591            } else {
592                return None;
593            };
594            // Its ends' vertices: where the coedges beside the gap end and start.
595            let vertex_end = |c: &CoedgeRecord| -> Option<u64> {
596                let e = edge_of.get(&c.edge_id)?;
597                Some(if c.forward { e.end_vertex_id } else { e.start_vertex_id })
598            };
599            let vertex_start = |c: &CoedgeRecord| -> Option<u64> {
600                let e = edge_of.get(&c.edge_id)?;
601                Some(if c.forward { e.start_vertex_id } else { e.end_vertex_id })
602            };
603            let (va, vb) = (vertex_end(&kept_coedges[gap])?, vertex_start(&kept_coedges[(gap + 1) % n])?);
604            let (start, end) = if forward { (va, vb) } else { (vb, va) };
605            let id = *next_id;
606            *next_id += 1;
607            let line_uv = |s: f64| if along_u { Vec4 { x: k, y: s, z: 0.0, w: 1.0 } } else { Vec4 { x: s, y: k, z: 0.0, w: 1.0 } };
608            let pcurve = NurbsCurve::new(1, vec![0.0, 0.0, 1.0, 1.0], vec![line_uv(from), line_uv(to)]).ok()?;
609            let iso_id = *next_id;
610            *next_id += 1;
611            kept_coedges.insert(gap + 1, CoedgeRecord { id: iso_id, edge_id: id, forward, pcurve });
612            iso_edges.push(IsoEdge { id, curve: iso, start, end });
613            return Some((kept_surface, kept_coedges));
614        }
615    }
616    None
617}
618