Skip to main content

brep_kernel/feature_pipeline/features/
transform_face.rs

1//! TF — Transform Face.
2//!
3//! Carries the selected faces of a single solid by ONE RIGID MOTION — a rotation
4//! about a stated pivot followed by a translation — preserving each carrier's
5//! shape, and re-intersects the neighbours the motion moves the selection
6//! relative to. The motion is the `transform` parameter the transform gizmo
7//! edits: dragging an axis or the centre handle writes `position`, dragging a
8//! ring writes `rotationEuler`.
9//!
10//! # The motion
11//!
12//! `p ↦ pivot + position + R·(p − pivot)`, with `R` the intrinsic XYZ Euler
13//! rotation of `rotationEuler` (degrees) — exactly
14//! [`common::compose_trs_matrix`]`(position, rotationEuler, [1,1,1], pivot)`, the
15//! one feature-transform convention the Transform feature, the assembly pose and
16//! the gizmo already speak. The gizmo is drawn at `pivot + position`, which is
17//! where the pivot point lands, so a ring drag turns the faces about the handle
18//! the user is holding.
19//!
20//! `scale` has no meaning for a face edit — a scaled carrier is a different
21//! surface, not a moved one. The schema's `default_value` omits it, which hides
22//! it in the form and in the tool schema, and a document that carries a
23//! non-unit scale anyway is refused BY NAME rather than silently ignored.
24//!
25//! # A rotation is not a mode of a translation — and this feature does not pretend it is
26//!
27//! [`crate::move_faces`] moves a carrier's POSITION and leaves its normal alone;
28//! [`crate::rotate_faces`] moves the normal too, so the neighbour pairs are
29//! re-intersected differently and the invariants that let a corner ride rigidly
30//! are different invariants (a cone about its own axis is invariant under a
31//! rotation and not under a translation). The two primitives stay two roads, and
32//! this feature is a DISPATCHER over them, not a third solver:
33//!
34//! * a pure TRANSLATION (`rotationEuler` is the identity) goes to `move_faces`
35//!   with `position` — Move Face's road, unchanged;
36//! * a pure ROTATION (`position` is zero) goes to `rotate_faces` about the axis
37//!   LINE through `pivot` along the rotation's own axis, by its own angle —
38//!   Rotate Face's road, unchanged. `R` is converted to that axis and angle from
39//!   the same matrix the compose builds, so the stored Euler angles and the
40//!   kernel's Rodrigues rotation are one rotation;
41//! * a COMBINED motion goes through the rotation solver with the translation
42//!   composed into its affine before any corner is solved. The carrier normals
43//!   turn and their positions move together, and every edge inversion, winding
44//!   and soundness check sees the final geometry. A rotation-only intermediate
45//!   can invert a wall that the final translation extends safely; it is not a
46//!   shape the user requested and must not block the edit.
47//!
48//! The rigid regime requires the fixed carrier to be invariant under both
49//! parts: an in-plane spin does not leave a plane invariant when followed by a
50//! normal translation, and a cone cannot ride an axial translation. Cylinders
51//! still admit an axial slide. Other pairs use the existing re-intersection
52//! and re-trimming machinery against the final moved planes and ruled frames.
53//!
54//! # The pivot
55//!
56//! `pivot` is a stored vec3. When it is null the pivot is the SELECTION'S CENTRE,
57//! computed by [`selection_centre`] from the feature's INPUT solid: the centre of
58//! the axis-aligned bounds of every vertex on the selected faces' boundaries and
59//! of each boundary edge sampled at [`CENTRE_SAMPLES`] equal steps across its
60//! active parameter range (a face with no edge at all — a closed sphere —
61//! contributes its surface control points). Exact for straight-edged faces.
62//! The app stores that value into `pivot` the moment the face selection is
63//! committed (through [`face_transform_pivot`], the same computation), so the
64//! rotation centre is a number in the document: re-running the history, dragging
65//! the gizmo, or editing a feature upstream never moves it. A null pivot in a
66//! hand-written document is resolved the same way on every run, from the same
67//! input, so it cannot drift either.
68//!
69//! # Reference resolution and behaviour mapping
70//!
71//! `faces` is a `reference_selection` of FACE names — the declaration Push Face
72//! and Delete Face use. A miss is an `unresolved` entry, never a panic. Every
73//! `transform` component and every `pivot` component may be a number or an
74//! expression.
75//!
76//! SOFT no-op (an empty result, no error) for an empty selection, names that all
77//! fail to resolve, faces spanning multiple solids, and the IDENTITY motion — a
78//! half-filled dialog must not shout. A kernel `Err` → `ctx.fail` (halt): the
79//! refusal names the offending entity, and neither primitive mutates its input,
80//! so the source solid is untouched.
81//!
82//! # Name preservation and the exit
83//!
84//! Both roads are pure geometry edits: no face, edge or vertex is created or
85//! destroyed, so every id and name survives. Names are COLLECTED, never
86//! re-stamped, and the result reuses the TARGET solid's name. The result goes
87//! through [`crate::accept_sound`] once, at the exit, as Move Face and Rotate
88//! Face each did.
89//!
90//! The acceptance is the one step that can change topology, and only on a
91//! BREAKOUT — a motion that carries the selection clean out of the faces it
92//! opened through, which both primitives build as a body passing through
93//! itself. Its crossing repair then splits the pair along their carriers' exact
94//! section, drops what ended up on the wrong side and RE-TRIMS the neighbour
95//! that is left holding an unanswered boundary, so edges and vertices move
96//! while every FACE name still survives. It says so in the result's `notes`
97//! rather than changing the answer silently.
98
99use crate::face_refusal_slugs::{PIVOT_GEOMETRY, RIGID_SCALE};
100use std::collections::HashSet;
101
102use crate::feature_pipeline::features::common;
103use crate::feature_pipeline::{AddedSolid, FeatureContext, FeatureRefusal, FeatureResult, SceneMap};
104use crate::{move_faces_unchecked, rotate_faces_unchecked, BrepSolid, KernelRefusal, KernelStage, Vec3};
105
106/// Stations per boundary edge in [`selection_centre`]. A power of two, so a
107/// rational circle split into quarter spans is sampled at its span ends — the
108/// points where an axis-aligned circle reaches its bounds.
109/// [`FeatureResult::refused_step`] of a Transform Face whose ROTATION refused
110/// (a turn alone, or a combined rigid motion through the rotation solver).
111pub const REFUSED_STEP_ROTATION: &str = "rotation";
112/// … whose pure TRANSLATION refused.
113pub const REFUSED_STEP_TRANSLATION: &str = "translation";
114
115pub const CENTRE_SAMPLES: usize = 64;
116
117pub fn execute(ctx: &FeatureContext) -> FeatureResult {
118    match build(ctx) {
119        Ok(result) => result,
120        Err(error) => ctx.fail(error),
121    }
122}
123
124/// The selection resolved against a scene: the one target solid's handle and
125/// the deduplicated face ids on it, or `None` for the soft no-ops (nothing
126/// resolved, or faces on more than one solid). Misses land in `unresolved`.
127fn resolve_selection(
128    scene: &SceneMap,
129    names: &[String],
130    unresolved: &mut Vec<String>,
131) -> Option<(u32, Vec<u64>)> {
132    let mut resolved: Vec<(u32, u64)> = Vec::new();
133    for name in names {
134        match scene.resolve_face(name) {
135            Some(face_ref) => resolved.push((face_ref.handle, face_ref.face_id)),
136            None => unresolved.push(name.clone()),
137        }
138    }
139    let &(target, _) = resolved.first()?;
140    if resolved.iter().any(|(handle, _)| *handle != target) {
141        return None;
142    }
143    let mut seen: HashSet<u64> = HashSet::new();
144    let face_ids = resolved
145        .iter()
146        .map(|(_, face_id)| *face_id)
147        .filter(|face_id| seen.insert(*face_id))
148        .collect();
149    Some((target, face_ids))
150}
151
152/// The centre of the selection's boundary bounds — the default pivot. See the
153/// module doc for exactly what is bounded. `None` only when the faces carry no
154/// geometry at all.
155pub fn selection_centre(solid: &BrepSolid, face_ids: &[u64]) -> Option<Vec3> {
156    let selected: HashSet<u64> = face_ids.iter().copied().collect();
157    let mut low = [f64::INFINITY; 3];
158    let mut high = [f64::NEG_INFINITY; 3];
159    let mut include = |point: Vec3| {
160        let point = [point.x, point.y, point.z];
161        if point.iter().all(|c| c.is_finite()) {
162            for axis in 0..3 {
163                low[axis] = low[axis].min(point[axis]);
164                high[axis] = high[axis].max(point[axis]);
165            }
166        }
167    };
168    let mut edge_ids: HashSet<u64> = HashSet::new();
169    let mut edgeless = Vec::new();
170    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
171        if !selected.contains(&face.id) {
172            continue;
173        }
174        let before = edge_ids.len();
175        for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
176            edge_ids.insert(coedge.edge_id);
177        }
178        if edge_ids.len() == before && face.loops.iter().all(|l| l.coedges.is_empty()) {
179            edgeless.push(face);
180        }
181    }
182    let vertex_ids: HashSet<u64> = solid
183        .edges
184        .iter()
185        .filter(|edge| edge_ids.contains(&edge.id))
186        .flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id])
187        .collect();
188    for vertex in &solid.vertices {
189        if vertex_ids.contains(&vertex.id) {
190            include(vertex.point);
191        }
192    }
193    for edge in solid.edges.iter().filter(|edge| edge_ids.contains(&edge.id)) {
194        if edge.degenerate {
195            continue;
196        }
197        for station in 0..=CENTRE_SAMPLES {
198            let t = edge.t0 + (edge.t1 - edge.t0) * station as f64 / CENTRE_SAMPLES as f64;
199            if let Ok(point) = edge.curve.evaluate(t) {
200                include(point);
201            }
202        }
203    }
204    for face in edgeless {
205        for control in face.surface.control_points.iter().flatten() {
206            if let Ok(point) = control.point() {
207                include(point);
208            }
209        }
210    }
211    if !low[0].is_finite() {
212        return None;
213    }
214    Some(Vec3::new(
215        0.5 * (low[0] + high[0]),
216        0.5 * (low[1] + high[1]),
217        0.5 * (low[2] + high[2]),
218    ))
219}
220
221/// The pivot a Transform Face whose `faces` are `names` gets by default, read
222/// off the scene the results BEFORE it build — the value the app stores into
223/// `pivot` when the selection is committed, and the value `build` falls back to
224/// for a null `pivot`, because both go through `resolve_selection` and
225/// `selection_centre`. `None` when the selection does not resolve to faces on
226/// one solid.
227pub fn face_transform_pivot(prefix: &[FeatureResult], names: &[String]) -> Option<[f64; 3]> {
228    let mut scene = SceneMap::default();
229    for result in prefix {
230        scene.apply(result);
231    }
232    let (handle, face_ids) = resolve_selection(&scene, names, &mut Vec::new())?;
233    let centre =
234        crate::with_registered_solid_str(handle, |solid| Ok(selection_centre(solid, &face_ids)))
235            .ok()??;
236    Some([centre.x, centre.y, centre.z])
237}
238
239/// The point a PICKED entity puts the pivot on — what the dialog's pivot pick
240/// stores, resolved against the scene the feature runs against (`prefix`, the
241/// results before it), so the stored number is the entity as the user saw it:
242///
243/// - a vertex (`{solid}@x,y,z`, world coordinates) → that vertex, exactly;
244/// - a straight edge → its midpoint, a point ON the line a rotation about that
245///   edge needs; a circular edge → its centre; any other edge → the point at
246///   the middle of its parameter range;
247/// - a sphere face → its centre; an axis-bearing face (cylinder, cone, torus,
248///   revolution) → the point of its axis level with the face's `selection_centre`;
249///   any other face → that centre, the value a face SELECTION defaults to;
250/// - a datum frame → its origin.
251///
252/// `Err` names what failed: an empty name, a name not in that scene, or an
253/// entity whose geometry does not evaluate. Nothing is guessed.
254pub fn reference_point(prefix: &[FeatureResult], name: &str) -> Result<[f64; 3], String> {
255    use crate::feature_pipeline::pmi::resolve::resolve_reference;
256    use crate::{resolve_edge_selection, resolve_face_selection, SelectionGeometry};
257    let name = name.trim();
258    if name.is_empty() {
259        return Err("nothing was picked".into());
260    }
261    let mut scene = SceneMap::default();
262    for result in prefix {
263        scene.apply(result);
264    }
265    let point = if let Some(face) = scene.resolve_face(name) {
266        crate::with_registered_solid_str(face.handle, |solid| {
267            let centre = selection_centre(solid, &[face.face_id])
268                .ok_or_else(|| format!("face '{name}' has no geometry to place a point on"))?;
269            Ok(match resolve_face_selection(solid, face.face_id) {
270                Ok(SelectionGeometry::Sphere { center, .. }) => center,
271                Ok(SelectionGeometry::Axis { origin, direction, .. }) => {
272                    origin.add(direction.scale(centre.sub(origin).dot(direction)))
273                }
274                _ => centre,
275            })
276        })?
277    } else if let Some(edge) = scene.resolve_edge(name) {
278        crate::with_registered_solid_str(edge.handle, |solid| {
279            let record = solid
280                .edges
281                .iter()
282                .find(|record| record.id == edge.edge_id)
283                .ok_or_else(|| format!("edge '{name}' has no record"))?;
284            let at = |t: f64| record.curve.evaluate(t).map_err(|error| format!("edge '{name}': {error}"));
285            let (start, middle, end) = (at(record.t0)?, at(0.5 * (record.t0 + record.t1))?, at(record.t1)?);
286            // The analytic classifier's tolerances grow with the distance from
287            // the world origin; the point it names is taken only when the
288            // edge's own middle agrees with it to a fraction of the edge's own
289            // size, and otherwise the middle of the edge is the answer.
290            let size = start.sub(middle).length().max(end.sub(middle).length());
291            let reach = [start, middle, end].iter().map(|p| p.x.abs().max(p.y.abs()).max(p.z.abs())).fold(0.0, f64::max);
292            let agrees = |distance: f64| distance <= 1e-9 * size + 64.0 * f64::EPSILON * reach;
293            Ok(match resolve_edge_selection(solid, edge.edge_id) {
294                Ok(SelectionGeometry::Line { origin, .. })
295                    if agrees(middle.sub(start.add(end).scale(0.5)).length()) =>
296                {
297                    origin
298                }
299                Ok(SelectionGeometry::Circle { center, radius, .. })
300                    if [start, middle, end].iter().all(|p| agrees((p.sub(center).length() - radius).abs())) =>
301                {
302                    center
303                }
304                _ => middle,
305            })
306        })?
307    } else {
308        match resolve_reference(&scene, name)? {
309            SelectionGeometry::Point { position } => position,
310            SelectionGeometry::Plane { origin, .. } => origin,
311            SelectionGeometry::Sphere { center, .. } | SelectionGeometry::Circle { center, .. } => center,
312            SelectionGeometry::Line { origin, .. } | SelectionGeometry::Axis { origin, .. } => origin,
313        }
314    };
315    let point = [point.x, point.y, point.z];
316    if point.iter().any(|c| !c.is_finite()) {
317        return Err(format!("'{name}' did not evaluate to a finite point"));
318    }
319    Ok(point)
320}
321
322/// The rotation part of the motion as the axis and angle `rotate_faces` takes:
323/// `R` is built by the shared compose (so the Euler convention is single-sourced)
324/// and converted through its quaternion, choosing the numerically largest
325/// component first so a half turn keeps its axis. `None` for the identity.
326pub fn rotation_axis_angle(rotation_deg: [f64; 3]) -> Option<(Vec3, f64)> {
327    if rotation_deg == [0.0; 3] {
328        return None;
329    }
330    let radians = rotation_deg.map(f64::to_radians);
331    let m = common::compose_trs_matrix([0.0; 3], radians, [1.0; 3], [0.0; 3]);
332    let at = |row: usize, col: usize| m[row * 4 + col];
333    let (m00, m11, m22) = (at(0, 0), at(1, 1), at(2, 2));
334    let trace = m00 + m11 + m22;
335    // [x, y, z, w]
336    let q = if trace >= m00 && trace >= m11 && trace >= m22 {
337        let w = 0.5 * (1.0 + trace).max(0.0).sqrt();
338        let k = 0.25 / w;
339        [(at(2, 1) - at(1, 2)) * k, (at(0, 2) - at(2, 0)) * k, (at(1, 0) - at(0, 1)) * k, w]
340    } else if m00 >= m11 && m00 >= m22 {
341        let x = 0.5 * (1.0 + m00 - m11 - m22).max(0.0).sqrt();
342        let k = 0.25 / x;
343        [x, (at(0, 1) + at(1, 0)) * k, (at(0, 2) + at(2, 0)) * k, (at(2, 1) - at(1, 2)) * k]
344    } else if m11 >= m22 {
345        let y = 0.5 * (1.0 - m00 + m11 - m22).max(0.0).sqrt();
346        let k = 0.25 / y;
347        [(at(0, 1) + at(1, 0)) * k, y, (at(1, 2) + at(2, 1)) * k, (at(0, 2) - at(2, 0)) * k]
348    } else {
349        let z = 0.5 * (1.0 - m00 - m11 + m22).max(0.0).sqrt();
350        let k = 0.25 / z;
351        [(at(0, 2) + at(2, 0)) * k, (at(1, 2) + at(2, 1)) * k, z, (at(1, 0) - at(0, 1)) * k]
352    };
353    // One sign for the quaternion, so the angle lands in [0, π].
354    let sign = if q[3] < 0.0 { -1.0 } else { 1.0 };
355    let axis = Vec3::new(q[0] * sign, q[1] * sign, q[2] * sign);
356    let half_sine = axis.length();
357    let angle = 2.0 * half_sine.atan2(q[3] * sign);
358    if angle <= 1e-12 {
359        return None;
360    }
361    Some((axis.scale(1.0 / half_sine), angle))
362}
363
364/// A `transform` component, read through the shared vec3 reader under its
365/// dotted name so an expression error names `transform.position` and not a bare
366/// key.
367fn transform_vec3(ctx: &FeatureContext, key: &str, default: [f64; 3]) -> Result<[f64; 3], String> {
368    common::vec3_from_value(
369        ctx.env,
370        ctx.param("transform").and_then(|transform| transform.get(key)),
371        &format!("transform.{key}"),
372        default,
373    )
374}
375
376fn build(ctx: &FeatureContext) -> Result<FeatureResult, FeatureRefusal> {
377    let mut result = FeatureResult::empty(ctx.id.clone(), ctx.feature_type.clone());
378
379    let names = common::reference_name_array(ctx.param("faces"));
380    if names.is_empty() {
381        return Ok(result); // Soft no-op — nothing selected.
382    }
383    let Some((target_handle, face_ids)) =
384        resolve_selection(ctx.scene, &names, &mut result.unresolved)
385    else {
386        return Ok(result); // Only unresolved names, or faces on several solids.
387    };
388    // The feature proceeds on the faces that resolved: a miss is reported as
389    // a typed partial fulfilment beside `unresolved`, never silently.
390    result.note_partial_resolution(&names);
391
392    // The motion. Scale first: a document that scales is refused before
393    // anything else is read, because no reading of the rest makes it rigid.
394    let scale = transform_vec3(ctx, "scale", [1.0; 3])?;
395    if scale != [1.0; 3] {
396        return Err(KernelRefusal::input(
397            KernelStage::Collect,
398            RIGID_SCALE,
399            format!(
400                "transformFace: `transform.scale` is {scale:?}, but a face transform is a RIGID \
401                 motion — a scaled carrier is a different surface, not a moved one — so scale must \
402                 be [1, 1, 1]; refusing"
403            ),
404        )
405        .into());
406    }
407    let position = transform_vec3(ctx, "position", [0.0; 3])?;
408    let rotation_deg = transform_vec3(ctx, "rotationEuler", [0.0; 3])?;
409    let translation = Vec3::new(position[0], position[1], position[2]);
410    let translates = translation.length() > 1e-12;
411    let rotation = rotation_axis_angle(rotation_deg);
412    if !translates && rotation.is_none() {
413        return Ok(result); // Soft no-op — the identity motion.
414    }
415
416    let target_name = ctx
417        .scene
418        .solids
419        .iter()
420        .find(|(_, handle)| **handle == target_handle)
421        .map(|(name, _)| name.clone())
422        .ok_or("transformFace: target solid has no scene-map name")?;
423    let solid = crate::with_registered_solid_str(target_handle, |solid| Ok(solid.clone()))?;
424
425    // The rotation as the re-cut road needs it too: axis point, axis, angle.
426    let turn = match rotation {
427        None => None,
428        Some((axis, angle)) => {
429            let pivot = match ctx.param("pivot") {
430                None | Some(serde_json::Value::Null) => selection_centre(&solid, &face_ids)
431                    .ok_or_else(|| {
432                        KernelRefusal::input(
433                            KernelStage::Collect,
434                            PIVOT_GEOMETRY,
435                            "transformFace: the selected faces carry no geometry to centre a pivot on",
436                        )
437                    })?,
438                Some(value) => {
439                    let [x, y, z] = common::vec3_from_value(ctx.env, Some(value), "pivot", [0.0; 3])?;
440                    Vec3::new(x, y, z)
441                }
442            };
443            Some((pivot, axis, angle))
444        }
445    };
446    // The motion records itself on refusal (`refused_step`), so the
447    // app names the motion the user asked for without reading this text.
448    let refused_at = |error: KernelRefusal, step: &str| {
449        let mut refused = ctx.fail(error);
450        refused.refused_step = Some(step.to_string());
451        refused
452    };
453    // A face beside a VARIABLE-RADIUS fillet has no road of its own: the band
454    // is a free-form carrier neither primitive re-intersects and the re-cut
455    // cannot bound a tool by — and where the re-cut is reached anyway (another
456    // fillet beside the face hands it the motion) it cuts the band where the
457    // moved plane crosses it and leaves it there, no longer tangent, under its
458    // name. The fillet is a derived face, so the motion is run on the body
459    // without it and the fillet is re-made on the edge the motion leaves,
460    // under its radius law (`edit/direct_edit/blend_rebuild.rs`). Offered
461    // first, and only where such a fillet borders the selection: without one
462    // it reads the selection's neighbours and steps aside.
463    let (moved, notes) = match move_faces_road(&solid, &face_ids, turn, translates, translation) {
464        Ok(solved) => solved,
465        Err((refusal, step)) => {
466            return match step {
467                Some(step) => Ok(refused_at(refusal, step)),
468                None => Err(refusal.into()),
469            };
470        }
471    };
472    result.notes.extend(notes);
473
474    // Both roads preserve every name — collect, never re-stamp.
475    let face_names = common::collect_face_names(&moved);
476    let edge_names = common::collect_edge_names(&moved);
477    let handle = crate::register_solid_value(moved);
478    result.added.push(AddedSolid {
479        handle,
480        name: target_name.clone(),
481        face_names,
482        edge_names,
483        ..AddedSolid::default()
484    });
485    result.removed.push(target_name);
486    Ok(result)
487}
488
489/// The motion's road with the variable-radius fillet rebuild offered first
490/// (see `build`), shared with the public [`crate::transform_faces`]: `Ok` is
491/// the edited body and its notes, `Err` the refusal (the rebuild's decline
492/// appended) and the motion's step it names.
493pub(crate) fn move_faces_road(
494    solid: &BrepSolid,
495    face_ids: &[u64],
496    turn: Option<(Vec3, Vec3, f64)>,
497    translates: bool,
498    translation: Vec3,
499) -> Result<(BrepSolid, Vec<String>), (KernelRefusal, Option<&'static str>)> {
500    let without = crate::rebuild_displaced_blends(solid, face_ids, "transformFace", |sharp| {
501        solve_motion(sharp, face_ids, turn, translates, translation).map_err(|(error, _)| error)
502    });
503    match without {
504        Some(Ok(solved)) => Ok(solved),
505        declined => solve_motion(solid, face_ids, turn, translates, translation).map_err(|(refusal, step)| {
506            let refusal = match &declined {
507                Some(Err(decline)) => crate::with_blend_rebuild_decline(refusal, decline),
508                _ => refusal,
509            };
510            (refusal, step)
511        }),
512    }
513}
514
515/// The motion's whole road on one body: the direct re-solve, its acceptance,
516/// and the re-cut where either hands the motion on. `Ok` is the edited body
517/// and the notes the road left; `Err` is the refusal and, for a refusal of
518/// the re-solve itself, the step of the motion it names (`refused_step`).
519fn solve_motion(
520    solid: &BrepSolid,
521    face_ids: &[u64],
522    turn: Option<(Vec3, Vec3, f64)>,
523    translates: bool,
524    translation: Vec3,
525) -> Result<(BrepSolid, Vec<String>), (KernelRefusal, Option<&'static str>)> {
526    let mut notes = Vec::new();
527    let moved = match turn {
528        None => match move_faces_unchecked(solid, face_ids, translation) {
529            Ok(moved) => moved,
530            // A straight edge the translation inverts or collapses on a face
531            // with an ISLAND is that face carried past the far end of the
532            // island's wall — a pocket floor pushed past the bottom of a hole
533            // through it — whose answer has that wall STOP EXISTING. No re-solve has such a body, so the
534            // re-cut is offered it, as it is offered an acceptance refusal
535            // below; the re-solve's refusal stays the primary one if it
536            // declines too.
537            Err(error) if is_straight_edge_inversion(&error) && has_island(solid, face_ids) => {
538                match recut_past_a_refusal(solid, face_ids, None, translation) {
539                    Ok((body, lost)) => {
540                        notes.push(format!(
541                            "transformFace: the moved carriers could not be re-solved ({error}), \
542                             so the selection was RE-CUT from the original body instead — the \
543                             result is the boolean this motion defines, and a face whose carrier \
544                             left the body is no longer on it"
545                        ));
546                        notes.extend(lost);
547                        return Ok((body, notes));
548                    }
549                    Err(reason) => {
550                        let error = error.with_message(|error| {
551                            format!("{error}. The re-cut road was offered it too and declined: {reason}")
552                        });
553                        return Err((with_declines_class(error, &[&reason]), Some(REFUSED_STEP_TRANSLATION)));
554                    }
555                }
556            }
557            Err(error) if is_no_route_refusal(&error) => match by_regions(solid, face_ids, None, translation) {
558                Ok((body, note)) => {
559                    notes.push(format!("transformFace: the moved carriers could not be re-solved ({error}), {note}"));
560                    body
561                }
562                Err(reason) => {
563                    let error = error.with_message(|error| format!("{error}. {reason}"));
564                    return Err((error, Some(REFUSED_STEP_TRANSLATION)));
565                }
566            },
567            Err(error) => return Err((error, Some(REFUSED_STEP_TRANSLATION))),
568        },
569        Some((pivot, axis, angle)) => {
570            let solved = if !translates {
571                rotate_faces_unchecked(solid, face_ids, pivot, axis, angle)
572            } else {
573                crate::direct_edit::rotate_faces_rigid(
574                    solid, face_ids, pivot, axis, angle, translation,
575                )
576                .map_err(|error| {
577                    error.with_message(|error| {
578                        format!("transformFace: the combined rigid motion refused — {error}")
579                    })
580                })
581            };
582            match solved {
583                Ok(moved) => moved,
584                // A face tangent to a fillet beside it has no rim to re-solve:
585                // turned, it cuts that fillet in a different ruling or leaves
586                // it altogether, and either way the answer is a different
587                // topology. That is what the re-cut road below is for, so this
588                // one refusal is offered to it directly. Its body still passes
589                // the acceptance below.
590                Err(error) if is_ruling_refusal(&error) => {
591                    match crate::recut_moved_planes_rigid(solid, face_ids, turn, translation) {
592                        Ok(body) => {
593                            notes.push(format!(
594                                "transformFace: the turned face could not be re-solved against \
595                                 the fillet beside it ({error}), so the selection was RE-CUT \
596                                 from the original body instead"
597                            ));
598                            let (body, lost) = crate::reblend_lost_fillets(solid, face_ids, body);
599                            notes.extend(lost);
600                            body
601                        }
602                        Err(reason) => {
603                            let error = error.with_message(|error| {
604                                format!(
605                                    "{error}. The re-cut road was offered it too and declined: {reason}"
606                                )
607                            });
608                            return Err((with_declines_class(error, &[&reason]), Some(REFUSED_STEP_ROTATION)));
609                        }
610                    }
611                }
612                // A turned face whose neighbour has no route on this road — a
613                // plane's section of a cylinder or cone it cannot mint (a whole
614                // frustum's top turned past the generatrices), a slanted cap on a
615                // coaxial wall, a sphere, torus or quadric neighbour — still
616                // has an answer where the body is the intersection of its faces'
617                // own regions, or where the selection is a through bore
618                // (`by_regions`). The rotation road's refusal stays the primary
619                // one if both decline.
620                Err(error) if is_no_route_refusal(&error) => match by_regions(solid, face_ids, turn, translation) {
621                    Ok((body, note)) => {
622                        notes.push(format!(
623                            "transformFace: the turned face could not be re-solved ({error}), {note}"
624                        ));
625                        body
626                    }
627                    Err(reason) => {
628                        let error = error.with_message(|error| format!("{error}. {reason}"));
629                        return Err((error, Some(REFUSED_STEP_ROTATION)));
630                    }
631                },
632                Err(error) => return Err((error, Some(REFUSED_STEP_ROTATION))),
633            }
634        }
635    };
636    // Carrying a face past a neighbour's own extent leaves it crossing one it
637    // should have stopped at, and both roads are pure geometry edits that create
638    // no cell for `validate()` to catch. The acceptance Push Face takes: split and
639    // trim where that can be proved, refuse by name where it cannot. Where the
640    // motion carried the selection clean OUT of the faces it opened through —
641    // the breakout — that split also re-trims the neighbour left holding an
642    // unanswered boundary, which is the only way such a body closes.
643    //
644    // And where the acceptance refuses, the RE-CUT road is offered the same
645    // edit from the other end — the original body, the selection and the
646    // motion, cut as a boolean rather than re-solved — because a motion whose
647    // answer needs a face to STOP EXISTING has no body for a repair to reach.
648    // A plane moved rigidly is still a plane, so the road takes a
649    // rotate-then-translate as well as a translation (the 2026-09-22 slot
650    // document with its wall also TURNED 16.9° refused here while the same
651    // drag without the turn built). See `edit/direct_edit/face_move_recut.rs`.
652    // It runs only after an acceptance refusal; a motion refused by the
653    // direct re-intersection solver never reaches it.
654    let moved = match crate::accept_sound(moved, "transformFace") {
655        Ok(body) => body,
656        Err(refusal) => {
657            match recut_past_a_refusal(solid, face_ids, turn, translation) {
658                Ok((body, lost)) => {
659                    notes.push(format!(
660                        "transformFace: the moved carriers could not be re-solved onto the body \
661                         they left ({refusal}), so the selection was RE-CUT from the original \
662                         body instead — the result is the boolean this motion defines, and a \
663                         face whose carrier left the body is no longer on it"
664                    ));
665                    notes.extend(lost);
666                    body
667                }
668                // A through bore's wall: the RE-DRILL road — the body with
669                // the bore healed shut, less the moved carrier run the body's
670                // whole way through (`edit/direct_edit/face_move_redrill.rs`).
671                // It answers a mouth straddling a corner, whose two crossing
672                // pairs the acceptance's repair does not take. The re-cut
673                // declines every curved carrier, so this is the only road
674                // left for a bore wall.
675                Err(reason) => match redrill_past_a_refusal(solid, face_ids, turn, translation) {
676                    Ok(body) => {
677                        notes.push(format!(
678                            "transformFace: the moved bore could not be re-trimmed onto the body \
679                             ({refusal}), so the bore was RE-DRILLED instead — the body with the \
680                             hole filled, less the moved carrier run the body's whole way through"
681                        ));
682                        body
683                    }
684                    // The acceptance's refusal stays the primary one — its
685                    // class is what the boundary reports, unless a road's
686                    // decline names the input (`with_declines_class`) — and
687                    // the other roads' declines are appended as context.
688                    Err(redrill) => {
689                        let combined = refusal.with_message(|refusal| {
690                            format!(
691                                "{refusal}. The re-cut road was offered it too and declined: \
692                                 {reason}. The re-drill road declined: {redrill}"
693                            )
694                        });
695                        return Err((with_declines_class(combined, &[&reason, &redrill]), None))
696                    }
697                },
698            }
699        }
700    };
701    Ok((moved, notes))
702}
703
704/// A refusal whose other roads declined too, their declines appended to its
705/// message by the caller: where a decline names the INPUT (ill-posed or
706/// invalid: the re-cut finding the motion takes away all of the body's
707/// material, or splits it), that is the act's answer and its class is the
708/// refusal's; otherwise the primary refusal's class stands.
709pub(crate) fn with_declines_class(mut refusal: KernelRefusal, declines: &[&KernelRefusal]) -> KernelRefusal {
710    use crate::RefusalClass::{IllPosed, InvalidInput};
711    if let Some(decline) = declines.iter().find(|d| matches!(d.class, IllPosed { .. } | InvalidInput { .. })) {
712        refusal.class = decline.class.clone();
713    }
714    refusal
715}
716
717/// The re-cut offered after the acceptance refused the moved body.
718///
719/// The body passes the SAME acceptance the primitives' body did: a boolean's
720/// output is sound by construction, so this is a check and not a repair, and a
721/// body it refuses is refused by name rather than returned. Fillets the re-cut
722/// filled in are then re-made one by one, and the second value names any that
723/// could not be.
724pub(crate) fn recut_past_a_refusal(
725    solid: &BrepSolid,
726    face_ids: &[u64],
727    turn: Option<(Vec3, Vec3, f64)>,
728    translation: Vec3,
729) -> Result<(BrepSolid, Vec<String>), KernelRefusal> {
730    let body = crate::recut_moved_planes_rigid(solid, face_ids, turn, translation)?;
731    let body = crate::accept_sound(body, "transformFace").map_err(|reason| {
732        reason.with_message(|reason| format!("the re-cut built a body the acceptance refused — {reason}"))
733    })?;
734    Ok(crate::reblend_lost_fillets(solid, face_ids, body))
735}
736
737/// The re-drill offered after the acceptance and the re-cut refused: checked
738/// by the same acceptance, as the re-cut's body is.
739fn redrill_past_a_refusal(
740    solid: &BrepSolid,
741    face_ids: &[u64],
742    turn: Option<(Vec3, Vec3, f64)>,
743    translation: Vec3,
744) -> Result<BrepSolid, KernelRefusal> {
745    let body = crate::redrill_moved_bore(solid, face_ids, turn, translation)?;
746    crate::accept_sound(body, "transformFace").map_err(|reason| {
747        reason.with_message(|reason| format!("the re-drill built a body the acceptance refused — {reason}"))
748    })
749}
750
751/// The translation primitive's refusal for a straight edge it inverts or
752/// collapses (`face_move.rs`).
753fn is_straight_edge_inversion(error: &KernelRefusal) -> bool {
754    matches!(&error.class, crate::RefusalClass::UnsupportedGeometry { what }
755        if what == crate::face_refusal_slugs::EDGE_INVERSION || what == "edge_collapse")
756}
757
758/// Whether a selected face has an inner loop (an island: a hole through it or
759/// a boss standing on it).
760fn has_island(solid: &BrepSolid, face_ids: &[u64]) -> bool {
761    solid
762        .shells
763        .iter()
764        .flat_map(|shell| &shell.faces)
765        .any(|face| face_ids.contains(&face.id) && face.loops.len() > 1)
766}
767
768/// The rotation primitive's refusal for a face tangent to a ruled neighbour.
769fn is_ruling_refusal(error: &KernelRefusal) -> bool {
770    matches!(&error.class, crate::RefusalClass::UnsupportedGeometry { what } if what == "ruling_edge")
771}
772
773/// A refusal of either primitive that says the neighbour or section has NO
774/// ROUTE on that road — not that the motion inverts, collapses or tears
775/// something, which stay refusals: a carrier kind it does not re-intersect, a
776/// curved edge it cannot rebuild, a plane's section of a ruled wall it cannot
777/// mint, a slanted chord off its wall, a sphere rim it does not model.
778fn is_no_route_refusal(error: &KernelRefusal) -> bool {
779    const NO_ROUTE: &[&str] = &[
780        "carrier_kind",
781        "curved_edge_rebuild",
782        "curved_fixed_edge_pair",
783        "ruled_section",
784        "chord_off_carrier",
785        "both_nappes",
786        "asymptotic_ruling",
787        "section_through_apex",
788        "cap_through_apex",
789        "sphere_oblique_rim",
790        "sphere_mixed_neighbours",
791        "sphere_open_rim",
792        "sphere_group",
793        // A moved ruled or revolved wall whose corner touches two fixed flats
794        // (no one image for the corner on the re-solve): a through bore slid
795        // across its plate, answered by the re-drill.
796        "mirror_corner_flats",
797    ];
798    matches!(&error.class, crate::RefusalClass::UnsupportedGeometry { what } if NO_ROUTE.contains(&what.as_str()))
799}
800
801/// The two roads that answer a motion from the body's own regions rather than
802/// by re-solving: the region re-cut for planar faces
803/// ([`crate::recut_convex_body`]: the body is the intersection of its faces'
804/// regions), the re-drill for a through bore ([`crate::redrill_moved_bore`]).
805/// `Ok` carries the body and the note naming the road; `Err` the declines.
806fn by_regions(
807    solid: &BrepSolid,
808    face_ids: &[u64],
809    turn: Option<(Vec3, Vec3, f64)>,
810    translation: Vec3,
811) -> Result<(BrepSolid, String), String> {
812    let recut = match crate::recut_convex_body(solid, face_ids, turn, translation) {
813        Ok(body) => {
814            return Ok((
815                body,
816                "so the body was RE-CUT as the intersection of its faces' own regions with the moved \
817                 planes' — the body this motion defines"
818                    .to_string(),
819            ))
820        }
821        Err(reason) => reason,
822    };
823    match crate::redrill_moved_bore(solid, face_ids, turn, translation) {
824        Ok(body) => Ok((
825            body,
826            "so the bore was RE-DRILLED — the body with the hole filled, less the moved carrier run \
827             the body's whole way through"
828                .to_string(),
829        )),
830        Err(redrill) => Err(format!(
831            "The region re-cut was offered it too and declined: {recut}. The re-drill road declined: {redrill}"
832        )),
833    }
834}
835
836/// Context-bar applicability ([`crate::feature_pipeline::context_offer`]):
837/// selected faces drive `faces`.
838pub fn context_applicable(probe: &crate::feature_pipeline::SelectionProbe) -> bool {
839    probe.faces > 0
840}
841
842pub fn schema() -> serde_json::Value {
843    serde_json::json!({
844    "type": "TF",
845    "shortName": "TF",
846    "longName": "Transform Face",
847    "ribbonPath": "Home/Synchronous Modeling/Transform Face",
848    "commandSize": "Compact",
849    "displayBuilder": false,
850    "inputParamsSchema": {
851        "id": {
852            "type": "string",
853            "default_value": null,
854            "hint": "Optional identifier for the transform face feature"
855        },
856        "faces": {
857            "type": "reference_selection",
858            "selectionFilter": [
859                "FACE"
860            ],
861            "timestampDependency": "parentSolid",
862            "multiple": true,
863            "default_value": [],
864            "hint": "Select one or more faces on a single solid to move and turn"
865        },
866        "pivot": {
867            "type": "vec3",
868            "label": "Pivot",
869            "default_value": null,
870            "selectionFilter": ["VERTEX", "EDGE", "FACE"],
871            "hint": "The point the rotation turns about, in world millimetres; set to the centre of the selection when the faces are picked, or picked from a vertex, edge or face"
872        },
873        "transform": {
874            "type": "transform",
875            "default_value": {
876                "position": [0, 0, 0],
877                "rotationEuler": [0, 0, 0]
878            },
879            "hint": "Rotate the faces about the pivot, then move them; drag the gizmo or type the values"
880        }
881    }
882})
883}
884