Files
ancient_astronaut_theorist ebbfc7ea96 Extrude and Revolve from a face: a face with too many edges is refused with its edge count and the limit (#18061) (#18227)
* claim: #18061

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gr84VuQWHKtTwJ7cC3CP3W

* Profile from a face: say how many edges the face has and the limit (#18061)

Extrude and Revolve refuse a planar face with more than 5,000 edges as
their profile. The refusal said "the face has no usable boundary", which
reads as if the face were broken. It now names the face's edge count and
the limit. The limit is a named constant, MAX_PROFILE_EDGES, checked in
profile_edge_count; a face with no edges keeps the old message.

Refs #18061

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gr84VuQWHKtTwJ7cC3CP3W

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 02:22:01 +00:00

603 lines
29 KiB
Rust

//! Sketches made from a planar body face, so a face can be extruded like a profile (Extrude
//! with `face`, Press Pull). The face boundary is copied into a new sketch on the face: straight
//! edges become lines, circular edges circles or arcs, anything else a chain of lines.
use serde_json::{Value, json};
use solidcore_record::{Vec2, Vec3};
use solidcraft_doc::{EmbossFace, apply_point, mat_inverse, mat_mul};
use solidcraft_geom::Mesh;
use solidcraft_geom::prelude::*;
use crate::params::{bad, str_, vec3};
use crate::{Result, Session};
fn point_triangle_dist(p: Vec3, a: Vec3, b: Vec3, c: Vec3) -> f64 {
let n = (b - a).cross(c - a);
let Some(nn) = n.normalized() else { return f64::INFINITY };
let h = (p - a).dot(nn);
let q = p - nn * h;
let inside = [(a, b), (b, c), (c, a)].iter().all(|(u, v)| (*v - *u).cross(q - *u).dot(n) >= -1e-12);
if inside { h.abs() } else { [(a, b), (b, c), (c, a)].iter().map(|(u, v)| p.dist_to_segment(*u, *v)).fold(f64::INFINITY, f64::min) }
}
/// The outward normal of the planar body face at `p`.
pub(super) fn face_normal(s: &Session, p: Vec3) -> Option<Vec3> {
face_normal_in(s, p, None)
}
/// The outward normal of the planar face at `p` of `body` (any body when `None`).
pub(super) fn face_normal_in(s: &Session, p: Vec3, body: Option<&str>) -> Option<Vec3> {
let (m, f, d, _) = face_at_in(s, p, body).ok().flatten()?;
if !near_face(&m, d) {
return None;
}
m.triangles
.iter()
.zip(&m.tri_face)
.filter(|(_, tf)| **tf == f)
.filter_map(|(t, _)| m.tri(t))
.find_map(|[a, b, c]| (b - a).cross(c - a).normalized())
}
/// Is a face `d` from a point near enough to hold it: within a thousandth of the body's
/// size (at least 1 µm), ten times over, as picks placed on faces are taken.
fn near_face(m: &Mesh, d: f64) -> bool {
let tol = (m.bounds().diagonal() * 1e-3).max(1e-3);
d <= tol * 10.0
}
/// Does `p` lie on a face of a body (planar or curved), as features placed on a face need?
/// Where flush bodies' faces are equally near, it lies on each of them. A point in the opening
/// of a planar face (the mouth of an existing bore, which a counterbore is centred on) is on
/// that face too.
pub(super) fn on_a_face(s: &Session, p: Vec3) -> bool {
let on_one = match face_at_in(s, p, None) {
Ok(Some((m, _, d, _))) => near_face(&m, d),
Ok(None) => false,
Err(tied) => tied.first().is_some_and(|b| matches!(face_at_in(s, p, Some(b)), Ok(Some((m, _, d, _))) if near_face(&m, d))),
};
on_one || s.model.state().bodies.iter().any(|b| in_a_planar_face_outline(&b.mesh(), p))
}
/// Does `p` lie in the plane of a planar face of `m`, inside the hull of that face's corners
/// (so over its openings, not past its edge)?
fn in_a_planar_face_outline(m: &Mesh, p: Vec3) -> bool {
let mut faces: std::collections::BTreeMap<u32, Vec<[Vec3; 3]>> = std::collections::BTreeMap::new();
for (t, f) in m.triangles.iter().zip(&m.tri_face) {
if let Some(tri) = m.tri(t) {
faces.entry(*f).or_default().push(tri);
}
}
faces.values().any(|tris| {
let Some([a, b, c]) = tris.first().copied() else { return false };
let Some(n) = (b - a).cross(c - a).normalized() else { return false };
let planar = tris.iter().all(|[a, b, c]| (*b - *a).cross(*c - *a).normalized().is_some_and(|k| k.dot(n) > 1.0 - 1e-6));
if !planar || !near_face(m, (p - a).dot(n).abs()) {
return false;
}
let reference = if n.x.abs() < 0.9 { Vec3::new(1.0, 0.0, 0.0) } else { Vec3::new(0.0, 1.0, 0.0) };
let Some(u) = n.cross(reference).normalized() else { return false };
let v = n.cross(u);
let flat = |q: Vec3| (q.dot(u), q.dot(v));
let mut corners: Vec<(f64, f64)> = tris.iter().flatten().map(|q| flat(*q)).collect();
corners.sort_by(|x, y| x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal));
corners.dedup();
inside_hull(&corners, flat(p))
})
}
/// Is `q` inside (or on) the convex hull of `sorted` points (sorted by x, then y)?
fn inside_hull(sorted: &[(f64, f64)], q: (f64, f64)) -> bool {
let cross = |o: (f64, f64), a: (f64, f64), b: (f64, f64)| (a.0 - o.0) * (b.1 - o.1) - (a.1 - o.1) * (b.0 - o.0);
let chain = |points: &mut dyn Iterator<Item = &(f64, f64)>| {
let mut h: Vec<(f64, f64)> = Vec::new();
for &pt in points {
while h.len() >= 2 && cross(h[h.len() - 2], h[h.len() - 1], pt) <= 0.0 {
h.pop();
}
h.push(pt);
}
h
};
let mut hull = chain(&mut sorted.iter());
hull.pop();
let mut upper = chain(&mut sorted.iter().rev());
upper.pop();
hull.extend(upper);
let eps = 1e-9;
hull.len() >= 3 && (0..hull.len()).all(|i| cross(hull[i], hull[(i + 1) % hull.len()], q) >= -eps)
}
/// The outward normal of the planar face at the world point `p`: on the model as the view
/// places it (moved components where they are shown).
pub(super) fn face_normal_world(s: &Session, p: Vec3) -> Option<Vec3> {
let (m, f, d, _) = face_at_state(&*s.world_state().ok()?, p, None).ok().flatten()?;
let tol = (m.bounds().diagonal() * 1e-3).max(1e-3);
if d > tol * 10.0 {
return None;
}
m.triangles
.iter()
.zip(&m.tri_face)
.filter(|(_, tf)| **tf == f)
.filter_map(|(t, _)| m.tri(t))
.find_map(|[a, b, c]| (b - a).cross(c - a).normalized())
}
/// Is the body face at `p` planar (`None`: no face there)?
pub(super) fn face_is_planar(s: &Session, p: Vec3) -> Option<bool> {
let (m, f, d, _) = face_at(s, p)?;
if !near_face(&m, d) {
return None;
}
let ns: Vec<Vec3> = m
.triangles
.iter()
.zip(&m.tri_face)
.filter(|(_, tf)| **tf == f)
.filter_map(|(t, _)| m.tri(t))
.filter_map(|[a, b, c]| (b - a).cross(c - a).normalized())
.collect();
let n0 = *ns.first()?;
Some(ns.iter().all(|n| n.dot(n0) > 1.0 - 1e-6))
}
/// A face given to a command: a point `[x, y, z]` on it (or `{point}`), or its name as
/// `model.faces` lists it, looked up on `body` (any body without one). A name becomes a point on
/// that face, which the feature keeps like a picked one, so it also keeps the face's name.
/// The point is in the frame of the command's other picks: the component's own when
/// they were mapped into it, else the world's.
pub(super) fn face_ref(s: &Session, v: &Value, body: Option<&str>, cmd: &str) -> Result<Vec3> {
match face_ref_form(v).map_err(|why| bad(cmd, why))? {
FaceRefForm::Point(p) => Ok(p),
FaceRefForm::Name(name) => {
let st = if crate::frames::mapped() { s.model.state() } else { s.world_state()? };
solidcraft_doc::naming::named_face_point(&st, body, name).map_err(|why| bad(cmd, why))
}
}
}
/// The body a command that works on one body's faces applies to: `body` when given, or else the
/// one body every picked point lies on, so the feature keeps it (its evaluation otherwise takes
/// the body whose box is nearest the first point, and coincident faces tie there).
/// A point on coincident faces of several bodies (bodies touching flush) says none of them:
/// evaluation decides as it always has, and the command's result warns and names them
/// ([`FacesBody::warn`]). With one body, names among the picks or picks on no face, nothing is
/// chosen here and evaluation decides as before.
/// Which bodies a point lies on is decided by each body's exact boundary
/// ([`bodies_on_boundary`]), never by its display mesh: two bodies that touch along a line (gears
/// in mesh) both hold a point on that line, whichever tessellation comes out nearer.
pub(super) fn faces_body(s: &Session, p: &Value, refs: &[Value], points: &[Vec3]) -> FacesBody {
if let Some(n) = str_(p, "body") {
return FacesBody { body: Some(n.to_string()), tie: None };
}
let none = FacesBody { body: None, tie: None };
let st = s.model.state();
if st.bodies.len() < 2 || refs.iter().any(Value::is_string) {
return none;
}
let mut found: Option<String> = None;
for &pt in points {
let mut on = bodies_on_boundary(&st, pt);
let name = match on.len() {
0 => return none,
1 => on.remove(0),
// Evaluation still decides, as it always has; the result says the pick was shared.
_ => return FacesBody { body: None, tie: Some((pt, on)) },
};
match &found {
Some(f) if *f != name => return none,
Some(_) => {}
None => found = Some(name),
}
}
FacesBody { body: found, tie: None }
}
/// The bodies whose exact boundary holds `p`, in model order. A pick of the running command
/// that was resolved against the placed model names its bodies, as for [`face_at_in`] (#419).
/// A body's exact box, grown by a micrometre, skips bodies away from the point before the
/// kernel's exact classification decides.
fn bodies_on_boundary(st: &solidcraft_doc::ModelState, p: Vec3) -> Vec<String> {
if let Some(names) = crate::frames::picked(p).filter(|n| !n.is_empty()) {
return model_names(st, &names);
}
st.bodies
.iter()
.filter(|b| {
let Ok(bounds) = b.body.exact_bounds() else { return true };
let (lo, hi, grow) = (bounds.min, bounds.max, 1e-3);
p.x >= lo.x - grow && p.x <= hi.x + grow && p.y >= lo.y - grow && p.y <= hi.y + grow && p.z >= lo.z - grow && p.z <= hi.z + grow
})
.filter(|b| matches!(b.body.classify_point(p), Ok(solidcraft_kernel::PointClass::OnBoundary)))
.map(|b| b.name.clone())
.collect()
}
/// What [`faces_body`] found for a command's face picks.
pub(super) struct FacesBody {
/// The body to save in the feature: the one named, or the one every pick lies on.
pub body: Option<String>,
/// A pick on coincident faces of several bodies (bodies touching flush), and those bodies.
tie: Option<(Vec3, Vec<String>)>,
}
impl FacesBody {
/// The body a face of the picks is looked up on: the feature's, or for a shared pick the
/// first body it lies on, as the faces are the same there.
pub fn lookup(&self) -> Option<&str> {
self.body.as_deref().or_else(|| self.tie.as_ref().and_then(|(_, b)| b.first()).map(String::as_str))
}
/// The command's result, with a warning when a pick lay on coincident faces of several
/// bodies: it names them and the body that changed, so a caller can name one with `body`.
pub fn warn(&self, mut out: Value) -> Value {
let Some((pt, tied)) = &self.tie else { return out };
let at = [pt.x, pt.y, pt.z].map(short_number).join(", ");
let changed = out.get("changed_bodies").and_then(Value::as_array).and_then(|a| a.first()).and_then(Value::as_str).map(str::to_string);
let mut note = format!("the face at [{at}] is on {}", and_list(tied));
if let Some(c) = changed {
note.push_str(&format!(", and {c} was changed"));
}
note.push_str("; name one with `body` to choose");
let note = match out.get("warning").and_then(Value::as_str) {
Some(w) if !w.is_empty() => format!("{w}; {note}"),
_ => note,
};
if let Some(o) = out.as_object_mut() {
o.insert("warning".into(), json!(note));
}
out
}
}
/// A coordinate for a message: at most three decimals, without trailing zeros.
fn short_number(v: f64) -> String {
let s = format!("{v:.3}");
let s = s.trim_end_matches('0').trim_end_matches('.');
if s == "-0" { "0".to_string() } else { s.to_string() }
}
/// "A", "A and B", "A, B and C".
fn and_list(names: &[String]) -> String {
match names.split_last() {
Some((last, rest)) if !rest.is_empty() => format!("{} and {last}", rest.join(", ")),
Some((last, _)) => last.clone(),
None => String::new(),
}
}
/// A face reference as given, before it is looked up: see [`face_ref`].
pub(crate) enum FaceRefForm<'a> {
Point(Vec3),
Name(&'a str),
}
/// What [`face_ref`] reads `v` as, without the design: a point, or a name of 1…512 bytes.
pub(crate) fn face_ref_form(v: &Value) -> std::result::Result<FaceRefForm<'_>, &'static str> {
if let Some(name) = v.as_str() {
if name.is_empty() || name.len() > 512 {
return Err("a face name is 1…512 characters");
}
return Ok(FaceRefForm::Name(name));
}
vec3(v).or_else(|| v.get("point").and_then(vec3)).map(FaceRefForm::Point).ok_or("a face is a point [x, y, z] on it, or its name from model.faces")
}
/// The body face under a point: (mesh, face index, distance, body).
fn face_at(s: &Session, p: Vec3) -> Option<(std::sync::Arc<Mesh>, u32, f64, String)> {
face_at_in(s, p, None).ok().flatten()
}
type FacePick = (std::sync::Arc<Mesh>, u32, f64, String);
/// The face under a point of `only` (any body when `None`). Where faces of several bodies are
/// equally near (bodies touching flush), the pick is ambiguous: `Err` names those bodies.
/// A pick of the running command was resolved against the placed model, so the body under it
/// wins: a body that only shares its place in the model is not in the way (#419). A named
/// body still wins over that.
fn face_at_in(s: &Session, p: Vec3, only: Option<&str>) -> std::result::Result<Option<FacePick>, Vec<String>> {
let st = s.model.state();
match (crate::frames::picked(p), only) {
(Some(names), None) if names.len() > 1 => Err(model_names(&st, &names)),
(Some(names), None) => {
let under = names.first().and_then(|n| st.bodies.iter().find(|b| b.definition_name() == n.as_str()).map(|b| b.name.clone()));
face_at_state(&st, p, under.as_deref())
}
(_, only) => face_at_state(&st, p, only),
}
}
/// The names the model gives the bodies a pick met.
fn model_names(st: &solidcraft_doc::ModelState, names: &[String]) -> Vec<String> {
names.iter().map(|n| st.bodies.iter().find(|b| b.definition_name() == n.as_str()).map(|b| b.name.clone()).unwrap_or_else(|| n.clone())).collect()
}
pub(super) fn face_at_state(st: &solidcraft_doc::ModelState, p: Vec3, only: Option<&str>) -> std::result::Result<Option<FacePick>, Vec<String>> {
let mut best: Option<FacePick> = None;
let mut tied: Vec<String> = Vec::new();
for b in st.bodies.iter().filter(|b| only.is_none_or(|n| b.name == n)) {
let m = b.mesh();
let mut near: Option<(u32, f64)> = None;
for (t, f) in m.triangles.iter().zip(&m.tri_face) {
let Some([a, bb, c]) = m.tri(t) else { continue };
let d = point_triangle_dist(p, a, bb, c);
if near.is_none_or(|(_, nd)| d < nd) {
near = Some((*f, d));
}
}
if let Some((f, d)) = near {
if best.as_ref().is_none_or(|x| d < x.2 - 1e-8) {
best = Some((m.clone(), f, d, b.name.clone()));
tied.clear();
} else if best.as_ref().is_some_and(|x| (d - x.2).abs() <= 1e-8) {
tied.push(b.name.clone());
}
}
}
match best {
Some(b) if !tied.is_empty() => Err(std::iter::once(b.3).chain(tied).collect()),
b => Ok(b),
}
}
/// Circle through three points.
fn circumcircle(a: Vec2, b: Vec2, c: Vec2) -> Option<(Vec2, f64)> {
let d = 2.0 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y));
if d.abs() < 1e-12 {
return None;
}
let (a2, b2, c2) = (a.len2(), b.len2(), c.len2());
let o = Vec2::new((a2 * (b.y - c.y) + b2 * (c.y - a.y) + c2 * (a.y - b.y)) / d, (a2 * (c.x - b.x) + b2 * (a.x - c.x) + c2 * (b.x - a.x)) / d);
let r = o.dist(a);
(o.is_finite() && r.is_finite() && r < 1e8).then_some((o, r))
}
fn xy(v: Vec2) -> Value {
json!([v.x, v.y])
}
/// The picked points split into runs of coplanar, equally oriented faces of one body, in the
/// order each run is first picked. Every pick is resolved against the body as it is now.
pub(super) fn face_groups(s: &Session, points: &[Vec3], cmd: &str, face_body: Option<&str>) -> Result<Vec<Vec<Vec3>>> {
if points.len() > 1024 {
return Err(bad(cmd, "faces exceed the 1024-face limit"));
}
let state = s.model.state();
let mut groups: Vec<(String, solidcore_record::Plane, Vec<Vec3>)> = Vec::new();
for &point in points {
if !point.is_finite() {
return Err(bad(cmd, "faces must be finite points"));
}
let (mesh, index, distance, name) = face_at_in(s, point, face_body)
.map_err(|_| bad(cmd, "ambiguous face; specify face_body"))?
.ok_or_else(|| bad(cmd, "no body face at a selected point"))?;
let body = state.body(&name).ok_or_else(|| bad(cmd, "selected body disappeared"))?;
let plane = body.body.planar_face(index as usize).ok_or_else(|| bad(cmd, "faces must be planar"))?;
if distance > (mesh.bounds().diagonal() * 1e-3).max(1e-3) * 10.0 {
return Err(bad(cmd, "no body face at a selected point"));
}
let tolerance = (body.body.size() * 1e-9).max(1e-8);
match groups
.iter_mut()
.find(|(n, base, _)| *n == name && base.normal().dot(plane.normal()) >= 1.0 - 1e-9 && base.height(plane.origin).abs() <= tolerance)
{
Some((_, _, run)) => run.push(point),
None => groups.push((name, plane, vec![point])),
}
}
Ok(groups.into_iter().map(|(_, _, run)| run).collect())
}
/// Coplanar faces share one linked profile sketch and one Extrude feature. Resolve every
/// pick before editing the document, so later picks never search an already modified body.
pub(super) fn sketch_of_faces(s: &mut Session, points: &[Vec3], cmd: &str, face_body: Option<&str>, fixed: bool) -> Result<(u64, Vec<Vec2>, String)> {
let first = points.first().copied().ok_or_else(|| bad(cmd, "faces must not be empty"))?;
if points.len() > 1024 {
return Err(bad(cmd, "faces exceed the 1024-face limit"));
}
let state = s.model.state();
let mut picked = Vec::new();
let mut common: Option<(String, solidcore_record::Plane)> = None;
for &point in points {
if !point.is_finite() {
return Err(bad(cmd, "faces must be finite points"));
}
let (mesh, index, distance, name) = face_at_in(s, point, face_body)
.map_err(|_| bad(cmd, "ambiguous face; specify face_body"))?
.ok_or_else(|| bad(cmd, "no body face at a selected point"))?;
let body = state.body(&name).ok_or_else(|| bad(cmd, "selected body disappeared"))?;
let plane = body.body.planar_face(index as usize).ok_or_else(|| bad(cmd, "faces must be planar"))?;
let tolerance = (body.body.size() * 1e-9).max(1e-8);
if distance > (mesh.bounds().diagonal() * 1e-3).max(1e-3) * 10.0 {
return Err(bad(cmd, "no body face at a selected point"));
}
if let Some((previous, base)) = &common {
if *previous != name || base.normal().dot(plane.normal()) < 1.0 - 1e-9 || base.height(plane.origin).abs() > tolerance {
return Err(bad(cmd, "faces must be coplanar, equally oriented faces of one body"));
}
} else {
common = Some((name.clone(), plane));
}
if picked.iter().any(|(face, _)| *face == index as usize) {
continue;
}
let inside = mesh
.triangles
.iter()
.zip(&mesh.tri_face)
.filter(|(_, face)| **face == index)
.filter_map(|(triangle, _)| mesh.tri(triangle))
.max_by(|[a, b, c], [x, y, z]| ((*b - *a).cross(*c - *a).len()).total_cmp(&((*y - *x).cross(*z - *x).len())))
.map(|[a, b, c]| (a + b + c) / 3.0)
.ok_or_else(|| bad(cmd, "degenerate face"))?;
picked.push((index as usize, inside));
}
let (id, first_inside, _) = sketch_of_face(s, first, cmd, face_body, fixed)?;
let (body, _) = common.ok_or_else(|| bad(cmd, "no faces selected"))?;
let doc = s.placed_document();
let source = state.body(&body).ok_or_else(|| bad(cmd, "source body disappeared"))?;
let component = doc.model_body_component(source);
let path = if component == s.active_component {
s.active_occurrence_path.clone().unwrap_or_else(|| doc.first_path(component))
} else {
let placements = super::component::properties::placements(&doc, cmd)?;
if placements.iter().filter(|(owner, _, _)| *owner == component).count() != 1 {
return Err(bad(cmd, "activate the selected occurrence before extruding its faces"));
}
doc.first_path(component)
};
let placement = EmbossFace::component_frame(&doc, component, &path)?;
let placement = doc.model_body_offset(source).map(|offset| mat_mul(&placement, offset)).unwrap_or(placement);
let author_path = s.active_occurrence_path.clone().unwrap_or_else(|| doc.first_path(s.active_component));
let author = EmbossFace::component_frame(&doc, s.active_component, &author_path)?;
let inverse = mat_inverse(&author).ok_or_else(|| bad(cmd, "invalid face profile author frame"))?;
let into_author = mat_mul(&inverse, &placement);
drop(doc);
let indices: Vec<_> = picked.iter().skip(1).map(|(index, _)| *index).collect();
super::sketch_project::project_internal_faces(s, id, &body, &indices)?;
s.refresh();
let plane = s.model.state().sketch(id).map(|sketch| sketch.plane).ok_or_else(|| bad(cmd, "face profile sketch disappeared"))?;
let mut selected = vec![first_inside];
selected.extend(picked.iter().skip(1).map(|(_, point)| plane.to_local(apply_point(&into_author, *point))));
Ok((id, selected, body))
}
/// Most edges a face used as a profile may have. Each one goes into the sketch, and with
/// thousands the result body's check alone takes minutes (#18061, #11574).
const MAX_PROFILE_EDGES: usize = 5000;
/// Whether a face with `edges` edges (seams left out) can be a profile. A face with too many is
/// refused with its count and the limit, so the user knows what is wrong (#18061).
fn profile_edge_count(cmd: &str, edges: usize) -> Result<()> {
if edges == 0 {
return Err(bad(cmd, "the face has no usable boundary"));
}
if edges > MAX_PROFILE_EDGES {
return Err(bad(cmd, format!("the face has {edges} edges; a face used as a profile can have at most {MAX_PROFILE_EDGES}")));
}
Ok(())
}
/// Start a sketch on the planar face at `point` holding a copy of the face boundary. Returns
/// the sketch id, a point inside the face (sketch coordinates), and the picked body's name.
/// The sketch is left active. `fixed` puts it on the face's plane as a fixed plane, which
/// doesn't follow later changes to the face: for a face whose history can't keep an
/// attachment (a converted mesh's, #6612), as the refusal of the attached sketch says.
pub(super) fn sketch_of_face(s: &mut Session, point: Vec3, cmd: &str, face_body: Option<&str>, fixed: bool) -> Result<(u64, Vec2, String)> {
let none = || match face_body {
Some(b) => bad(cmd, format!("no face of `{b}` at `face`")),
None => bad(cmd, "no body face at `face`"),
};
let (m, f, d, body) = face_at_in(s, point, face_body)
.map_err(|names| bad(cmd, format!("faces of several bodies meet at `face` ({}): name one with `face_body`", names.join(", "))))?
.ok_or_else(none)?;
let tol = (m.bounds().diagonal() * 1e-3).max(1e-3);
if d > tol * 10.0 {
return Err(none());
}
let tris: Vec<[Vec3; 3]> = m.triangles.iter().zip(&m.tri_face).filter(|(_, tf)| **tf == f).filter_map(|(t, _)| m.tri(t)).collect();
let normal = tris.iter().find_map(|[a, b, c]| (*b - *a).cross(*c - *a).normalized()).ok_or_else(|| bad(cmd, "degenerate face"))?;
if tris.iter().any(|[a, b, c]| (*b - *a).cross(*c - *a).normalized().is_some_and(|n| n.dot(normal) < 1.0 - 1e-6)) {
return Err(bad(cmd, "only planar faces can be extruded"));
}
// A point well inside the face: the centroid of its largest triangle.
let inside = tris
.iter()
.max_by(|x, y| (x[1] - x[0]).cross(x[2] - x[0]).len().total_cmp(&(y[1] - y[0]).cross(y[2] - y[0]).len()))
.map(|[a, b, c]| (*a + *b + *c) / 3.0)
.unwrap_or(point);
let edges: Vec<Vec<Vec3>> =
m.face_edges(f).into_iter().filter(|e| !m.seams.get(*e).copied().unwrap_or(false)).filter_map(|e| m.edges.get(e).cloned()).collect();
profile_edge_count(cmd, edges.len())?;
let run = |s: &mut Session, id: &str, p: Value| -> Result<Value> {
let spec = crate::find_command(id).ok_or_else(|| bad(cmd, id))?;
(spec.run)(s, &p)
};
// Command frame normalization already made `point` definition-local. Capture takes
// world coordinates; convert exactly once using the picked body's actual occurrence.
let state = s.model.state();
let doc = s.placed_document();
let picked = state.body(&body).ok_or_else(|| bad(cmd, "picked body disappeared"))?;
let component = doc.model_body_component(picked);
let path = if component == s.active_component {
s.active_occurrence_path.clone().unwrap_or_else(|| doc.first_path(component))
} else {
// The command mapper discarded the original placement when making this pick
// definition-local. A repeated cross-owner source cannot be re-found safely.
let placements = super::component::properties::placements(&doc, cmd)?;
if placements.iter().filter(|(owner, _, _)| *owner == component).count() != 1 {
return Err(bad(cmd, "activate the picked occurrence before generating a face profile from a repeated component"));
}
doc.first_path(component)
};
let placement = EmbossFace::component_frame(&doc, component, &path)?;
let placement = doc.model_body_offset(picked).map(|offset| mat_mul(&placement, offset)).unwrap_or(placement);
let world_inside = apply_point(&placement, inside);
let world_body = doc.world_body_name(&state, &body, component, &path);
let author_path = s.active_occurrence_path.clone().unwrap_or_else(|| doc.first_path(s.active_component));
let author = EmbossFace::component_frame(&doc, s.active_component, &author_path)?;
let author_inverse = mat_inverse(&author).ok_or_else(|| bad(cmd, "invalid face profile author frame"))?;
let author_inside = apply_point(&author_inverse, world_inside);
drop(doc);
let r = super::sketch::create_face_profile(
s,
&json!({"plane": {"face": [world_inside.x, world_inside.y, world_inside.z], "body": world_body, "index": f, "path":path, "fixed": fixed}, "project_edges": true}),
&body,
f as usize,
)?;
let sid = r.get("sketch").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "could not start a sketch on the face"))?;
s.refresh();
let plane = s.model.state().sketch(sid).map(|ss| ss.plane).ok_or_else(|| bad(cmd, "could not start a sketch on the face"))?;
// The face's edges came in as linked projections: they follow the face when earlier
// features change, so nothing is copied.
if r.get("projected").is_some_and(|x| !x.is_null()) {
return Ok((sid, plane.to_local(author_inside), body));
}
for e in &edges {
let pts: Vec<Vec2> = e.iter().map(|p| plane.to_local(*p)).collect();
let (Some(first), Some(last)) = (pts.first().copied(), pts.last().copied()) else { continue };
let closed = pts.len() > 3 && first.dist(last) < tol;
let circle = if pts.len() >= 4 {
let n = pts.len() - usize::from(closed);
let (a, b, c) = (pts.first(), pts.get(n / 3), pts.get(2 * n / 3));
match (a, b, c) {
(Some(a), Some(b), Some(c)) => circumcircle(*a, *b, *c).filter(|(o, r)| pts.iter().all(|q| (q.dist(*o) - r).abs() < tol)),
_ => None,
}
} else {
None
};
match circle {
Some((o, r)) if closed => run(s, "sketch.circle.center", json!({"center": xy(o), "radius": r}))?,
Some(_) => {
let mid = pts.get(pts.len() / 2).copied().unwrap_or(first);
run(s, "sketch.arc.three_point", json!({"start": xy(first), "end": xy(last), "through": xy(mid)}))?
}
None => {
let mut list: Vec<Value> = Vec::new();
for q in &pts {
// Drop points that repeat (a closed polyline ends where it starts).
if list.last().is_none_or(|l| l != &xy(*q)) {
list.push(xy(*q));
}
}
let closed_poly = list.len() > 2 && list.first() == list.last();
if closed_poly {
list.pop();
}
run(s, "sketch.line", json!({"points": list, "closed": closed_poly}))?
}
};
}
Ok((sid, plane.to_local(author_inside), body))
}
#[cfg(test)]
#[path = "face_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "face_join_tests.rs"]
mod join_tests;