Skip to main content

brep_kernel/edit/direct_edit/
face_rotate.rs

1use super::*;
2use crate::{KernelRefusal, KernelStage, OrRefuse};
3use super::face_move::{
4    cached_plane, carrier_is_planar, carrier_kind_name, carrier_ruled,
5    corner_on_plane_and_ruled, plane_and_ruled_carriers, resolve_corner_on_fixed_edge,
6    retrim_ruled_face, solve_corner, verify_section_between,
7};
8
9// ---------------------------------------------------------------------------
10// §6.12 sibling operation: ROTATE a face group about a picked axis.
11//
12// This file is what implements it, and nothing here reaches past what that
13// section claims.
14//
15// Rotation is NOT a mode of the translation. `move_faces` moves a carrier's
16// POSITION and leaves its normal alone, which is why a plane the translation is
17// parallel to is invariant and why a moved rim can ride an exact affine of the
18// fixed carrier. A rotation moves the normal too: the invariants are different
19// (a cone about its OWN axis is invariant here and not there), the sections are
20// different (plane × oblique cylinder is an ellipse, not a translated circle),
21// and the corners must be solved from the ROTATED carriers rather than mapped.
22// Sharing the machinery would mean an `if rotation` in every one of those
23// places; the shared parts are the pure helpers this file imports.
24// ---------------------------------------------------------------------------
25
26/// How the rotated group uses an edge — the same three-way split
27/// [`super::face_move`] makes, because the question ("is this edge inside the
28/// group, on its boundary, or untouched?") is about the SELECTION, not the
29/// transform.
30enum EdgeClass {
31    Fixed,
32    Interior,
33    Boundary { moved_face: u64, fixed_face: u64 },
34}
35
36enum EdgeAction {
37    /// Map the curve by the rotation. Exact for any curve type: an affine maps
38    /// a rational NURBS control-point-wise, so the parametrisation survives.
39    Rotate,
40    /// Replace the curve by the straight line between two re-solved corners.
41    Rebuild { start: Vec3, end: Vec3 },
42    /// Replace the curve outright by the EXACT conic section of the ROTATED
43    /// planar carrier with a fixed OBLIQUE cylinder or cone — an ellipse on a
44    /// cylinder, a conic on a cone. Unlike a translation, a rotation has no
45    /// affine that carries the old rim to the new one (it moves the carrier's
46    /// NORMAL, and neither the cylinder's axial shift nor the cone's homothety
47    /// about the apex is a symmetry that does that), so the rim is
48    /// re-intersected rather than mapped. The curve spans its own whole domain,
49    /// so the edge's trim becomes that domain.
50    Replace { curve: NurbsCurve },
51}
52
53enum FaceAction {
54    /// Rotate the whole control net. Exact for any carrier type; the analytic
55    /// tag is re-derived from the moved net, so a rotated plane is still a
56    /// plane and a rotated cylinder still a cylinder of the same radius.
57    RotateSurface,
58    /// Rebuild the (planar) carrier around the new boundary and recompute every
59    /// pcurve. `plane` is the carrier the face ends up on: the ROTATED plane for
60    /// a moved face, its own unchanged plane for a re-trimmed fixed neighbour.
61    Retrim(Plane),
62}
63
64/// The refusal a face whose carrier this operation cannot use deserves: one
65/// that names the FACE, its CARRIER KIND and the ROLE it plays in the rotation.
66///
67/// [`super::face_move`] has the same helper with its own wording; the sentence
68/// differs because the reach differs in its details. Both re-intersect a PLANE
69/// and a CYLINDER or CONE neighbour, but a translation carries a ruled rim by
70/// an exact affine while a rotation re-intersects it, and a rotation carries
71/// any other curved carrier only when the axis leaves it invariant. Either side
72/// of such a pair may be the one that turns — a tilted cap against a fixed bore,
73/// or a tilted bore against a fixed flat — but ONE of the two must be the plane.
74/// What is refused through here — a sphere, a torus, a general revolution, a
75/// free-form patch, or a quadric meeting a quadric — is what the sentence names.
76fn unsupported_carrier(
77    solid: &BrepSolid,
78    face_lookup: &HashMap<u64, (usize, usize)>,
79    face_id: u64,
80    role: &str,
81) -> KernelRefusal {
82    KernelRefusal::unsupported(KernelStage::Classify, "carrier_kind", format!(
83        "rotate_faces: {role} is a {}; a rotation re-intersects a PLANE with a plane, a \
84         cylinder or a cone — whichever of the two it turns — and carries any other curved \
85         carrier only when the axis leaves it invariant — refusing",
86        face_label(solid, face_lookup, face_id)
87    ))
88}
89
90/// `name (face id) … kind` in one phrase, so every refusal names the thing the
91/// user picked and not just an integer they have no way to see.
92fn face_label(
93    solid: &BrepSolid,
94    face_lookup: &HashMap<u64, (usize, usize)>,
95    face_id: u64,
96) -> String {
97    match face_lookup.get(&face_id) {
98        Some(&(shell, face)) => {
99            let record = &solid.shells[shell].faces[face];
100            let kind = carrier_kind_name(&record.surface);
101            match record.name.as_deref() {
102                Some(name) => format!("`{name}` (face {face_id}) {kind}"),
103                None => format!("face {face_id} {kind}"),
104            }
105        }
106        None => format!("face {face_id} (missing)"),
107    }
108}
109
110/// A short `name (id)` for a face, for messages that name a PAIR and would be
111/// unreadable with two carrier kinds in them.
112fn face_short(
113    solid: &BrepSolid,
114    face_lookup: &HashMap<u64, (usize, usize)>,
115    face_id: u64,
116) -> String {
117    match face_lookup.get(&face_id) {
118        Some(&(shell, face)) => match solid.shells[shell].faces[face].name.as_deref() {
119            Some(name) => format!("`{name}` (face {face_id})"),
120            None => format!("face {face_id}"),
121        },
122        None => format!("face {face_id}"),
123    }
124}
125
126/// The rigid motion `p ↦ a + R·(p − a)` as one affine: Rodrigues' rotation of
127/// `angle` radians about the unit `direction`, with the translation that pins
128/// the axis point `a`.
129pub(super) fn rotation_about(point: Vec3, direction: Vec3, angle: f64) -> Result<AffineTransform, String> {
130    let (s, c) = angle.sin_cos();
131    let t = 1.0 - c;
132    let (x, y, z) = (direction.x, direction.y, direction.z);
133    // Row-major 3x3, the layout `AffineTransform` indexes.
134    let r = [
135        t * x * x + c,
136        t * x * y - s * z,
137        t * x * z + s * y,
138        t * x * y + s * z,
139        t * y * y + c,
140        t * y * z - s * x,
141        t * x * z - s * y,
142        t * y * z + s * x,
143        t * z * z + c,
144    ];
145    let a = [point.x, point.y, point.z];
146    let mut elements = [0.0f64; 16];
147    for row in 0..3 {
148        for col in 0..3 {
149            elements[row * 4 + col] = r[row * 3 + col];
150        }
151        // a − R·a, so the axis point is a fixed point of the map.
152        elements[row * 4 + 3] = a[row] - (0..3).map(|k| r[row * 3 + k] * a[k]).sum::<f64>();
153    }
154    elements[15] = 1.0;
155    AffineTransform::new(elements)
156}
157
158/// The rotation applied to a DIRECTION: the linear part alone, without the
159/// translation that pins the axis point. A plane's normal, and the `u_dir` /
160/// `v_dir` that carry its `same_sense`, all move this way.
161pub(super) fn rotate_direction(rotation: &AffineTransform, vector: Vec3) -> Vec3 {
162    let m = rotation.elements;
163    Vec3::new(
164        m[0] * vector.x + m[1] * vector.y + m[2] * vector.z,
165        m[4] * vector.x + m[5] * vector.y + m[6] * vector.z,
166        m[8] * vector.x + m[9] * vector.y + m[10] * vector.z,
167    )
168}
169
170/// A whole plane carried by the rotation. `retrim_planar_face` rebuilds the
171/// carrier from `origin`/`u_dir`/`v_dir` and relies on `normal = u × v` matching
172/// the surface's own normal, so all four move together — rotating the origin and
173/// leaving the frame behind would silently flip a face's `same_sense`.
174fn rotate_plane(rotation: &AffineTransform, plane: &Plane) -> Plane {
175    Plane {
176        origin: rotation.point(plane.origin),
177        u_dir: rotate_direction(rotation, plane.u_dir),
178        v_dir: rotate_direction(rotation, plane.v_dir),
179        normal: rotate_direction(rotation, plane.normal),
180    }
181}
182
183/// The SIGNED AREA VECTOR of a trim loop, walked in its own coedge order in 3D:
184/// `½ Σ pᵢ × pᵢ₊₁` over samples of every coedge, taken in the direction the
185/// coedge runs. On a PLANAR loop this is Newell's normal — it points along the
186/// side the loop winds counter-clockwise about, and its length is the loop's
187/// area, so a degenerate loop reports a short vector rather than a wrong
188/// direction.
189///
190/// This is the quantity that decides a re-trimmed planar carrier's FRAME. The
191/// loop itself is the authority because the rotation does not move it: this
192/// operation RE-SOLVES every corner from the carriers meeting there, so a
193/// re-trimmed face's boundary is wherever those carriers put it and its 3D
194/// traversal order is the topology's, which the edit never touches.
195fn loop_area_vector(
196    loop_record: &LoopRecord,
197    edges: &HashMap<u64, EdgeRecord>,
198    op: &str,
199) -> Result<Vec3, KernelRefusal> {
200    let mut points: Vec<Vec3> = Vec::new();
201    for coedge in &loop_record.coedges {
202        let edge = edges.get(&coedge.edge_id).ok_or_else(|| {
203            KernelRefusal::internal(
204                KernelStage::Sew,
205                "loop_edge_lookup",
206                format!("{op}: missing edge {}", coedge.edge_id),
207            )
208        })?;
209        if edge.degenerate {
210            continue;
211        }
212        for step in 0..8 {
213            let fraction = step as f64 / 8.0;
214            // ...in the direction the COEDGE runs, which is the direction the
215            // loop is traversed and therefore the one the winding is about.
216            let fraction = if coedge.forward {
217                fraction
218            } else {
219                1.0 - fraction
220            };
221            points.push(edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * fraction).or_refuse(KernelStage::Sew, "evaluate")?);
222        }
223    }
224    if points.len() < 3 {
225        return Ok(Vec3::default());
226    }
227    let mut total = Vec3::default();
228    for index in 0..points.len() {
229        let a = points[index];
230        let b = points[(index + 1) % points.len()];
231        total = total.add(a.cross(b));
232    }
233    Ok(total.scale(0.5))
234}
235
236/// Point a re-trimmed planar carrier's frame the way the face's OWN outer loop
237/// winds, flipping `v_dir` (and with it the carrier normal `u × v`) when the
238/// candidate frame would hand the face a LEFT-HANDED chart.
239///
240/// # Why a rotated frame is not always the legal one
241///
242/// [`rotate_plane`] carries a moved face's frame by `R`, which is right for as
243/// long as the face's boundary rides with it. It is not right once the rotation
244/// has carried the carrier far enough that the face's re-solved boundary comes
245/// back around the OTHER side of it: a half-turn about an axis IN the face maps
246/// the carrier onto itself with its normal reversed, every corner re-solves to
247/// exactly where it was, and the transported frame then describes the same
248/// patch INSIDE OUT. `validate()` cannot see that — it tests incidence, and the
249/// incidences are all still perfect — but the face's outer wire now winds
250/// against its own sense, which is the chart convention
251/// `validate_uv_wire` asserts and that `face_profile`, `thicken` and the
252/// periodic trimmer all read as kernel-wide law.
253///
254/// The loop decides because the loop is the fixed point of the rebuild: its 3D
255/// traversal is the topology's, and the neighbours on the other side of every
256/// one of its edges keep the winding they had. Choosing the frame that agrees
257/// with it is what keeps the shell COHERENT — and it is a real geometric
258/// decision, not bookkeeping, because it is the face's outward normal that
259/// changes with it. Whether the shell as a whole ends up inside out is a
260/// separate question, and the signed-volume guard at the end is what answers it.
261fn orient_plane_to_loop(
262    face: &FaceRecord,
263    plane: &Plane,
264    edges: &HashMap<u64, EdgeRecord>,
265) -> Result<Plane, KernelRefusal> {
266    let Some(outer) = face.loops.first() else {
267        return Ok(*plane);
268    };
269    let area = loop_area_vector(outer, edges, "rotate_faces")?;
270    let projection = area.dot(plane.normal);
271    // A loop with no area in this carrier decides nothing; leave the carried
272    // frame alone rather than flip on rounding noise.
273    if projection.abs() <= 1e-12 * area.length().max(1.0) {
274        return Ok(*plane);
275    }
276    // The chart is right-handed (`normal = u × v`), so the outer loop winds
277    // POSITIVELY in (u, v) exactly when it winds counter-clockwise about the
278    // carrier normal — which is what `same_sense` asks of it.
279    if (projection > 0.0) == face.same_sense {
280        return Ok(*plane);
281    }
282    Ok(Plane {
283        origin: plane.origin,
284        u_dir: plane.u_dir,
285        v_dir: plane.v_dir.scale(-1.0),
286        normal: plane.normal.scale(-1.0),
287    })
288}
289
290/// A ruled revolution's frame carried by the rotation. `R` is rigid, so the
291/// turned frame describes the turned carrier EXACTLY and its radii and height
292/// are untouched — which is what lets the bore wall's own section against a
293/// fixed flat be re-intersected with the same closed form the mirror case uses.
294fn rotate_ruled_frame(
295    rotation: &AffineTransform,
296    frame: &crate::RevolutionFrame,
297) -> crate::RevolutionFrame {
298    crate::RevolutionFrame {
299        origin: rotation.point(frame.origin),
300        axis: rotate_direction(rotation, frame.axis),
301        x_axis: rotate_direction(rotation, frame.x_axis),
302        y_axis: rotate_direction(rotation, frame.y_axis),
303    }
304}
305
306/// True iff a FIXED carrier is INVARIANT under the rotation, so a corner on it
307/// rides by `R` and provably stays on it. Two carriers are:
308///   • a PLANE whose normal is parallel to the axis direction — the rotation
309///     spins it within itself, at any offset along the axis; and
310///   • a RULED REVOLUTION (cylinder, cone, or a partial-sweep fillet band) whose
311///     own axis LINE *is* the rotation axis line.
312///
313/// The cone is the interesting difference from the translation's rule, which
314/// excludes it: an axial TRANSLATION moves a cone's point to a station with a
315/// different radius and so leaves the carrier, while a rotation about the cone's
316/// own axis maps it exactly onto itself.
317///
318/// A sphere centred on the axis and a torus about it are invariant too, and are
319/// deliberately NOT admitted here: this operation has no re-trim route for
320/// either carrier, so a rim that rode onto one would arrive at the face pass
321/// with a stale pcurve and no way to rebuild it. They refuse by name instead.
322fn carrier_invariant_under(
323    solid: &BrepSolid,
324    face_lookup: &HashMap<u64, (usize, usize)>,
325    face_id: u64,
326    axis_point: Vec3,
327    axis_direction: Vec3,
328    angular_tolerance: f64,
329    distance_tolerance: f64,
330) -> bool {
331    let Some(&(shell, face)) = face_lookup.get(&face_id) else {
332        return false;
333    };
334    let surface = &solid.shells[shell].faces[face].surface;
335    if let Some(AnalyticSurface::Plane { u_dir, v_dir, .. }) = surface.analytic() {
336        let unit = match u_dir.cross(*v_dir).normalized() {
337            Ok(unit) => unit,
338            Err(_) => return false,
339        };
340        return unit.cross(axis_direction).length() <= angular_tolerance;
341    }
342    let Some((frame, _, _, _)) = carrier_ruled(solid, face_lookup, face_id) else {
343        return false;
344    };
345    if frame.axis.cross(axis_direction).length() > angular_tolerance {
346        return false;
347    }
348    // Parallel is not enough: the carrier's axis must be the SAME LINE, or the
349    // rotation carries the whole surface sideways.
350    let offset = frame.origin.sub(axis_point);
351    offset
352        .sub(axis_direction.scale(offset.dot(axis_direction)))
353        .length()
354        <= distance_tolerance
355}
356
357/// The ROTATED ruled carrier of the one moved face at a corner, when that is
358/// what the corner has to be solved against: `Some((face id, the frame `R`
359/// leaves, rho0, rho1, height))` for exactly one moved face at the vertex whose
360/// carrier is a cylinder or cone the axis does NOT leave invariant.
361///
362/// `None` — and so the ordinary three-plane solve — for a planar moved face, for
363/// a moved carrier the rotation maps onto itself (the identity/rigid regimes
364/// above have already claimed those), and for a group that brings TWO faces to
365/// the corner, where "the seam generatrix places it" is no longer a statement
366/// about one carrier. A moved sphere, torus, revolution or free-form patch is
367/// not ruled, so it falls through to the three-plane solve and refuses there by
368/// name, as it did before this route existed.
369fn rotated_moved_ruled_carrier(
370    solid: &BrepSolid,
371    face_lookup: &HashMap<u64, (usize, usize)>,
372    rotation: &AffineTransform,
373    moved: &HashSet<u64>,
374    adjacent: &HashSet<u64>,
375    invariant: &dyn Fn(u64) -> bool,
376) -> Option<(u64, crate::RevolutionFrame, f64, f64, f64)> {
377    let mut here = adjacent.iter().copied().filter(|id| moved.contains(id));
378    let face_id = here.next()?;
379    if here.next().is_some() {
380        return None;
381    }
382    if invariant(face_id) {
383        return None;
384    }
385    let (frame, rho0, rho1, height) = carrier_ruled(solid, face_lookup, face_id)?;
386    Some((
387        face_id,
388        rotate_ruled_frame(rotation, &frame),
389        rho0,
390        rho1,
391        height,
392    ))
393}
394
395/// How far `point` sits off a ruled revolution's carrier: the difference between
396/// its radial distance from the axis and the carrier's own radius at that axial
397/// station (constant for a cylinder, linear for a cone).
398fn ruled_offset(frame: &crate::RevolutionFrame, rho0: f64, rho1: f64, height: f64, point: Vec3) -> f64 {
399    let delta = point.sub(frame.origin);
400    let axial = delta.dot(frame.axis);
401    let radial = delta.sub(frame.axis.scale(axial)).length();
402    let target = if height == 0.0 {
403        rho0
404    } else {
405        rho0 + (rho1 - rho0) * (axial / height)
406    };
407    (radial - target).abs()
408}
409
410/// A STRAIGHT rebuilt edge bordering a curved carrier must still lie ON that
411/// carrier — endpoints and midpoint — or the rebuild has torn the edge off it.
412///
413/// This is the guard that answers the coaxial-cap question the contract asks.
414/// Spinning a cylinder's cap about the cylinder's OWN axis leaves both carriers
415/// invariant, so the rim rides by `R` — but the WALL's seam edge has one
416/// endpoint on that rim and one on the untouched bottom rim, and the straight
417/// chord between them is not a generatrix: it cuts the chord of a 25° arc
418/// through the inside of the cylinder. Measured before this guard existed, the
419/// result reached `validate()` and failed there on a stale pcurve with the
420/// arc's chord length as the deviation. The refusal names the wall.
421///
422/// `carrier_rotation` is `Some(R)` when the face is one the rotation MOVES —
423/// the tilted bore wall carrying its own seam generatrix — in which case the
424/// chord is measured against the carrier `R` leaves, not the one on record.
425/// Measuring against the stored frame there would convict every tilt of a bore
426/// of tearing its own seam off itself.
427fn verify_chord_on_curved(
428    solid: &BrepSolid,
429    face_lookup: &HashMap<u64, (usize, usize)>,
430    face_id: u64,
431    edge_id: u64,
432    start: Vec3,
433    end: Vec3,
434    carrier_rotation: Option<&AffineTransform>,
435    tolerance: f64,
436) -> Result<(), KernelRefusal> {
437    let Some((frame, rho0, rho1, height)) = carrier_ruled(solid, face_lookup, face_id) else {
438        return Ok(());
439    };
440    let frame = match carrier_rotation {
441        Some(rotation) => rotate_ruled_frame(rotation, &frame),
442        None => frame,
443    };
444    let midpoint = start.add(end).scale(0.5);
445    for point in [start, midpoint, end] {
446        let off = ruled_offset(&frame, rho0, rho1, height, point);
447        if off > 10.0 * tolerance {
448            return Err(KernelRefusal::unsupported(KernelStage::Validate, "chord_off_carrier", format!(
449                "rotate_faces: rebuilding edge {edge_id} straight between its re-solved corners                  would leave its curved neighbour {} (off {off:.3e}); the rotation moves one end                  of that edge along the carrier and the other not at all, and no straight chord                  spans that — refusing",
450                face_short(solid, face_lookup, face_id)
451            )));
452        }
453    }
454    Ok(())
455}
456
457/// A point that rode rigidly must genuinely still be ON every fixed carrier it
458/// touches. The invariance predicate proves it in exact arithmetic; this is the
459/// measurement that says so on the actual numbers, and it is what turns "rigid"
460/// into a checked claim rather than an asserted one.
461fn verify_point_on_fixed(
462    solid: &BrepSolid,
463    face_lookup: &HashMap<u64, (usize, usize)>,
464    planes: &mut HashMap<u64, Plane>,
465    face_id: u64,
466    point: Vec3,
467    vertex_id: u64,
468    plane_tolerance: f64,
469    tolerance: f64,
470) -> Result<(), KernelRefusal> {
471    if let Some((frame, rho0, rho1, height)) = carrier_ruled(solid, face_lookup, face_id) {
472        let off = ruled_offset(&frame, rho0, rho1, height, point);
473        if off > 10.0 * tolerance {
474            return Err(KernelRefusal::unsupported(KernelStage::Validate, "corner_off_curved_neighbour", format!(
475                "rotate_faces: the rotated corner at vertex {vertex_id} left its curved \
476                 neighbour {} (off {off:.3e}) — refusing",
477                face_short(solid, face_lookup, face_id)
478            )));
479        }
480        return Ok(());
481    }
482    let plane = cached_plane(planes, solid, face_lookup, face_id, plane_tolerance)
483        .map_err(|_| {
484            unsupported_carrier(
485                solid,
486                face_lookup,
487                face_id,
488                &format!("a FIXED neighbour at vertex {vertex_id}"),
489            )
490        })?;
491    let off = point.sub(plane.origin).dot(plane.normal).abs();
492    if off > 10.0 * tolerance {
493        return Err(KernelRefusal::unsupported(KernelStage::Validate, "corner_off_fixed_neighbour", format!(
494            "rotate_faces: the rotated corner at vertex {vertex_id} left its fixed neighbour \
495             {} (off {off:.3e}) — refusing",
496            face_short(solid, face_lookup, face_id)
497        )));
498    }
499    Ok(())
500}
501
502/// Rebuild a straight edge between two re-solved corners, refusing the two ways
503/// an angle can turn a neighbour's trim inside out.
504///
505/// Both refusals name the EDGE and the two faces that carry it, which is the
506/// half of the message a user can act on: "edge 9" alone does not say which wall
507/// stopped the rotation.
508fn plan_straight_rebuild(
509    solid: &BrepSolid,
510    face_lookup: &HashMap<u64, (usize, usize)>,
511    faces_of_edge: &HashMap<u64, Vec<u64>>,
512    edge: &EdgeRecord,
513    start_old: Vec3,
514    end_old: Vec3,
515    start_new: Vec3,
516    end_new: Vec3,
517    tolerance: f64,
518) -> Result<EdgeAction, KernelRefusal> {
519    let between = || -> String {
520        let carriers = faces_of_edge
521            .get(&edge.id)
522            .map(Vec::as_slice)
523            .unwrap_or(&[])
524            .iter()
525            .map(|&face_id| face_short(solid, face_lookup, face_id))
526            .collect::<Vec<_>>();
527        match carriers.len() {
528            2 => format!("{} and {}", carriers[0], carriers[1]),
529            _ => carriers.join(", "),
530        }
531    };
532    if edge.degenerate {
533        return Err(KernelRefusal::unsupported(KernelStage::Refine, "degenerate_edge", format!(
534            "rotate_faces: degenerate edge {} between {} would need re-stretching (deferred) \
535             — refusing",
536            edge.id,
537            between()
538        )));
539    }
540    if edge.curve.straight_segment(tolerance).is_none() {
541        return Err(KernelRefusal::unsupported(KernelStage::Refine, "curved_edge_rebuild", format!(
542            "rotate_faces: edge {} between {} must be re-stretched but is not a straight line; \
543             a rotation rebuilds a curved edge only where a plane meets a cylinder or cone \
544             — refusing",
545            edge.id,
546            between()
547        )));
548    }
549    let new_chord = end_new.sub(start_new);
550    if new_chord.length() <= tolerance {
551        return Err(KernelRefusal::unsupported(KernelStage::Refine, "edge_collapse", format!(
552            "rotate_faces: the rotation collapses edge {} between {} to zero length — refusing",
553            edge.id,
554            between()
555        )));
556    }
557    if end_old.sub(start_old).dot(new_chord) <= 0.0 {
558        return Err(KernelRefusal::unsupported(KernelStage::Refine, EDGE_INVERSION, format!(
559            "rotate_faces: the rotation inverts edge {} between {} (the trim is turned inside \
560             out) — refusing",
561            edge.id,
562            between()
563        )));
564    }
565    Ok(EdgeAction::Rebuild {
566        start: start_new,
567        end: end_new,
568    })
569}
570
571/// A corner solve shared with [`super::face_move`] words its refusals for a
572/// PUSH ("the pushed cap plane … the push drives the corner off the carrier").
573/// Swapping only the prefix left a rotation telling the user it had pushed
574/// something, so the vocabulary is translated and the vertex named.
575fn translate_corner_refusal(error: &str, vertex_id: u64) -> String {
576    let body = error
577        .trim_start_matches("move_faces: ")
578        .replace("pushed cap plane", "rotated plane")
579        .replace("the push drives", "the rotation drives")
580        .replace("the push tears", "the rotation tears")
581        .replace("pushed cap", "rotated face");
582    format!("rotate_faces: at vertex {vertex_id}, {body}")
583}
584
585/// The SIGNED AREA VECTOR of a CLOSED curve over `[t0, t1]`: `½ Σ pᵢ × pᵢ₊₁`
586/// around it. Dotted with a direction it gives the sense the curve winds about
587/// that direction — positive for counter-clockwise looking down it — and the
588/// magnitude is the projected area, so a rim seen edge-on reports ~0 rather
589/// than a sign read off noise.
590fn closed_curve_area_vector(curve: &NurbsCurve, t0: f64, t1: f64) -> Result<Vec3, String> {
591    const STEPS: usize = 64;
592    let mut points = Vec::with_capacity(STEPS);
593    for step in 0..STEPS {
594        let t = t0 + (t1 - t0) * (step as f64 / STEPS as f64);
595        points.push(curve.evaluate(t)?);
596    }
597    let mut total = Vec3::default();
598    for index in 0..points.len() {
599        total = total.add(points[index].cross(points[(index + 1) % points.len()]));
600    }
601    Ok(total.scale(0.5))
602}
603
604/// The sense a rim runs in about the carrier's axis: `true` when its azimuth
605/// INCREASES along its own parameterisation.
606///
607/// [`super::face_move::arc_sweeps_forward`] answers this from the midpoint's
608/// azimuth against the endpoints', which is undecidable for a CLOSED rim (the
609/// start and end azimuths are the same one). This sums the wrapped azimuth
610/// steps instead, so it reads a closed rim and an open arc the same way.
611fn rim_runs_forward(
612    frame: &crate::RevolutionFrame,
613    curve: &NurbsCurve,
614    t0: f64,
615    t1: f64,
616) -> Result<bool, String> {
617    let azimuth = |point: Vec3| {
618        let delta = point.sub(frame.origin);
619        delta.dot(frame.y_axis).atan2(delta.dot(frame.x_axis))
620    };
621    const STEPS: usize = 32;
622    let mut total = 0.0;
623    let mut previous = azimuth(curve.evaluate(t0)?);
624    for step in 1..=STEPS {
625        let t = t0 + (t1 - t0) * (step as f64 / STEPS as f64);
626        let current = azimuth(curve.evaluate(t)?);
627        let mut delta = current - previous;
628        while delta > std::f64::consts::PI {
629            delta -= std::f64::consts::TAU;
630        }
631        while delta < -std::f64::consts::PI {
632            delta += std::f64::consts::TAU;
633        }
634        total += delta;
635        previous = current;
636    }
637    Ok(total >= 0.0)
638}
639
640/// The new rim where a ROTATED planar carrier meets a fixed OBLIQUE cylinder or
641/// cone: the EXACT conic section, anchored on the re-solved corners.
642///
643/// Two shapes of rim, one rule:
644///
645/// * a **CLOSED** rim — the hole mouth an oblique bore opens through the face —
646///   is the WHOLE section, and the one thing that is free about it is where its
647///   single vertex sits. That vertex is the face's own SEAM vertex, and the
648///   section must start there, not at the carrier's `u = 0`: a face's seam EDGE
649///   need not sit at the generatrix (the push-face seam fix, `becc64a98`), and a
650///   rim anchored anywhere else would relocate the seam vertex and strand the
651///   wall's seam edge. So the arc is built from the re-solved seam vertex's own
652///   azimuth through a full turn.
653/// * an **OPEN** rim is the sub-arc between the two re-solved corners' azimuths.
654///
655/// Both run in the OLD rim's own sense, so every coedge's `forward` flag — and
656/// therefore every trim loop's orientation — survives the rebuild untouched.
657///
658/// The section is `plane ∩ frame`, and which of the two the rotation moved is
659/// not this function's business: a rotated plane against a fixed cylinder and a
660/// fixed plane against a ROTATED cylinder are the same closed form with the
661/// roles swapped. `sense_frame` is the frame the OLD rim curve was measured in —
662/// the carrier as it stands in `solid` — because that is the only frame
663/// `edge.curve` is consistent with; `frame` is where the carrier ENDS UP, and it
664/// is what the anchor azimuth and the section itself are built in.
665#[allow(clippy::too_many_arguments)]
666fn rotated_rim_section(
667    edge: &EdgeRecord,
668    frame: &crate::RevolutionFrame,
669    sense_frame: &crate::RevolutionFrame,
670    rho0: f64,
671    rho1: f64,
672    height: f64,
673    plane: &Plane,
674    fixed_reference: Vec3,
675    start_new: Vec3,
676    end_new: Vec3,
677    tolerance: f64,
678) -> Result<NurbsCurve, KernelRefusal> {
679    let azimuth = |point: Vec3| {
680        let delta = point.sub(frame.origin);
681        delta.dot(frame.y_axis).atan2(delta.dot(frame.x_axis))
682    };
683    let tau = std::f64::consts::TAU;
684    let wrap = |angle: f64| {
685        let value = angle % tau;
686        if value < 0.0 {
687            value + tau
688        } else {
689            value
690        }
691    };
692    let forward = rim_runs_forward(sense_frame, &edge.curve, edge.t0, edge.t1).or_refuse(KernelStage::Refine, "rim_runs_forward")?;
693    let closed = edge.start_vertex_id == edge.end_vertex_id;
694    let (anchor, sweep) = if closed {
695        (azimuth(start_new), tau)
696    } else if forward {
697        (azimuth(start_new), wrap(azimuth(end_new) - azimuth(start_new)))
698    } else {
699        (azimuth(end_new), wrap(azimuth(start_new) - azimuth(end_new)))
700    };
701    if !closed && (sweep <= 1e-9 || sweep >= tau - 1e-9) {
702        return Err(KernelRefusal::unsupported(KernelStage::Refine, "rim_degenerate", format!(
703            "rotate_faces: the re-intersected rim of edge {} degenerates to a point or a \
704             full turn — refusing",
705            edge.id
706        )));
707    }
708    let mut curve = plane_ruled_section_arc(
709        plane.origin,
710        plane.normal,
711        frame,
712        rho0,
713        rho1,
714        height,
715        anchor,
716        sweep,
717        tolerance,
718    )
719    .map_err(|error| {
720        KernelRefusal::unsupported(KernelStage::Refine, "ruled_section", format!(
721            "rotate_faces: rebuilding the rim of edge {} as the section of the rotated \
722             carrier with its fixed neighbour — {}",
723            edge.id,
724            error.trim_start_matches("plane_ruled_section_arc: ")
725        ))
726    })?;
727    if !forward {
728        curve = curve.reversed().or_refuse(KernelStage::Refine, "reversed")?;
729    }
730    if closed {
731        // THE TURNOVER. A closed rim's direction is genuinely FREE — reversing a
732        // closed edge's curve leaves its single vertex where it is, so both
733        // faces it bounds simply traverse it the other way and no topology
734        // moves — and the sense above transports it in the carrier that TURNED.
735        // Once that carrier's axis has swung past the fixed neighbour's own
736        // direction, a rim that keeps its sense about the turning axis reverses
737        // its sense about the FIXED one, and the fixed face — whose chart the
738        // rotation never touched — is handed a hole that winds backwards.
739        //
740        // So the sense is kept in the carrier that did NOT move: the cylinder's
741        // axis when the plane is the side that turned, the plane's normal when
742        // it is the bore. That face has no freedom left — its carrier, its
743        // `same_sense` and its other loops all stand — so it is the one the rim
744        // must agree with, and agreeing with it puts the TURNED face right too,
745        // because the two traverse the one rim in opposite directions.
746        //
747        // Below the turnover this changes nothing: the transported sense and the
748        // fixed carrier's already agree, and the branch is a measured no-op.
749        let before = closed_curve_area_vector(&edge.curve, edge.t0, edge.t1).or_refuse(KernelStage::Refine, "closed_curve_area_vector")?.dot(fixed_reference);
750        let [d0, d1] = curve.domain().or_refuse(KernelStage::Refine, "domain")?;
751        let after = closed_curve_area_vector(&curve, d0, d1).or_refuse(KernelStage::Refine, "closed_curve_area_vector")?.dot(fixed_reference);
752        if before * after < 0.0 {
753            curve = curve.reversed().or_refuse(KernelStage::Refine, "reversed")?;
754        }
755    }
756    // The same "reapply the trimming" contract every rebuilt section is held to:
757    // it runs between the re-solved corners and every sample sits on BOTH
758    // carriers. For a closed rim both corners are the one seam vertex.
759    verify_section_between(
760        &curve,
761        frame,
762        rho0,
763        rho1,
764        height,
765        plane.normal,
766        plane.normal.dot(plane.origin),
767        start_new,
768        end_new,
769        tolerance,
770    )
771    .map_err(|error| error.with_message(|error| error.replace("move_faces:", "rotate_faces:")))?;
772    Ok(curve)
773}
774
775/// ROTATE the faces `face_ids` of `solid` by `angle_radians` about the axis
776/// through `axis_point` along `axis_direction` (right-handed), re-intersecting
777/// the neighbours the rotation moves the selection relative to.
778///
779/// `solid` is never touched: every refusal below happens before a clone is even
780/// made, or on the clone before it is returned, so a refused rotation leaves the
781/// caller's solid exactly as it was.
782///
783/// # Regimes
784///
785/// **Rigid** — every fixed carrier a boundary vertex touches is invariant under
786/// the rotation (`carrier_invariant_under`). The corner rides by `R`, the
787/// edges map by `R` exactly, and the fixed faces re-trim around them. This is
788/// what makes a cylindrical wall spun about its own axis a no-op that BUILDS.
789///
790/// **Re-intersection** — otherwise the corner is the common point of the
791/// carriers meeting there, with the moved ones ROTATED, and every affected edge
792/// is rebuilt between the new corners — straight between planes, and as the
793/// EXACT conic wherever a plane meets an oblique cylinder or cone, whichever of
794/// the two the rotation turns, or neither, for a fixed edge whose corner rides
795/// it. The TURNED side of such a pair is the tilted
796/// bore: its mouth is re-intersected in the frame `R` leaves, and its seam
797/// corner rides its own generatrix down to the fixed flat. A quadric meeting a
798/// quadric, or a sphere, torus, general revolution or free-form neighbour,
799/// refuses by name.
800///
801/// The re-solve only looks at the faces the selection borders, so a rotation
802/// that carries it into a face it does not border (a bore's wall turned until
803/// a mouth walks off its cap and out through a side) closes incidence-clean on
804/// a body that passes through itself. [`crate::accept_sound`] is the floor on
805/// the way out of this entry, as it is for [`crate::move_faces`]: it repairs
806/// where the crossing can be proved and refuses by name where it cannot.
807/// [`rotate_faces_unchecked`] is the re-solve alone, for a caller that runs
808/// its own acceptance on the result.
809pub fn rotate_faces(
810    solid: &BrepSolid,
811    face_ids: &[u64],
812    axis_point: Vec3,
813    axis_direction: Vec3,
814    angle_radians: f64,
815) -> Result<BrepSolid, KernelRefusal> {
816    crate::accept_sound(rotate_faces_unchecked(solid, face_ids, axis_point, axis_direction, angle_radians)?, "rotateFaces")
817}
818
819/// [`rotate_faces`] without its soundness floor: the direct re-solve, returned
820/// as soon as its incidences validate. The result can pass through itself; the
821/// caller owes it an acceptance scan ([`crate::accept_sound`]) before it is
822/// used as a body.
823pub fn rotate_faces_unchecked(
824    solid: &BrepSolid,
825    face_ids: &[u64],
826    axis_point: Vec3,
827    axis_direction: Vec3,
828    angle_radians: f64,
829) -> Result<BrepSolid, KernelRefusal> {
830    rotate_faces_rigid(
831        solid, face_ids, axis_point, axis_direction, angle_radians, Vec3::new(0.0, 0.0, 0.0),
832    )
833}
834
835/// Re-intersect against the final rigidly moved carriers. The translation is
836/// applied to the rotation's affine before solving any corner, so a combined
837/// face edit never has to build or validate a rotation-only intermediate body.
838/// The public rotation primitive uses exactly this solver with zero translation.
839pub(crate) fn rotate_faces_rigid(
840    solid: &BrepSolid,
841    face_ids: &[u64],
842    axis_point: Vec3,
843    axis_direction: Vec3,
844    angle_radians: f64,
845    translation: Vec3,
846) -> Result<BrepSolid, KernelRefusal> {
847    if !(translation.x.is_finite() && translation.y.is_finite() && translation.z.is_finite()) {
848        return Err(KernelRefusal::input(KernelStage::Collect, "translation", "rotate_faces: the translation must be finite"));
849    }
850    if !(axis_point.x.is_finite() && axis_point.y.is_finite() && axis_point.z.is_finite()) {
851        return Err(KernelRefusal::input(KernelStage::Collect, "axis_point", "rotate_faces: the axis point must be finite"));
852    }
853    if !(axis_direction.x.is_finite()
854        && axis_direction.y.is_finite()
855        && axis_direction.z.is_finite())
856    {
857        return Err(KernelRefusal::input(KernelStage::Collect, "axis_direction", "rotate_faces: the axis direction must be finite"));
858    }
859    if !angle_radians.is_finite() {
860        return Err(KernelRefusal::input(KernelStage::Collect, "angle", "rotate_faces: the angle must be finite"));
861    }
862    let axis = axis_direction.normalized().map_err(|_| {
863        KernelRefusal::input(
864            KernelStage::Collect,
865            "axis_length",
866            "rotate_faces: the axis direction has zero length",
867        )
868    })?;
869    if face_ids.is_empty() {
870        return Err(KernelRefusal::input(KernelStage::Collect, "selection", "rotate_faces: no faces selected"));
871    }
872    let moved: HashSet<u64> = face_ids.iter().copied().collect();
873    let mut face_lookup: HashMap<u64, (usize, usize)> = HashMap::default();
874    for (shell_index, shell) in solid.shells.iter().enumerate() {
875        for (face_index, face) in shell.faces.iter().enumerate() {
876            face_lookup
877                .entry(face.id)
878                .or_insert((shell_index, face_index));
879        }
880    }
881    for &face_id in face_ids {
882        if !face_lookup.contains_key(&face_id) {
883            return Err(KernelRefusal::input(KernelStage::Collect, "face_id", format!("rotate_faces: no face with id {face_id}")));
884        }
885    }
886
887    let scale = solid_model_scale(solid);
888    let tolerance = (scale * 1e-7).max(1e-9);
889    let plane_tolerance = (scale * 1e-6).max(1e-7);
890    // Direction comparisons are between UNIT vectors, so the band is
891    // dimensionless — the sine of the angle two carriers' directions differ by.
892    let angular_tolerance = 1e-9;
893    // "The corner landed exactly where R put it": the rigid endpoints are
894    // assigned `R(point)` verbatim, so this only absorbs rounding noise.
895    let rigid_tolerance = (scale * 1e-9).max(1e-12);
896    let mut rotation = rotation_about(axis_point, axis, angle_radians).or_refuse(KernelStage::Collect, "rotation")?;
897    rotation.elements[3] += translation.x;
898    rotation.elements[7] += translation.y;
899    rotation.elements[11] += translation.z;
900
901    // --- Classify every edge by how the group uses it ----------------------
902    let mut faces_of_edge: HashMap<u64, Vec<u64>> = HashMap::default();
903    for shell in &solid.shells {
904        for face in &shell.faces {
905            for loop_record in &face.loops {
906                for coedge in &loop_record.coedges {
907                    faces_of_edge
908                        .entry(coedge.edge_id)
909                        .or_default()
910                        .push(face.id);
911                }
912            }
913        }
914    }
915    let invariant = |face_id: u64| -> bool {
916        let rotation_invariant = carrier_invariant_under(
917            solid,
918            &face_lookup,
919            face_id,
920            axis_point,
921            axis,
922            angular_tolerance,
923            plane_tolerance,
924        );
925        if !rotation_invariant || translation.length() == 0.0 {
926            return rotation_invariant;
927        }
928        // A rigid corner may ride only when BOTH parts leave its carrier
929        // invariant. In particular, a plane spun within itself is no longer
930        // invariant when translated along its normal, nor is an axially shifted
931        // cone. A cylinder still admits a slide along its own axis.
932        let (shell, face) = face_lookup[&face_id];
933        let surface = &solid.shells[shell].faces[face].surface;
934        if let Some(AnalyticSurface::Plane { u_dir, v_dir, .. }) = surface.analytic() {
935            return u_dir.cross(*v_dir).normalized()
936                .map(|normal| normal.dot(translation).abs() <= rigid_tolerance)
937                .unwrap_or(false);
938        }
939        let Some((frame, rho0, rho1, _)) = carrier_ruled(solid, &face_lookup, face_id) else {
940            return false;
941        };
942        if (rho1 - rho0).abs() > 1e-9 * rho0.abs().max(rho1.abs()).max(1.0) {
943            return translation.length() <= rigid_tolerance;
944        }
945        translation.sub(frame.axis.scale(translation.dot(frame.axis))).length() <= rigid_tolerance
946    };
947
948    let mut classes: HashMap<u64, EdgeClass> = HashMap::default();
949    let mut planes: HashMap<u64, Plane> = HashMap::default();
950    for edge in &solid.edges {
951        let uses = faces_of_edge
952            .get(&edge.id)
953            .map(Vec::as_slice)
954            .unwrap_or(&[]);
955        let expected = if edge.degenerate { 1 } else { 2 };
956        if uses.len() != expected {
957            return Err(KernelRefusal::input(KernelStage::Collect, "non_manifold", format!(
958                "rotate_faces: edge {} is used {} times (non-manifold input)",
959                edge.id,
960                uses.len()
961            )));
962        }
963        let moved_uses = uses.iter().filter(|face_id| moved.contains(*face_id)).count();
964        let class = if moved_uses == 0 {
965            EdgeClass::Fixed
966        } else if moved_uses == uses.len() {
967            EdgeClass::Interior
968        } else {
969            let moved_face = *uses.iter().find(|face_id| moved.contains(*face_id)).unwrap();
970            let fixed_face = *uses.iter().find(|face_id| !moved.contains(*face_id)).unwrap();
971            // The face left behind across a boundary edge is what the rotated
972            // carrier is re-intersected with. Planar → cache its plane. An
973            // INVARIANT curved carrier → allowed: the rim rides it by `R`.
974            // Anything else refuses HERE, before a single number is computed,
975            // which is what makes "the refusal names the pair" true of the
976            // curved cases as well as the planar ones.
977            if carrier_is_planar(solid, &face_lookup, fixed_face) {
978                cached_plane(&mut planes, solid, &face_lookup, fixed_face, plane_tolerance)?;
979            } else if !invariant(fixed_face)
980                && carrier_ruled(solid, &face_lookup, fixed_face).is_some()
981                && !edge.degenerate
982                && edge.curve.straight_segment(tolerance).is_some()
983            {
984                // A STRAIGHT boundary edge against a cylinder or cone is one of
985                // the carrier's own rulings: the face was TANGENT to it (a fillet
986                // band beside the face) or runs along its axis. Rotating such a
987                // plane either separates it from the carrier or cuts it in a
988                // different pair of rulings — a topology change, not a conic rim
989                // — so there is nothing for the oblique route to re-intersect.
990                // Refused here, before any corner is solved, so the message says
991                // that instead of whichever corner solve would have failed first.
992                return Err(KernelRefusal::unsupported(KernelStage::Classify, "ruling_edge", format!(
993                    "rotate_faces: boundary edge {} of {} is a straight ruling of its neighbour {} \
994                     — the face is tangent to that carrier or runs along its axis, as beside a \
995                     fillet band — and a rotation re-intersects a cylinder or cone only where the \
996                     face cuts it in a conic — refusing",
997                    edge.id,
998                    face_short(solid, &face_lookup, moved_face),
999                    face_label(solid, &face_lookup, fixed_face)
1000                )));
1001            } else if !invariant(fixed_face)
1002                && carrier_ruled(solid, &face_lookup, fixed_face).is_none()
1003            {
1004                // An OBLIQUE cylinder or cone is admitted here: the rotated
1005                // planar carrier meets it in an exact ELLIPSE (a conic on a
1006                // cone), which `rotated_rim_section` builds and which the wall
1007                // is then re-trimmed around. A sphere, a torus, a general
1008                // revolution and a free-form patch have no such route and still
1009                // refuse, by name, before a single number is computed.
1010                return Err(unsupported_carrier(
1011                    solid,
1012                    &face_lookup,
1013                    fixed_face,
1014                    &format!(
1015                        "the fixed neighbour across boundary edge {} of {}",
1016                        edge.id,
1017                        face_short(solid, &face_lookup, moved_face)
1018                    ),
1019                ));
1020            }
1021            EdgeClass::Boundary {
1022                moved_face,
1023                fixed_face,
1024            }
1025        };
1026        classes.insert(edge.id, class);
1027    }
1028
1029    // --- THE PARALLEL LIMIT, before anything is solved ---------------------
1030    // A boundary pair that must be re-intersected needs the rotated moved plane
1031    // and the fixed plane to MEET. `solve_corner` would report the same failure
1032    // later as "parallel or under-constrained planes" at a vertex, which names
1033    // neither face and cannot distinguish this from a tearing corner. The angle
1034    // is in the message because the angle is the input that caused it.
1035    for edge in &solid.edges {
1036        let EdgeClass::Boundary {
1037            moved_face,
1038            fixed_face,
1039        } = classes[&edge.id]
1040        else {
1041            continue;
1042        };
1043        if invariant(fixed_face) {
1044            continue; // rides rigidly; the two carriers never have to meet anew
1045        }
1046        if carrier_ruled(solid, &face_lookup, fixed_face).is_some() {
1047            // A plane and a quadric are never PARALLEL — they meet in a conic
1048            // unless the plane misses the carrier entirely, which the section
1049            // construction itself reports (and names) at the rim rebuild.
1050            continue;
1051        }
1052        if let Some((frame, rho0, rho1, _)) = carrier_ruled(solid, &face_lookup, moved_face)
1053            .filter(|_| !invariant(moved_face))
1054        {
1055            // THE MIRROR LIMIT. A turned CYLINDER meets the flat in an ellipse
1056            // until its axis runs PARALLEL to that flat: there the section is a
1057            // pair of rulings, and there is no rim to build.
1058            // `plane_ruled_section_arc` reports it too, but only once a corner
1059            // has been solved on a carrier the rotation has already ruined, so
1060            // the angle that caused it is named here instead.
1061            //
1062            // A CONE is deliberately not tested here: an axis parallel to the
1063            // flat cuts it in a HYPERBOLA, not a ruling pair, and the limits
1064            // that actually stop a cone — the apex plane, and a section whose
1065            // rational weights change sign — are the ones the section
1066            // construction names for itself, on the fixed-cone row's wording.
1067            let radius_scale = rho0.abs().max(rho1.abs()).max(1.0);
1068            if (rho1 - rho0).abs() <= 1e-9 * radius_scale {
1069                let turned_axis = rotate_direction(&rotation, frame.axis);
1070                let fixed_plane = planes[&fixed_face];
1071                if turned_axis.dot(fixed_plane.normal).abs() <= PARALLEL_EPS {
1072                    return Err(KernelRefusal::unsupported(KernelStage::Classify, AXIS_PARALLEL_LIMIT, format!(
1073                        "rotate_faces: {:.6}° lays the axis of {} parallel to its neighbour {} \
1074                         across edge {}; the two carriers then meet in a pair of rulings rather \
1075                         than a conic, so there is no rim to rebuild — refusing",
1076                        angle_radians.to_degrees(),
1077                        face_short(solid, &face_lookup, moved_face),
1078                        face_short(solid, &face_lookup, fixed_face),
1079                        edge.id
1080                    )));
1081                }
1082            }
1083            continue;
1084        }
1085        if !carrier_is_planar(solid, &face_lookup, moved_face) {
1086            continue; // refused below, by the carrier gate, with a better message
1087        }
1088        let moved_plane =
1089            cached_plane(&mut planes, solid, &face_lookup, moved_face, plane_tolerance)?;
1090        let fixed_plane = planes[&fixed_face];
1091        let rotated_normal = rotate_direction(&rotation, moved_plane.normal);
1092        if rotated_normal.cross(fixed_plane.normal).length() <= PARALLEL_EPS {
1093            return Err(KernelRefusal::unsupported(KernelStage::Classify, PARALLEL_LIMIT, format!(
1094                "rotate_faces: {:.6}° turns {} parallel to its neighbour {} across edge {}; \
1095                 the two carriers no longer meet, so there is no edge to rebuild — refusing",
1096                angle_radians.to_degrees(),
1097                face_short(solid, &face_lookup, moved_face),
1098                face_short(solid, &face_lookup, fixed_face),
1099                edge.id
1100            )));
1101        }
1102    }
1103
1104    // --- Relocate every vertex the group touches ---------------------------
1105    let mut vertex_faces: HashMap<u64, HashSet<u64>> = HashMap::default();
1106    for edge in &solid.edges {
1107        if let Some(uses) = faces_of_edge.get(&edge.id) {
1108            for vertex_id in [edge.start_vertex_id, edge.end_vertex_id] {
1109                vertex_faces
1110                    .entry(vertex_id)
1111                    .or_default()
1112                    .extend(uses.iter().copied());
1113            }
1114        }
1115    }
1116    let mut new_vertex: HashMap<u64, Vec3> = HashMap::default();
1117    for vertex in &solid.vertices {
1118        let Some(adjacent) = vertex_faces.get(&vertex.id) else {
1119            continue;
1120        };
1121        if !adjacent.iter().any(|face_id| moved.contains(face_id)) {
1122            continue;
1123        }
1124        // THE IDENTITY. If EVERY carrier at this vertex — the rotated ones as
1125        // well as the fixed ones — is invariant under `R`, the rotation
1126        // constrains the vertex to nothing: its old position already satisfies
1127        // every (unchanged) carrier equation. Leaving it is not an optimisation,
1128        // it is the right answer, and it is what makes a cap spun about its own
1129        // cylinder's axis return the input rather than dragging the rim's seam
1130        // vertex around a circle the wall's own seam edge cannot follow.
1131        if adjacent.iter().all(|&face_id| invariant(face_id))
1132            || (translation.length() > 0.0
1133                && adjacent.iter().filter(|face_id| moved.contains(face_id))
1134                    .all(|&face_id| invariant(face_id)))
1135        {
1136            // In a combined motion an axially spun/slid cylinder can stay
1137            // invariant while its fixed cap would not. Only the selected
1138            // carriers actually move: when they all stay put, so does this
1139            // vertex, regardless of how the affine would move a fixed face.
1140            continue;
1141        }
1142        let fixed_at: Vec<u64> = adjacent
1143            .iter()
1144            .copied()
1145            .filter(|face_id| !moved.contains(face_id))
1146            .collect();
1147        if fixed_at.is_empty() {
1148            // Interior vertex: carried rigidly with the group.
1149            new_vertex.insert(vertex.id, rotation.point(vertex.point));
1150            continue;
1151        }
1152        // RIGID: every fixed carrier here is invariant, so `R(vertex)` is on all
1153        // of them. Verified rather than asserted.
1154        if fixed_at.iter().all(|&face_id| invariant(face_id)) {
1155            let point = rotation.point(vertex.point);
1156            for &face_id in &fixed_at {
1157                verify_point_on_fixed(
1158                    solid,
1159                    &face_lookup,
1160                    &mut planes,
1161                    face_id,
1162                    point,
1163                    vertex.id,
1164                    plane_tolerance,
1165                    tolerance,
1166                )?;
1167            }
1168            new_vertex.insert(vertex.id, point);
1169            continue;
1170        }
1171        // A corner against a NON-INVARIANT ruled carrier — the oblique bore's
1172        // seam vertex. Its carrier is not a plane, so the three-plane solve
1173        // below cannot place it; it rides the ONE fixed edge it shares with the
1174        // body (the wall's seam generatrix, or a cone's straight meridian) to
1175        // where the ROTATED cap plane crosses it. Move Face solves the same
1176        // corner the same way under a translation; only the cap plane differs.
1177        if fixed_at
1178            .iter()
1179            .any(|&face_id| carrier_ruled(solid, &face_lookup, face_id).is_some() && !invariant(face_id))
1180        {
1181            let moved_here: Vec<u64> = adjacent
1182                .iter()
1183                .copied()
1184                .filter(|face_id| moved.contains(face_id))
1185                .collect();
1186            if moved_here.len() != 1 {
1187                return Err(KernelRefusal::unsupported(KernelStage::Classify, "single_cap_only", format!(
1188                    "rotate_faces: the corner at vertex {} touches {} rotated faces against a \
1189                     ruled neighbour (a single rotated cap only) — refusing",
1190                    vertex.id,
1191                    moved_here.len()
1192                )));
1193            }
1194            let cap_plane =
1195                cached_plane(&mut planes, solid, &face_lookup, moved_here[0], plane_tolerance)
1196                    .map_err(|_| {
1197                        unsupported_carrier(
1198                            solid,
1199                            &face_lookup,
1200                            moved_here[0],
1201                            &format!("the ROTATED cap at vertex {}", vertex.id),
1202                        )
1203                    })?;
1204            let rotated_cap = rotate_plane(&rotation, &cap_plane);
1205            let plane_c = rotated_cap.normal.dot(rotated_cap.origin);
1206            let fixed_edges: Vec<&EdgeRecord> = solid
1207                .edges
1208                .iter()
1209                .filter(|edge| {
1210                    (edge.start_vertex_id == vertex.id || edge.end_vertex_id == vertex.id)
1211                        && matches!(classes.get(&edge.id), Some(EdgeClass::Fixed))
1212                })
1213                .collect();
1214            if fixed_edges.len() != 1 {
1215                return Err(KernelRefusal::unsupported(KernelStage::Classify, "single_fixed_edge_only", format!(
1216                    "rotate_faces: the corner at vertex {} rides {} fixed edges against a ruled \
1217                     neighbour (exactly one required) — refusing",
1218                    vertex.id,
1219                    fixed_edges.len()
1220                )));
1221            }
1222            let fixed_edge = fixed_edges[0];
1223            let seed = if fixed_edge.start_vertex_id == vertex.id {
1224                fixed_edge.t0
1225            } else {
1226                fixed_edge.t1
1227            };
1228            // A STRAIGHT fixed edge rides its own line exactly, and a crossing
1229            // OUTSIDE its current span is still exact (a line is its own
1230            // extension) — which is what lets the rotation lengthen the wall.
1231            // A CURVED one is solved on the CARRIERS instead: the boolean split
1232            // it exactly at the corner, so riding it could only move the corner
1233            // inward. Straightness is geometry, not pole count.
1234            let carriers = if fixed_edge.curve.straight_segment(tolerance).is_some() {
1235                None
1236            } else {
1237                plane_and_ruled_carriers(
1238                    solid,
1239                    &face_lookup,
1240                    &mut planes,
1241                    &fixed_at,
1242                    plane_tolerance,
1243                )
1244            };
1245            let corner = match carriers {
1246                Some((fixed_plane, (frame, rho0, rho1, height))) => corner_on_plane_and_ruled(
1247                    &fixed_plane,
1248                    rotated_cap.normal,
1249                    plane_c,
1250                    &frame,
1251                    rho0,
1252                    rho1,
1253                    height,
1254                    vertex.point,
1255                    tolerance,
1256                )
1257                .map_err(|error| error.with_message(|error| translate_corner_refusal(error, vertex.id)))?,
1258                None => resolve_corner_on_fixed_edge(
1259                    fixed_edge,
1260                    seed,
1261                    rotated_cap.normal,
1262                    plane_c,
1263                    tolerance,
1264                )
1265                .map_err(|error| error.with_message(|error| translate_corner_refusal(error, vertex.id)))?,
1266            };
1267            // Checked, not asserted: the corner must sit on EVERY fixed carrier
1268            // at the vertex and on the rotated cap, or the group tore off.
1269            for &face_id in &fixed_at {
1270                verify_point_on_fixed(
1271                    solid,
1272                    &face_lookup,
1273                    &mut planes,
1274                    face_id,
1275                    corner,
1276                    vertex.id,
1277                    plane_tolerance,
1278                    tolerance,
1279                )?;
1280            }
1281            let off_cap = corner.sub(rotated_cap.origin).dot(rotated_cap.normal).abs();
1282            if off_cap > 10.0 * tolerance {
1283                return Err(KernelRefusal::internal(KernelStage::Validate, "corner_on_cap", format!(
1284                    "rotate_faces: the re-solved corner at vertex {} left the ROTATED cap \
1285                     (off {off_cap:.3e}) — refusing",
1286                    vertex.id
1287                )));
1288            }
1289            new_vertex.insert(vertex.id, corner);
1290            continue;
1291        }
1292        // THE MIRROR CORNER — a ROTATED ruled carrier against a fixed FLAT.
1293        // This is the bore wall the user tilts: the moved face is the cylinder
1294        // (or cone), the fixed neighbour is the flat it opens through, and the
1295        // rim they meet in is an ELLIPSE on that flat. The three-plane solve
1296        // below cannot place the corner (the moved carrier is not a plane), and
1297        // the branch above cannot either (it is the FIXED side that is curved
1298        // there). One point on the rim is free — the ellipse is a whole
1299        // one-parameter family — and the thing that fixes it is the face's own
1300        // SEAM: the corner is where the seam generatrix, carried by `R` with the
1301        // rest of the wall, crosses the flat. Riding the rotated edge is exact
1302        // for a straight generatrix, and it keeps the seam vertex on the seam,
1303        // which is what the rim section is then anchored at.
1304        if let Some(moved_ruled) = rotated_moved_ruled_carrier(
1305            solid,
1306            &face_lookup,
1307            &rotation,
1308            &moved,
1309            &adjacent,
1310            &invariant,
1311        ) {
1312            let (moved_face, turned_frame, rho0, rho1, height) = moved_ruled;
1313            if fixed_at.len() != 1 {
1314                return Err(KernelRefusal::unsupported(KernelStage::Classify, "mirror_corner_flats", format!(
1315                    "rotate_faces: the corner at vertex {} where the rotated {} meets its \
1316                     neighbours touches {} fixed faces (a rotated cylinder or cone is \
1317                     re-intersected against exactly one flat there) — refusing",
1318                    vertex.id,
1319                    face_short(solid, &face_lookup, moved_face),
1320                    fixed_at.len()
1321                )));
1322            }
1323            let fixed_face = fixed_at[0];
1324            let flat = cached_plane(&mut planes, solid, &face_lookup, fixed_face, plane_tolerance)
1325                .map_err(|_| {
1326                    unsupported_carrier(
1327                        solid,
1328                        &face_lookup,
1329                        fixed_face,
1330                        &format!(
1331                            "the fixed neighbour of the rotated {} at vertex {}",
1332                            face_short(solid, &face_lookup, moved_face),
1333                            vertex.id
1334                        ),
1335                    )
1336                })?;
1337            let seam: Vec<&EdgeRecord> = solid
1338                .edges
1339                .iter()
1340                .filter(|edge| {
1341                    (edge.start_vertex_id == vertex.id || edge.end_vertex_id == vertex.id)
1342                        && matches!(classes.get(&edge.id), Some(EdgeClass::Interior))
1343                        && !edge.degenerate
1344                })
1345                .collect();
1346            // A rim vertex that is NOT the seam vertex — the bookkeeping split an
1347            // import leaves at a carrier's parameter origin — has no edge of the
1348            // group's own at it, and nothing then says where on the new ellipse
1349            // it belongs. It refuses here rather than being placed by guesswork.
1350            if seam.len() != 1 {
1351                return Err(KernelRefusal::unsupported(KernelStage::Classify, "seam_edge_count", format!(
1352                    "rotate_faces: the corner at vertex {} on the rotated {} rides {} of the \
1353                     group's own edges (the seam generatrix, exactly one, is what places it) \
1354                     — refusing",
1355                    vertex.id,
1356                    face_short(solid, &face_lookup, moved_face),
1357                    seam.len()
1358                )));
1359            }
1360            let seam = seam[0];
1361            let seed = if seam.start_vertex_id == vertex.id {
1362                seam.t0
1363            } else {
1364                seam.t1
1365            };
1366            let turned_seam = EdgeRecord {
1367                curve: transform_curve(&seam.curve, rotation).or_refuse(KernelStage::Refine, "transform_curve")?,
1368                ..seam.clone()
1369            };
1370            let corner = resolve_corner_on_fixed_edge(
1371                &turned_seam,
1372                seed,
1373                flat.normal,
1374                flat.normal.dot(flat.origin),
1375                tolerance,
1376            )
1377            .map_err(|error| error.with_message(|error| translate_corner_refusal(error, vertex.id)))?;
1378            // Checked, not asserted, exactly as every other corner here is: on
1379            // the flat it must stay on, and on the carrier the rotation left.
1380            verify_point_on_fixed(
1381                solid,
1382                &face_lookup,
1383                &mut planes,
1384                fixed_face,
1385                corner,
1386                vertex.id,
1387                plane_tolerance,
1388                tolerance,
1389            )?;
1390            let off = ruled_offset(&turned_frame, rho0, rho1, height, corner);
1391            if off > 10.0 * tolerance {
1392                return Err(KernelRefusal::internal(KernelStage::Validate, "mirror_corner_on_carrier", format!(
1393                    "rotate_faces: the re-solved corner at vertex {} left the ROTATED {} \
1394                     (off {off:.3e}) — refusing",
1395                    vertex.id,
1396                    face_short(solid, &face_lookup, moved_face)
1397                )));
1398            }
1399            new_vertex.insert(vertex.id, corner);
1400            continue;
1401        }
1402        // RE-INTERSECTION: the corner is the common point of the carriers
1403        // meeting here, with the moved ones ROTATED. Every one of them must be
1404        // planar to solve it in closed form.
1405        let mut corner_planes = Vec::with_capacity(adjacent.len());
1406        for &face_id in &fixed_at {
1407            corner_planes.push(
1408                cached_plane(&mut planes, solid, &face_lookup, face_id, plane_tolerance).map_err(
1409                    |_| {
1410                        unsupported_carrier(
1411                            solid,
1412                            &face_lookup,
1413                            face_id,
1414                            &format!(
1415                                "a FIXED carrier meeting the rotated group at vertex {}",
1416                                vertex.id
1417                            ),
1418                        )
1419                    },
1420                )?,
1421            );
1422        }
1423        for face_id in adjacent.iter().copied().filter(|id| moved.contains(id)) {
1424            let plane = cached_plane(&mut planes, solid, &face_lookup, face_id, plane_tolerance)
1425                .map_err(|_| {
1426                    unsupported_carrier(
1427                        solid,
1428                        &face_lookup,
1429                        face_id,
1430                        &format!(
1431                            "a ROTATED carrier meeting a fixed neighbour at vertex {}",
1432                            vertex.id
1433                        ),
1434                    )
1435                })?;
1436            corner_planes.push(rotate_plane(&rotation, &plane));
1437        }
1438        let corner = solve_corner(&corner_planes).ok_or_else(|| {
1439            KernelRefusal::ill_posed(KernelStage::Refine, "corner_underconstrained", format!(
1440                "rotate_faces: cannot re-intersect the carriers meeting at vertex {} \
1441                 (parallel or under-constrained planes) — refusing",
1442                vertex.id
1443            ))
1444        })?;
1445        // The corner must genuinely sit on EVERY carrier; otherwise the group
1446        // tears away from its fixed neighbours and no manifold heal exists.
1447        for plane in &corner_planes {
1448            if corner.sub(plane.origin).dot(plane.normal).abs() > tolerance {
1449                return Err(KernelRefusal::unsupported(KernelStage::Refine, "corner_tear", format!(
1450                    "rotate_faces: the rotated group tears away from its neighbours at \
1451                     vertex {} — refusing rather than emitting an invalid solid",
1452                    vertex.id
1453                )));
1454            }
1455        }
1456        new_vertex.insert(vertex.id, corner);
1457    }
1458
1459    // --- Plan every edge update -------------------------------------------
1460    let vertex_position: HashMap<u64, Vec3> = solid
1461        .vertices
1462        .iter()
1463        .map(|vertex| (vertex.id, vertex.point))
1464        .collect();
1465    let mut actions: HashMap<u64, EdgeAction> = HashMap::default();
1466    for edge in &solid.edges {
1467        let position = |vertex_id: u64| -> Result<Vec3, KernelRefusal> {
1468            vertex_position.get(&vertex_id).copied().ok_or_else(|| {
1469                KernelRefusal::internal(
1470                    KernelStage::Collect,
1471                    "vertex_lookup",
1472                    format!("rotate_faces: missing vertex {vertex_id}"),
1473                )
1474            })
1475        };
1476        let start_old = position(edge.start_vertex_id)?;
1477        let end_old = position(edge.end_vertex_id)?;
1478        let start_new = new_vertex
1479            .get(&edge.start_vertex_id)
1480            .copied()
1481            .unwrap_or(start_old);
1482        let end_new = new_vertex
1483            .get(&edge.end_vertex_id)
1484            .copied()
1485            .unwrap_or(end_old);
1486        // Neither endpoint relocated, and every ROTATED carrier the edge lies on
1487        // maps onto itself: the edge is where it belongs already. (For a Fixed
1488        // edge the second clause is vacuous — no face using it is moved.)
1489        if start_new.sub(start_old).length() == 0.0
1490            && end_new.sub(end_old).length() == 0.0
1491            && faces_of_edge[&edge.id]
1492                .iter()
1493                .all(|face_id| !moved.contains(face_id) || invariant(*face_id))
1494        {
1495            continue;
1496        }
1497        let rigid = start_new.sub(rotation.point(start_old)).length() <= rigid_tolerance
1498            && end_new.sub(rotation.point(end_old)).length() <= rigid_tolerance;
1499        let rebuild = |planes: &mut HashMap<u64, Plane>| -> Result<EdgeAction, KernelRefusal> {
1500            // Every carrier of an edge that is REBUILT straight has to be
1501            // re-trimmed around it afterwards, and the only re-trims here are the
1502            // planar one and the invariant-ruled one.
1503            for &face_id in &faces_of_edge[&edge.id] {
1504                if invariant(face_id) {
1505                    continue;
1506                }
1507                // A NON-invariant RULED carrier re-trims too, on its own grown
1508                // carrier (`retrim_ruled_face`) — this is the arm the oblique
1509                // bore's seam generatrix takes, and `verify_chord_on_curved`
1510                // below is what proves the straight chord stayed on it.
1511                if carrier_ruled(solid, &face_lookup, face_id).is_some() {
1512                    continue;
1513                }
1514                cached_plane(planes, solid, &face_lookup, face_id, plane_tolerance).map_err(
1515                    |_| {
1516                        unsupported_carrier(
1517                            solid,
1518                            &face_lookup,
1519                            face_id,
1520                            &format!("a carrier of edge {}, whose trim the rotation moves", edge.id),
1521                        )
1522                    },
1523                )?;
1524            }
1525            let action = plan_straight_rebuild(
1526                solid,
1527                &face_lookup,
1528                &faces_of_edge,
1529                edge,
1530                start_old,
1531                end_old,
1532                start_new,
1533                end_new,
1534                tolerance,
1535            )?;
1536            if let EdgeAction::Rebuild { start, end } = &action {
1537                for &face_id in &faces_of_edge[&edge.id] {
1538                    verify_chord_on_curved(
1539                        solid,
1540                        &face_lookup,
1541                        face_id,
1542                        edge.id,
1543                        *start,
1544                        *end,
1545                        moved.contains(&face_id).then_some(&rotation),
1546                        tolerance,
1547                    )?;
1548                }
1549            }
1550            Ok(action)
1551        };
1552        match classes[&edge.id] {
1553            EdgeClass::Fixed => {
1554                // A CURVED fixed edge between a flat and a cylinder or cone: an
1555                // Offset Shell's enlarged bore cutting a tilted inner floor runs
1556                // such an ellipse arc out to the rotated face. Both carriers
1557                // stayed put, so the section is unchanged as a SET; only the end
1558                // on the rotated face moved, along it (the vertex pass solved
1559                // that corner on these two carriers). So it is re-cut between
1560                // its corners, under the guards a straight rebuild gets.
1561                if !edge.degenerate
1562                    && edge.start_vertex_id != edge.end_vertex_id
1563                    && edge.curve.straight_segment(tolerance).is_none()
1564                {
1565                    if let Some((fixed_plane, (frame, rho0, rho1, height))) = plane_and_ruled_carriers(
1566                        solid,
1567                        &face_lookup,
1568                        &mut planes,
1569                        &faces_of_edge[&edge.id],
1570                        plane_tolerance,
1571                    ) {
1572                        let new_chord = end_new.sub(start_new);
1573                        if new_chord.length() <= tolerance {
1574                            return Err(KernelRefusal::unsupported(KernelStage::Refine, "edge_collapse", format!(
1575                                "rotate_faces: the rotation collapses curved edge {} to zero length — refusing",
1576                                edge.id
1577                            )));
1578                        }
1579                        if end_old.sub(start_old).dot(new_chord) <= 0.0 {
1580                            return Err(KernelRefusal::unsupported(KernelStage::Refine, EDGE_INVERSION, format!(
1581                                "rotate_faces: the rotation inverts curved edge {} (the trim is turned \
1582                                 inside out) — refusing",
1583                                edge.id
1584                            )));
1585                        }
1586                        let curve = rotated_rim_section(
1587                            edge,
1588                            &frame,
1589                            &frame,
1590                            rho0,
1591                            rho1,
1592                            height,
1593                            &fixed_plane,
1594                            fixed_plane.normal,
1595                            start_new,
1596                            end_new,
1597                            tolerance,
1598                        )?;
1599                        actions.insert(edge.id, EdgeAction::Replace { curve });
1600                        continue;
1601                    }
1602                }
1603                // A fixed side edge follows its re-solved endpoint. Both of its
1604                // own carriers stayed put, so it cannot ride `R`: it is rebuilt
1605                // between the endpoints, straight.
1606                actions.insert(edge.id, rebuild(&mut planes)?);
1607            }
1608            EdgeClass::Interior => {
1609                if rigid {
1610                    actions.insert(edge.id, EdgeAction::Rotate);
1611                } else {
1612                    actions.insert(edge.id, rebuild(&mut planes)?);
1613                }
1614            }
1615            EdgeClass::Boundary {
1616                moved_face,
1617                fixed_face,
1618            } => {
1619                if rigid && invariant(fixed_face) {
1620                    // The edge maps by `R` and lands on the (unchanged) fixed
1621                    // carrier as well as on the rotated moved one — exact for any
1622                    // curve type, no re-intersection needed. This is the arm a
1623                    // cap spun about its own cylinder's axis takes.
1624                    actions.insert(edge.id, EdgeAction::Rotate);
1625                } else if let Some((frame, rho0, rho1, height)) =
1626                    carrier_ruled(solid, &face_lookup, fixed_face).filter(|_| !invariant(fixed_face))
1627                {
1628                    // THE OBLIQUE QUADRIC RIM. The rotated planar carrier meets
1629                    // the fixed cylinder in an ELLIPSE and the fixed cone in a
1630                    // conic, and no affine carries the old rim to it — a
1631                    // rotation moves the carrier's NORMAL, which neither the
1632                    // cylinder's axial shift nor the cone's homothety about its
1633                    // apex can follow. So the rim is RE-INTERSECTED, exactly,
1634                    // and anchored on the corners already re-solved above.
1635                    let moved_plane =
1636                        cached_plane(&mut planes, solid, &face_lookup, moved_face, plane_tolerance)
1637                            .map_err(|_| {
1638                                unsupported_carrier(
1639                                    solid,
1640                                    &face_lookup,
1641                                    moved_face,
1642                                    &format!(
1643                                        "the ROTATED side of boundary edge {} against {}",
1644                                        edge.id,
1645                                        face_short(solid, &face_lookup, fixed_face)
1646                                    ),
1647                                )
1648                            })?;
1649                    let curve = rotated_rim_section(
1650                        edge,
1651                        &frame,
1652                        &frame,
1653                        rho0,
1654                        rho1,
1655                        height,
1656                        &rotate_plane(&rotation, &moved_plane),
1657                        frame.axis,
1658                        start_new,
1659                        end_new,
1660                        tolerance,
1661                    )?;
1662                    actions.insert(edge.id, EdgeAction::Replace { curve });
1663                } else if let Some((frame, rho0, rho1, height)) =
1664                    carrier_ruled(solid, &face_lookup, moved_face)
1665                        .filter(|_| !invariant(moved_face))
1666                {
1667                    // THE MIRROR RIM — the tilted bore's mouth. The same
1668                    // `plane ∩ quadric` section as the arm above, with the roles
1669                    // swapped: here it is the CYLINDER (or cone) that turned and
1670                    // the FLAT that stayed, so the section is built in the frame
1671                    // `R` leaves and against the fixed plane. The sense is still
1672                    // read in the carrier's OLD frame, the only one the rim
1673                    // curve on record is consistent with, and the anchor is the
1674                    // seam corner the vertex pass just rode down the generatrix.
1675                    let fixed_plane =
1676                        cached_plane(&mut planes, solid, &face_lookup, fixed_face, plane_tolerance)
1677                            .map_err(|_| {
1678                                unsupported_carrier(
1679                                    solid,
1680                                    &face_lookup,
1681                                    fixed_face,
1682                                    &format!(
1683                                        "the FIXED side of boundary edge {} against the rotated {}",
1684                                        edge.id,
1685                                        face_short(solid, &face_lookup, moved_face)
1686                                    ),
1687                                )
1688                            })?;
1689                    let curve = rotated_rim_section(
1690                        edge,
1691                        &rotate_ruled_frame(&rotation, &frame),
1692                        &frame,
1693                        rho0,
1694                        rho1,
1695                        height,
1696                        &fixed_plane,
1697                        fixed_plane.normal,
1698                        start_new,
1699                        end_new,
1700                        tolerance,
1701                    )?;
1702                    actions.insert(edge.id, EdgeAction::Replace { curve });
1703                } else {
1704                    // Real re-intersection: the line where the ROTATED moved
1705                    // plane meets the fixed plane, delimited by the re-solved
1706                    // corners. The moved side must be planar for the chord to
1707                    // stay on it.
1708                    cached_plane(&mut planes, solid, &face_lookup, moved_face, plane_tolerance)
1709                        .map_err(|_| {
1710                            unsupported_carrier(
1711                                solid,
1712                                &face_lookup,
1713                                moved_face,
1714                                &format!(
1715                                    "the ROTATED side of boundary edge {} against {}",
1716                                    edge.id,
1717                                    face_short(solid, &face_lookup, fixed_face)
1718                                ),
1719                            )
1720                        })?;
1721                    actions.insert(edge.id, rebuild(&mut planes)?);
1722                }
1723            }
1724        }
1725    }
1726
1727    // --- Plan face updates -------------------------------------------------
1728    // Edges whose SHAPE changed. A face bounding one of these must be RE-TRIMMED
1729    // (its rim moved to a new curve), not merely surface-transformed, else its
1730    // pcurve goes stale. A rigidly ROTATED edge on a rigidly rotated face keeps
1731    // its pcurve exactly, which is what the rigid regime is worth.
1732    let reshaped: HashSet<u64> = actions
1733        .iter()
1734        .filter(|(_, action)| {
1735            matches!(
1736                action,
1737                EdgeAction::Rebuild { .. } | EdgeAction::Replace { .. }
1738            )
1739        })
1740        .map(|(edge_id, _)| *edge_id)
1741        .collect();
1742    let dirty: HashSet<u64> = actions.keys().copied().collect();
1743    let mut face_actions: Vec<(usize, usize, FaceAction)> = Vec::new();
1744    // Ruled faces re-trim in a post-pass (they need `&mut solid`): the fixed
1745    // neighbours a rim rode onto, and the ROTATED wall whose own rims moved.
1746    let mut ruled_retrim_faces: Vec<u64> = Vec::new();
1747    for (shell_index, shell) in solid.shells.iter().enumerate() {
1748        for (face_index, face) in shell.faces.iter().enumerate() {
1749            let edge_ids = || {
1750                face.loops
1751                    .iter()
1752                    .flat_map(|loop_record| &loop_record.coedges)
1753                    .map(|coedge| coedge.edge_id)
1754            };
1755            if moved.contains(&face.id) {
1756                if edge_ids().any(|edge_id| reshaped.contains(&edge_id))
1757                    && carrier_ruled(solid, &face_lookup, face.id).is_some()
1758                    && !invariant(face.id)
1759                {
1760                    // THE TILTED WALL ITSELF. Its rims were re-intersected, so
1761                    // the pcurves on record are stale — a bore that met its
1762                    // flats in circles meets them in ellipses once it leans, and
1763                    // in the wall's own parameters that is a sine, not a line.
1764                    // Turning the control net is exact (a rotated cylinder is a
1765                    // cylinder of the same radius), and the re-trim afterwards
1766                    // rebuilds the loops on THAT carrier, grown along its axis
1767                    // to cover the new rims — the tilt lengthens the wall.
1768                    face_actions.push((shell_index, face_index, FaceAction::RotateSurface));
1769                    ruled_retrim_faces.push(face.id);
1770                } else if edge_ids().any(|edge_id| reshaped.contains(&edge_id)) {
1771                    // A boundary edge changed shape, so the patch is re-trimmed
1772                    // around it — on the ROTATED plane, frame and all.
1773                    let plane =
1774                        cached_plane(&mut planes, solid, &face_lookup, face.id, plane_tolerance)
1775                            .map_err(|_| {
1776                                unsupported_carrier(
1777                                    solid,
1778                                    &face_lookup,
1779                                    face.id,
1780                                    "the ROTATED face whose rim the neighbours reshaped",
1781                                )
1782                            })?;
1783                    face_actions.push((
1784                        shell_index,
1785                        face_index,
1786                        FaceAction::Retrim(rotate_plane(&rotation, &plane)),
1787                    ));
1788                } else if edge_ids().any(|edge_id| dirty.contains(&edge_id)) {
1789                    // Every edge of the face rode along rigidly: rotating the
1790                    // control net keeps surface, curves and pcurves in exact
1791                    // agreement for ANY carrier type.
1792                    face_actions.push((shell_index, face_index, FaceAction::RotateSurface));
1793                } else if !invariant(face.id) {
1794                    // Nothing moved and the carrier does not map onto itself —
1795                    // which the vertex rule above makes unreachable, since a face
1796                    // whose boundary stayed put had every carrier at every one of
1797                    // its corners invariant, this one included. Rotate the net
1798                    // rather than silently emit a face off its own boundary.
1799                    face_actions.push((shell_index, face_index, FaceAction::RotateSurface));
1800                }
1801                // ...and an invariant carrier nothing touched is left ALONE: the
1802                // rotation maps it onto itself, so turning the control net would
1803                // only re-parameterise the surface under pcurves that were never
1804                // rebuilt. This is the arm the identity rotations exit through.
1805            } else if edge_ids().any(|edge_id| dirty.contains(&edge_id)) {
1806                if carrier_is_planar(solid, &face_lookup, face.id) {
1807                    // A FIXED plane keeps its carrier; only its trim moved.
1808                    let plane =
1809                        cached_plane(&mut planes, solid, &face_lookup, face.id, plane_tolerance)?;
1810                    face_actions.push((shell_index, face_index, FaceAction::Retrim(plane)));
1811                } else if carrier_ruled(solid, &face_lookup, face.id).is_some() {
1812                    // Both the INVARIANT coaxial band (whose rim rode by `R`)
1813                    // and the OBLIQUE cylinder or cone (whose rim was
1814                    // re-intersected) re-trim on their own carrier, grown along
1815                    // its axis to cover the new rim.
1816                    ruled_retrim_faces.push(face.id);
1817                } else {
1818                    return Err(unsupported_carrier(
1819                        solid,
1820                        &face_lookup,
1821                        face.id,
1822                        "a FIXED face the rotation must re-trim",
1823                    ));
1824                }
1825            }
1826        }
1827    }
1828
1829    // --- Apply to a fresh clone (the input is never touched) ---------------
1830    let mut result = solid.clone();
1831    for edge in &mut result.edges {
1832        match actions.get(&edge.id) {
1833            Some(EdgeAction::Rotate) => {
1834                edge.curve = transform_curve(&edge.curve, rotation).or_refuse(KernelStage::Sew, "transform_curve")?;
1835            }
1836            Some(EdgeAction::Rebuild { start, end }) => {
1837                edge.curve = make_line(*start, *end).or_refuse(KernelStage::Sew, "make_line")?;
1838                edge.t0 = 0.0;
1839                edge.t1 = 1.0;
1840            }
1841            Some(EdgeAction::Replace { curve }) => {
1842                // An exactly re-intersected section spans its whole domain by
1843                // construction, so the trim IS the domain.
1844                let [d0, d1] = curve.domain().or_refuse(KernelStage::Sew, "domain")?;
1845                edge.curve = curve.clone();
1846                edge.t0 = d0;
1847                edge.t1 = d1;
1848            }
1849            None => {}
1850        }
1851    }
1852    for vertex in &mut result.vertices {
1853        if let Some(point) = new_vertex.get(&vertex.id) {
1854            vertex.point = *point;
1855        }
1856    }
1857    let final_edges: HashMap<u64, EdgeRecord> = result
1858        .edges
1859        .iter()
1860        .map(|edge| (edge.id, edge.clone()))
1861        .collect();
1862    for (shell_index, face_index, action) in face_actions {
1863        let face = &mut result.shells[shell_index].faces[face_index];
1864        match action {
1865            FaceAction::RotateSurface => {
1866                face.surface = transform_surface(&face.surface, rotation).or_refuse(KernelStage::Sew, "transform_surface")?;
1867            }
1868            FaceAction::Retrim(plane) => {
1869                // A MOVED face's carrier frame is this operation's to choose,
1870                // and `R` is not always the choice that leaves the chart legal;
1871                // a FIXED neighbour's frame is not ours to touch, and its
1872                // outward normal must survive the re-trim exactly.
1873                let plane = if moved.contains(&face.id) {
1874                    orient_plane_to_loop(face, &plane, &final_edges)?
1875                } else {
1876                    plane
1877                };
1878                retrim_planar_face(face, &plane, &final_edges, scale, "rotate_faces")?;
1879                // `retrim_planar_face` maps each edge's WHOLE curve onto the
1880                // rebuilt plane, so an edge that represents a strict SUBRANGE of
1881                // its curve needs the range fitter to span exactly [t0, t1];
1882                // full-domain edges keep the exact affine pcurve just built.
1883                let face_edges: HashSet<u64> = face
1884                    .loops
1885                    .iter()
1886                    .flat_map(|loop_record| loop_record.coedges.iter().map(|c| c.edge_id))
1887                    .collect();
1888                refit_touched_pcurves(
1889                    face,
1890                    &final_edges,
1891                    &face_edges,
1892                    true,
1893                    tolerance,
1894                    "rotate_faces",
1895                )?;
1896            }
1897        }
1898    }
1899    for face_id in ruled_retrim_faces {
1900        retrim_ruled_face(&mut result, face_id, &final_edges, tolerance, "rotate_faces")?;
1901    }
1902
1903    // Topology (and therefore genus) is untouched — only geometry moved — so
1904    // validate() re-checks Euler, loop closure and pcurve agreement.
1905    //
1906    // Taken through `validate_detailed` in ONE pass, because the floor below
1907    // needs the `wire_warnings` half of the same report and a second validation
1908    // of the same solid would buy nothing.
1909    let report = result.validate_detailed(&crate::KernelTolerances::for_solid(&result, 1e-7));
1910    if !report.issues.is_empty() {
1911        return Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!(
1912            "rotate_faces: rotated solid failed validation: {:?}",
1913            report.issues
1914        )));
1915    }
1916    // THE ACCEPTANCE FLOOR. `validate()` tests INCIDENCE: it would pass a face
1917    // whose own trim loop crosses itself in its own parameter domain, because no
1918    // incidence check can see a bowtie — and that is exactly what a neighbour's
1919    // re-trim produces when the rotation folds it. Read `unreadable` as well as
1920    // the verdict: an empty crossing list beside a loop the scan could not read
1921    // is no answer, not a clean one.
1922    let crossings = crate::loop_self_crossings(&result);
1923    if !crossings.unreadable.is_empty() {
1924        return Err(KernelRefusal::internal(KernelStage::Validate, "crossing_scan_unreadable", format!(
1925            "rotate_faces: the loop self-crossing scan could not read {:?}; refusing rather \
1926             than shipping an unchecked result",
1927            crossings.unreadable
1928        )));
1929    }
1930    if crossings.loops == 0 {
1931        return Err(KernelRefusal::internal(KernelStage::Validate, "crossing_scan_empty",
1932            "rotate_faces: the loop self-crossing scan read no loops at all; refusing rather              than shipping an unchecked result"));
1933    }
1934    if crossings.is_flagged() {
1935        return Err(KernelRefusal::internal(KernelStage::Validate, "loop_self_crossing", format!(
1936            "rotate_faces: the rotation makes a re-trimmed neighbour's own loop cross itself \
1937             ({}) — refusing",
1938            crossings.summary().unwrap_or_default()
1939        )));
1940    }
1941    // Belt and braces on top of the per-edge inversion guard: a global inversion
1942    // flips the signed volume even if every edge kept its direction.
1943    // Sign only, through the per-face term memo (`solid_signed_volume_for_sign`:
1944    // the verdict against the bar is the exact integral's; a face read about
1945    // the same reference before is served its term). 2026-10-17, the
1946    // shelled-box report: the exact reads cost 0.26 s a body here.
1947    if let (Ok(before), Ok(after)) =
1948        (crate::signed_volume_against(solid, 0.0), crate::signed_volume_against(&result, 0.0))
1949    {
1950        if before * after <= 0.0 {
1951            return Err(KernelRefusal::unsupported(KernelStage::Validate, SOLID_INVERSION,
1952                "rotate_faces: the rotation inverts the solid (signed volume changed sign) \
1953                 — refusing"));
1954        }
1955    }
1956    // ...and a guard on a quantity the signed volume CANNOT carry.
1957    //
1958    // The volume is `⅓ ∮ x·n dA`, and on a trimmed face that integral reads the
1959    // carrier normal and the trim loop's winding TOGETHER — Green's theorem
1960    // turns the loop into the sign of the area element. Flip both at once, as a
1961    // carrier frame carried past its own turnover does, and the two negatives
1962    // cancel: the number comes back unchanged. That is not a weak signal, it is
1963    // a BLIND one, and no threshold on it can ever be made to see this. The
1964    // measured proof is the half-turn, where the body agreed with its input to
1965    // 3.6e-15 and the volume to 3.0e-16 with a face inside out.
1966    //
1967    // So the floor also reads the winding DIRECTLY, against the same
1968    // `validate_uv_wire` convention the rest of the kernel cites as law.
1969    // `validate()` drops that verdict — it returns `issues` and this lives under
1970    // `wire_warnings` — which is why a mis-wound result walked out past a
1971    // validation the operation already ran.
1972    //
1973    // The comparison is with what the INPUT carried, not with zero: a body that
1974    // arrives already mis-wound (an import, or an older edit) is not this
1975    // rotation's doing, and refusing it here would strand a user on a file they
1976    // cannot edit. Count, not identity — a rotation that repaired one face and
1977    // broke another would read as even here, and that is a narrower lie than
1978    // the blindness this replaces.
1979    //
1980    // The input is only validated when the result actually carries a warning,
1981    // so a rotation that leaves a clean body pays nothing for this at all.
1982    if !report.wire_warnings.is_empty() {
1983        let inherited = solid
1984            .validate_detailed(&crate::KernelTolerances::for_solid(solid, 1e-7))
1985            .wire_warnings;
1986        if report.wire_warnings.len() > inherited.len() {
1987            return Err(KernelRefusal::internal(KernelStage::Validate, "chart_winding", format!(
1988                "rotate_faces: the rotation leaves a face whose (u,v) chart is left-handed \
1989                 against its own normal ({}) — refusing",
1990                report
1991                    .wire_warnings
1992                    .iter()
1993                    .map(|warning| warning.message.as_str())
1994                    .collect::<Vec<_>>()
1995                    .join("; ")
1996            )));
1997        }
1998    }
1999    Ok(result)
2000}