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 without = crate::rebuild_displaced_blends(&solid, &face_ids, "transformFace", |sharp| {
464 solve_motion(sharp, &face_ids, turn, translates, translation).map_err(|(error, _)| error)
465 });
466 let (moved, notes) = match without {
467 Some(Ok(solved)) => solved,
468 declined => match solve_motion(&solid, &face_ids, turn, translates, translation) {
469 Ok(solved) => solved,
470 Err((refusal, step)) => {
471 let refusal = match &declined {
472 Some(Err(decline)) => crate::with_blend_rebuild_decline(refusal, decline),
473 _ => refusal,
474 };
475 return match step {
476 Some(step) => Ok(refused_at(refusal, step)),
477 None => Err(refusal.into()),
478 };
479 }
480 },
481 };
482 result.notes.extend(notes);
483
484 // Both roads preserve every name — collect, never re-stamp.
485 let face_names = common::collect_face_names(&moved);
486 let edge_names = common::collect_edge_names(&moved);
487 let handle = crate::register_solid_value(moved);
488 result.added.push(AddedSolid {
489 handle,
490 name: target_name.clone(),
491 face_names,
492 edge_names,
493 ..AddedSolid::default()
494 });
495 result.removed.push(target_name);
496 Ok(result)
497}
498
499/// The motion's whole road on one body: the direct re-solve, its acceptance,
500/// and the re-cut where either hands the motion on. `Ok` is the edited body
501/// and the notes the road left; `Err` is the refusal and, for a refusal of
502/// the re-solve itself, the step of the motion it names (`refused_step`).
503fn solve_motion(
504 solid: &BrepSolid,
505 face_ids: &[u64],
506 turn: Option<(Vec3, Vec3, f64)>,
507 translates: bool,
508 translation: Vec3,
509) -> Result<(BrepSolid, Vec<String>), (KernelRefusal, Option<&'static str>)> {
510 let mut notes = Vec::new();
511 let moved = match turn {
512 None => match move_faces_unchecked(solid, face_ids, translation) {
513 Ok(moved) => moved,
514 // A straight edge the translation inverts or collapses on a face
515 // with an ISLAND is that face carried past the far end of the
516 // island's wall — a pocket floor pushed past the bottom of a hole
517 // through it — whose answer has that wall STOP EXISTING. No re-solve has such a body, so the
518 // re-cut is offered it, as it is offered an acceptance refusal
519 // below; the re-solve's refusal stays the primary one if it
520 // declines too.
521 Err(error) if is_straight_edge_inversion(&error) && has_island(solid, face_ids) => {
522 match recut_past_a_refusal(solid, face_ids, None, translation) {
523 Ok((body, lost)) => {
524 notes.push(format!(
525 "transformFace: the moved carriers could not be re-solved ({error}), \
526 so the selection was RE-CUT from the original body instead — the \
527 result is the boolean this motion defines, and a face whose carrier \
528 left the body is no longer on it"
529 ));
530 notes.extend(lost);
531 return Ok((body, notes));
532 }
533 Err(reason) => {
534 let error = error.with_message(|error| {
535 format!("{error}. The re-cut road was offered it too and declined: {reason}")
536 });
537 return Err((error, Some(REFUSED_STEP_TRANSLATION)));
538 }
539 }
540 }
541 Err(error) if is_no_route_refusal(&error) => match by_regions(solid, face_ids, None, translation) {
542 Ok((body, note)) => {
543 notes.push(format!("transformFace: the moved carriers could not be re-solved ({error}), {note}"));
544 body
545 }
546 Err(reason) => {
547 let error = error.with_message(|error| format!("{error}. {reason}"));
548 return Err((error, Some(REFUSED_STEP_TRANSLATION)));
549 }
550 },
551 Err(error) => return Err((error, Some(REFUSED_STEP_TRANSLATION))),
552 },
553 Some((pivot, axis, angle)) => {
554 let solved = if !translates {
555 rotate_faces_unchecked(solid, face_ids, pivot, axis, angle)
556 } else {
557 crate::direct_edit::rotate_faces_rigid(
558 solid, face_ids, pivot, axis, angle, translation,
559 )
560 .map_err(|error| {
561 error.with_message(|error| {
562 format!("transformFace: the combined rigid motion refused — {error}")
563 })
564 })
565 };
566 match solved {
567 Ok(moved) => moved,
568 // A face tangent to a fillet beside it has no rim to re-solve:
569 // turned, it cuts that fillet in a different ruling or leaves
570 // it altogether, and either way the answer is a different
571 // topology. That is what the re-cut road below is for, so this
572 // one refusal is offered to it directly. Its body still passes
573 // the acceptance below.
574 Err(error) if is_ruling_refusal(&error) => {
575 match crate::recut_moved_planes_rigid(solid, face_ids, turn, translation) {
576 Ok(body) => {
577 notes.push(format!(
578 "transformFace: the turned face could not be re-solved against \
579 the fillet beside it ({error}), so the selection was RE-CUT \
580 from the original body instead"
581 ));
582 let (body, lost) = crate::reblend_lost_fillets(solid, face_ids, body);
583 notes.extend(lost);
584 body
585 }
586 Err(reason) => {
587 let error = error.with_message(|error| {
588 format!(
589 "{error}. The re-cut road was offered it too and declined: {reason}"
590 )
591 });
592 return Err((error, Some(REFUSED_STEP_ROTATION)));
593 }
594 }
595 }
596 // A turned face whose neighbour has no route on this road — a
597 // plane's section of a cylinder or cone it cannot mint (a whole
598 // frustum's top turned past the generatrices), a slanted cap on a
599 // coaxial wall, a sphere, torus or quadric neighbour — still
600 // has an answer where the body is the intersection of its faces'
601 // own regions, or where the selection is a through bore
602 // (`by_regions`). The rotation road's refusal stays the primary
603 // one if both decline.
604 Err(error) if is_no_route_refusal(&error) => match by_regions(solid, face_ids, turn, translation) {
605 Ok((body, note)) => {
606 notes.push(format!(
607 "transformFace: the turned face could not be re-solved ({error}), {note}"
608 ));
609 body
610 }
611 Err(reason) => {
612 let error = error.with_message(|error| format!("{error}. {reason}"));
613 return Err((error, Some(REFUSED_STEP_ROTATION)));
614 }
615 },
616 Err(error) => return Err((error, Some(REFUSED_STEP_ROTATION))),
617 }
618 }
619 };
620 // Carrying a face past a neighbour's own extent leaves it crossing one it
621 // should have stopped at, and both roads are pure geometry edits that create
622 // no cell for `validate()` to catch. The acceptance Push Face takes: split and
623 // trim where that can be proved, refuse by name where it cannot. Where the
624 // motion carried the selection clean OUT of the faces it opened through —
625 // the breakout — that split also re-trims the neighbour left holding an
626 // unanswered boundary, which is the only way such a body closes.
627 //
628 // And where the acceptance refuses, the RE-CUT road is offered the same
629 // edit from the other end — the original body, the selection and the
630 // motion, cut as a boolean rather than re-solved — because a motion whose
631 // answer needs a face to STOP EXISTING has no body for a repair to reach.
632 // A plane moved rigidly is still a plane, so the road takes a
633 // rotate-then-translate as well as a translation (the 2026-09-22 slot
634 // document with its wall also TURNED 16.9° refused here while the same
635 // drag without the turn built). See `edit/direct_edit/face_move_recut.rs`.
636 // It runs only after an acceptance refusal; a motion refused by the
637 // direct re-intersection solver never reaches it.
638 let moved = match crate::accept_sound(moved, "transformFace") {
639 Ok(body) => body,
640 Err(refusal) => {
641 match recut_past_a_refusal(solid, face_ids, turn, translation) {
642 Ok((body, lost)) => {
643 notes.push(format!(
644 "transformFace: the moved carriers could not be re-solved onto the body \
645 they left ({refusal}), so the selection was RE-CUT from the original \
646 body instead — the result is the boolean this motion defines, and a \
647 face whose carrier left the body is no longer on it"
648 ));
649 notes.extend(lost);
650 body
651 }
652 // A through bore's wall: the RE-DRILL road — the body with
653 // the bore healed shut, less the moved carrier run the body's
654 // whole way through (`edit/direct_edit/face_move_redrill.rs`).
655 // It answers a mouth straddling a corner, whose two crossing
656 // pairs the acceptance's repair does not take. The re-cut
657 // declines every curved carrier, so this is the only road
658 // left for a bore wall.
659 Err(reason) => match redrill_past_a_refusal(solid, face_ids, turn, translation) {
660 Ok(body) => {
661 notes.push(format!(
662 "transformFace: the moved bore could not be re-trimmed onto the body \
663 ({refusal}), so the bore was RE-DRILLED instead — the body with the \
664 hole filled, less the moved carrier run the body's whole way through"
665 ));
666 body
667 }
668 // The acceptance's refusal stays the primary one — its
669 // class is what the boundary reports — and the other
670 // roads' declines are appended as context.
671 Err(redrill) => {
672 return Err((
673 refusal.with_message(|refusal| {
674 format!(
675 "{refusal}. The re-cut road was offered it too and declined: \
676 {reason}. The re-drill road declined: {redrill}"
677 )
678 }),
679 None,
680 ))
681 }
682 },
683 }
684 }
685 };
686 Ok((moved, notes))
687}
688
689/// The re-cut offered after the acceptance refused the moved body.
690///
691/// The body passes the SAME acceptance the primitives' body did: a boolean's
692/// output is sound by construction, so this is a check and not a repair, and a
693/// body it refuses is refused by name rather than returned. Fillets the re-cut
694/// filled in are then re-made one by one, and the second value names any that
695/// could not be.
696fn recut_past_a_refusal(
697 solid: &BrepSolid,
698 face_ids: &[u64],
699 turn: Option<(Vec3, Vec3, f64)>,
700 translation: Vec3,
701) -> Result<(BrepSolid, Vec<String>), KernelRefusal> {
702 let body = crate::recut_moved_planes_rigid(solid, face_ids, turn, translation)?;
703 let body = crate::accept_sound(body, "transformFace").map_err(|reason| {
704 reason.with_message(|reason| format!("the re-cut built a body the acceptance refused — {reason}"))
705 })?;
706 Ok(crate::reblend_lost_fillets(solid, face_ids, body))
707}
708
709/// The re-drill offered after the acceptance and the re-cut refused: checked
710/// by the same acceptance, as the re-cut's body is.
711fn redrill_past_a_refusal(
712 solid: &BrepSolid,
713 face_ids: &[u64],
714 turn: Option<(Vec3, Vec3, f64)>,
715 translation: Vec3,
716) -> Result<BrepSolid, KernelRefusal> {
717 let body = crate::redrill_moved_bore(solid, face_ids, turn, translation)?;
718 crate::accept_sound(body, "transformFace").map_err(|reason| {
719 reason.with_message(|reason| format!("the re-drill built a body the acceptance refused — {reason}"))
720 })
721}
722
723/// The translation primitive's refusal for a straight edge it inverts or
724/// collapses (`face_move.rs`).
725fn is_straight_edge_inversion(error: &KernelRefusal) -> bool {
726 matches!(&error.class, crate::RefusalClass::UnsupportedGeometry { what }
727 if what == crate::face_refusal_slugs::EDGE_INVERSION || what == "edge_collapse")
728}
729
730/// Whether a selected face has an inner loop (an island: a hole through it or
731/// a boss standing on it).
732fn has_island(solid: &BrepSolid, face_ids: &[u64]) -> bool {
733 solid
734 .shells
735 .iter()
736 .flat_map(|shell| &shell.faces)
737 .any(|face| face_ids.contains(&face.id) && face.loops.len() > 1)
738}
739
740/// The rotation primitive's refusal for a face tangent to a ruled neighbour.
741fn is_ruling_refusal(error: &KernelRefusal) -> bool {
742 matches!(&error.class, crate::RefusalClass::UnsupportedGeometry { what } if what == "ruling_edge")
743}
744
745/// A refusal of either primitive that says the neighbour or section has NO
746/// ROUTE on that road — not that the motion inverts, collapses or tears
747/// something, which stay refusals: a carrier kind it does not re-intersect, a
748/// curved edge it cannot rebuild, a plane's section of a ruled wall it cannot
749/// mint, a slanted chord off its wall, a sphere rim it does not model.
750fn is_no_route_refusal(error: &KernelRefusal) -> bool {
751 const NO_ROUTE: &[&str] = &[
752 "carrier_kind",
753 "curved_edge_rebuild",
754 "curved_fixed_edge_pair",
755 "ruled_section",
756 "chord_off_carrier",
757 "both_nappes",
758 "asymptotic_ruling",
759 "section_through_apex",
760 "cap_through_apex",
761 "sphere_oblique_rim",
762 "sphere_mixed_neighbours",
763 "sphere_open_rim",
764 "sphere_group",
765 ];
766 matches!(&error.class, crate::RefusalClass::UnsupportedGeometry { what } if NO_ROUTE.contains(&what.as_str()))
767}
768
769/// The two roads that answer a motion from the body's own regions rather than
770/// by re-solving: the region re-cut for planar faces
771/// ([`crate::recut_convex_body`]: the body is the intersection of its faces'
772/// regions), the re-drill for a through bore ([`crate::redrill_moved_bore`]).
773/// `Ok` carries the body and the note naming the road; `Err` the declines.
774fn by_regions(
775 solid: &BrepSolid,
776 face_ids: &[u64],
777 turn: Option<(Vec3, Vec3, f64)>,
778 translation: Vec3,
779) -> Result<(BrepSolid, String), String> {
780 let recut = match crate::recut_convex_body(solid, face_ids, turn, translation) {
781 Ok(body) => {
782 return Ok((
783 body,
784 "so the body was RE-CUT as the intersection of its faces' own regions with the moved \
785 planes' — the body this motion defines"
786 .to_string(),
787 ))
788 }
789 Err(reason) => reason,
790 };
791 match crate::redrill_moved_bore(solid, face_ids, turn, translation) {
792 Ok(body) => Ok((
793 body,
794 "so the bore was RE-DRILLED — the body with the hole filled, less the moved carrier run \
795 the body's whole way through"
796 .to_string(),
797 )),
798 Err(redrill) => Err(format!(
799 "The region re-cut was offered it too and declined: {recut}. The re-drill road declined: {redrill}"
800 )),
801 }
802}
803
804/// Context-bar applicability ([`crate::feature_pipeline::context_offer`]):
805/// selected faces drive `faces`.
806pub fn context_applicable(probe: &crate::feature_pipeline::SelectionProbe) -> bool {
807 probe.faces > 0
808}
809
810pub fn schema() -> serde_json::Value {
811 serde_json::json!({
812 "type": "TF",
813 "shortName": "TF",
814 "longName": "Transform Face",
815 "ribbonPath": "Home/Synchronous Modeling/Transform Face",
816 "commandSize": "Compact",
817 "displayBuilder": false,
818 "inputParamsSchema": {
819 "id": {
820 "type": "string",
821 "default_value": null,
822 "hint": "Optional identifier for the transform face feature"
823 },
824 "faces": {
825 "type": "reference_selection",
826 "selectionFilter": [
827 "FACE"
828 ],
829 "timestampDependency": "parentSolid",
830 "multiple": true,
831 "default_value": [],
832 "hint": "Select one or more faces on a single solid to move and turn"
833 },
834 "pivot": {
835 "type": "vec3",
836 "label": "Pivot",
837 "default_value": null,
838 "selectionFilter": ["VERTEX", "EDGE", "FACE"],
839 "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"
840 },
841 "transform": {
842 "type": "transform",
843 "default_value": {
844 "position": [0, 0, 0],
845 "rotationEuler": [0, 0, 0]
846 },
847 "hint": "Rotate the faces about the pivot, then move them; drag the gizmo or type the values"
848 }
849 }
850})
851}
852