Skip to main content

brep_kernel/edit/direct_edit/
face_move_recut.rs

1//! Move Face by RE-CUTTING — the second road, for a motion whose answer is a
2//! different topology rather than the same topology re-solved.
3//!
4//! # Why a second road at all
5//!
6//! `face_move.rs` and `face_move_carrier.rs` both MOVE A CARRIER and re-solve
7//! the boundary that is already there. Where the motion leaves the body with
8//! the same faces meeting the same faces, that is the whole answer, and where
9//! it leaves two of them crossing, `healing/accept.rs` splits the pair along
10//! their exact section and drops the overshoot. Between them they cover every
11//! Transform Face the capability matrix records as building.
12//!
13//! They do not cover a motion whose result needs a face to STOP EXISTING.
14//! The 2026-09-22 inbox document is the first report of one: a rectangular
15//! through-slot cut into a block, with the slot's CEILING and one of its SIDE
16//! WALLS dragged together, the ceiling carried 90 mm — clean out of the top of
17//! the part. The right body is the slot re-cut as an open channel, which has
18//! the ceiling gone, both side walls re-trimmed against two different outer
19//! faces, and the slot's mouth loops on the two end faces merged into those
20//! faces' outer loops. Measured against the boolean that cuts the same channel
21//! directly: **10F 24E 16V**, where the direct edit leaves 11F.
22//!
23//! The pairwise crossing repair cannot reach that body, and the reason is
24//! structural rather than a threshold. It splits ONE pair of crossing faces
25//! along their carriers' section and drops pieces, closed over the faces the
26//! imprint cut. Here the two crossings (`Box_PZ | P.CU6_NX` and `Box_PX |
27//! P.CU6_PX`) BOUND EACH OTHER — the strip of the top face that has to go is
28//! bounded by both sections at once — and the face that has to go whole, the
29//! ceiling, is crossed by nothing at all, so no imprint ever cuts it.
30//!
31//! # The construction
32//!
33//! A planar face of a solid states a constraint on where the material is:
34//! everything inside lies on one side of its carrier. Moving that face moves
35//! the constraint, and the material that changes hands is the SLAB the carrier
36//! sweeps, bounded sideways by the faces that bound the moved face today. So:
37//!
38//! 1. Each moved face must carry a PLANE, and its trim must be one loop of
39//!    straight edges (`trim_polygon`). `delta` is how far the face moves
40//!    along its own outward normal `n̂` — `translation · n̂` for a
41//!    translation; a face whose `delta` is zero only slides inside its own
42//!    carrier, moves no material at all, and contributes no tool.
43//! 2. The trim is cut into convex CELLS (`convex_cells`): along its own
44//!    reflex corners — each cut extends the edge arriving at the corner across
45//!    the face to the boundary, so the new edge still lies on that edge's own
46//!    neighbour carrier — and, for a turn, along the HINGE the old and new
47//!    carriers meet in, wherever it crosses a cell. Every cell then lies on
48//!    one side of every plane that bounds it and moves one way.
49//! 3. The TOOL for a cell is the slab (for a turn, the wedge) between the
50//!    face's old and new carrier, intersected with one half-space per cell
51//!    edge — the neighbour's carrier across that edge, or the plane through
52//!    the hinge — and clipped to a box around the body big enough to hold the
53//!    motion.
54//! 4. Which SIDE of each bound the tool lies on is read from a PROBE POINT
55//!    rather than classified: the cell's centroid, displaced half way along
56//!    the cell's own normal motion, lies inside the slab (or wedge) by
57//!    construction, and the tool is on the side of every bound that contains
58//!    it. That one rule covers a cell moving INTO the body and a cell moving
59//!    OUT of it without a convexity branch.
60//! 5. Which POSITION of a neighbour that is itself in the selection bounds
61//!    the tool — where it was, or where the motion leaves it — is set algebra
62//!    on the feature the two faces bound together. For a boss `P = ∩ Mⱼ` (the
63//!    material half-spaces) the material added is `P' − P = ∪ᵢ (P' ∩ ¬Mᵢ)`,
64//!    bounded by the neighbours where the motion LEAVES them, and the material
65//!    removed is `P − P' = ∪ᵢ (P ∩ ¬M'ᵢ)`, bounded where they WERE; for a
66//!    cavity `C = ∩ ¬Mⱼ` the two swap. Read locally per (cell, neighbour): the
67//!    neighbour's MOVED plane iff the cell's seat is on the neighbour's
68//!    material side exactly when the cell moves out; its HOME plane otherwise.
69//!    (Always-moved, the rule until 2026-09-30, is the growth half of this; a
70//!    slot wall swinging out below a ceiling lifted clean out of the part would
71//!    have been filled up to that ceiling, a fin above the part.)
72//! 6. `delta < 0` — a cell moving against the face's outward normal — takes
73//!    material away, `delta > 0` adds it. The removing cells are unioned into
74//!    one tool and SUBTRACTED, the adding cells into another and UNIONED, in
75//!    that order. In the set algebra above the two tools are disjoint (what
76//!    a face removes lies inside the body's old bounds, what it adds outside
77//!    them), and on every fixture measured the order made no difference; a
78//!    selection that does both is what a turn across the hinge IS, and is no
79//!    longer refused.
80//!
81//! The cells of a direction are unioned before the body is cut, because two
82//! tools that share a carrier — the two arms of an L, or the reported
83//! document's two faces, which share both `x` and `z` planes — leave coplanar
84//! residue when they are subtracted one at a time.
85//!
86//! Two guards read every cell against its own bounds, so a decomposition that
87//! left something for a tool to miss refuses by name rather than cutting some
88//! of the material: `cell_is_its_bounds` (class `reflex_trim`; the pre-cell
89//! road's convex-core failure, measured at 3600 for a through-L of 3250) and
90//! `one_way_only` (the other wedge of a turned cell has volume inside the
91//! cell's bounds). Neither fires on a cell the cut produced; both fire the
92//! moment the cut is stubbed out.
93//!
94//! # A turn, too
95//!
96//! Transform Face's motion is rotate-then-translate, and a plane moved rigidly
97//! is still a plane, so `recut_moved_planes_rigid` takes the whole motion: the
98//! new carrier is the old one carried by it, the tool is the WEDGE between the
99//! two (inside one, outside the other — the slab's own two half-spaces, no
100//! longer parallel), `delta` is how far a cell's seat travels along `n̂` to
101//! reach the new carrier, and the probe sits half way there. A turn whose
102//! hinge crosses the face carries one side into the body and the other out;
103//! the hinge split gives each side its own cell and its own tool. A pure
104//! translation keeps this road's original SLAB arithmetic (`offset.max(offset
105//! + delta)`), so a convex face's slab is the same set of planes it was. The
106//! 2026-09-22 report that needed the turn is the slot document with its wall
107//! also turned 16.9°
108//! (`tests/suites/inbox_20260922_turned_slot_wall_transform_face.rs`); the
109//! same document turned 10° about a line ACROSS the wall is the case the
110//! hinge split closed on 2026-09-30.
111//!
112//! # What it is not
113//!
114//! It is not a repair: nothing about the self-intersecting body the direct
115//! edit built is read. It is the same edit performed the other way round, from
116//! the ORIGINAL body and the motion, which is why it can return a body with a
117//! different face count. `transform_face` reaches it only after `accept_sound`
118//! has refused, so no motion that builds today changes by a bit. Of the motions
119//! `move_faces` / `rotate_faces` themselves refuse, only one reaches it: a turned
120//! face TANGENT to a fillet beside it (`ruling_edge`). The fillet has no
121//! half-space, so the tool is bounded past it by the planar faces around it
122//! (`tangent_surround`). On the side that moves in, the plane cuts the fillet in
123//! a new ruling. On the side that moves out, it may miss the fillet altogether,
124//! and the fillet is then filled in, the tilted face meeting the wall beyond it.
125//! `reblend_lost_fillets` rounds that edge again at the fillet's radius, or
126//! under its radius law where the radius varies along it.
127//!
128//! Names are RE-STAMPED rather than collected, because the boolean mints its
129//! own faces: a result face whose carrier is an original face's carrier (at its
130//! moved position, for a moved face) takes that face's name, a carrier that
131//! arrives as two faces takes `name_1` for the second as the breakout already
132//! does, and a face whose carrier left the body keeps no name because it is no
133//! longer there.
134
135use super::*;
136use crate::offset_retrim::plane_of_surface;
137use crate::topology::ShellRecord;
138use crate::{
139    boolean_operation, make_plane, BooleanOperation, BooleanOptions,
140
141};
142use crate::curve::parameter_line;
143use crate::{KernelRefusal, KernelStage, OrRefuse};
144
145const OP: &str = "move_faces(re-cut)";
146
147/// A closed half-space `n̂·x ≤ offset`, with `n̂` a unit vector.
148#[derive(Clone, Copy, Debug)]
149struct HalfSpace {
150    normal: Vec3,
151    offset: f64,
152}
153
154
155/// Re-cut a solid for a pure TRANSLATION of planar faces.
156///
157/// `solid` is the body BEFORE the edit and `moved` its face ids; the result is
158/// the body the same selection and translation define, built as a boolean
159/// rather than as a carrier re-solve. See the module header for the
160/// construction and for every refusal.
161pub fn recut_moved_planes(
162    solid: &BrepSolid,
163    moved: &[u64],
164    translation: Vec3,
165) -> Result<BrepSolid, KernelRefusal> {
166    recut_moved_planes_rigid(solid, moved, None, translation)
167}
168
169/// The rigid motion a re-cut carries its selection by: an optional rotation
170/// (`p ↦ a + R·(p − a)`, the affine `rotate_faces` applies) FOLLOWED by a
171/// translation — Transform Face's rotate-then-translate, in its own order.
172struct Motion {
173    rotation: Option<AffineTransform>,
174    translation: Vec3,
175}
176
177impl Motion {
178    fn point(&self, point: Vec3) -> Vec3 {
179        match &self.rotation {
180            None => point.add(self.translation),
181            Some(rotation) => rotation.point(point).add(self.translation),
182        }
183    }
184
185    /// The oriented plane `n̂·x = offset`, carried. A pure translation keeps
186    /// the exact arithmetic the translation-only road always used —
187    /// `offset + t·n̂`.
188    fn plane(&self, normal: Vec3, offset: f64) -> (Vec3, f64) {
189        match &self.rotation {
190            None => (normal, offset + self.translation.dot(normal)),
191            Some(rotation) => {
192                let turned = super::face_rotate::rotate_direction(rotation, normal);
193                (turned, turned.dot(self.point(normal.scale(offset))))
194            }
195        }
196    }
197}
198
199/// Re-cut a solid for a RIGID motion of planar faces: `rotation`, when given as
200/// `(axis point, unit axis, angle in radians)`, is applied first and
201/// `translation` after it — Transform Face's rotate-then-translate.
202///
203/// A plane moved rigidly is still a plane, so everything the translation road
204/// does carries over with one generalisation: the old and the new carrier need
205/// no longer be parallel, and the material that changes hands is the WEDGE
206/// between them rather than a slab. That wedge is the same two half-spaces —
207/// inside the old carrier and outside the new one (material taken away), or
208/// the other way round (material added) — so `convex_solid` builds it as it
209/// built the slab.
210///
211/// The tool for one face is built per CELL of its trim rather than once for
212/// the face (`convex_cells`): the trim is cut into convex pieces along its own
213/// reflex edges, and a turned face is cut along the HINGE its two carriers
214/// meet in, so a cell lies on one side of every plane that bounds it and moves
215/// one way only. Each cell's tool is the slab or wedge intersected with one
216/// half-space per cell edge, the cells that take material away are unioned
217/// into one tool and subtracted, and the cells that add material are unioned
218/// into another and added. Two guards read every cell against its own bounds
219/// (`cell_is_its_bounds`, `one_way_only`), so a decomposition that left a cell
220/// reflex or straddling the hinge refuses by name rather than cutting some of
221/// the material.
222pub fn recut_moved_planes_rigid(
223    solid: &BrepSolid,
224    moved: &[u64],
225    rotation: Option<(Vec3, Vec3, f64)>,
226    translation: Vec3,
227) -> Result<BrepSolid, KernelRefusal> {
228    let scale = solid_model_scale(solid);
229    let tolerance = (scale * 1e-7).max(1e-9);
230    let moved_set: HashSet<u64> = moved.iter().copied().collect();
231    if moved_set.is_empty() {
232        return Err(KernelRefusal::input(
233            KernelStage::Collect,
234            "selection",
235            format!("{OP}: no face was selected"),
236        ));
237    }
238    let motion = Motion {
239        rotation: match rotation {
240            None => None,
241            Some((point, axis, angle)) => {
242                let axis = axis.normalized().map_err(|_| {
243                    KernelRefusal::input(
244                        KernelStage::Collect,
245                        "rotation_axis",
246                        format!("{OP}: the rotation axis has zero length"),
247                    )
248                })?;
249                Some(
250                    super::face_rotate::rotation_about(point, axis, angle)
251                        .or_input(KernelStage::Collect, "rotation")?,
252                )
253            }
254        },
255        translation,
256    };
257
258    // Every moved face's carrier, as an outward-pointing plane. A curved
259    // carrier is refused here and not approximated: the slab this road sweeps
260    // is a PLANE's slab and nothing else.
261    let mut carriers: Vec<(u64, Vec3, f64)> = Vec::new();
262    for &id in &moved_set {
263        let face = face_by_id(solid, id)?;
264        let plane = plane_of_surface(&face.surface, tolerance.max(1e-9) * 10.0, OP).map_err(
265            |error| {
266                KernelRefusal::unsupported(
267                    KernelStage::Classify,
268                    "curved_carrier",
269                    format!(
270                        "{error} — this road sweeps a PLANE's slab, so face {id}{} cannot take it",
271                        named(face)
272                    ),
273                )
274            },
275        )?;
276        let normal = if face.same_sense {
277            plane.normal
278        } else {
279            plane.normal.scale(-1.0)
280        };
281        carriers.push((id, normal, normal.dot(plane.origin)));
282    }
283    // Deterministic order: the tools are unioned in this order.
284    carriers.sort_by_key(|entry| entry.0);
285
286    // The clip box: the body's own bounds, grown by the motion and a margin,
287    // so a tool is a bounded polytope whatever its half-spaces leave open. A
288    // turn carries corners further than its translation alone says, so the
289    // bounds then also take every vertex where the motion leaves it.
290    let bounds = solid_bounds(solid)?;
291    let bounds = if motion.rotation.is_none() {
292        bounds
293    } else {
294        solid.vertices.iter().fold(bounds, |(low, high), vertex| {
295            let point = motion.point(vertex.point);
296            (
297                Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z)),
298                Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z)),
299            )
300        })
301    };
302    let margin = translation.length() + scale.max(1.0);
303    let clip = box_half_spaces(bounds, margin);
304
305    let motion_floor = (scale * 1e-9).max(1e-12);
306    let edge_band = (scale * 1e-7).max(1e-9);
307    let mut removing: Vec<BrepSolid> = Vec::new();
308    let mut adding: Vec<BrepSolid> = Vec::new();
309
310    for &(id, normal, offset) in &carriers {
311        let face = face_by_id(solid, id)?;
312        let (moved_normal, moved_offset) = motion.plane(normal, offset);
313        let facing = moved_normal.dot(normal);
314        if motion.rotation.is_some() && facing <= 1e-6 {
315            return Err(KernelRefusal::ill_posed(
316                KernelStage::Classify,
317                "turned_past_right_angle",
318                format!(
319                    "{OP}: the motion turns face {id}{} through a right angle or more, so its \
320                     new carrier does not face the way the old one did and there is no wedge \
321                     between them for a tool to fill; refusing",
322                    named(face)
323                ),
324            ));
325        }
326        let unturned = moved_normal.sub(normal).length() <= 1e-12;
327        // A pure translation reads the SAME delta everywhere on the face, in
328        // the arithmetic the translation-only road always used.
329        let translation_delta = translation.dot(normal);
330        if motion.rotation.is_none() && translation_delta.abs() <= motion_floor {
331            // Slides inside its own carrier: no material moves, no tool.
332            continue;
333        }
334
335        // Every face that bounds this one, with its outward plane at HOME and
336        // where the motion LEAVES it (the same plane for an unmoved face).
337        let mut neighbour_planes: HashMap<u64, ((Vec3, f64), (Vec3, f64))> = HashMap::default();
338        // A turned face's TANGENT curved neighbours (see `tangent_surround`).
339        let mut tangent_bands: HashSet<u64> = HashSet::default();
340        let polygon = trim_polygon(solid, face, normal, edge_band)?;
341        for source in &polygon.sources {
342            let &EdgeSource::Neighbour(neighbour) = source else { continue };
343            if neighbour_planes.contains_key(&neighbour) || tangent_bands.contains(&neighbour) {
344                continue;
345            }
346            let other = face_by_id(solid, neighbour)?;
347            if motion.rotation.is_some()
348                && !moved_set.contains(&neighbour)
349                && plane_of_surface(&other.surface, tolerance.max(1e-9) * 10.0, OP).is_err()
350                && band_is_tangent_along_shared_edges(face, other, normal)
351            {
352                tangent_bands.insert(neighbour);
353                continue;
354            }
355            let plane = plane_of_surface(&other.surface, tolerance.max(1e-9) * 10.0, OP)
356                .map_err(|error| {
357                    KernelRefusal::unsupported(
358                        KernelStage::Classify,
359                        "curved_neighbour",
360                        format!(
361                            "{error} — face {id}{} is bounded by face {neighbour}{}, and this road \
362                             needs every bounding carrier as a half-space",
363                            named(face),
364                            named(other)
365                        ),
366                    )
367                })?;
368            let outward = if other.same_sense {
369                plane.normal
370            } else {
371                plane.normal.scale(-1.0)
372            };
373            let home = (outward, outward.dot(plane.origin));
374            let left = if moved_set.contains(&neighbour) {
375                motion.plane(home.0, home.1)
376            } else {
377                home
378            };
379            neighbour_planes.insert(neighbour, (home, left));
380        }
381
382        // The hinge: the line the old and the new carrier meet in, in the
383        // face's own 2-D frame — only a TURN has one.
384        let hinge = if unturned {
385            None
386        } else {
387            polygon.frame.hinge(normal, offset, moved_normal, moved_offset)
388        };
389        let cells = convex_cells(&polygon, hinge, edge_band, scale).map_err(|error| {
390            KernelRefusal::internal(
391                KernelStage::Classify,
392                "cell_split",
393                format!("{OP}: face {id}{}'s trim could not be cut into convex cells — {error}", named(face)),
394            )
395        })?;
396
397        let surround = if tangent_bands.is_empty() {
398            None
399        } else {
400            Some(tangent_surround(solid, face, normal, offset, &tangent_bands, &moved_set, tolerance)?)
401        };
402
403        for cell in &cells {
404            let seat = polygon.frame.lift(cell.centroid());
405            // How far this cell travels along the face's own normal to reach
406            // the new carrier: `t·n̂` for a translation, the same everywhere;
407            // for a turn, read at the cell's own seat, which is on one side of
408            // the hinge by construction.
409            let delta = if motion.rotation.is_none() {
410                translation_delta
411            } else {
412                (moved_offset - moved_normal.dot(seat)) / facing
413            };
414            if delta.abs() <= motion_floor {
415                if unturned {
416                    continue;
417                }
418                return Err(KernelRefusal::ill_posed(
419                    KernelStage::Classify,
420                    "turned_through_trim",
421                    format!(
422                        "{OP}: the motion turns face {id}{} about a line through its own trim, and a \
423                         cell of the trim still sits on that line after the hinge split, so which way \
424                         it moves is not decided by the geometry; refusing rather than choosing",
425                        named(face)
426                    ),
427                ));
428            }
429            let adds = delta > 0.0;
430
431            // The two carriers the cell moves between. The tool is inside one
432            // and outside the other: inside the OLD and outside the NEW when
433            // the cell moves in (material leaves), the other way round when it
434            // moves out.
435            let (inner, outer) = if adds {
436                ((moved_normal, moved_offset), (normal, offset))
437            } else {
438                ((normal, offset), (moved_normal, moved_offset))
439            };
440            let wedge = |inner: (Vec3, f64), outer: (Vec3, f64)| {
441                [
442                    HalfSpace { normal: inner.0, offset: inner.1 },
443                    HalfSpace { normal: outer.0.scale(-1.0), offset: -outer.1 },
444                ]
445            };
446            // A growing cell beside a tangent band also fills what the band
447            // rounded off, so its inner wall starts behind the band.
448            let touches_band = cell.sources.iter().any(|source| {
449                matches!(source, EdgeSource::Neighbour(neighbour) if tangent_bands.contains(neighbour))
450            });
451            let (inner, outer) = match (&surround, adds && touches_band) {
452                (Some(surround), true) => (inner, (outer.0, outer.1 - surround.inner_wall_depth)),
453                _ => (inner, outer),
454            };
455            let mut spaces = clip.clone();
456            if let (Some(surround), true) = (&surround, touches_band) {
457                for plane in &surround.planes {
458                    push_unique(
459                        &mut spaces,
460                        HalfSpace { normal: plane.0, offset: plane.1 },
461                        tolerance,
462                    );
463                }
464            }
465            if motion.rotation.is_none() {
466                // The slab the carrier sweeps, in the arithmetic this road has
467                // always used for it.
468                spaces.push(HalfSpace {
469                    normal,
470                    offset: offset.max(offset + delta),
471                });
472                spaces.push(HalfSpace {
473                    normal: normal.scale(-1.0),
474                    offset: -offset.min(offset + delta),
475                });
476            } else {
477                spaces.extend(wedge(inner, outer));
478            }
479
480            // A point inside the cell, carried half way along the face's own
481            // normal to where its new carrier is: inside the slab (or wedge) by
482            // construction, and on the tool's side of every plane that bounds it.
483            let probe = seat.add(normal.scale(delta * 0.5));
484
485            // The bounds as they stand TODAY, kept beside the ones the tool
486            // uses so the cell can be read against them (`cell_is_its_bounds`).
487            let mut at_home: Vec<HalfSpace> = Vec::new();
488            // The bounds alone, for the other wedge (`one_way_only`).
489            let mut sides: Vec<HalfSpace> = Vec::new();
490
491            for (edge, source) in cell.sources.iter().enumerate() {
492                // A tangent band has no half-space: `surround.planes` bound the
493                // tool past it. For the cell's own read of its bounds, the edge
494                // stands for itself.
495                if matches!(source, EdgeSource::Neighbour(neighbour) if tangent_bands.contains(neighbour)) {
496                    let plane = polygon.frame.edge_plane(cell, edge);
497                    let home_sign = if plane.0.dot(seat) - plane.1 > 0.0 { -1.0 } else { 1.0 };
498                    push_unique(
499                        &mut at_home,
500                        HalfSpace { normal: plane.0.scale(home_sign), offset: plane.1 * home_sign },
501                        tolerance,
502                    );
503                    continue;
504                }
505                let (home, bound) = match source {
506                    EdgeSource::Neighbour(neighbour) => {
507                        let &(home, left) = neighbour_planes
508                            .get(neighbour)
509                            .expect("every neighbour's plane was read above");
510                        // Which position of a MOVED neighbour bounds the tool is
511                        // decided by set algebra on the feature the two faces
512                        // bound together. For a convex edge (the cell is on the
513                        // neighbour's MATERIAL side — a boss's top against its
514                        // wall) material added is `P' − P`, bounded by the
515                        // neighbours where the motion leaves them, and material
516                        // removed is `P − P'`, bounded where they were. For a
517                        // concave edge (the cell is on the neighbour's EMPTY
518                        // side — a slot's ceiling against its wall) it is the
519                        // other way round: the cavity that grows is bounded by
520                        // its new walls, the cavity that shrinks by its old ones.
521                        // So: the neighbour's MOVED plane iff the cell sits on
522                        // its material side exactly when the cell moves out.
523                        let material_side = home.0.dot(seat) - home.1 < 0.0;
524                        let bound = if material_side == adds { left } else { home };
525                        (home, bound)
526                    }
527                    EdgeSource::Hinge => {
528                        let plane = polygon.frame.edge_plane(cell, edge);
529                        (plane, plane)
530                    }
531                };
532                let reach = bound.0.dot(probe) - bound.1;
533                if reach.abs() <= tolerance {
534                    return Err(KernelRefusal::ill_posed(
535                        KernelStage::Classify,
536                        "probe_on_carrier",
537                        format!(
538                            "{OP}: the probe point for face {id} lies ON the carrier of one of its \
539                             bounds ({reach:.3e} from it), so which side of that carrier the tool \
540                             is on is not decided by the geometry; refusing rather than choosing"
541                        ),
542                    ));
543                }
544                let sign = if reach > 0.0 { -1.0 } else { 1.0 };
545                let bound = HalfSpace {
546                    normal: bound.0.scale(sign),
547                    offset: bound.1 * sign,
548                };
549                // HOME is oriented by the SEAT, which lies in the face's plane
550                // and strictly inside the cell: the side the trim is on.
551                let home_sign = if home.0.dot(seat) - home.1 > 0.0 { -1.0 } else { 1.0 };
552                push_unique(&mut spaces, bound, tolerance);
553                push_unique(&mut sides, bound, tolerance);
554                push_unique(
555                    &mut at_home,
556                    HalfSpace {
557                        normal: home.0.scale(home_sign),
558                        offset: home.1 * home_sign,
559                    },
560                    tolerance,
561                );
562            }
563            cell_is_its_bounds(face, cell, &polygon.frame, &at_home, scale)?;
564            if motion.rotation.is_some() {
565                let (home_inner, home_outer) = if adds {
566                    ((moved_normal, moved_offset), (normal, offset))
567                } else {
568                    ((normal, offset), (moved_normal, moved_offset))
569                };
570                one_way_only(id, &clip, &sides, wedge(home_outer, home_inner), tolerance, || named(face))?;
571            }
572
573            let tool = convex_solid(&spaces, probe, tolerance).map_err(|error| {
574                KernelRefusal::internal(
575                    KernelStage::Fragment,
576                    "tool_polytope",
577                    format!("{OP}: the tool for face {id} could not be built — {error}"),
578                )
579            })?;
580            if adds {
581                adding.push(tool);
582            } else {
583                removing.push(tool);
584            }
585        }
586    }
587    if removing.is_empty() && adding.is_empty() {
588        return Err(KernelRefusal::input(
589            KernelStage::Classify,
590            "in_plane_motion",
591            format!(
592                "{OP}: every selected face slides inside its own carrier (the motion has no \
593                 component along any of their normals), so there is no material for a re-cut to \
594                 move"
595            ),
596        ));
597    }
598
599    // One tool per direction, then one cut per direction. Two tools that share
600    // a carrier leave coplanar residue when they are applied one at a time,
601    // so the cells of a direction are unioned before the body is touched. The
602    // two directions' tools are disjoint by construction — what a face removes
603    // lies inside the body's old bounds and what it adds lies outside them —
604    // so the order of the two cuts is not a choice of answer; the subtract
605    // runs first so the added material meets a body already at its new bounds.
606    let unite = |mut tools: Vec<BrepSolid>| -> Result<Option<BrepSolid>, KernelRefusal> {
607        if tools.is_empty() {
608            return Ok(None);
609        }
610        let mut tool = tools.remove(0);
611        for next in tools {
612            // The boolean's own class rides through: a degeneracy inside the
613            // union is still a degeneracy at this road's boundary.
614            tool = boolean_operation(&tool, &next, BooleanOperation::Union, &BooleanOptions::default())
615                .map_err(|error| {
616                    error.with_message(|message| {
617                        format!("{OP}: the tools could not be unioned into one — {message}")
618                    })
619                })?;
620        }
621        Ok(Some(tool))
622    };
623    let mut cut = solid.clone();
624    if let Some(tool) = unite(removing)? {
625        cut = boolean_operation(&cut, &tool, BooleanOperation::Subtract, &BooleanOptions::default())
626            .map_err(|error| {
627                error.with_message(|message| format!("{OP}: the re-cut's subtract refused — {message}"))
628            })?;
629    }
630    if let Some(tool) = unite(adding)? {
631        cut = boolean_operation(&cut, &tool, BooleanOperation::Union, &BooleanOptions::default())
632            .map_err(|error| {
633                error.with_message(|message| format!("{OP}: the re-cut's union refused — {message}"))
634            })?;
635    }
636    Ok(restamp(cut, solid, &moved_set, &motion, tolerance))
637}
638
639/// Put back the fillets a re-cut filled in.
640///
641/// Where a turned plane misses a tangent fillet, the re-cut leaves the turned
642/// face meeting the wall beyond it at a sharp edge. That edge is rounded again
643/// at the fillet's radius and under its name, so the face re-meets its fillet.
644/// A fillet that cannot be re-made stays filled in; the returned notes name
645/// each one, with the reason, so the loss is never silent.
646pub fn reblend_lost_fillets(original: &BrepSolid, moved: &[u64], mut body: BrepSolid) -> (BrepSolid, Vec<String>) {
647    let tolerance = (solid_model_scale(original) * 1e-6).max(1e-9);
648    let moved_set: HashSet<u64> = moved.iter().copied().collect();
649    let faces: HashMap<u64, &FaceRecord> =
650        original.shells.iter().flat_map(|shell| &shell.faces).map(|face| (face.id, face)).collect();
651    let mut owners: HashMap<u64, Vec<u64>> = HashMap::default();
652    for face in faces.values() {
653        for coedge in face.loops.iter().flat_map(|wire| &wire.coedges) {
654            owners.entry(coedge.edge_id).or_default().push(face.id);
655        }
656    }
657    let across = |face: &FaceRecord| -> Vec<u64> {
658        let mut found: Vec<u64> = face
659            .loops
660            .iter()
661            .flat_map(|wire| &wire.coedges)
662            .flat_map(|coedge| owners.get(&coedge.edge_id).into_iter().flatten().copied())
663            .filter(|id| *id != face.id)
664            .collect();
665        found.sort_unstable();
666        found.dedup();
667        found
668    };
669    let mut notes = Vec::new();
670    let mut ordered = moved.to_vec();
671    ordered.sort_unstable();
672    for id in ordered {
673        let Some(&face) = faces.get(&id) else { continue };
674        let Ok(plane) = plane_of_surface(&face.surface, tolerance * 10.0, OP) else { continue };
675        for band_id in across(face) {
676            let band = faces[&band_id];
677            let Some(band_name) = band.name.clone() else { continue };
678            if moved_set.contains(&band_id)
679                || plane_of_surface(&band.surface, tolerance * 10.0, OP).is_ok()
680                || !band_is_tangent_along_shared_edges(face, band, plane.normal)
681                || body.shells.iter().flat_map(|shell| &shell.faces).any(|f| f.name.as_deref() == Some(&band_name))
682            {
683                continue;
684            }
685            // A constant radius is rolled again as it was. Any other band is
686            // read as a rolling-ball fillet under a radius law and re-made
687            // under that law (`blend_rebuild.rs`); one that reads as neither
688            // is still a fillet this edit filled in, so it is named.
689            let radius = super::face_move::ruled_revolution_carrier(&band.surface)
690                .filter(|(_, rho0, rho1, _)| (rho0 - rho1).abs() <= tolerance)
691                .map(|(_, rho0, _, _)| rho0);
692            let (remade, radius_label) = match radius {
693                Some(rho0) => (
694                    across(band)
695                        .into_iter()
696                        .filter(|wall| *wall != id)
697                        .find_map(|wall| {
698                            let wall = faces[&wall];
699                            let wall_plane = plane_of_surface(&wall.surface, tolerance * 10.0, OP).ok()?;
700                            band_is_tangent_along_shared_edges(wall, band, wall_plane.normal).then_some(wall)
701                        })
702                        .ok_or_else(|| "the wall beyond it could not be read".to_string())
703                        .and_then(|wall| sharp_edge_between(&body, face, wall))
704                        .and_then(|edge| {
705                            let rebuilt =
706                                crate::fillet_edge(&body, edge, rho0, Some(&band_name)).map_err(|e| e.to_string())?;
707                            let issues = rebuilt.validate();
708                            if !issues.is_empty() {
709                                return Err(format!("the new fillet is invalid: {issues:?}"));
710                            }
711                            // Checked one by one, so a fillet the acceptance would
712                            // refuse costs that fillet and not the whole edit.
713                            crate::accept_sound(rebuilt, "transformFace").map_err(|e| e.to_string())
714                        }),
715                    format!(" (radius {rho0})"),
716                ),
717                None => (
718                    super::blend_rebuild::read_band_law(original, band_id)
719                        .map_err(|reason| {
720                            format!(
721                                "it is neither a constant-radius fillet nor a rolling-ball fillet under a \
722                                 radius law: {reason}"
723                            )
724                        })
725                        .and_then(|law| super::blend_rebuild::remake_band(&body, &law, false, "transformFace")),
726                    String::new(),
727                ),
728            };
729            match remade {
730                Ok(rebuilt) => {
731                    body = rebuilt;
732                    // A blend that ran round the old fillet has nothing to run
733                    // round until it too is re-made; that is not built.
734                    for beside in across(band) {
735                        let beside = faces[&beside];
736                        let Some(beside_name) = beside.name.as_deref() else { continue };
737                        if !moved_set.contains(&beside.id)
738                            && plane_of_surface(&beside.surface, tolerance * 10.0, OP).is_err()
739                            && !body.shells.iter().flat_map(|shell| &shell.faces).any(|f| f.name.as_deref() == Some(beside_name))
740                        {
741                            notes.push(format!(
742                                "transformFace: blend `{beside_name}`, which ran round fillet \
743                                 `{band_name}`, was not re-made: the fillet was rebuilt at its radius \
744                                 and the faces either side of that blend now meet over it"
745                            ));
746                        }
747                    }
748                }
749                Err(reason) => notes.push(format!(
750                    "transformFace: fillet `{band_name}`{radius_label} was lost: the moved face no \
751                     longer reaches it, so it was filled in, and it could not be re-made ({reason})"
752                )),
753            }
754        }
755    }
756    (body, notes)
757}
758
759/// The one edge of `body` between the faces named as `first` and `second`.
760fn sharp_edge_between(body: &BrepSolid, first: &FaceRecord, second: &FaceRecord) -> Result<u64, String> {
761    let edges_of = |face: &FaceRecord| -> Result<HashSet<u64>, String> {
762        let name = face.name.as_deref().ok_or_else(|| format!("face {} has no name to find it by", face.id))?;
763        Ok(body
764            .shells
765            .iter()
766            .flat_map(|shell| &shell.faces)
767            .filter(|f| f.name.as_deref() == Some(name))
768            .flat_map(|f| f.loops.iter().flat_map(|wire| &wire.coedges).map(|coedge| coedge.edge_id))
769            .collect())
770    };
771    let (a, b) = (edges_of(first)?, edges_of(second)?);
772    let mut shared = a.intersection(&b).copied();
773    match (shared.next(), shared.next()) {
774        (Some(edge), None) => Ok(edge),
775        _ => Err("no single sharp edge joins the turned face to the wall beyond it".to_string()),
776    }
777}
778
779/// What bounds a turned face's wedge past the tangent band (a fillet) beside it.
780struct TangentSurround {
781    /// Outward planes `n̂·x ≤ o` of the planar faces reached across curved faces.
782    planes: Vec<(Vec3, f64)>,
783    /// How far behind the face a growing tool's inner wall must start.
784    inner_wall_depth: f64,
785}
786
787/// Is `band` tangent to the planar `face` along the edges they share?
788fn band_is_tangent_along_shared_edges(
789    face: &FaceRecord,
790    band: &FaceRecord,
791    normal: Vec3,
792) -> bool {
793    let own: HashSet<u64> =
794        face.loops.iter().flat_map(|wire| &wire.coedges).map(|coedge| coedge.edge_id).collect();
795    let mut shared = 0usize;
796    for coedge in band.loops.iter().flat_map(|wire| &wire.coedges) {
797        if !own.contains(&coedge.edge_id) {
798            continue;
799        }
800        let Ok([q0, q1]) = coedge.pcurve.domain() else {
801            return false;
802        };
803        let Ok(uv) = coedge.pcurve.evaluate(0.5 * (q0 + q1)) else {
804            return false;
805        };
806        let Ok(band_normal) = band.surface.normal(uv.x, uv.y) else {
807            return false;
808        };
809        if band_normal.cross(normal).length() > 1e-4 {
810            return false;
811        }
812        shared += 1;
813    }
814    shared > 0
815}
816
817/// The planar faces that close the region around a turned face's tangent bands:
818/// every planar face reached from the bands through curved faces only.
819///
820/// A plane missing a fillet leaves no ruling to re-meet, so the growing side's
821/// answer is the fillet filled in and the tilted face meeting the wall beyond
822/// it. Those walls bound the tool, which is sound only where the material is
823/// convex: every plane must hold every vertex of the region, or the tool could
824/// fill a pocket the part really has.
825fn tangent_surround(
826    solid: &BrepSolid,
827    face: &FaceRecord,
828    normal: Vec3,
829    offset: f64,
830    bands: &HashSet<u64>,
831    moved: &HashSet<u64>,
832    tolerance: f64,
833) -> Result<TangentSurround, KernelRefusal> {
834    let mut owners: HashMap<u64, Vec<u64>> = HashMap::default();
835    for other in solid.shells.iter().flat_map(|shell| &shell.faces) {
836        for coedge in other.loops.iter().flat_map(|wire| &wire.coedges) {
837            owners.entry(coedge.edge_id).or_default().push(other.id);
838        }
839    }
840    let edges: HashMap<u64, &EdgeRecord> = solid.edges.iter().map(|edge| (edge.id, edge)).collect();
841    let points: HashMap<u64, Vec3> =
842        solid.vertices.iter().map(|vertex| (vertex.id, vertex.point)).collect();
843    let plane_band = tolerance.max(1e-9) * 10.0;
844
845    let mut curved: HashSet<u64> = bands.clone();
846    let mut planar: HashSet<u64> = HashSet::default();
847    let mut stack: Vec<u64> = bands.iter().copied().collect();
848    while let Some(id) = stack.pop() {
849        let current = face_by_id(solid, id)?;
850        for coedge in current.loops.iter().flat_map(|wire| &wire.coedges) {
851            for &next in owners.get(&coedge.edge_id).into_iter().flatten() {
852                if next == id || next == face.id || curved.contains(&next) || planar.contains(&next) {
853                    continue;
854                }
855                if moved.contains(&next) {
856                    return Err(KernelRefusal::unsupported(
857                        KernelStage::Classify,
858                        "curved_neighbour",
859                        format!(
860                            "{OP}: face {next} is also selected and borders the fillet beside face \
861                             {}, so what bounds the tool past that fillet is itself moving; refusing",
862                            face.id
863                        ),
864                    ));
865                }
866                let other = face_by_id(solid, next)?;
867                if plane_of_surface(&other.surface, plane_band, OP).is_ok() {
868                    planar.insert(next);
869                } else {
870                    curved.insert(next);
871                    stack.push(next);
872                }
873            }
874        }
875    }
876
877    let vertices_of = |id: u64| -> Result<Vec<Vec3>, KernelRefusal> {
878        let mut found = Vec::new();
879        for coedge in face_by_id(solid, id)?.loops.iter().flat_map(|wire| &wire.coedges) {
880            if let Some(edge) = edges.get(&coedge.edge_id) {
881                found.extend(points.get(&edge.start_vertex_id).copied());
882                found.extend(points.get(&edge.end_vertex_id).copied());
883            }
884        }
885        Ok(found)
886    };
887    let mut region: Vec<Vec3> = Vec::new();
888    let mut depth = 0.0f64;
889    for &id in &curved {
890        for point in vertices_of(id)? {
891            depth = depth.max(offset - normal.dot(point));
892            region.push(point);
893        }
894    }
895    let mut ordered: Vec<u64> = planar.iter().copied().collect();
896    ordered.sort_unstable();
897    for &id in &ordered {
898        region.extend(vertices_of(id)?);
899    }
900
901    let mut planes = Vec::new();
902    for &id in &ordered {
903        let other = face_by_id(solid, id)?;
904        let plane = plane_of_surface(&other.surface, plane_band, OP)
905            .map_err(|error| KernelRefusal::unsupported(KernelStage::Classify, "curved_neighbour", error.to_string()))?;
906        let outward = if other.same_sense { plane.normal } else { plane.normal.scale(-1.0) };
907        let outward_offset = outward.dot(plane.origin);
908        if let Some(point) = region.iter().find(|point| outward.dot(**point) - outward_offset > plane_band) {
909            return Err(KernelRefusal::unsupported(
910                KernelStage::Classify,
911                "curved_neighbour",
912                format!(
913                    "{OP}: the part is not convex around the fillet beside face {} (face {id}{} has \
914                     material on both sides, at {point:?}), so the wedge a turn adds there has no \
915                     bound that keeps it out of the part's other features; refusing",
916                    face.id,
917                    named(other)
918                ),
919            ));
920        }
921        planes.push((outward, outward_offset));
922    }
923    Ok(TangentSurround { planes, inner_wall_depth: depth * 1.5 + tolerance })
924}
925
926/// Add a half-space unless an equal one (same normal, same offset within the
927/// band) is already listed: two cell edges on one carrier — a bookkeeping split,
928/// or an edge and the extension the reflex cut drew through it — must not put
929/// two coincident faces on the polytope.
930fn push_unique(spaces: &mut Vec<HalfSpace>, space: HalfSpace, tolerance: f64) {
931    let band = tolerance.max(1e-9) * 10.0;
932    if spaces.iter().any(|other| {
933        other.normal.sub(space.normal).length() <= 1e-9 && (other.offset - space.offset).abs() <= band
934    }) {
935        return;
936    }
937    spaces.push(space);
938}
939
940/// What a cell's edge lies on: the carrier of the face across that edge (an
941/// edge of the trim, or the extension of one the reflex cut drew), or the
942/// hinge line a turn splits the face along.
943#[derive(Clone, Copy, Debug, PartialEq)]
944enum EdgeSource {
945    Neighbour(u64),
946    Hinge,
947}
948
949/// A 2-D frame on a moved face's carrier: `origin + x·u + y·v`, with
950/// `u × v = n̂`, so counter-clockwise in `(x, y)` is counter-clockwise about
951/// the OUTWARD normal.
952#[derive(Clone, Copy, Debug)]
953struct Frame {
954    origin: Vec3,
955    u: Vec3,
956    v: Vec3,
957}
958
959impl Frame {
960    fn new(origin: Vec3, normal: Vec3) -> Result<Self, String> {
961        let u = normal.perpendicular()?.normalized()?;
962        let v = normal.cross(u).normalized()?;
963        Ok(Self { origin, u, v })
964    }
965
966    fn drop(&self, point: Vec3) -> [f64; 2] {
967        let delta = point.sub(self.origin);
968        [delta.dot(self.u), delta.dot(self.v)]
969    }
970
971    fn lift(&self, point: [f64; 2]) -> Vec3 {
972        self.origin.add(self.u.scale(point[0])).add(self.v.scale(point[1]))
973    }
974
975    /// The line the carrier `n̂·x = o` and the carrier `m̂·x = p` meet in, in
976    /// this frame, as `(point, unit direction)`; `None` when they are parallel.
977    fn hinge(&self, normal: Vec3, offset: f64, moved: Vec3, moved_offset: f64) -> Option<Line2> {
978        let direction = normal.cross(moved);
979        if direction.length() <= 1e-12 {
980            return None;
981        }
982        let direction = direction.normalized().ok()?;
983        // A point on both planes: the frame's origin is on the first; slide it
984        // within the first plane along the in-plane normal of the second.
985        let across = direction.cross(normal).normalized().ok()?;
986        let rate = moved.dot(across);
987        if rate.abs() <= 1e-12 {
988            return None;
989        }
990        let _ = offset;
991        let point = self.origin.add(across.scale((moved_offset - moved.dot(self.origin)) / rate));
992        let [px, py] = self.drop(point);
993        let [qx, qy] = self.drop(point.add(direction));
994        Some(Line2 {
995            point: [px, py],
996            direction: [qx - px, qy - py],
997        })
998    }
999
1000    /// The plane through the cell's `edge`, perpendicular to the face, as an
1001    /// outward half-space read from the cell's inside: the cell is on its `≤`
1002    /// side.
1003    fn edge_plane(&self, cell: &Cell, edge: usize) -> (Vec3, f64) {
1004        let a = cell.points[edge];
1005        let b = cell.points[(edge + 1) % cell.points.len()];
1006        // Counter-clockwise polygon: the outward normal of edge a→b is the
1007        // edge direction turned clockwise.
1008        let d = [b[0] - a[0], b[1] - a[1]];
1009        let length = (d[0] * d[0] + d[1] * d[1]).sqrt().max(1e-300);
1010        let out = [d[1] / length, -d[0] / length];
1011        let normal = self.u.scale(out[0]).add(self.v.scale(out[1]));
1012        let normal = normal.normalized().unwrap_or(normal);
1013        (normal, normal.dot(self.lift(a)))
1014    }
1015}
1016
1017/// A line in a `Frame`.
1018#[derive(Clone, Copy, Debug)]
1019struct Line2 {
1020    point: [f64; 2],
1021    direction: [f64; 2],
1022}
1023
1024impl Line2 {
1025    /// Signed distance of `p` from the line: positive to the LEFT of the
1026    /// direction.
1027    fn side(&self, p: [f64; 2]) -> f64 {
1028        let d = self.direction;
1029        let length = (d[0] * d[0] + d[1] * d[1]).sqrt().max(1e-300);
1030        (d[0] * (p[1] - self.point[1]) - d[1] * (p[0] - self.point[0])) / length
1031    }
1032}
1033
1034/// A planar polygon with each edge's source: edge `k` runs from `points[k]`
1035/// to `points[k + 1]` (wrapping) and lies on `sources[k]`. Wound
1036/// counter-clockwise about the face's outward normal.
1037#[derive(Clone, Debug)]
1038struct Cell {
1039    points: Vec<[f64; 2]>,
1040    sources: Vec<EdgeSource>,
1041}
1042
1043impl Cell {
1044    fn signed_area(&self) -> f64 {
1045        let n = self.points.len();
1046        (0..n)
1047            .map(|i| {
1048                let a = self.points[i];
1049                let b = self.points[(i + 1) % n];
1050                crate::polygon::area_term(a, b)
1051            })
1052            .sum::<f64>()
1053            * 0.5
1054    }
1055
1056    /// The area centroid — strictly inside a convex cell.
1057    fn centroid(&self) -> [f64; 2] {
1058        let n = self.points.len();
1059        let area = self.signed_area();
1060        if area.abs() <= 1e-300 {
1061            let mean = self.points.iter().fold([0.0, 0.0], |s, p| [s[0] + p[0], s[1] + p[1]]);
1062            return [mean[0] / n as f64, mean[1] / n as f64];
1063        }
1064        let mut cx = 0.0;
1065        let mut cy = 0.0;
1066        for i in 0..n {
1067            let a = self.points[i];
1068            let b = self.points[(i + 1) % n];
1069            let w = crate::polygon::area_term(a, b);
1070            cx += (a[0] + b[0]) * w;
1071            cy += (a[1] + b[1]) * w;
1072        }
1073        [cx / (6.0 * area), cy / (6.0 * area)]
1074    }
1075
1076    /// The first vertex where the boundary turns RIGHT (a reflex corner of a
1077    /// counter-clockwise polygon), or `None` for a convex one. A straight
1078    /// continuation (a bookkeeping split of one edge) is not a turn.
1079    fn reflex_vertex(&self, band: f64) -> Option<usize> {
1080        let n = self.points.len();
1081        (0..n).find(|&i| {
1082            let p = self.points[(i + n - 1) % n];
1083            let q = self.points[i];
1084            let r = self.points[(i + 1) % n];
1085            let a = [q[0] - p[0], q[1] - p[1]];
1086            let b = [r[0] - q[0], r[1] - q[1]];
1087            let la = (a[0] * a[0] + a[1] * a[1]).sqrt();
1088            let lb = (b[0] * b[0] + b[1] * b[1]).sqrt();
1089            if la <= band || lb <= band {
1090                return false;
1091            }
1092            // The turn's sine times the shorter edge: a right turn deeper than
1093            // the band.
1094            (a[0] * b[1] - a[1] * b[0]) / la.max(lb) < -band
1095        })
1096    }
1097}
1098
1099/// The polygon a moved face's trim is, with its frame.
1100struct TrimPolygon {
1101    frame: Frame,
1102    points: Vec<[f64; 2]>,
1103    sources: Vec<EdgeSource>,
1104}
1105
1106/// Read a moved face's trim as a polygon in its own frame: one loop, every
1107/// edge straight, every edge shared with exactly one other face, which is the
1108/// edge's source. Refuses by name what it cannot read: an island (a second
1109/// loop, whose neighbours bound nothing this decomposition sees), a curved
1110/// edge (which a planar neighbour cannot produce) and an edge no other face
1111/// holds.
1112fn trim_polygon(
1113    solid: &BrepSolid,
1114    face: &FaceRecord,
1115    normal: Vec3,
1116    band: f64,
1117) -> Result<TrimPolygon, KernelRefusal> {
1118    let id = face.id;
1119    if face.loops.len() != 1 {
1120        return Err(KernelRefusal::unsupported(
1121            KernelStage::Classify,
1122            "island_trim",
1123            format!(
1124                "{OP}: face {id}{} has {} loops, so its trim has an island whose walls bound no cell \
1125                 of the outer trim, and this road cuts one convex cell at a time; refusing rather \
1126                 than filling the island",
1127                named(face),
1128                face.loops.len()
1129            ),
1130        ));
1131    }
1132    let edges: HashMap<u64, &EdgeRecord> = solid.edges.iter().map(|edge| (edge.id, edge)).collect();
1133    let vertices: HashMap<u64, Vec3> =
1134        solid.vertices.iter().map(|vertex| (vertex.id, vertex.point)).collect();
1135    // The face across each edge of this face.
1136    let mut across: HashMap<u64, u64> = HashMap::default();
1137    for other in solid.shells.iter().flat_map(|shell| &shell.faces) {
1138        if other.id == id {
1139            continue;
1140        }
1141        for coedge in other.loops.iter().flat_map(|wire| &wire.coedges) {
1142            across.entry(coedge.edge_id).or_insert(other.id);
1143        }
1144    }
1145    let mut points3: Vec<Vec3> = Vec::new();
1146    let mut sources: Vec<EdgeSource> = Vec::new();
1147    for coedge in &face.loops[0].coedges {
1148        let edge = edges.get(&coedge.edge_id).ok_or_else(|| {
1149            KernelRefusal::input(
1150                KernelStage::Collect,
1151                "missing_edge",
1152                format!("{OP}: face {id} uses edge {} which the solid does not hold", coedge.edge_id),
1153            )
1154        })?;
1155        if edge.degenerate {
1156            continue;
1157        }
1158        let (start_id, end_id) = if coedge.forward {
1159            (edge.start_vertex_id, edge.end_vertex_id)
1160        } else {
1161            (edge.end_vertex_id, edge.start_vertex_id)
1162        };
1163        let start = *vertices.get(&start_id).ok_or_else(|| {
1164            KernelRefusal::input(
1165                KernelStage::Collect,
1166                "missing_vertex",
1167                format!("{OP}: edge {} starts at vertex {start_id}, which the solid does not hold", edge.id),
1168            )
1169        })?;
1170        let end = *vertices.get(&end_id).ok_or_else(|| {
1171            KernelRefusal::input(
1172                KernelStage::Collect,
1173                "missing_vertex",
1174                format!("{OP}: edge {} ends at vertex {end_id}, which the solid does not hold", edge.id),
1175            )
1176        })?;
1177        // Straight: the curve's midpoint is the chord's.
1178        let middle = edge
1179            .curve
1180            .evaluate(0.5 * (edge.t0 + edge.t1))
1181            .or_refuse(KernelStage::Classify, "evaluate")?;
1182        let chord_middle = start.add(end).scale(0.5);
1183        if middle.sub(chord_middle).length() > band.max(1e-9) * 100.0 {
1184            return Err(KernelRefusal::unsupported(
1185                KernelStage::Classify,
1186                "curved_edge",
1187                format!(
1188                    "{OP}: edge {} of face {id}{} is not straight (its midpoint is {:.3e} off its \
1189                     chord), so the trim is not a polygon this road can cut into cells",
1190                    edge.id,
1191                    named(face),
1192                    middle.sub(chord_middle).length()
1193                ),
1194            ));
1195        }
1196        let neighbour = *across.get(&edge.id).ok_or_else(|| {
1197            KernelRefusal::unsupported(
1198                KernelStage::Classify,
1199                "open_edge",
1200                format!(
1201                    "{OP}: edge {} of face {id}{} is held by no other face, so nothing bounds the \
1202                     tool there",
1203                    edge.id,
1204                    named(face)
1205                ),
1206            )
1207        })?;
1208        points3.push(start);
1209        sources.push(EdgeSource::Neighbour(neighbour));
1210    }
1211    if points3.len() < 3 {
1212        return Err(KernelRefusal::unsupported(
1213            KernelStage::Classify,
1214            "thin_trim",
1215            format!("{OP}: face {id}{} has fewer than three corners", named(face)),
1216        ));
1217    }
1218    let frame = Frame::new(points3[0], normal).map_err(|error| {
1219        KernelRefusal::internal(KernelStage::Classify, "frame", format!("{OP}: {error}"))
1220    })?;
1221    let mut points: Vec<[f64; 2]> = points3.iter().map(|point| frame.drop(*point)).collect();
1222    let probe = Cell { points: points.clone(), sources: sources.clone() };
1223    if probe.signed_area() < 0.0 {
1224        // Wound clockwise about the outward normal: reverse, keeping each
1225        // edge's source with its edge.
1226        points.reverse();
1227        sources.reverse();
1228        sources.rotate_left(1);
1229        let _ = &mut points;
1230    }
1231    Ok(TrimPolygon { frame, points, sources })
1232}
1233
1234/// Cut a trim polygon into convex cells: first along its own reflex corners
1235/// (each cut extends the edge ARRIVING at the corner through the interior to
1236/// the boundary, so the new edge lies on that edge's own carrier), then, for
1237/// a turn, along the hinge wherever it crosses a cell. Cells thinner than the
1238/// band are dropped.
1239fn convex_cells(
1240    polygon: &TrimPolygon,
1241    hinge: Option<Line2>,
1242    band: f64,
1243    scale: f64,
1244) -> Result<Vec<Cell>, String> {
1245    let area_floor = (band * scale).max(1e-18);
1246    let mut pending = vec![Cell {
1247        points: polygon.points.clone(),
1248        sources: polygon.sources.clone(),
1249    }];
1250    let mut convex: Vec<Cell> = Vec::new();
1251    let mut rounds = 0usize;
1252    while let Some(cell) = pending.pop() {
1253        rounds += 1;
1254        if rounds > 256 {
1255            return Err("the reflex cut did not converge in 256 rounds".into());
1256        }
1257        let cell = dedupe(cell, band);
1258        if cell.points.len() < 3 || cell.signed_area().abs() <= area_floor {
1259            continue;
1260        }
1261        match cell.reflex_vertex(band) {
1262            None => convex.push(cell),
1263            Some(vertex) => {
1264                let (first, second) = split_at_reflex(&cell, vertex, band)?;
1265                pending.push(first);
1266                pending.push(second);
1267            }
1268        }
1269    }
1270    let Some(hinge) = hinge else { return Ok(convex) };
1271    let mut cells: Vec<Cell> = Vec::new();
1272    for cell in convex {
1273        let sides: Vec<f64> = cell.points.iter().map(|point| hinge.side(*point)).collect();
1274        let high = sides.iter().copied().fold(f64::MIN, f64::max);
1275        let low = sides.iter().copied().fold(f64::MAX, f64::min);
1276        if high > band && low < -band {
1277            for half in split_by_line(&cell, &sides, band) {
1278                let half = dedupe(half, band);
1279                if half.points.len() >= 3 && half.signed_area().abs() > area_floor {
1280                    cells.push(half);
1281                }
1282            }
1283        } else {
1284            cells.push(cell);
1285        }
1286    }
1287    Ok(cells)
1288}
1289
1290/// Drop consecutive points closer than the band, keeping the source of the
1291/// edge that LEAVES the surviving point.
1292fn dedupe(cell: Cell, band: f64) -> Cell {
1293    let mut points: Vec<[f64; 2]> = Vec::new();
1294    let mut sources: Vec<EdgeSource> = Vec::new();
1295    for (point, source) in cell.points.iter().zip(&cell.sources) {
1296        if let Some(last) = points.last() {
1297            if (last[0] - point[0]).hypot(last[1] - point[1]) <= band {
1298                // The edge leaving the merged point is this one's.
1299                *sources.last_mut().expect("as many sources as points") = *source;
1300                continue;
1301            }
1302        }
1303        points.push(*point);
1304        sources.push(*source);
1305    }
1306    while points.len() >= 2 {
1307        let first = points[0];
1308        let last = points[points.len() - 1];
1309        if (last[0] - first[0]).hypot(last[1] - first[1]) <= band {
1310            points.pop();
1311            let source = sources.pop().expect("as many sources as points");
1312            let _ = source;
1313        } else {
1314            break;
1315        }
1316    }
1317    Cell { points, sources }
1318}
1319
1320/// Cut `cell` at its reflex `vertex`: the edge arriving there is extended
1321/// through the interior to the first boundary edge it meets, and the polygon
1322/// is split along that segment. Both pieces keep every edge's source, and
1323/// the new edge takes the arriving edge's.
1324fn split_at_reflex(cell: &Cell, vertex: usize, band: f64) -> Result<(Cell, Cell), String> {
1325    let n = cell.points.len();
1326    // Rotate so the reflex vertex is index 0; the arriving edge is then n − 1.
1327    let points: Vec<[f64; 2]> = (0..n).map(|i| cell.points[(vertex + i) % n]).collect();
1328    let sources: Vec<EdgeSource> = (0..n).map(|i| cell.sources[(vertex + i) % n]).collect();
1329    let p0 = points[0];
1330    let prev = points[n - 1];
1331    let d = [p0[0] - prev[0], p0[1] - prev[1]];
1332    let length = (d[0] * d[0] + d[1] * d[1]).sqrt();
1333    if length <= band {
1334        return Err("a reflex corner with a zero-length arriving edge".into());
1335    }
1336    let d = [d[0] / length, d[1] / length];
1337    // The first edge the ray meets, not counting the two at the corner.
1338    let mut best: Option<(usize, f64, f64)> = None;
1339    for j in 1..(n - 1) {
1340        let a = points[j];
1341        let b = points[(j + 1) % n];
1342        let e = [b[0] - a[0], b[1] - a[1]];
1343        let denominator = d[0] * e[1] - d[1] * e[0];
1344        if denominator.abs() <= 1e-15 {
1345            continue;
1346        }
1347        let w = [a[0] - p0[0], a[1] - p0[1]];
1348        let t = (w[0] * e[1] - w[1] * e[0]) / denominator;
1349        let s = (w[0] * d[1] - w[1] * d[0]) / denominator;
1350        let e_length = (e[0] * e[0] + e[1] * e[1]).sqrt().max(1e-300);
1351        let s_band = band / e_length;
1352        if t <= band || s < -s_band || s > 1.0 + s_band {
1353            continue;
1354        }
1355        if best.map_or(true, |(_, best_t, _)| t < best_t) {
1356            best = Some((j, t, s.clamp(0.0, 1.0)));
1357        }
1358    }
1359    let Some((j, t, s)) = best else {
1360        return Err(format!("the extension of the edge arriving at corner {vertex} meets no boundary edge"));
1361    };
1362    let hit = [p0[0] + d[0] * t, p0[1] + d[1] * t];
1363    let a = points[j];
1364    let b = points[(j + 1) % n];
1365    let e_length = ((b[0] - a[0]).powi(2) + (b[1] - a[1]).powi(2)).sqrt().max(1e-300);
1366    let at_a = s * e_length <= band;
1367    let at_b = (1.0 - s) * e_length <= band;
1368    let arriving = sources[n - 1];
1369    // First piece: P0 … Pj (, hit), closed back to P0 along the extension.
1370    let mut first_points: Vec<[f64; 2]> = points[0..=j].to_vec();
1371    let mut first_sources: Vec<EdgeSource> = sources[0..j].to_vec();
1372    if at_b {
1373        first_points.push(b);
1374        first_sources.push(sources[j]);
1375    } else if !at_a {
1376        first_points.push(hit);
1377        first_sources.push(sources[j]);
1378    }
1379    first_sources.push(arriving);
1380    // Second piece: (hit,) P(j+1) … P(n−1), closed back along the extension
1381    // through P0, which is a straight continuation and is dropped.
1382    let mut second_points: Vec<[f64; 2]> = Vec::new();
1383    let mut second_sources: Vec<EdgeSource> = Vec::new();
1384    if at_a {
1385        second_points.push(a);
1386        second_sources.push(sources[j]);
1387    } else if !at_b {
1388        second_points.push(hit);
1389        second_sources.push(sources[j]);
1390    }
1391    for k in (j + 1)..n {
1392        second_points.push(points[k]);
1393        second_sources.push(sources[k]);
1394    }
1395    // The last source is that of P(n−1) → P0 → hit: the arriving edge's.
1396    *second_sources.last_mut().expect("the second piece has an edge") = arriving;
1397    Ok((
1398        Cell { points: first_points, sources: first_sources },
1399        Cell { points: second_points, sources: second_sources },
1400    ))
1401}
1402
1403/// Split a CONVEX cell by a line, given each vertex's signed side; the two
1404/// halves keep their edges' sources and the edges along the line are `Hinge`.
1405fn split_by_line(cell: &Cell, sides: &[f64], band: f64) -> [Cell; 2] {
1406    let n = cell.points.len();
1407    let mut positive = Cell { points: Vec::new(), sources: Vec::new() };
1408    let mut negative = Cell { points: Vec::new(), sources: Vec::new() };
1409    for j in 0..n {
1410        let p = cell.points[j];
1411        let q = cell.points[(j + 1) % n];
1412        let (fp, fq) = (sides[j], sides[(j + 1) % n]);
1413        let source = cell.sources[j];
1414        let p_on = fp.abs() <= band;
1415        let q_on = fq.abs() <= band;
1416        // P itself, to every side it is on. Only an on-line point's leaving
1417        // edge can run along the line, and only when Q is off that side. A
1418        // point strictly on a side keeps the edge's source even when the edge
1419        // crosses: the piece from P to the crossing is still that edge.
1420        if fp > band || p_on {
1421            positive.points.push(p);
1422            positive.sources.push(if !p_on || fq > band || q_on { source } else { EdgeSource::Hinge });
1423        }
1424        if fp < -band || p_on {
1425            negative.points.push(p);
1426            negative.sources.push(if !p_on || fq < -band || q_on { source } else { EdgeSource::Hinge });
1427        }
1428        // A strict crossing: the crossing point goes to both sides.
1429        if (fp > band && fq < -band) || (fp < -band && fq > band) {
1430            let t = fp / (fp - fq);
1431            let x = [p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t];
1432            if fp > band {
1433                positive.points.push(x);
1434                positive.sources.push(EdgeSource::Hinge);
1435                negative.points.push(x);
1436                negative.sources.push(source);
1437            } else {
1438                negative.points.push(x);
1439                negative.sources.push(EdgeSource::Hinge);
1440                positive.points.push(x);
1441                positive.sources.push(source);
1442            }
1443        }
1444    }
1445    [positive, negative]
1446}
1447
1448/// A TURNED cell must move one way only. The wedge on the other side of the
1449/// carriers' common line — the same bounds, the carrier pair swapped — is the
1450/// material the cell would carry the other way; any corner it has further than
1451/// the band from BOTH carriers means that wedge has volume inside the cell's
1452/// bounds, and the tool this road builds would leave it untouched. A cell the
1453/// hinge split left on one side of the hinge has that hinge among its bounds,
1454/// so the other wedge is squeezed onto the line and reads zero.
1455fn one_way_only(
1456    id: u64,
1457    clip: &[HalfSpace],
1458    sides: &[HalfSpace],
1459    other: [HalfSpace; 2],
1460    tolerance: f64,
1461    name: impl Fn() -> String,
1462) -> Result<(), KernelRefusal> {
1463    let band = tolerance.max(1e-9) * 10.0;
1464    let spaces: Vec<HalfSpace> = clip.iter().chain(sides).chain(&other).copied().collect();
1465    let mut depth = 0.0f64;
1466    for a in 0..spaces.len() {
1467        for b in (a + 1)..spaces.len() {
1468            for c in (b + 1)..spaces.len() {
1469                let Some(point) = three_plane_point(&spaces[a], &spaces[b], &spaces[c]) else {
1470                    continue;
1471                };
1472                if spaces
1473                    .iter()
1474                    .any(|space| space.normal.dot(point) - space.offset > band)
1475                {
1476                    continue;
1477                }
1478                // How far inside the two carriers this corner is.
1479                let inside = other
1480                    .iter()
1481                    .map(|space| space.offset - space.normal.dot(point))
1482                    .fold(0.0f64, f64::max);
1483                depth = depth.max(inside);
1484            }
1485        }
1486    }
1487    if depth > band * 1e3 {
1488        return Err(KernelRefusal::ill_posed(
1489            KernelStage::Classify,
1490            "one_way_only",
1491            format!(
1492                "{OP}: the motion turns face {id}{} so that the line its old and new carriers meet \
1493                 in crosses its own bounds — part of the face moves into the body and part out of it \
1494                 (the other wedge reaches {depth:.3e} past them), so one tool would add material \
1495                 where the other takes it away; refusing rather than choosing",
1496                name()
1497            ),
1498        ));
1499    }
1500    Ok(())
1501}
1502
1503/// The one way this road could return a plausible WRONG body, closed.
1504///
1505/// A cell's tool is the INTERSECTION of the half-spaces its edges state, and
1506/// that intersection is the cell only while the cell IS the region they
1507/// enclose — true of every convex polygon, and of nothing reflex. Measured,
1508/// before the reflex cut existed, on an L pocket whose arms are
1509/// `x[5,15]×y[5,10]` and `x[5,10]×y[10,15]` in a `20×20×10` block: the
1510/// intersection of the L's six bounds is its CONVEX CORE `x[5,10]×y[5,10]`, the
1511/// floor pushed out through the bottom built **16F 39E 25V, 3600** where the
1512/// through-L is **3250**, and `validate()` was clean, the scan was clean, no
1513/// closed form existed downstream and nothing refused. The reflex cut is what
1514/// makes every cell convex; this reads each cell's corners and edge midpoints
1515/// against its bounds at their HOME positions so that a cell the cut left
1516/// reflex refuses by name instead of cutting its core.
1517fn cell_is_its_bounds(
1518    face: &FaceRecord,
1519    cell: &Cell,
1520    frame: &Frame,
1521    at_home: &[HalfSpace],
1522    scale: f64,
1523) -> Result<(), KernelRefusal> {
1524    // The cell's boundary lies ON these carriers, so the reading is an
1525    // equality and the band only has to absorb the residual a built body
1526    // carries. Every violation this is here to catch is of the order of the
1527    // feature's own size.
1528    let band = (scale * 1e-4).max(1e-6);
1529    let n = cell.points.len();
1530    let mut worst = 0.0f64;
1531    for i in 0..n {
1532        let a = cell.points[i];
1533        let b = cell.points[(i + 1) % n];
1534        for point in [a, [(a[0] + b[0]) * 0.5, (a[1] + b[1]) * 0.5]] {
1535            let point = frame.lift(point);
1536            for space in at_home {
1537                worst = worst.max(space.normal.dot(point) - space.offset);
1538            }
1539        }
1540    }
1541    if worst > band {
1542        return Err(KernelRefusal::unsupported(
1543            KernelStage::Classify,
1544            "reflex_trim",
1545            format!(
1546                "{OP}: face {}{} has a boundary point {worst:.3e} outside one of its own \
1547                 bounding carriers, so its trim is not the region its bounding carriers \
1548                 enclose — their intersection is the trim's CONVEX CORE, and the tool this \
1549                 road would build is that core rather than all the material the motion \
1550                 moves. Refusing rather than cutting some of it",
1551                face.id,
1552                named(face)
1553            ),
1554        ));
1555    }
1556    Ok(())
1557}
1558
1559
1560fn face_by_id(solid: &BrepSolid, id: u64) -> Result<&FaceRecord, KernelRefusal> {
1561    solid
1562        .shells
1563        .iter()
1564        .flat_map(|shell| &shell.faces)
1565        .find(|face| face.id == id)
1566        .ok_or_else(|| {
1567            KernelRefusal::input(
1568                KernelStage::Collect,
1569                "face_id",
1570                format!("{OP}: no face with id {id} on this solid"),
1571            )
1572        })
1573}
1574
1575fn named(face: &FaceRecord) -> String {
1576    face.name
1577        .as_ref()
1578        .map(|name| format!(" '{name}'"))
1579        .unwrap_or_default()
1580}
1581
1582/// Every face that shares an edge with `id`.
1583
1584/// The body's axis-aligned bounds, from its vertices.
1585fn solid_bounds(solid: &BrepSolid) -> Result<(Vec3, Vec3), KernelRefusal> {
1586    if solid.vertices.is_empty() {
1587        return Err(KernelRefusal::input(
1588            KernelStage::Collect,
1589            "empty_solid",
1590            format!("{OP}: the solid has no vertices to bound"),
1591        ));
1592    }
1593    let mut low = Vec3::new(f64::MAX, f64::MAX, f64::MAX);
1594    let mut high = Vec3::new(f64::MIN, f64::MIN, f64::MIN);
1595    for vertex in &solid.vertices {
1596        low = Vec3::new(
1597            low.x.min(vertex.point.x),
1598            low.y.min(vertex.point.y),
1599            low.z.min(vertex.point.z),
1600        );
1601        high = Vec3::new(
1602            high.x.max(vertex.point.x),
1603            high.y.max(vertex.point.y),
1604            high.z.max(vertex.point.z),
1605        );
1606    }
1607    Ok((low, high))
1608}
1609
1610/// Six half-spaces around `bounds`, grown by `margin` on every side.
1611fn box_half_spaces((low, high): (Vec3, Vec3), margin: f64) -> Vec<HalfSpace> {
1612    let low = Vec3::new(low.x - margin, low.y - margin, low.z - margin);
1613    let high = Vec3::new(high.x + margin, high.y + margin, high.z + margin);
1614    vec![
1615        HalfSpace { normal: Vec3::new(1.0, 0.0, 0.0), offset: high.x },
1616        HalfSpace { normal: Vec3::new(-1.0, 0.0, 0.0), offset: -low.x },
1617        HalfSpace { normal: Vec3::new(0.0, 1.0, 0.0), offset: high.y },
1618        HalfSpace { normal: Vec3::new(0.0, -1.0, 0.0), offset: -low.y },
1619        HalfSpace { normal: Vec3::new(0.0, 0.0, 1.0), offset: high.z },
1620        HalfSpace { normal: Vec3::new(0.0, 0.0, -1.0), offset: -low.z },
1621    ]
1622}
1623
1624/// The bounded convex polytope a set of half-spaces encloses, as a solid.
1625///
1626/// The vertices are every triple of half-spaces' common point that satisfies
1627/// all of them; the faces are one per half-space that carries three or more of
1628/// those vertices, wound so the face normal is the half-space's own — which is
1629/// outward, because the polytope is on the `≤` side of every one. A half-space
1630/// that carries fewer than three is redundant and contributes no face.
1631///
1632/// `inside` is a point the polytope must contain; it is what makes an empty or
1633/// degenerate intersection a refusal rather than a body nobody asked for.
1634fn convex_solid(
1635    spaces: &[HalfSpace],
1636    inside: Vec3,
1637    tolerance: f64,
1638) -> Result<BrepSolid, String> {
1639    let band = tolerance.max(1e-9) * 10.0;
1640    for space in spaces {
1641        if space.normal.dot(inside) - space.offset > -band {
1642            return Err(format!(
1643                "the seat point is not strictly inside the half-space set (it is {:.3e} past one \
1644                 of them), so the slab and its bounds enclose nothing",
1645                space.normal.dot(inside) - space.offset
1646            ));
1647        }
1648    }
1649    // Corners: every triple's common point that every half-space admits.
1650    let mut corners: Vec<Vec3> = Vec::new();
1651    for a in 0..spaces.len() {
1652        for b in (a + 1)..spaces.len() {
1653            for c in (b + 1)..spaces.len() {
1654                let Some(point) = three_plane_point(&spaces[a], &spaces[b], &spaces[c]) else {
1655                    continue;
1656                };
1657                if spaces
1658                    .iter()
1659                    .any(|space| space.normal.dot(point) - space.offset > band)
1660                {
1661                    continue;
1662                }
1663                if corners
1664                    .iter()
1665                    .any(|other| other.sub(point).length() <= band)
1666                {
1667                    continue;
1668                }
1669                corners.push(point);
1670            }
1671        }
1672    }
1673    if corners.len() < 4 {
1674        return Err(format!(
1675            "the half-space set has {} corner(s), which is not a bounded volume",
1676            corners.len()
1677        ));
1678    }
1679
1680    let vertices: Vec<VertexRecord> = corners
1681        .iter()
1682        .enumerate()
1683        .map(|(index, point)| VertexRecord { id: index as u64 + 1, point: *point })
1684        .collect();
1685    let mut edges: Vec<EdgeRecord> = Vec::new();
1686    let mut edge_index: HashMap<(usize, usize), u64> = HashMap::default();
1687    let mut faces: Vec<FaceRecord> = Vec::new();
1688    let mut next_id = 1000u64;
1689
1690    for space in spaces {
1691        let mut on: Vec<usize> = (0..corners.len())
1692            .filter(|&index| (space.normal.dot(corners[index]) - space.offset).abs() <= band)
1693            .collect();
1694        if on.len() < 3 {
1695            continue;
1696        }
1697        // Wind them about the face's own centroid, counter-clockwise as seen
1698        // from OUTSIDE (the `+normal` side), which is the sense a solid's face
1699        // needs.
1700        let centroid = on
1701            .iter()
1702            .fold(Vec3::new(0.0, 0.0, 0.0), |sum, &index| sum.add(corners[index]))
1703            .scale(1.0 / on.len() as f64);
1704        let u_dir = corners[on[0]].sub(centroid).normalized()?;
1705        let v_dir = space.normal.cross(u_dir).normalized()?;
1706        on.sort_by(|&a, &b| {
1707            let angle = |index: usize| {
1708                let delta = corners[index].sub(centroid);
1709                delta.dot(v_dir).atan2(delta.dot(u_dir))
1710            };
1711            angle(a).total_cmp(&angle(b))
1712        });
1713        faces.push(polygon_face(
1714            &vertices,
1715            &on,
1716            space.normal,
1717            &mut edges,
1718            &mut edge_index,
1719            &mut next_id,
1720        )?);
1721    }
1722    if faces.len() < 4 {
1723        return Err(format!(
1724            "the half-space set produced {} face(s), which does not close a volume",
1725            faces.len()
1726        ));
1727    }
1728
1729    let shell_id = next_id + 1;
1730    let solid_id = next_id + 2;
1731    let solid = BrepSolid {
1732        mass_properties_cache: Default::default(),
1733        cells: Default::default(),
1734        id: solid_id,
1735        vertices,
1736        edges,
1737        shells: vec![ShellRecord { id: shell_id, faces }],
1738        genus: 0,
1739        kind: crate::BodyKind::Solid,
1740    };
1741    let issues = solid.validate();
1742    if !issues.is_empty() {
1743        return Err(format!("the tool polytope did not validate: {issues:?}"));
1744    }
1745    Ok(solid)
1746}
1747
1748/// Where three half-spaces' carriers meet, or `None` when they do not meet in
1749/// a point.
1750fn three_plane_point(a: &HalfSpace, b: &HalfSpace, c: &HalfSpace) -> Option<Vec3> {
1751    let cross = b.normal.cross(c.normal);
1752    let determinant = a.normal.dot(cross);
1753    if determinant.abs() <= 1e-9 {
1754        return None;
1755    }
1756    let point = cross
1757        .scale(a.offset)
1758        .add(c.normal.cross(a.normal).scale(b.offset))
1759        .add(a.normal.cross(b.normal).scale(c.offset))
1760        .scale(1.0 / determinant);
1761    Some(point)
1762}
1763
1764/// One planar face of the polytope, from corners already wound about `normal`.
1765/// Shared edges are minted once and reused, so the shell closes.
1766fn polygon_face(
1767    vertices: &[VertexRecord],
1768    corners: &[usize],
1769    normal: Vec3,
1770    edges: &mut Vec<EdgeRecord>,
1771    edge_index: &mut HashMap<(usize, usize), u64>,
1772    next_id: &mut u64,
1773) -> Result<FaceRecord, String> {
1774    let origin_point = vertices[corners[0]].point;
1775    let u_dir = vertices[corners[1]]
1776        .point
1777        .sub(origin_point)
1778        .normalized()?;
1779    let v_dir = normal.cross(u_dir).normalized()?;
1780    let mut low_u = f64::MAX;
1781    let mut low_v = f64::MAX;
1782    let mut high_u = f64::MIN;
1783    let mut high_v = f64::MIN;
1784    let projected: Vec<(f64, f64)> = corners
1785        .iter()
1786        .map(|&index| {
1787            let delta = vertices[index].point.sub(origin_point);
1788            let (u, v) = (delta.dot(u_dir), delta.dot(v_dir));
1789            low_u = low_u.min(u);
1790            low_v = low_v.min(v);
1791            high_u = high_u.max(u);
1792            high_v = high_v.max(v);
1793            (u, v)
1794        })
1795        .collect();
1796    let plane_origin = origin_point.add(u_dir.scale(low_u)).add(v_dir.scale(low_v));
1797    let surface = make_plane(
1798        plane_origin,
1799        u_dir,
1800        v_dir,
1801        high_u - low_u,
1802        high_v - low_v,
1803    )?;
1804
1805    let mut coedges: Vec<CoedgeRecord> = Vec::with_capacity(corners.len());
1806    for index in 0..corners.len() {
1807        let start = corners[index];
1808        let end = corners[(index + 1) % corners.len()];
1809        let key = if start < end { (start, end) } else { (end, start) };
1810        let edge_id = match edge_index.get(&key) {
1811            Some(id) => *id,
1812            None => {
1813                let id = *next_id;
1814                *next_id += 1;
1815                edges.push(EdgeRecord {
1816                    id,
1817                    curve: make_line(vertices[key.0].point, vertices[key.1].point)?,
1818                    t0: 0.0,
1819                    t1: 1.0,
1820                    start_vertex_id: vertices[key.0].id,
1821                    end_vertex_id: vertices[key.1].id,
1822                    degenerate: false,
1823                    name: None,
1824                });
1825                edge_index.insert(key, id);
1826                id
1827            }
1828        };
1829        let start_uv = projected[index];
1830        let end_uv = projected[(index + 1) % corners.len()];
1831        coedges.push(CoedgeRecord {
1832            id: *next_id,
1833            edge_id,
1834            forward: vertices[start].id
1835                == edges
1836                    .iter()
1837                    .find(|edge| edge.id == edge_id)
1838                    .expect("the edge was just minted")
1839                    .start_vertex_id,
1840            pcurve: parameter_line(
1841                start_uv.0 - low_u,
1842                start_uv.1 - low_v,
1843                end_uv.0 - low_u,
1844                end_uv.1 - low_v,
1845            )?,
1846        });
1847        *next_id += 1;
1848    }
1849    let loop_id = *next_id;
1850    *next_id += 1;
1851    let face_id = *next_id;
1852    *next_id += 1;
1853    Ok(FaceRecord {
1854        id: face_id,
1855        surface,
1856        same_sense: true,
1857        loops: vec![LoopRecord { id: loop_id, coedges }],
1858        name: None,
1859    })
1860}
1861
1862/// Give the re-cut body the ORIGINAL body's face names back.
1863///
1864/// The boolean mints its own faces, so a collect would lose every name the
1865/// cut touched. A result face whose carrier is an original face's carrier —
1866/// at its MOVED position, for a face in the selection — is that face, and takes
1867/// its name; a carrier that comes back as two faces gives the second `name_1`,
1868/// the spelling the crossing repair's own split already uses. A name whose
1869/// carrier is no longer on the body is simply not stamped: the face is gone,
1870/// which for this road is an answer rather than a loss.
1871fn restamp(
1872    mut cut: BrepSolid,
1873    original: &BrepSolid,
1874    moved: &HashSet<u64>,
1875    motion: &Motion,
1876    tolerance: f64,
1877) -> BrepSolid {
1878    let band = tolerance.max(1e-9) * 1e3;
1879    // Every original name, with the plane it should be found on.
1880    let mut wanted: Vec<(String, Vec3, f64)> = Vec::new();
1881    for face in original.shells.iter().flat_map(|shell| &shell.faces) {
1882        let Some(name) = face.name.clone() else { continue };
1883        let Ok(plane) = plane_of_surface(&face.surface, band, OP) else {
1884            continue;
1885        };
1886        let normal = if face.same_sense {
1887            plane.normal
1888        } else {
1889            plane.normal.scale(-1.0)
1890        };
1891        let (normal, offset) = if moved.contains(&face.id) {
1892            motion.plane(normal, normal.dot(plane.origin))
1893        } else {
1894            (normal, normal.dot(plane.origin))
1895        };
1896        wanted.push((name, normal, offset));
1897    }
1898    let taken: HashSet<String> = cut
1899        .shells
1900        .iter()
1901        .flat_map(|shell| &shell.faces)
1902        .filter_map(|face| face.name.clone())
1903        .collect();
1904    let mut used: HashMap<String, usize> = HashMap::default();
1905    for name in &taken {
1906        used.insert(name.clone(), 1);
1907    }
1908    for shell in &mut cut.shells {
1909        for face in &mut shell.faces {
1910            if face.name.is_some() {
1911                continue;
1912            }
1913            let Ok(plane) = plane_of_surface(&face.surface, band, OP) else {
1914                continue;
1915            };
1916            let normal = if face.same_sense {
1917                plane.normal
1918            } else {
1919                plane.normal.scale(-1.0)
1920            };
1921            let offset = normal.dot(plane.origin);
1922            let Some((name, _, _)) = wanted.iter().find(|(_, other, other_offset)| {
1923                other.sub(normal).length() <= 1e-9 && (other_offset - offset).abs() <= band
1924            }) else {
1925                continue;
1926            };
1927            let count = used.entry(name.clone()).or_insert(0);
1928            *count += 1;
1929            face.name = Some(if *count == 1 {
1930                name.clone()
1931            } else {
1932                format!("{name}_{}", *count - 1)
1933            });
1934        }
1935    }
1936    cut
1937}