use crate::face_refusal_slugs::{PIVOT_GEOMETRY, RIGID_SCALE};
use std::collections::HashSet;
use crate::feature_pipeline::features::common;
use crate::feature_pipeline::{AddedSolid, FeatureContext, FeatureRefusal, FeatureResult, SceneMap};
use crate::{move_faces_unchecked, rotate_faces_unchecked, BrepSolid, KernelRefusal, KernelStage, Vec3};
pub const REFUSED_STEP_ROTATION: &str = "rotation";
pub const REFUSED_STEP_TRANSLATION: &str = "translation";
pub const CENTRE_SAMPLES: usize = 64;
pub fn execute(ctx: &FeatureContext) -> FeatureResult {
match build(ctx) {
Ok(result) => result,
Err(error) => ctx.fail(error),
}
}
fn resolve_selection(
scene: &SceneMap,
names: &[String],
unresolved: &mut Vec<String>,
) -> Option<(u32, Vec<u64>)> {
let mut resolved: Vec<(u32, u64)> = Vec::new();
for name in names {
match scene.resolve_face(name) {
Some(face_ref) => resolved.push((face_ref.handle, face_ref.face_id)),
None => unresolved.push(name.clone()),
}
}
let &(target, _) = resolved.first()?;
if resolved.iter().any(|(handle, _)| *handle != target) {
return None;
}
let mut seen: HashSet<u64> = HashSet::new();
let face_ids = resolved
.iter()
.map(|(_, face_id)| *face_id)
.filter(|face_id| seen.insert(*face_id))
.collect();
Some((target, face_ids))
}
pub fn selection_centre(solid: &BrepSolid, face_ids: &[u64]) -> Option<Vec3> {
let selected: HashSet<u64> = face_ids.iter().copied().collect();
let mut low = [f64::INFINITY; 3];
let mut high = [f64::NEG_INFINITY; 3];
let mut include = |point: Vec3| {
let point = [point.x, point.y, point.z];
if point.iter().all(|c| c.is_finite()) {
for axis in 0..3 {
low[axis] = low[axis].min(point[axis]);
high[axis] = high[axis].max(point[axis]);
}
}
};
let mut edge_ids: HashSet<u64> = HashSet::new();
let mut edgeless = Vec::new();
for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
if !selected.contains(&face.id) {
continue;
}
let before = edge_ids.len();
for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
edge_ids.insert(coedge.edge_id);
}
if edge_ids.len() == before && face.loops.iter().all(|l| l.coedges.is_empty()) {
edgeless.push(face);
}
}
let vertex_ids: HashSet<u64> = solid
.edges
.iter()
.filter(|edge| edge_ids.contains(&edge.id))
.flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id])
.collect();
for vertex in &solid.vertices {
if vertex_ids.contains(&vertex.id) {
include(vertex.point);
}
}
for edge in solid.edges.iter().filter(|edge| edge_ids.contains(&edge.id)) {
if edge.degenerate {
continue;
}
for station in 0..=CENTRE_SAMPLES {
let t = edge.t0 + (edge.t1 - edge.t0) * station as f64 / CENTRE_SAMPLES as f64;
if let Ok(point) = edge.curve.evaluate(t) {
include(point);
}
}
}
for face in edgeless {
for control in face.surface.control_points.iter().flatten() {
if let Ok(point) = control.point() {
include(point);
}
}
}
if !low[0].is_finite() {
return None;
}
Some(Vec3::new(
0.5 * (low[0] + high[0]),
0.5 * (low[1] + high[1]),
0.5 * (low[2] + high[2]),
))
}
pub fn face_transform_pivot(prefix: &[FeatureResult], names: &[String]) -> Option<[f64; 3]> {
let mut scene = SceneMap::default();
for result in prefix {
scene.apply(result);
}
let (handle, face_ids) = resolve_selection(&scene, names, &mut Vec::new())?;
let centre =
crate::with_registered_solid_str(handle, |solid| Ok(selection_centre(solid, &face_ids)))
.ok()??;
Some([centre.x, centre.y, centre.z])
}
pub fn reference_point(prefix: &[FeatureResult], name: &str) -> Result<[f64; 3], String> {
use crate::feature_pipeline::pmi::resolve::resolve_reference;
use crate::{resolve_edge_selection, resolve_face_selection, SelectionGeometry};
let name = name.trim();
if name.is_empty() {
return Err("nothing was picked".into());
}
let mut scene = SceneMap::default();
for result in prefix {
scene.apply(result);
}
let point = if let Some(face) = scene.resolve_face(name) {
crate::with_registered_solid_str(face.handle, |solid| {
let centre = selection_centre(solid, &[face.face_id])
.ok_or_else(|| format!("face '{name}' has no geometry to place a point on"))?;
Ok(match resolve_face_selection(solid, face.face_id) {
Ok(SelectionGeometry::Sphere { center, .. }) => center,
Ok(SelectionGeometry::Axis { origin, direction, .. }) => {
origin.add(direction.scale(centre.sub(origin).dot(direction)))
}
_ => centre,
})
})?
} else if let Some(edge) = scene.resolve_edge(name) {
crate::with_registered_solid_str(edge.handle, |solid| {
let record = solid
.edges
.iter()
.find(|record| record.id == edge.edge_id)
.ok_or_else(|| format!("edge '{name}' has no record"))?;
let at = |t: f64| record.curve.evaluate(t).map_err(|error| format!("edge '{name}': {error}"));
let (start, middle, end) = (at(record.t0)?, at(0.5 * (record.t0 + record.t1))?, at(record.t1)?);
let size = start.sub(middle).length().max(end.sub(middle).length());
let reach = [start, middle, end].iter().map(|p| p.x.abs().max(p.y.abs()).max(p.z.abs())).fold(0.0, f64::max);
let agrees = |distance: f64| distance <= 1e-9 * size + 64.0 * f64::EPSILON * reach;
Ok(match resolve_edge_selection(solid, edge.edge_id) {
Ok(SelectionGeometry::Line { origin, .. })
if agrees(middle.sub(start.add(end).scale(0.5)).length()) =>
{
origin
}
Ok(SelectionGeometry::Circle { center, radius, .. })
if [start, middle, end].iter().all(|p| agrees((p.sub(center).length() - radius).abs())) =>
{
center
}
_ => middle,
})
})?
} else {
match resolve_reference(&scene, name)? {
SelectionGeometry::Point { position } => position,
SelectionGeometry::Plane { origin, .. } => origin,
SelectionGeometry::Sphere { center, .. } | SelectionGeometry::Circle { center, .. } => center,
SelectionGeometry::Line { origin, .. } | SelectionGeometry::Axis { origin, .. } => origin,
}
};
let point = [point.x, point.y, point.z];
if point.iter().any(|c| !c.is_finite()) {
return Err(format!("'{name}' did not evaluate to a finite point"));
}
Ok(point)
}
pub fn rotation_axis_angle(rotation_deg: [f64; 3]) -> Option<(Vec3, f64)> {
if rotation_deg == [0.0; 3] {
return None;
}
let radians = rotation_deg.map(f64::to_radians);
let m = common::compose_trs_matrix([0.0; 3], radians, [1.0; 3], [0.0; 3]);
let at = |row: usize, col: usize| m[row * 4 + col];
let (m00, m11, m22) = (at(0, 0), at(1, 1), at(2, 2));
let trace = m00 + m11 + m22;
let q = if trace >= m00 && trace >= m11 && trace >= m22 {
let w = 0.5 * (1.0 + trace).max(0.0).sqrt();
let k = 0.25 / w;
[(at(2, 1) - at(1, 2)) * k, (at(0, 2) - at(2, 0)) * k, (at(1, 0) - at(0, 1)) * k, w]
} else if m00 >= m11 && m00 >= m22 {
let x = 0.5 * (1.0 + m00 - m11 - m22).max(0.0).sqrt();
let k = 0.25 / x;
[x, (at(0, 1) + at(1, 0)) * k, (at(0, 2) + at(2, 0)) * k, (at(2, 1) - at(1, 2)) * k]
} else if m11 >= m22 {
let y = 0.5 * (1.0 - m00 + m11 - m22).max(0.0).sqrt();
let k = 0.25 / y;
[(at(0, 1) + at(1, 0)) * k, y, (at(1, 2) + at(2, 1)) * k, (at(0, 2) - at(2, 0)) * k]
} else {
let z = 0.5 * (1.0 - m00 - m11 + m22).max(0.0).sqrt();
let k = 0.25 / z;
[(at(0, 2) + at(2, 0)) * k, (at(1, 2) + at(2, 1)) * k, z, (at(1, 0) - at(0, 1)) * k]
};
let sign = if q[3] < 0.0 { -1.0 } else { 1.0 };
let axis = Vec3::new(q[0] * sign, q[1] * sign, q[2] * sign);
let half_sine = axis.length();
let angle = 2.0 * half_sine.atan2(q[3] * sign);
if angle <= 1e-12 {
return None;
}
Some((axis.scale(1.0 / half_sine), angle))
}
fn transform_vec3(ctx: &FeatureContext, key: &str, default: [f64; 3]) -> Result<[f64; 3], String> {
common::vec3_from_value(
ctx.env,
ctx.param("transform").and_then(|transform| transform.get(key)),
&format!("transform.{key}"),
default,
)
}
fn build(ctx: &FeatureContext) -> Result<FeatureResult, FeatureRefusal> {
let mut result = FeatureResult::empty(ctx.id.clone(), ctx.feature_type.clone());
let names = common::reference_name_array(ctx.param("faces"));
if names.is_empty() {
return Ok(result); }
let Some((target_handle, face_ids)) =
resolve_selection(ctx.scene, &names, &mut result.unresolved)
else {
return Ok(result); };
result.note_partial_resolution(&names);
let scale = transform_vec3(ctx, "scale", [1.0; 3])?;
if scale != [1.0; 3] {
return Err(KernelRefusal::input(
KernelStage::Collect,
RIGID_SCALE,
format!(
"transformFace: `transform.scale` is {scale:?}, but a face transform is a RIGID \
motion — a scaled carrier is a different surface, not a moved one — so scale must \
be [1, 1, 1]; refusing"
),
)
.into());
}
let position = transform_vec3(ctx, "position", [0.0; 3])?;
let rotation_deg = transform_vec3(ctx, "rotationEuler", [0.0; 3])?;
let translation = Vec3::new(position[0], position[1], position[2]);
let translates = translation.length() > 1e-12;
let rotation = rotation_axis_angle(rotation_deg);
if !translates && rotation.is_none() {
return Ok(result); }
let target_name = ctx
.scene
.solids
.iter()
.find(|(_, handle)| **handle == target_handle)
.map(|(name, _)| name.clone())
.ok_or("transformFace: target solid has no scene-map name")?;
let solid = crate::with_registered_solid_str(target_handle, |solid| Ok(solid.clone()))?;
let turn = match rotation {
None => None,
Some((axis, angle)) => {
let pivot = match ctx.param("pivot") {
None | Some(serde_json::Value::Null) => selection_centre(&solid, &face_ids)
.ok_or_else(|| {
KernelRefusal::input(
KernelStage::Collect,
PIVOT_GEOMETRY,
"transformFace: the selected faces carry no geometry to centre a pivot on",
)
})?,
Some(value) => {
let [x, y, z] = common::vec3_from_value(ctx.env, Some(value), "pivot", [0.0; 3])?;
Vec3::new(x, y, z)
}
};
Some((pivot, axis, angle))
}
};
let refused_at = |error: KernelRefusal, step: &str| {
let mut refused = ctx.fail(error);
refused.refused_step = Some(step.to_string());
refused
};
let without = crate::rebuild_displaced_blends(&solid, &face_ids, "transformFace", |sharp| {
solve_motion(sharp, &face_ids, turn, translates, translation).map_err(|(error, _)| error)
});
let (moved, notes) = match without {
Some(Ok(solved)) => solved,
declined => match solve_motion(&solid, &face_ids, turn, translates, translation) {
Ok(solved) => solved,
Err((refusal, step)) => {
let refusal = match &declined {
Some(Err(decline)) => crate::with_blend_rebuild_decline(refusal, decline),
_ => refusal,
};
return match step {
Some(step) => Ok(refused_at(refusal, step)),
None => Err(refusal.into()),
};
}
},
};
result.notes.extend(notes);
let face_names = common::collect_face_names(&moved);
let edge_names = common::collect_edge_names(&moved);
let handle = crate::register_solid_value(moved);
result.added.push(AddedSolid {
handle,
name: target_name.clone(),
face_names,
edge_names,
..AddedSolid::default()
});
result.removed.push(target_name);
Ok(result)
}
fn solve_motion(
solid: &BrepSolid,
face_ids: &[u64],
turn: Option<(Vec3, Vec3, f64)>,
translates: bool,
translation: Vec3,
) -> Result<(BrepSolid, Vec<String>), (KernelRefusal, Option<&'static str>)> {
let mut notes = Vec::new();
let moved = match turn {
None => match move_faces_unchecked(solid, face_ids, translation) {
Ok(moved) => moved,
Err(error) if is_straight_edge_inversion(&error) && has_island(solid, face_ids) => {
match recut_past_a_refusal(solid, face_ids, None, translation) {
Ok((body, lost)) => {
notes.push(format!(
"transformFace: the moved carriers could not be re-solved ({error}), \
so the selection was RE-CUT from the original body instead — the \
result is the boolean this motion defines, and a face whose carrier \
left the body is no longer on it"
));
notes.extend(lost);
return Ok((body, notes));
}
Err(reason) => {
let error = error.with_message(|error| {
format!("{error}. The re-cut road was offered it too and declined: {reason}")
});
return Err((error, Some(REFUSED_STEP_TRANSLATION)));
}
}
}
Err(error) if is_no_route_refusal(&error) => match by_regions(solid, face_ids, None, translation) {
Ok((body, note)) => {
notes.push(format!("transformFace: the moved carriers could not be re-solved ({error}), {note}"));
body
}
Err(reason) => {
let error = error.with_message(|error| format!("{error}. {reason}"));
return Err((error, Some(REFUSED_STEP_TRANSLATION)));
}
},
Err(error) => return Err((error, Some(REFUSED_STEP_TRANSLATION))),
},
Some((pivot, axis, angle)) => {
let solved = if !translates {
rotate_faces_unchecked(solid, face_ids, pivot, axis, angle)
} else {
crate::direct_edit::rotate_faces_rigid(
solid, face_ids, pivot, axis, angle, translation,
)
.map_err(|error| {
error.with_message(|error| {
format!("transformFace: the combined rigid motion refused — {error}")
})
})
};
match solved {
Ok(moved) => moved,
Err(error) if is_ruling_refusal(&error) => {
match crate::recut_moved_planes_rigid(solid, face_ids, turn, translation) {
Ok(body) => {
notes.push(format!(
"transformFace: the turned face could not be re-solved against \
the fillet beside it ({error}), so the selection was RE-CUT \
from the original body instead"
));
let (body, lost) = crate::reblend_lost_fillets(solid, face_ids, body);
notes.extend(lost);
body
}
Err(reason) => {
let error = error.with_message(|error| {
format!(
"{error}. The re-cut road was offered it too and declined: {reason}"
)
});
return Err((error, Some(REFUSED_STEP_ROTATION)));
}
}
}
Err(error) if is_no_route_refusal(&error) => match by_regions(solid, face_ids, turn, translation) {
Ok((body, note)) => {
notes.push(format!(
"transformFace: the turned face could not be re-solved ({error}), {note}"
));
body
}
Err(reason) => {
let error = error.with_message(|error| format!("{error}. {reason}"));
return Err((error, Some(REFUSED_STEP_ROTATION)));
}
},
Err(error) => return Err((error, Some(REFUSED_STEP_ROTATION))),
}
}
};
let moved = match crate::accept_sound(moved, "transformFace") {
Ok(body) => body,
Err(refusal) => {
match recut_past_a_refusal(solid, face_ids, turn, translation) {
Ok((body, lost)) => {
notes.push(format!(
"transformFace: the moved carriers could not be re-solved onto the body \
they left ({refusal}), so the selection was RE-CUT from the original \
body instead — the result is the boolean this motion defines, and a \
face whose carrier left the body is no longer on it"
));
notes.extend(lost);
body
}
Err(reason) => match redrill_past_a_refusal(solid, face_ids, turn, translation) {
Ok(body) => {
notes.push(format!(
"transformFace: the moved bore could not be re-trimmed onto the body \
({refusal}), so the bore was RE-DRILLED instead — the body with the \
hole filled, less the moved carrier run the body's whole way through"
));
body
}
Err(redrill) => {
return Err((
refusal.with_message(|refusal| {
format!(
"{refusal}. The re-cut road was offered it too and declined: \
{reason}. The re-drill road declined: {redrill}"
)
}),
None,
))
}
},
}
}
};
Ok((moved, notes))
}
fn recut_past_a_refusal(
solid: &BrepSolid,
face_ids: &[u64],
turn: Option<(Vec3, Vec3, f64)>,
translation: Vec3,
) -> Result<(BrepSolid, Vec<String>), KernelRefusal> {
let body = crate::recut_moved_planes_rigid(solid, face_ids, turn, translation)?;
let body = crate::accept_sound(body, "transformFace").map_err(|reason| {
reason.with_message(|reason| format!("the re-cut built a body the acceptance refused — {reason}"))
})?;
Ok(crate::reblend_lost_fillets(solid, face_ids, body))
}
fn redrill_past_a_refusal(
solid: &BrepSolid,
face_ids: &[u64],
turn: Option<(Vec3, Vec3, f64)>,
translation: Vec3,
) -> Result<BrepSolid, KernelRefusal> {
let body = crate::redrill_moved_bore(solid, face_ids, turn, translation)?;
crate::accept_sound(body, "transformFace").map_err(|reason| {
reason.with_message(|reason| format!("the re-drill built a body the acceptance refused — {reason}"))
})
}
fn is_straight_edge_inversion(error: &KernelRefusal) -> bool {
matches!(&error.class, crate::RefusalClass::UnsupportedGeometry { what }
if what == crate::face_refusal_slugs::EDGE_INVERSION || what == "edge_collapse")
}
fn has_island(solid: &BrepSolid, face_ids: &[u64]) -> bool {
solid
.shells
.iter()
.flat_map(|shell| &shell.faces)
.any(|face| face_ids.contains(&face.id) && face.loops.len() > 1)
}
fn is_ruling_refusal(error: &KernelRefusal) -> bool {
matches!(&error.class, crate::RefusalClass::UnsupportedGeometry { what } if what == "ruling_edge")
}
fn is_no_route_refusal(error: &KernelRefusal) -> bool {
const NO_ROUTE: &[&str] = &[
"carrier_kind",
"curved_edge_rebuild",
"curved_fixed_edge_pair",
"ruled_section",
"chord_off_carrier",
"both_nappes",
"asymptotic_ruling",
"section_through_apex",
"cap_through_apex",
"sphere_oblique_rim",
"sphere_mixed_neighbours",
"sphere_open_rim",
"sphere_group",
];
matches!(&error.class, crate::RefusalClass::UnsupportedGeometry { what } if NO_ROUTE.contains(&what.as_str()))
}
fn by_regions(
solid: &BrepSolid,
face_ids: &[u64],
turn: Option<(Vec3, Vec3, f64)>,
translation: Vec3,
) -> Result<(BrepSolid, String), String> {
let recut = match crate::recut_convex_body(solid, face_ids, turn, translation) {
Ok(body) => {
return Ok((
body,
"so the body was RE-CUT as the intersection of its faces' own regions with the moved \
planes' — the body this motion defines"
.to_string(),
))
}
Err(reason) => reason,
};
match crate::redrill_moved_bore(solid, face_ids, turn, translation) {
Ok(body) => Ok((
body,
"so the bore was RE-DRILLED — the body with the hole filled, less the moved carrier run \
the body's whole way through"
.to_string(),
)),
Err(redrill) => Err(format!(
"The region re-cut was offered it too and declined: {recut}. The re-drill road declined: {redrill}"
)),
}
}
pub fn context_applicable(probe: &crate::feature_pipeline::SelectionProbe) -> bool {
probe.faces > 0
}
pub fn schema() -> serde_json::Value {
serde_json::json!({
"type": "TF",
"shortName": "TF",
"longName": "Transform Face",
"ribbonPath": "Home/Synchronous Modeling/Transform Face",
"commandSize": "Compact",
"displayBuilder": false,
"inputParamsSchema": {
"id": {
"type": "string",
"default_value": null,
"hint": "Optional identifier for the transform face feature"
},
"faces": {
"type": "reference_selection",
"selectionFilter": [
"FACE"
],
"timestampDependency": "parentSolid",
"multiple": true,
"default_value": [],
"hint": "Select one or more faces on a single solid to move and turn"
},
"pivot": {
"type": "vec3",
"label": "Pivot",
"default_value": null,
"selectionFilter": ["VERTEX", "EDGE", "FACE"],
"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"
},
"transform": {
"type": "transform",
"default_value": {
"position": [0, 0, 0],
"rotationEuler": [0, 0, 0]
},
"hint": "Rotate the faces about the pivot, then move them; drag the gizmo or type the values"
}
}
})
}