diff --git a/crates/kernel/src/assemble.rs b/crates/kernel/src/assemble.rs new file mode 100644 index 000000000..49e0ed84c --- /dev/null +++ b/crates/kernel/src/assemble.rs @@ -0,0 +1,456 @@ +//! Bodies built face by face on the schema 4 record: an operation that rebuilds part of a body +//! from its own topology (an emboss on a cylinder, a raised band, a deleted face healed by its +//! neighbours) starts from the body's record, takes faces away, adds faces bounded by new or +//! existing edges, and finishes into a record in canonical order (docs/native-brep.md): pcurves +//! from the record's one routine ([`solidcraft_geom::brep::pcurve`]) for every new use, the +//! record's own for every use kept, edge uses, regions and shells. SMLib builds the body from +//! that record, as from any other. +//! +//! Faces keep the record's convention as the operation gives them: each face's loops are seen +//! from the side the material is not on (the outward side), the outer loop counter-clockwise +//! and holes clockwise there; [`Assembly::finish`] stores them relative to the surface's natural +//! normal, as the record does. + +use solidcraft_geom::Vec3; +use solidcraft_geom::brep::eval::{CurveEval, SurfaceEval}; +use solidcraft_geom::brep::pcurve::{EdgeUse, pcurves_within}; +use solidcraft_geom::brep::{Brep, Curve, Curve2, Edge, EdgeUseRef, Face, Loop, Natural, OrientedEdge, OrientedFace, Region, Shell, Surface, VERSION, Vertex}; + +use crate::body::Body; +use crate::history::{EdgeOrigin, EdgeProv, FaceProv, History}; +use crate::{KernelError, Result}; + +fn invalid(m: impl std::fmt::Display) -> KernelError { + KernelError::Failed(format!("rebuilding the B-rep: {m}")) +} + +/// One edge of the assembly: its curve on `interval`, from `vertices[0]` to `vertices[1]`. +#[derive(Clone, Debug)] +pub(crate) struct AEdge { + pub curve: Curve, + pub interval: [f64; 2], + pub vertices: [u32; 2], + pub tolerance: f64, + /// The source record's edge this edge is, kept as it was. + pub source: Option, +} + +/// One use of an edge in a face's loop: the loop runs along it from its start (`forward`) or +/// from its end, with the source record's pcurve where the use is one the record had. +#[derive(Clone, Debug)] +pub(crate) struct AUse { + pub edge: u32, + pub forward: bool, + pub given: Option, +} + +/// One face of the assembly: its surface, whether its natural normal points out of the +/// material, its loops (outer first) seen from outside, and the shell it belongs to (a shell of +/// the source record, by index). +#[derive(Clone, Debug)] +pub(crate) struct AFace { + pub surface: Surface, + pub natural_out: bool, + pub loops: Vec>, + pub shell: usize, + /// The source record's face whose surface and parameter box this face keeps. + pub domain: Option<[[f64; 2]; 2]>, +} + +/// A body taken apart: vertices, edges and faces that [`Assembly::finish`] builds into a record. +#[derive(Clone, Debug)] +pub(crate) struct Assembly { + pub tolerance: f64, + pub vertices: Vec, + pub edges: Vec, + /// `None`: a face taken away. + pub faces: Vec>, + /// The source's regions, by shell index (shells keep their indices; a shell left with no + /// face is dropped). + regions: Vec, + shells: usize, +} + +/// A finished record, with where each face of the assembly went in it (`None`: taken away). +pub(crate) struct Finished { + pub record: Brep, + pub faces: Vec>, + /// For each edge of the record, the assembly edge it is. + pub edges: Vec, +} + +impl Assembly { + /// The record `b` taken apart, every face and edge as it is (face i and edge i of the + /// assembly are the record's). Only face shells: a record with wire or vertex shells is not + /// rebuilt here. + pub(crate) fn from_record(b: &Brep) -> Result { + let mut faces: Vec> = vec![None; b.faces.len()]; + for (s, shell) in b.shells.iter().enumerate() { + let Shell::Faces { faces: uses, wires } = shell else { return Err(invalid("a wire or vertex shell")) }; + if !wires.is_empty() { + return Err(invalid("wire edges inside a shell")); + } + for of in uses { + let f = b.faces.get(of.face as usize).ok_or_else(|| invalid("face reference"))?; + let mut loops = Vec::with_capacity(f.loops.len()); + for l in &f.loops { + let Loop::Edges { edges } = l else { return Err(invalid("a vertex loop")) }; + let mut lp: Vec = edges.iter().map(|u| AUse { edge: u.edge, forward: u.forward, given: Some(u.pcurve.clone()) }).collect(); + // Stored about the natural normal; the assembly sees loops from outside. + if !of.forward { + reverse(&mut lp); + } + loops.push(lp); + } + let slot = faces.get_mut(of.face as usize).ok_or_else(|| invalid("face reference"))?; + if slot.is_some() { + return Err(invalid("a face used by two shells")); + } + *slot = Some(AFace { surface: f.surface.clone(), natural_out: of.forward, loops, shell: s, domain: Some(f.domain) }); + } + } + if faces.iter().any(Option::is_none) { + return Err(invalid("a face no shell uses")); + } + let edges = b + .edges + .iter() + .enumerate() + .map(|(i, e)| AEdge { curve: e.curve.clone(), interval: e.interval, vertices: e.vertices, tolerance: e.tolerance, source: Some(i) }) + .collect(); + Ok(Assembly { tolerance: b.tolerance, vertices: b.vertices.clone(), edges, faces, regions: b.regions.clone(), shells: b.shells.len() }) + } + + /// A new vertex at `p`. + pub(crate) fn vertex(&mut self, p: Vec3) -> Result { + if !p.is_finite() { + return Err(invalid("a vertex off the finite range")); + } + self.vertices.push(Vertex { point: [p.x, p.y, p.z], tolerance: self.tolerance }); + index(self.vertices.len() - 1) + } + + /// A vertex's point. + pub(crate) fn point(&self, v: u32) -> Option { + self.vertices.get(v as usize).map(|v| Vec3::from(v.point)) + } + + /// A new edge on `curve` over `interval`, from `a` to `b`. + pub(crate) fn edge(&mut self, curve: Curve, interval: [f64; 2], a: u32, b: u32) -> Result { + self.edges.push(AEdge { curve, interval, vertices: [a, b], tolerance: self.tolerance, source: None }); + index(self.edges.len() - 1) + } + + /// A new straight edge from vertex `a` to vertex `b` (t from 0 to 1). + pub(crate) fn line(&mut self, a: u32, b: u32) -> Result { + let (Some(p), Some(q)) = (self.point(a), self.point(b)) else { return Err(invalid("vertex reference")) }; + if p.dist(q) <= self.tolerance { + return Err(invalid("a line of no length")); + } + self.edge(Curve::Line { start: [p.x, p.y, p.z], end: [q.x, q.y, q.z] }, [0.0, 1.0], a, b) + } + + /// A new face. + pub(crate) fn face(&mut self, face: AFace) { + self.faces.push(Some(face)); + } + + /// Where an edge use starts and ends (in the loop's direction). + pub(crate) fn ends(&self, u: &AUse) -> Option<(u32, u32)> { + let e = self.edges.get(u.edge as usize)?; + let [a, b] = e.vertices; + Some(if u.forward { (a, b) } else { (b, a) }) + } + + /// The point of edge `e` at its parameter `t`. + pub(crate) fn edge_point(&self, e: u32, t: f64) -> Option { + let e = self.edges.get(e as usize)?; + CurveEval::new(&e.curve).ok()?.point(t) + } + + /// The record of the faces left and added, in canonical order. + pub(crate) fn finish(&self) -> Result { + // Faces in canonical order: by region, shell and the shell's own order (the assembly's). + let mut by_shell: Vec> = vec![Vec::new(); self.shells]; + for (i, f) in self.faces.iter().enumerate() { + if let Some(f) = f { + by_shell.get_mut(f.shell).ok_or_else(|| invalid("shell reference"))?.push(i); + } + } + let mut shell_order: Vec = Vec::new(); + let mut shell_new: Vec> = vec![None; self.shells]; + let mut regions: Vec = Vec::new(); + for region in &self.regions { + let mut shells = Vec::new(); + for &s in ®ion.shells { + let s = s as usize; + if by_shell.get(s).is_none_or(Vec::is_empty) { + continue; + } + let slot = shell_new.get_mut(s).ok_or_else(|| invalid("shell reference"))?; + let n = match slot { + Some(n) => *n, + None => { + let n = index(shell_order.len())?; + shell_order.push(s); + *slot = Some(n); + n + } + }; + shells.push(n); + } + // A bounded region whose outer shell went is gone (its faces were all taken away). + if regions.is_empty() || region.shells.first().is_some_and(|s| by_shell.get(*s as usize).is_some_and(|f| !f.is_empty())) { + regions.push(Region { shells, void: region.void }); + } + } + let order: Vec = shell_order.iter().filter_map(|s| by_shell.get(*s)).flatten().copied().collect(); + let mut face_map: Vec> = vec![None; self.faces.len()]; + for (k, i) in order.iter().enumerate() { + if let Some(slot) = face_map.get_mut(*i) { + *slot = Some(k); + } + } + // Each face's pcurves and stored loops, in canonical face order. + let mut faces: Vec = Vec::with_capacity(order.len()); + let mut forward: Vec = Vec::with_capacity(order.len()); + for &i in &order { + let f = self.faces.get(i).and_then(Option::as_ref).ok_or_else(|| invalid("face reference"))?; + let loops: Vec> = f + .loops + .iter() + .map(|l| { + let mut l = l.clone(); + if !f.natural_out { + reverse(&mut l); + } + l + }) + .collect(); + let uses: Vec>> = loops + .iter() + .map(|l| { + l.iter() + .map(|u| { + let e = self.edges.get(u.edge as usize).ok_or_else(|| invalid("edge reference"))?; + Ok(EdgeUse { edge: u.edge, curve: &e.curve, interval: e.interval, forward: u.forward, tolerance: e.tolerance, given: u.given.as_ref() }) + }) + .collect::>>() + }) + .collect::>()?; + let pcurves = pcurves_within(&f.surface, &uses, self.tolerance, f.domain).map_err(|e| invalid(format!("face {i}: {e}")))?; + let domain = domain_of(&f.surface, &pcurves, f.domain).ok_or_else(|| invalid(format!("face {i}: no parameter box")))?; + let stored = loops + .iter() + .zip(&pcurves) + .map(|(l, pc)| Loop::Edges { + edges: l.iter().zip(pc).map(|(u, pcurve)| OrientedEdge { edge: u.edge, forward: u.forward, pcurve: pcurve.clone() }).collect(), + }) + .collect(); + faces.push(Face { surface: f.surface.clone(), domain, loops: stored }); + forward.push(f.natural_out); + } + // Edges in first appearance walking faces → loops → uses (backwards in a face whose + // side in its shell is reversed), with their uses in that order. + let mut edge_new: Vec> = vec![None; self.edges.len()]; + let mut edge_order: Vec = Vec::new(); + let mut walked: Vec> = Vec::new(); + for (fi, (f, fw)) in faces.iter().zip(&forward).enumerate() { + for (li, l) in f.loops.iter().enumerate() { + let Loop::Edges { edges } = l else { continue }; + let n = edges.len(); + for k in 0..n { + let p = if *fw { k } else { n - 1 - k }; + let u = edges.get(p).ok_or_else(|| invalid("edge use"))?; + let slot = edge_new.get_mut(u.edge as usize).ok_or_else(|| invalid("edge reference"))?; + let ne = match slot { + Some(ne) => *ne, + None => { + let ne = index(edge_order.len())?; + edge_order.push(u.edge as usize); + walked.push(Vec::new()); + *slot = Some(ne); + ne + } + }; + let at = EdgeUseRef { face: index(fi)?, r#loop: index(li)?, position: index(p)?, upper: !u.forward }; + walked.get_mut(ne as usize).ok_or_else(|| invalid("edge use"))?.push(at); + } + } + } + for f in &mut faces { + for l in &mut f.loops { + if let Loop::Edges { edges } = l { + for u in edges { + u.edge = edge_new.get(u.edge as usize).copied().flatten().ok_or_else(|| invalid("edge reference"))?; + } + } + } + } + // Vertices in first appearance walking edges (start, end). + let mut vertex_new: Vec> = vec![None; self.vertices.len()]; + let mut vertices: Vec = Vec::new(); + let mut edges: Vec = Vec::with_capacity(edge_order.len()); + for (e, uses) in edge_order.iter().zip(walked) { + let a = self.edges.get(*e).ok_or_else(|| invalid("edge reference"))?; + let mut ends = [0u32; 2]; + for (slot, v) in ends.iter_mut().zip(a.vertices) { + let nv = vertex_new.get_mut(v as usize).ok_or_else(|| invalid("vertex reference"))?; + *slot = match nv { + Some(n) => *n, + None => { + let n = index(vertices.len())?; + vertices.push(self.vertices.get(v as usize).cloned().ok_or_else(|| invalid("vertex reference"))?); + *nv = Some(n); + n + } + }; + } + edges.push(Edge { curve: a.curve.clone(), interval: a.interval, vertices: ends, tolerance: a.tolerance, uses }); + } + let shells = shell_order + .iter() + .map(|s| { + let faces = by_shell + .get(*s) + .into_iter() + .flatten() + .map(|i| { + let k = face_map.get(*i).copied().flatten().ok_or_else(|| invalid("face reference"))?; + Ok(OrientedFace { face: index(k)?, forward: *forward.get(k).ok_or_else(|| invalid("face reference"))? }) + }) + .collect::>>()?; + Ok(Shell::Faces { faces, wires: Vec::new() }) + }) + .collect::>>()?; + let record = Brep { version: VERSION, tolerance: self.tolerance, regions, shells, faces, edges, vertices }; + record.validate().map_err(invalid)?; + record.check_geometry().map_err(invalid)?; + Ok(Finished { record, faces: face_map, edges: edge_order }) + } +} + +/// Reverse a loop: the same edges, the other way round. +fn reverse(l: &mut [AUse]) { + l.reverse(); + for u in l { + u.forward = !u.forward; + } +} + +fn index(i: usize) -> Result { + u32::try_from(i).map_err(|_| invalid("too many items")) +} + +/// A face's parameter box: the source face's where it kept it, else the box of its pcurves' +/// control points (which holds the curves), inside the surface's natural domain. +fn domain_of(surface: &Surface, pcurves: &[Vec], kept: Option<[[f64; 2]; 2]>) -> Option<[[f64; 2]; 2]> { + let mut lo = [f64::INFINITY; 2]; + let mut hi = [f64::NEG_INFINITY; 2]; + for c in pcurves.iter().flatten() { + let points: Vec<[f64; 2]> = match c { + Curve2::Spline { points, .. } => points.clone(), + Curve2::RationalSpline { homogeneous, .. } => homogeneous.iter().map(|h| [h[0] / h[2], h[1] / h[2]]).collect(), + }; + for p in points { + for d in 0..2 { + if let (Some(l), Some(h), Some(x)) = (lo.get_mut(d), hi.get_mut(d), p.get(d)) { + *l = l.min(*x); + *h = h.max(*x); + } + } + } + } + if let Some(k) = kept { + // The source's box, grown to hold any loop the face has now. + for d in 0..2 { + if let (Some(l), Some(h), Some(r)) = (lo.get_mut(d), hi.get_mut(d), k.get(d)) { + *l = l.min(r[0]); + *h = h.max(r[1]); + } + } + } + let natural = surface.natural(); + let mut out = [[0.0; 2]; 2]; + for d in 0..2 { + let (mut a, mut b) = (*lo.get(d)?, *hi.get(d)?); + if !(a.is_finite() && b.is_finite()) { + return None; + } + match natural.get(d)? { + Natural::Periodic => b = b.min(a + std::f64::consts::TAU), + Natural::Range(x, y) => { + a = a.max(*x); + b = b.min(*y); + } + } + if !(a < b) { + return None; + } + *out.get_mut(d)? = [a, b]; + } + Some(out) +} + +/// The body SMLib builds from `record`, and whether its faces and edges are numbered as the +/// record's (then face i of the body is face i of the record, and so for edges). +pub(crate) fn body_of(record: &Brep) -> Result<(Body, bool)> { + let (brep, same) = crate::native::smlib_record_ordered(record)?; + let (body, kept) = crate::native::body_from_smlib_ordered(&brep)?; + Ok((body, same.is_some() && kept.is_some())) +} + +/// The body of `finished`, built from the one operand `from`, with the history whose faces are +/// `faces` (in the assembly's face order, taken-away faces skipped): each kept edge the operand +/// edge it is, each new one where its two faces meet. No history where SMLib renumbered the +/// record. +pub(crate) fn body_with_history(finished: &Finished, assembly: &Assembly, from: &Body, faces: Vec) -> Result { + let (body, same) = body_of(&finished.record)?; + let counts = crate::record::counts(&[from]); + if !same { + return Ok(body.with_checked_history(None, &counts)); + } + // The provenance of each record face, from the assembly's face order. + let mut provs: Vec> = vec![None; finished.record.faces.len()]; + let mut given = faces.into_iter(); + for k in finished.faces.iter().flatten() { + let p = given.next().ok_or_else(|| invalid("history: fewer faces than the body"))?; + *provs.get_mut(*k).ok_or_else(|| invalid("history: face"))? = Some(p); + } + let faces: Vec = provs.into_iter().collect::>().ok_or_else(|| invalid("history: a face without provenance"))?; + let edges = finished + .record + .edges + .iter() + .zip(&finished.edges) + .map(|(e, a)| { + let mut between: Vec = e.uses.iter().map(|u| u.face as usize).collect(); + between.sort_unstable(); + between.dedup(); + let origins = match assembly.edges.get(*a).and_then(|x| x.source) { + Some(edge) => vec![EdgeOrigin::Edge { operand: 0, edge }], + None => crate::record::meeting(&between, &faces), + }; + EdgeProv { faces: between, origins } + }) + .collect(); + Ok(body.with_checked_history(Some(History { operands: 1, faces, edges }), &counts)) +} + +/// Whether the face `face` of `b` has its natural normal out of the material. +pub(crate) fn natural_out(b: &Brep, face: usize) -> Option { + b.shells.iter().find_map(|s| match s { + Shell::Faces { faces, .. } => faces.iter().find(|f| f.face as usize == face).map(|f| f.forward), + _ => None, + }) +} + +/// The outward unit normal of face `face` of `b` at the parameters of `p`, a point on it. +pub(crate) fn outward_normal(b: &Brep, face: usize, p: Vec3) -> Option { + let f = b.faces.get(face)?; + let s = SurfaceEval::new(&f.surface).ok()?; + let uv = s.project(p, None, f64::INFINITY)?; + let (_, su, sv) = s.derivs(uv[0], uv[1])?; + let n = su.cross(sv).normalized()?; + Some(if natural_out(b, face)? { n } else { -n }) +} diff --git a/crates/kernel/src/emboss.rs b/crates/kernel/src/emboss.rs index ec8563ef9..7e35b1cd3 100644 --- a/crates/kernel/src/emboss.rs +++ b/crates/kernel/src/emboss.rs @@ -1,12 +1,16 @@ -//! Exact radial embossing of orthogonal profiles on complete cylindrical walls. -use crate::body::{Body, Solid, from_p3, p3}; +//! Exact radial embossing of orthogonal profiles on complete cylindrical walls, built on the +//! body's schema 4 record: the wall's face loses the profiles' footprints, and each profile +//! adds its walls (planes, along the axis or square to it) and its raised or sunk cap (the +//! wall's cylinder at the new radius). +use crate::assemble::{AFace, AUse, Assembly}; +use crate::body::Body; use crate::history::Change; use crate::numbered::NumberedRegion; -use crate::offset::{Surf, surf_of}; -use crate::record::Operand; +use crate::offset::{Surf, face_edges, surf_of}; use crate::{KernelError, Result, guard}; +use solidcraft_geom::brep::eval::CurveEval; +use solidcraft_geom::brep::{Brep, Curve, Frame, Loop, Surface}; use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; -use truck_modeling::{self as mt, Transformed, builder}; fn fail(s: &str) -> KernelError { KernelError::Invalid(format!("cylinder emboss: {s}")) @@ -19,31 +23,51 @@ fn angle(p: Vec3, o: Vec3, axis: Vec3, radial: Vec3, tangent: Vec3) -> f64 { fn unwrap(a: f64, around: f64) -> f64 { around + (a - around + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI } +fn arr(v: Vec3) -> [f64; 3] { + [v.x, v.y, v.z] +} -fn wall_angles(face: &mt::Face, o: Vec3, axis: Vec3, radial: Vec3, tangent: Vec3, tol: f64) -> Option<(f64, f64)> { - if face.boundaries().len() != 1 || face.edge_iter().count() != 4 { +/// The angles a wall face spans about the axis, seen from `radial`: from one of its arcs about +/// the axis (a face of one loop of four edges). +fn wall_angles(b: &Brep, face: usize, o: Vec3, axis: Vec3, radial: Vec3, tangent: Vec3) -> Option<(f64, f64)> { + let f = b.faces.get(face)?; + let [Loop::Edges { edges }] = f.loops.as_slice() else { return None }; + if edges.len() != 4 { return None; } - for edge in face.edge_iter() { - if let Some(Some(mid)) = crate::offset::arc_mid(&edge, tol * 10.) { - let am = angle(mid, o, axis, radial, tangent); - let aa = unwrap(angle(from_p3(edge.front().point()), o, axis, radial, tangent), am); - let ab = unwrap(angle(from_p3(edge.back().point()), o, axis, radial, tangent), am); - return Some((aa.min(ab), aa.max(ab))); + for u in edges { + let e = b.edges.get(u.edge as usize)?; + let Curve::Circle { frame, .. } = &e.curve else { continue }; + let z = Vec3::from(frame.x_axis).cross(Vec3::from(frame.y_axis)); + if z.dot(axis).abs() < 1.0 - 1e-9 { + continue; } + let c = CurveEval::new(&e.curve).ok()?; + let [t0, t1] = e.interval; + let am = angle(c.point(0.5 * (t0 + t1))?, o, axis, radial, tangent); + let aa = unwrap(angle(c.point(t0)?, o, axis, radial, tangent), am); + let ab = unwrap(angle(c.point(t1)?, o, axis, radial, tangent), am); + return Some((aa.min(ab), aa.max(ab))); } None } +/// The body's record, for the queries below (a mesh body has none). +fn record(body: &Body) -> Result { + crate::native::brep_record(body) +} + /// Certify a tessellated pick and project it onto the cylinder used by emboss. pub fn cylinder_emboss_anchor(body: &Body, face: usize, at: Vec3) -> Result { if !at.is_finite() || at.len() > 1e9 { return Err(fail("invalid selected face point")); } guard("cylinder emboss anchor", || { - let f = body.solid.face_iter().nth(face).ok_or_else(|| fail("selected face"))?; - let tol = (body.size() * 1e-8).max(1e-8); - let Some(Surf::Cylinder { o, a, r, convex: true }) = surf_of(f, tol) else { + let rec = record(body)?; + if face >= rec.faces.len() { + return Err(fail("selected face")); + } + let Some(Surf::Cylinder { o, a, r, convex: true }) = surf_of(&rec, face) else { return Err(fail("selected face is not an exterior cylinder")); }; let w = at - o; @@ -92,13 +116,14 @@ pub fn infer_cylinder_emboss(body: &Body, plane: &Plane, regions: &[Region2], de return Ok(None); } guard("cylinder emboss inference", || { + let rec = record(body)?; let tol = (body.size() * 1e-8).max(1e-8); let mut tangent = false; - for (index, face) in body.solid.face_iter().enumerate() { - if index >= 50_000 { + for face in 0..rec.faces.len() { + if face >= 50_000 { return Err(fail("target search exceeds face work limit")); } - if let Some(Surf::Cylinder { o, a, r, convex: true }) = surf_of(face, tol) { + if let Some(Surf::Cylinder { o, a, r, convex: true }) = surf_of(&rec, face) { let w = plane.origin - o; let normal = plane.normal(); let signed = w.dot(normal); @@ -111,7 +136,7 @@ pub fn infer_cylinder_emboss(body: &Body, plane: &Plane, regions: &[Region2], de if !profile_interval_overlaps(plane, regions, o, a.cross(radial), -std::f64::consts::PI * r, std::f64::consts::PI * r)? { continue; } - if let Some((lo, hi)) = wall_angles(face, o, a, radial, a.cross(radial), tol) { + if let Some((lo, hi)) = wall_angles(&rec, face, o, a, radial, a.cross(radial)) { if lo >= -tol / r || hi <= tol / r { continue; } @@ -119,7 +144,7 @@ pub fn infer_cylinder_emboss(body: &Body, plane: &Plane, regions: &[Region2], de continue; } } - let relevant = match face_axial_bounds(face, o, a)? { + let relevant = match face_axial_bounds(&rec, face, o, a)? { Some((lo, hi)) => profile_interval_overlaps(plane, regions, o, a, lo, hi)?, None => true, }; @@ -148,18 +173,14 @@ pub fn has_cylinder_emboss_wall(body: &Body) -> Result { return Ok(false); } guard("cylinder emboss target", || { - let tol = (body.size() * 1e-8).max(1e-8); - for (index, face) in body.solid.face_iter().enumerate() { - if index >= 50_000 { - return Err(fail("target search exceeds face work limit")); - } - if matches!(surf_of(face, tol), Some(Surf::Cylinder { convex: true, .. })) { - return Ok(true); - } + let rec = record(body)?; + if rec.faces.len() > 50_000 { + return Err(fail("target search exceeds face work limit")); } - Ok(false) + Ok((0..rec.faces.len()).any(|face| matches!(surf_of(&rec, face), Some(Surf::Cylinder { convex: true, .. })))) }) } + fn emboss_impl(body: &Body, anchor: Option, plane: &Plane, regions: &[Region2], depth: f64, qualify: bool) -> Result { body.require_brep("cylinder emboss")?; if !depth.is_finite() || depth.abs() < 1e-6 || depth.abs() > 1e6 || regions.is_empty() || regions.len() > 64 { @@ -175,13 +196,14 @@ fn emboss_impl(body: &Body, anchor: Option, plane: &Plane, regions: &[Regi return Err(fail("invalid sketch frame")); } guard("cylinder emboss", || { - if body.solid.boundaries().len() != 1 || body.solid.face_iter().take(17).count() > 16 || body.solid.edge_iter().take(257).count() > 256 { + let rec = record(body)?; + if rec.shells.len() != 1 || rec.faces.len() > 16 || rec.edges.len() > 256 { return Err(fail("requires a complete cylinder or coaxial sleeve")); } - let faces: Vec<_> = body.solid.face_iter().cloned().collect(); let tol = (body.size() * 1e-8).max(1e-8); - let surfaces: Vec<_> = - faces.iter().map(|f| surf_of(f, tol).ok_or_else(|| fail("requires only cylindrical walls and planar endcaps"))).collect::>()?; + let surfaces: Vec = (0..rec.faces.len()) + .map(|f| surf_of(&rec, f).ok_or_else(|| fail("requires only cylindrical walls and planar endcaps"))) + .collect::>()?; let mut chosen = None; for (fi, s) in surfaces.iter().enumerate() { let Surf::Cylinder { o, a, r, convex: true } = *s else { continue }; @@ -192,11 +214,7 @@ fn emboss_impl(body: &Body, anchor: Option, plane: &Plane, regions: &[Regi } let radial = radial.normalized().ok_or_else(|| fail("radial frame"))?; let tangent = a.cross(radial); - let f = faces.get(fi).ok_or_else(|| fail("face"))?; - if f.boundaries().len() != 1 || f.edge_iter().count() != 4 { - continue; - } - let Some((alo, ahi)) = wall_angles(f, o, a, radial, tangent, tol) else { + let Some((alo, ahi)) = wall_angles(&rec, fi, o, a, radial, tangent) else { continue; }; if alo >= -tol / r || ahi <= tol / r { @@ -246,10 +264,13 @@ fn emboss_impl(body: &Body, anchor: Option, plane: &Plane, regions: &[Regi return Err(fail("depth reaches the axis or inner wall")); } if let Some(at) = anchor { + // The saved pick identifies the wall, not the face the sketch is tangent to: every + // exterior cylindrical face of the body is that wall (a stepped or interrupted + // cylinder was refused above), stored as several faces between its seams. So the + // pick lies on it wherever it is on the cylinder between the endcaps (#3782). let h = (at - o).dot(axis); let v = at - o - axis * h; - let theta = angle(at, o, axis, radial, tangent); - if (v.len() - r).abs() > tol * 10.0 || theta <= alo + tol / r || theta >= ahi - tol / r || h <= lo + tol || h >= hi - tol { + if (v.len() - r).abs() > tol * 10.0 || h <= lo + tol || h >= hi - tol { return Err(fail("saved selection no longer identifies the sketch's cylindrical face")); } } @@ -307,39 +328,15 @@ fn emboss_impl(body: &Body, anchor: Option, plane: &Plane, regions: &[Regi let at = o + axis * p.y + (radial * (p.x / r).cos() + tangent * (p.x / r).sin()) * r; return Ok(EmbossOutcome::Anchor(fi, at)); } - let at = |p: Vec2, radius: f64| o + axis * p.y + (radial * (p.x / r).cos() + tangent * (p.x / r).sin()) * radius; - let selected = faces.get(fi).ok_or_else(|| fail("face"))?; - let mut base_patches = vec![selected.absolute_boundaries().clone()]; + let wall = Wrap { o, axis, radial, tangent, r }; + let mut asm = Assembly::from_record(&rec)?; + let selected = asm.faces.get_mut(fi).and_then(Option::take).ok_or_else(|| fail("face"))?; + // The wall's pieces left around the footprints: the face itself, then one per profile + // hole (the original radius inside it). + let mut base_patches: Vec>> = vec![selected.loops.clone()]; let mut hole_patches = Vec::new(); let mut footprints = Vec::new(); - let mut added = Vec::new(); - let k = rr / r; - let coord = |v: Vec3| [v.x, v.y, v.z]; - let av = coord(axis); - let ov = coord(o); - let mut m = [[0.0; 4]; 4]; - for (j, col) in m.iter_mut().take(3).enumerate() { - for (i, slot) in col.iter_mut().take(3).enumerate() { - *slot = if i == j { k } else { 0.0 } + (1.0 - k) * av.get(i).copied().unwrap_or(0.0) * av.get(j).copied().unwrap_or(0.0); - } - } - for (i, oi) in ov.iter().enumerate() { - let translation = - *oi - (0..3).map(|j| m.get(j).and_then(|row| row.get(i)).copied().unwrap_or(0.0) * ov.get(j).copied().unwrap_or(0.0)).sum::(); - if let Some(slot) = m.get_mut(3).and_then(|row| row.get_mut(i)) { - *slot = translation; - } - } - if let Some(slot) = m.get_mut(3).and_then(|row| row.get_mut(3)) { - *slot = 1.0; - } - let [c0, c1, c2, c3] = m; - let [a, b, c, d] = c0; - let [e, f, g, h] = c1; - let [i, j, l, n] = c2; - let [p, q, s, t] = c3; - let mat = mt::Matrix4::new(a, b, c, d, e, f, g, h, i, j, l, n, p, q, s, t); - let raised = selected.oriented_surface().transformed(mat); + let mut added: Vec = Vec::new(); // History of the faces added (walls from their profile segments, the raised or sunk // region the profile's end cap), in the order added. let mut added_history = Vec::new(); @@ -347,20 +344,21 @@ fn emboss_impl(body: &Body, anchor: Option, plane: &Plane, regions: &[Regi let mut cap = Vec::new(); for (li, numbered_loop) in reg.loops().enumerate() { let lp = &numbered_loop.lp; - let (base, top, walls) = wrapped_loop(lp, r, rr, &at)?; + let (base, top, walls) = wall.wrapped_loop(&mut asm, lp, rr, selected.shell)?; // One wall per segment, in order. added_history.extend((0..walls.len()).map(|j| crate::record::profile(numbered_loop.numbers(j)))); + let hole = reversed(&base); if li == 0 { - footprints.push((lp, base.inverse())); + footprints.push((lp, hole)); } else { let index = base_patches.len(); - base_patches.push(vec![base.inverse()]); + base_patches.push(vec![hole]); hole_patches.push((lp, index)); } cap.push(top); added.extend(walls); } - added.push(mt::Face::try_new(cap, raised.clone()).map_err(|e| fail(&e.to_string()))?); + added.push(AFace { surface: wall.cylinder(rr), natural_out: true, loops: cap, shell: selected.shell, domain: None }); added_history.push(crate::record::cap(true)); } // An island inside a profile hole cuts that hole's original-radius patch, @@ -375,27 +373,176 @@ fn emboss_impl(body: &Body, anchor: Option, plane: &Plane, regions: &[Regi .unwrap_or(0); base_patches.get_mut(owner).ok_or_else(|| fail("profile ownership"))?.push(wire); } - let mut all: Vec<_> = faces.iter().enumerate().filter(|(i, _)| *i != fi).map(|(_, f)| f.clone()).collect(); // History (one operand, the body; profile numbering over `regions`), face by face as // gathered: the other faces kept, the wall's pieces left around the footprints (split // when the profile's holes leave more than one), then the faces added. let pieces = if base_patches.len() > 1 { Change::Split } else { Change::Modified }; - let mut history: Vec<_> = crate::record::kept_except(faces.len(), fi).collect(); + let mut history: Vec<_> = crate::record::kept_except(rec.faces.len(), fi).collect(); history.extend(std::iter::repeat_n(crate::record::from_face(0, fi, pieces), base_patches.len())); history.extend(added_history); - for patch in base_patches { - all.push(mt::Face::try_new(patch, selected.oriented_surface()).map_err(|e| fail(&e.to_string()))?); + for (k, loops) in base_patches.into_iter().enumerate() { + // The face's own parameter box only where it keeps its outer loop. + let domain = if k == 0 { selected.domain } else { None }; + asm.face(AFace { surface: selected.surface.clone(), natural_out: selected.natural_out, loops, shell: selected.shell, domain }); } - all.extend(added); - let solid = Solid::try_new(vec![all.into()]).map_err(|e| fail(&e.to_string()))?; - let result = Body::new(solid)?; + for f in added { + asm.face(f); + } + let finished = asm.finish()?; + let result = crate::assemble::body_with_history(&finished, &asm, body, history)?; if !result.validity().is_empty() { return Err(fail("rebuilt cylinder is not a closed manifold")); } - Ok(EmbossOutcome::Body(crate::record::attach(result, &[Operand::new(body)], Some(history), Default::default())?)) + Ok(EmbossOutcome::Body(result)) }) } +/// A loop's uses the other way round. +fn reversed(l: &[AUse]) -> Vec { + l.iter().rev().map(|u| AUse { edge: u.edge, forward: !u.forward, given: None }).collect() +} + +/// The wall a profile wraps onto: its axis, the sketch's radial and tangent directions there, +/// and its radius. +struct Wrap { + o: Vec3, + axis: Vec3, + radial: Vec3, + tangent: Vec3, + r: f64, +} + +impl Wrap { + /// The point at wrapped profile coordinates `p` (arc length at the wall, height) at `radius`. + fn at(&self, p: Vec2, radius: f64) -> Vec3 { + let t = p.x / self.r; + self.o + self.axis * p.y + (self.radial * t.cos() + self.tangent * t.sin()) * radius + } + + /// The wall's cylinder at `radius` (its angle measured from the sketch's radial). + fn cylinder(&self, radius: f64) -> Surface { + Surface::Cylinder { frame: Frame { origin: arr(self.o), x_axis: arr(self.radial), y_axis: arr(self.tangent) }, radius } + } + + /// An edge from vertex `a` at `p` to vertex `b` at `q` (wrapped coordinates) at `radius`: + /// an arc about the axis where the segment runs round the wall, else a line along it. The + /// use that runs from `a` to `b`. + fn edge(&self, asm: &mut Assembly, a: u32, b: u32, p: Vec2, q: Vec2, radius: f64) -> Result { + if (q.x - p.x).abs() <= 1e-10 { + return Ok(AUse { edge: asm.line(a, b)?, forward: true, given: None }); + } + let frame = Frame { origin: arr(self.o + self.axis * p.y), x_axis: arr(self.radial), y_axis: arr(self.tangent) }; + let (ta, tb) = (p.x / self.r, q.x / self.r); + let forward = ta < tb; + let (interval, ends) = if forward { ([ta, tb], (a, b)) } else { ([tb, ta], (b, a)) }; + Ok(AUse { edge: asm.edge(Curve::Circle { frame, radius }, interval, ends.0, ends.1)?, forward, given: None }) + } + + /// A profile loop wrapped onto the wall: its footprint at the wall's radius and its cap's + /// loop at `rr`, both running as the loop does, and one planar wall per segment between + /// them (each loop seen from outside the body). + fn wrapped_loop(&self, asm: &mut Assembly, lp: &Loop2, rr: f64, shell: usize) -> Result<(Vec, Vec, Vec)> { + let corners: Vec = lp.segs.iter().map(Seg2::start).collect(); + let base: Vec = corners.iter().map(|p| asm.vertex(self.at(*p, self.r))).collect::>()?; + let top: Vec = corners.iter().map(|p| asm.vertex(self.at(*p, rr))).collect::>()?; + let radial: Vec = base.iter().zip(&top).map(|(a, b)| asm.line(*a, *b)).collect::>()?; + let n = corners.len(); + let (mut be, mut te, mut walls) = (Vec::with_capacity(n), Vec::with_capacity(n), Vec::with_capacity(n)); + for i in 0..n { + let j = (i + 1) % n; + let (Some(&p), Some(&q), Some(&ba), Some(&bb), Some(&ta), Some(&tb), Some(&ra), Some(&rb)) = + (corners.get(i), corners.get(j), base.get(i), base.get(j), top.get(i), top.get(j), radial.get(i), radial.get(j)) + else { + return Err(fail("loop topology")); + }; + let eb = self.edge(asm, ba, bb, p, q, self.r)?; + let et = self.edge(asm, ta, tb, p, q, rr)?; + // The wall's plane, its natural normal along the loop's turning: out of the + // material whether the cap is raised or sunk. + let mid = (p + q) * 0.5; + let ring = [self.at(p, self.r), self.at(mid, self.r), self.at(q, self.r), self.at(q, rr), self.at(mid, rr), self.at(p, rr)]; + let normal = newell(&ring).ok_or_else(|| fail("a wall of no area"))?; + let u = (ring[2] - ring[0]).normalized().ok_or_else(|| fail("a wall of no width"))?; + let u = (u - normal * u.dot(normal)).normalized().ok_or_else(|| fail("a wall of no width"))?; + let surface = Surface::Plane { origin: arr(ring[0]), u_axis: arr(u), v_axis: arr(normal.cross(u)) }; + let lp = vec![ + eb.clone(), + AUse { edge: rb, forward: true, given: None }, + AUse { edge: et.edge, forward: !et.forward, given: None }, + AUse { edge: ra, forward: false, given: None }, + ]; + walls.push(AFace { surface, natural_out: true, loops: vec![lp], shell, domain: None }); + be.push(eb); + te.push(et); + } + Ok((be, te, walls)) + } +} + +/// The unit normal of a planar ring of points, along its turning (right-hand rule). +fn newell(ring: &[Vec3]) -> Option { + let n = ring.len(); + let mut s = Vec3::ZERO; + for i in 0..n { + let (a, b) = (*ring.get(i)?, *ring.get((i + 1) % n)?); + s = s + a.cross(b); + } + s.normalized() +} + +/// The span along `axis` from `o` of face `face`'s edges, from their exact bounds (a line's +/// ends, a circle's extreme heights, a spline's control points); `None` for any other curve. +fn face_axial_bounds(b: &Brep, face: usize, o: Vec3, axis: Vec3) -> Result> { + let mut lo = f64::INFINITY; + let mut hi = f64::NEG_INFINITY; + let mut count = 0usize; + let mut add = |z0: f64, z1: f64| -> Result<()> { + count = count.saturating_add(1); + if count > 100_000 || !z0.is_finite() || !z1.is_finite() { + return Err(fail("target boundary work limit or nonfinite geometry")); + } + lo = lo.min(z0); + hi = hi.max(z1); + Ok(()) + }; + let height = |p: Vec3| (p - o).dot(axis); + for e in face_edges(b, face) { + let edge = b.edges.get(e as usize).ok_or_else(|| fail("edge"))?; + match &edge.curve { + Curve::Line { .. } => { + let c = CurveEval::new(&edge.curve).map_err(|e| fail(&e.to_string()))?; + for t in edge.interval { + let z = height(c.point(t).ok_or_else(|| fail("edge point"))?); + add(z, z)?; + } + } + Curve::Circle { frame, radius } => { + let (x, y) = (Vec3::from(frame.x_axis), Vec3::from(frame.y_axis)); + let z = height(Vec3::from(frame.origin)); + let reach = radius * x.dot(axis).hypot(y.dot(axis)); + add(z - reach, z + reach)?; + } + Curve::Spline { points, .. } => { + for p in points { + let z = height(Vec3::from(*p)); + add(z, z)?; + } + } + Curve::RationalSpline { homogeneous, .. } => { + for h in homogeneous { + if !h[3].is_finite() || h[3] <= 0.0 { + return Ok(None); + } + let z = height(Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3])); + add(z, z)?; + } + } + Curve::Ellipse { .. } | Curve::Polyline { .. } | Curve::SurfaceIntersection { .. } => return Ok(None), + } + } + Ok((lo.is_finite() && hi.is_finite()).then_some((lo, hi))) +} + fn profile_interval_overlaps(plane: &Plane, regions: &[Region2], o: Vec3, axis: Vec3, lo: f64, hi: f64) -> Result { let z0 = (plane.origin - o).dot(axis); let direction = Vec2::new(plane.x.dot(axis), plane.y.dot(axis)); @@ -455,70 +602,6 @@ fn profile_interval_overlaps(plane: &Plane, regions: &[Region2], o: Vec3, axis: Ok(overlaps) } -fn face_axial_bounds(face: &mt::Face, o: Vec3, axis: Vec3) -> Result> { - let mut lo = f64::INFINITY; - let mut hi = f64::NEG_INFINITY; - let mut count = 0usize; - let mut add = |point: Vec3| -> Result<()> { - count = count.saturating_add(1); - if count > 100_000 || !point.is_finite() { - return Err(fail("target boundary work limit or nonfinite geometry")); - } - let z = (point - o).dot(axis); - lo = lo.min(z); - hi = hi.max(z); - Ok(()) - }; - for edge in face.edge_iter() { - match edge.curve() { - mt::Curve::Line(_) => { - add(from_p3(edge.front().point()))?; - add(from_p3(edge.back().point()))?; - } - mt::Curve::BSplineCurve(curve) => { - for point in curve.control_points() { - add(from_p3(*point))?; - } - } - mt::Curve::NurbsCurve(curve) => { - for point in curve.control_points() { - if !point.w.is_finite() || point.w <= 0.0 { - return Ok(None); - } - add(Vec3::new(point.x / point.w, point.y / point.w, point.z / point.w))?; - } - } - mt::Curve::IntersectionCurve(_) => return Ok(None), - } - } - Ok((lo.is_finite() && hi.is_finite()).then_some((lo, hi))) -} - -fn wrapped_loop(lp: &Loop2, r: f64, rr: f64, at: &impl Fn(Vec2, f64) -> Vec3) -> Result<(mt::Wire, mt::Wire, Vec)> { - let base: Vec<_> = lp.segs.iter().map(|s| builder::vertex(p3(at(s.start(), r)))).collect(); - let top: Vec<_> = lp.segs.iter().map(|s| builder::vertex(p3(at(s.start(), rr)))).collect(); - let radial: Vec<_> = base.iter().zip(&top).map(|(a, b)| builder::line(a, b)).collect(); - let mut be = Vec::new(); - let mut te = Vec::new(); - let mut walls = Vec::new(); - for (i, s) in lp.segs.iter().enumerate() { - let next = (i + 1) % lp.segs.len(); - let (Some(a), Some(b), Some(c), Some(d), Some(ra), Some(rb)) = - (base.get(i), base.get(next), top.get(i), top.get(next), radial.get(i), radial.get(next)) - else { - return Err(fail("loop topology")); - }; - let circular = (s.end().x - s.start().x).abs() > 1e-10; - let eb = if circular { builder::circle_arc(a, b, p3(at(s.mid(), r))) } else { builder::line(a, b) }; - let et = if circular { builder::circle_arc(c, d, p3(at(s.mid(), rr))) } else { builder::line(c, d) }; - let w: mt::Wire = vec![eb.clone(), rb.clone(), et.inverse(), ra.inverse()].into(); - walls.push(builder::try_attach_plane(&[w]).map_err(|e| fail(&e.to_string()))?); - be.push(eb); - te.push(et); - } - Ok((be.into(), te.into(), walls)) -} - fn validate_profiles(regions: &[Region2], tol: f64) -> Result<()> { let loops: Vec<_> = regions.iter().flat_map(|r| std::iter::once(&r.outer).chain(&r.holes)).collect(); let edges: Vec<_> = loops.iter().enumerate().flat_map(|(l, lp)| lp.segs.iter().enumerate().map(move |(i, s)| (l, i, *s))).collect(); @@ -744,7 +827,9 @@ mod tests { ] { assert!(emboss_cylinder(&sleeve, &plane(), &profiles, d).is_err()); } - assert!(emboss_cylinder_at(&sleeve, -Vec3::Y * 10. + Vec3::Z * 7.5, &plane(), &[profile()], 1.).is_err()); + // A pick anywhere on the exterior wall identifies it (#3782); one on the bore does not. + assert!(emboss_cylinder_at(&sleeve, -Vec3::Y * 10. + Vec3::Z * 7.5, &plane(), &[profile()], 1.).is_ok()); + assert!(emboss_cylinder_at(&sleeve, -Vec3::Y * 8. + Vec3::Z * 7.5, &plane(), &[profile()], 1.).is_err()); assert_eq!(crate::step_export(&[&sleeve], "unchanged").unwrap(), before); } } diff --git a/crates/kernel/src/offset.rs b/crates/kernel/src/offset.rs index 264b82387..f482d6cea 100644 --- a/crates/kernel/src/offset.rs +++ b/crates/kernel/src/offset.rs @@ -1,19 +1,13 @@ -//! Topology-preserving face offsets for bodies made of planes and cylinders (shells, offset -//! faces). Each face moves along its outward normal by its own distance: a plane is translated, -//! a cylinder changes radius about its axis. Every vertex and edge goes to where its faces' -//! moved surfaces meet; edges are lines or circular arcs. This is exact when the moved -//! surfaces meet the way the old ones did (prismatic parts, bosses, fillets between walls). -//! A corner where more than three planes meet, whose moved planes miss a common point (a -//! floor falling to a drain, a pyramid's apex), becomes several corners joined by short edges. -//! Anything else is refused, so callers can fall back. - -use std::collections::HashMap; +//! What analytic surface a face of the schema 4 record lies on, with its outward side, and the +//! faces that continue a chosen face on the same surface (a hole's wall stored in halves). +//! Moving faces along their normals (offset faces, shell, draft) is SMLib's +//! (`crate::offset_backend`). use solidcraft_geom::Vec3; -use truck_modeling::{self as mt, builder}; +use solidcraft_geom::brep::eval::CurveEval; +use solidcraft_geom::brep::{Brep, Frame, Loop, Surface}; -use crate::body::{Body, Solid, from_p3, p3}; -use crate::{KernelError, Result, guard}; +use crate::body::Body; #[derive(Clone, Copy, Debug)] pub(crate) enum Surf { @@ -28,17 +22,51 @@ pub(crate) enum Surf { /// outward normal points away from the axis. Cone { v: Vec3, a: Vec3, half: f64, convex: bool }, /// Axis point and unit axis, the tube's centre circle (radius `big` at height `h` along the - /// axis) and the tube radius; `big` is negative on the inner sheet of a spindle torus, - /// whose meridian circle's centre lies across the axis. `convex` when the outward normal - /// points away from the tube's centre. + /// axis) and the tube radius; `convex` when the outward normal points away from the tube's + /// centre. Torus { o: Vec3, a: Vec3, big: f64, h: f64, r: f64, convex: bool }, } -/// The centre of a torus tube nearest `p`. -fn tube_centre(o: Vec3, a: Vec3, big: f64, h: f64, p: Vec3) -> Option { - let w = p - o; - let u = (w - a * w.dot(a)).normalized()?; - Some(o + a * h + u * big) +fn axes(f: &Frame) -> Option<(Vec3, Vec3)> { + let (x, y) = (Vec3::from(f.x_axis), Vec3::from(f.y_axis)); + Some((Vec3::from(f.origin), x.cross(y).normalized()?)) +} + +/// What surface face `face` of the record `b` lies on, as its record says (planes, cylinders, +/// cones, spheres and tori; `None` for a free-form face). The record's analytic surfaces have +/// their natural normals away from their axis or centre, so a face is convex when its shell +/// uses its natural side. +pub(crate) fn surf_of(b: &Brep, face: usize) -> Option { + let f = b.faces.get(face)?; + let out = crate::assemble::natural_out(b, face)?; + let sign = if out { 1.0 } else { -1.0 }; + Some(match &f.surface { + Surface::Plane { origin, u_axis, v_axis } => { + let n = Vec3::from(*u_axis).cross(Vec3::from(*v_axis)).normalized()? * sign; + Surf::Plane { n, d: n.dot(Vec3::from(*origin)) } + } + Surface::PlaneThrough { origin, u_point, v_point } => { + let o = Vec3::from(*origin); + let n = (Vec3::from(*u_point) - o).cross(Vec3::from(*v_point) - o).normalized()? * sign; + Surf::Plane { n, d: n.dot(o) } + } + Surface::Cylinder { frame, radius } => { + let (o, a) = axes(frame)?; + Surf::Cylinder { o, a, r: *radius, convex: out } + } + Surface::Sphere { frame, radius } => Surf::Sphere { c: Vec3::from(frame.origin), r: *radius, convex: out }, + Surface::Cone { frame, radius_at_origin, half_angle } => { + let (o, z) = axes(frame)?; + let apex = o + z * (-radius_at_origin / half_angle.tan()); + let a = if *half_angle > 0.0 { z } else { -z }; + Surf::Cone { v: apex, a, half: half_angle.abs(), convex: out } + } + Surface::Torus { frame, major_radius, minor_radius } => { + let (o, a) = axes(frame)?; + Surf::Torus { o, a, big: *major_radius, h: 0.0, r: *minor_radius, convex: out } + } + Surface::Spline { .. } | Surface::RationalSpline { .. } | Surface::PlacedRevolution { .. } => return None, + }) } impl Surf { @@ -62,1386 +90,81 @@ impl Surf { Some(if convex { n } else { -n }) } Surf::Torus { o, a, big, h, convex, .. } => { - let n = (p - tube_centre(o, a, big, h, p)?).normalized()?; + let w = p - o; + let u = (w - a * w.dot(a)).normalized()?; + let n = (p - (o + a * h + u * big)).normalized()?; Some(if convex { n } else { -n }) } } } - /// The gradient of [`Surf::dist`] (the normal before orientation). - fn grad(&self, p: Vec3) -> Option { - match *self { - Surf::Plane { n, .. } => Some(n), - Surf::Cylinder { convex, .. } | Surf::Sphere { convex, .. } | Surf::Cone { convex, .. } | Surf::Torus { convex, .. } => { - self.normal(p).map(|n| if convex { n } else { -n }) + + /// Whether `other` is this surface, with the same outward side, within `tol`. + pub(crate) fn same(&self, other: &Surf, tol: f64) -> bool { + match (*self, *other) { + (Surf::Plane { n, d }, Surf::Plane { n: m, d: e }) => n.dot(m) > 1.0 - 1e-9 && (d - e).abs() < tol, + (Surf::Cylinder { o, a, r, convex }, Surf::Cylinder { o: o2, a: a2, r: r2, convex: c2 }) => { + a.dot(a2).abs() > 1.0 - 1e-9 && (r - r2).abs() < tol && convex == c2 && (o2 - o - a * (o2 - o).dot(a)).len() < tol } - } - } - fn moved(&self, s: f64) -> Option { - match *self { - Surf::Plane { n, d } => Some(Surf::Plane { n, d: d + s }), - Surf::Cylinder { o, a, r, convex } => { - let r2 = if convex { r + s } else { r - s }; - (r2 > 1e-9).then_some(Surf::Cylinder { o, a, r: r2, convex }) + (Surf::Sphere { c, r, convex }, Surf::Sphere { c: c2, r: r2, convex: k2 }) => c.dist(c2) < tol && (r - r2).abs() < tol && convex == k2, + (Surf::Cone { v, a, half, convex }, Surf::Cone { v: v2, a: a2, half: h2, convex: k2 }) => { + v.dist(v2) < tol && a.dot(a2) > 1.0 - 1e-9 && (half - h2).abs() < 1e-9 && convex == k2 } - Surf::Sphere { c, r, convex } => { - let r2 = if convex { r + s } else { r - s }; - (r2 > 1e-9).then_some(Surf::Sphere { c, r: r2, convex }) + (Surf::Torus { o, a, big, h, r, convex }, Surf::Torus { o: o2, a: a2, big: b2, h: h2, r: r2, convex: k2 }) => { + (o + a * h).dist(o2 + a2 * h2) < tol && a.dot(a2).abs() > 1.0 - 1e-9 && (big - b2).abs() < tol && (r - r2).abs() < tol && convex == k2 } - // Moving a cone along its normal moves its apex along the axis. - Surf::Cone { v, a, half, convex } => { - let s = if convex { s } else { -s }; - let sh = half.sin(); - (sh > 1e-9).then_some(Surf::Cone { v: v - a * (s / sh), a, half, convex }) - } - Surf::Torus { o, a, big, h, r, convex } => { - let r2 = if convex { r + s } else { r - s }; - (r2 > 1e-9).then_some(Surf::Torus { o, a, big, h, r: r2, convex }) - } - } - } - fn dist(&self, p: Vec3) -> f64 { - match *self { - Surf::Plane { n, d } => n.dot(p) - d, - Surf::Cylinder { o, a, r, .. } => { - let v = p - o; - (v - a * v.dot(a)).len() - r - } - Surf::Sphere { c, r, .. } => p.dist(c) - r, - Surf::Cone { v, a, half, .. } => { - let w = p - v; - let h = w.dot(a); - (w - a * h).len() * half.cos() - h * half.sin() - } - Surf::Torus { o, a, big, h, r, .. } => tube_centre(o, a, big, h, p).map(|c| p.dist(c) - r).unwrap_or(f64::INFINITY), - } - } - /// The affine map taking this surface onto `to` (same kind, same axis). - fn map_to(&self, to: &Surf) -> Option { - match (*self, *to) { - (Surf::Sphere { c, r, .. }, Surf::Sphere { r: r2, .. }) => { - let k = r2 / r; - let t = c * (1.0 - k); - Some(mt::Matrix4::from_translation(mt::Vector3::new(t.x, t.y, t.z)) * mt::Matrix4::from_scale(k)) - } - (Surf::Cone { v, .. }, Surf::Cone { v: v2, .. }) => { - let t = v2 - v; - Some(mt::Matrix4::from_translation(mt::Vector3::new(t.x, t.y, t.z))) - } - (Surf::Plane { n, d }, Surf::Plane { d: d2, .. }) => { - let t = n * (d2 - d); - Some(mt::Matrix4::from_translation(mt::Vector3::new(t.x, t.y, t.z))) - } - (Surf::Cylinder { o, a, r, .. }, Surf::Cylinder { r: r2, .. }) => { - // Scale by k across the axis: x ↦ o + k (x − o) + (1 − k) a a·(x − o). - let k = r2 / r; - let m = |i: usize, j: usize| { - let (ai, aj) = ([a.x, a.y, a.z][i], [a.x, a.y, a.z][j]); - (if i == j { k } else { 0.0 }) + (1.0 - k) * ai * aj - }; - let lin = [[m(0, 0), m(0, 1), m(0, 2)], [m(1, 0), m(1, 1), m(1, 2)], [m(2, 0), m(2, 1), m(2, 2)]]; - let ov = [o.x, o.y, o.z]; - let t: Vec = (0..3).map(|i| ov[i] - (0..3).map(|j| lin[i][j] * ov[j]).sum::()).collect(); - // Column-major. - Some(mt::Matrix4::new( - lin[0][0], - lin[1][0], - lin[2][0], - 0.0, - lin[0][1], - lin[1][1], - lin[2][1], - 0.0, - lin[0][2], - lin[1][2], - lin[2][2], - 0.0, - *t.first()?, - *t.get(1)?, - *t.get(2)?, - 1.0, - )) - } - _ => None, + _ => false, } } } -fn fail(m: &str) -> KernelError { - KernelError::Failed(format!("offset: {m}")) -} - -/// Points and outward normals sampled over a face (boundary and a grid inside its -/// parameter box). -fn samples(f: &mt::Face) -> Vec<(Vec3, Vec3)> { - use mt::{BoundedCurve, ParametricCurve, ParametricSurface, ParametricSurface3D, SearchNearestParameter}; - let surf = f.oriented_surface(); - let mut uv: Vec<(f64, f64)> = Vec::new(); - for w in f.boundaries() { - for e in w.edge_iter() { - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); - for k in 0..5 { - // The previous point's parameters as a hint, unless that lands elsewhere (a - // singular point such as a pole holds the search). - let q = c.subs(t0 + (t1 - t0) * k as f64 / 5.0); - let near = |x: (f64, f64)| from_p3(surf.subs(x.0, x.1)).dist(from_p3(q)) < 1e-6 * (1.0 + from_p3(q).len()); - let found = surf - .search_nearest_parameter(q, uv.last().copied(), 50) - .filter(|x| near(*x)) - .or_else(|| surf.search_nearest_parameter(q, None, 100).filter(|x| near(*x))); - if let Some(x) = found { - uv.push(x); - } - } - } - } - let Some(&(u0, v0)) = uv.first() else { return Vec::new() }; - let (mut lo, mut hi) = ((u0, v0), (u0, v0)); - for (u, v) in &uv { - lo = (lo.0.min(*u), lo.1.min(*v)); - hi = (hi.0.max(*u), hi.1.max(*v)); - } - for i in 0..=4 { - for j in 0..=4 { - uv.push((lo.0 + (hi.0 - lo.0) * i as f64 / 4.0, lo.1 + (hi.1 - lo.1) * j as f64 / 4.0)); - } - } - // Parameter steps for checking that the normal is steady (not at a cone's apex). - let (du, dv) = (((hi.0 - lo.0) * 1e-6).max(1e-9), ((hi.1 - lo.1) * 1e-6).max(1e-9)); - let nrm = |u: f64, v: f64| { - let n = surf.normal(u, v); - Vec3::new(n.x, n.y, n.z).normalized() - }; - uv.iter() - .filter_map(|(u, v)| { - let n = nrm(*u, *v)?; - let steady = - [nrm(*u + du, *v), nrm(*u - du, *v), nrm(*u, *v + dv), nrm(*u, *v - dv)].iter().all(|m| m.is_some_and(|m| m.dot(n) > 1.0 - 1e-6)); - steady.then(|| (from_p3(surf.subs(*u, *v)), n)) - }) - .collect() -} - -/// What surface a face lies on (planes and cylinders only). -pub(crate) fn surf_of(f: &mt::Face, tol: f64) -> Option { - if let mt::Surface::Plane(pl) = f.oriented_surface() { - let n = pl.normal(); - let n = Vec3::new(n.x, n.y, n.z).normalized()?; - return Some(Surf::Plane { n, d: n.dot(from_p3(pl.origin())) }); - } - let s = samples(f); - if let Some(t) = torus_of(f, &s, tol) { - return Some(t); - } - let (p0, n0) = *s.first()?; - // Flat though not built as a plane (a radial line swept round an axis). - if s.iter().all(|(p, n)| n.dot(n0) > 1.0 - 1e-9 && (*p - p0).dot(n0).abs() < tol) { - return Some(Surf::Plane { n: n0, d: n0.dot(p0) }); - } - // The normal most square to the first (a half cylinder's two ends are opposite). - let far = s.iter().map(|x| x.1).min_by(|a, b| a.dot(n0).abs().total_cmp(&b.dot(n0).abs()))?; - let Some(a) = n0.cross(far).normalized() else { return sphere_or_cone(&s, tol) }; - if s.iter().any(|(_, n)| n.dot(a).abs() > 1e-6) { - return sphere_or_cone(&s, tol); - } - // The axis: where the normal lines through two samples meet (seen along a). - let (p1, n1) = *s.iter().min_by(|x, y| x.1.dot(n0).abs().total_cmp(&y.1.dot(n0).abs()))?; - // p0 + t0 n0 = p1 + t1 n1 (projected): solve in the plane ⟂ a. - let w = p1 - p0; - let c = n0.dot(n1); - let den = 1.0 - c * c; - if den.abs() < 1e-9 { - return None; - } - let t0 = (w.dot(n0) - c * w.dot(n1)) / den; - let o = p0 + n0 * t0; - let o = o - a * (o - p0).dot(a); - let r = t0.abs(); - // Outward normal away from the axis: p = o + r n (t0 < 0 means o = p − r n). - let convex = t0 < 0.0; - let cyl = Surf::Cylinder { o, a, r, convex }; - let ok = s.iter().all(|(p, n)| cyl.dist(*p).abs() < tol && cyl.normal(*p).is_some_and(|m| m.dot(*n) > 1.0 - 1e-6)); - ok.then_some(cyl) -} - -/// A torus: a surface of revolution whose normals (in the meridian plane) all point from one -/// circle, the tube's centre, at one distance. -fn torus_of(f: &mt::Face, s: &[(Vec3, Vec3)], tol: f64) -> Option { - let mt::Surface::RevolutedCurve(rc) = f.surface() else { return None }; - if *rc.transform() != ::one() { - return None; - } - let (o, ax) = (from_p3(rc.entity().origin()), rc.entity().axis()); - let a = Vec3::new(ax.x, ax.y, ax.z).normalized()?; - // Meridian coordinates: ρ − r n_ρ = R and h − r n_h = h0 for every sample, least squares - // in (R, h0, r). - let mut m = [[0.0f64; 3]; 3]; - let mut rhs = [0.0f64; 3]; - for (p, n) in s { - let w = *p - o; - let hh = w.dot(a); - let radial = w - a * hh; - let u = radial.normalized()?; - for (row, val) in [([1.0, 0.0, n.dot(u)], radial.len()), ([0.0, 1.0, n.dot(a)], hh)] { - for i in 0..3 { - for j in 0..3 { - m[i][j] += row[i] * row[j]; - } - rhs[i] += row[i] * val; - } - } - } - let x = crate::polyhedron::solve3_pub(m, rhs)?; - let (big, h, r) = (x[0], x[1], x[2]); - // A spindle torus also has an inner sheet: a barrel revolved from an arc whose - // centre is across the axis. Its signed ring radius is negative; retain that sign - // so distances, normals and the moved meridian use the centre on the opposite side. - if !(big.abs() > 1e-9 && r.abs() > 1e-9) { - return None; - } - let t = Surf::Torus { o, a, big, h, r: r.abs(), convex: r > 0.0 }; - s.iter().all(|(p, n)| t.dist(*p).abs() < tol && t.normal(*p).is_some_and(|m| m.dot(*n) > 1.0 - 1e-6)).then_some(t) -} - -/// A sphere (normal lines all through one point) or a cone (tangent planes all through one -/// point, normals at one angle to an axis) through the samples. -fn sphere_or_cone(s: &[(Vec3, Vec3)], tol: f64) -> Option { - // Least squares point nearest all the normal lines: Σ (I − n nᵀ) x = Σ (I − n nᵀ) p. - let mut m = [[0.0f64; 3]; 3]; - let mut r = [0.0f64; 3]; - for (p, n) in s { - let nv = [n.x, n.y, n.z]; - let pv = [p.x, p.y, p.z]; - for i in 0..3 { - for j in 0..3 { - let a = (if i == j { 1.0 } else { 0.0 }) - nv[i] * nv[j]; - m[i][j] += a; - r[i] += a * pv[j]; - } - } - } - if let Some(x) = crate::polyhedron::solve3_pub(m, r) { - let c = Vec3::new(x[0], x[1], x[2]); - let (p0, n0) = *s.first()?; - let rad = p0.dist(c); - let convex = (p0 - c).dot(n0) > 0.0; - let sp = Surf::Sphere { c, r: rad, convex }; - if rad > tol && s.iter().all(|(p, n)| sp.dist(*p).abs() < tol && sp.normal(*p).is_some_and(|q| q.dot(*n) > 1.0 - 1e-6)) { - return Some(sp); - } - } - // Cone: the apex lies on every tangent plane, n·(v − p) = 0. - let mut m = [[0.0f64; 3]; 3]; - let mut r = [0.0f64; 3]; - for (p, n) in s { - let nv = [n.x, n.y, n.z]; - let k = n.dot(*p); - for i in 0..3 { - for j in 0..3 { - m[i][j] += nv[i] * nv[j]; - } - r[i] += nv[i] * k; - } - } - let x = crate::polyhedron::solve3_pub(m, r)?; - let v = Vec3::new(x[0], x[1], x[2]); - // Axis: from the apex toward the samples' centroid (the cone opens that way). - let cen = s.iter().fold(Vec3::ZERO, |acc, (p, _)| acc + *p) * (1.0 / s.len() as f64); - // Normals make a constant angle with the axis: fit it from three spread normals. - let n0 = s.first()?.1; - let n1 = s.iter().map(|x| x.1).max_by(|a, b| (*a - n0).len().total_cmp(&(*b - n0).len()))?; - let n2 = s.iter().map(|x| x.1).max_by(|a, b| (*a - n0).cross(n1 - n0).len().total_cmp(&(*b - n0).cross(n1 - n0).len()))?; - let mut a = (n1 - n0).cross(n2 - n0).normalized()?; - if a.dot(cen - v) < 0.0 { - a = -a; - } - let half = n0.dot(a).abs().clamp(0.0, 1.0).asin(); - if !(half > 1e-3 && half < std::f64::consts::FRAC_PI_2 - 1e-3) { - return None; - } - let (p0, n0) = *s.first()?; - let q = { - let w = p0 - v; - (w - a * w.dot(a)).normalized()? - }; - let convex = n0.dot(q) > 0.0; - let cone = Surf::Cone { v, a, half, convex }; - s.iter().all(|(p, n)| cone.dist(*p).abs() < tol && cone.normal(*p).is_some_and(|m| m.dot(*n) > 1.0 - 1e-6)).then_some(cone) -} - -/// Move `p` (on all of `old`) onto the moved surfaces `new`: the smallest displacement δ with -/// n_i · δ = s_i for each face's normal n_i at p, then checked against the moved surfaces. -fn move_point(p: Vec3, old: &[Surf], shifts: &[f64], new: &[Surf], tol: f64) -> Option { - let ns: Vec = old.iter().map(|sf| sf.normal(p)).collect::>()?; - let mut q = p + span_step(&ns, shifts)?; - // The step is exact for planes; a curved face meeting another at an angle needs a few - // Newton steps onto the moved surfaces. - for _ in 0..30 { - let d: Vec = new.iter().map(|sf| sf.dist(q)).collect(); - if d.iter().all(|x| x.abs() < tol) { - return Some(q); - } - let gs: Vec = new.iter().map(|sf| sf.grad(q)).collect::>()?; - let rhs: Vec = d.iter().map(|x| -x).collect(); - q += span_step(&gs, &rhs)?; - } - new.iter().all(|sf| sf.dist(q).abs() < tol).then_some(q) -} - -/// The smallest move `v` (in the span of `ns`) with `n_i · v = s_i` (least squares). -fn span_step(ns: &[Vec3], s: &[f64]) -> Option { - // Orthonormal basis of the normals' span (tangent faces share a normal). - let mut basis: Vec = Vec::new(); - for n in ns { - let mut v = *n; - for e in &basis { - v = v - *e * v.dot(*e); - } - if let Some(u) = v.normalized().filter(|_| v.len() > 1e-6) { - basis.push(u); - } - } - // Least squares in the span: rows n_i · e_k, right-hand sides s_i. - let r = basis.len(); - let mut m = [[0.0f64; 3]; 3]; - let mut rhs = [0.0f64; 3]; - for (n, si) in ns.iter().zip(s) { - let row: Vec = basis.iter().map(|e| n.dot(*e)).collect(); - for i in 0..r { - for j in 0..r { - m[i][j] += row[i] * row[j]; - } - rhs[i] += row[i] * si; - } - } - // Pad unused dimensions with the identity. - for (i, row) in m.iter_mut().enumerate().skip(r) { - row[i] = 1.0; - } - let c = crate::polyhedron::solve3_pub(m, rhs)?; - let mut v = Vec3::ZERO; - for (k, e) in basis.iter().enumerate() { - v += *e * c[k]; - } - Some(v) -} - -/// Most faces round one corner that [`split_corner`] takes on. -const MAX_SPLIT_FACES: usize = 48; - -/// The corners in place of a corner where more than three planar faces meet and whose moved -/// planes miss a common point (a hip floor's corner, a pyramid's apex): each new corner with -/// the faces through it. Corners sharing two faces are joined by a new edge on those faces. -/// Only corners whose edges are all convex or all concave: the faces there bound a convex -/// region (the body's side or the outside's), and after the move its corners are the points on -/// three moved planes inside all the others. -fn split_corner( - v: &mt::Vertex, - at: &[usize], - faces: &[mt::Face], - efaces: &HashMap>, - old: &[Surf], - new: &[Surf], - size: f64, -) -> Option)>> { - if at.len() < 4 || at.len() > MAX_SPLIT_FACES { - return None; - } - let p = from_p3(v.point()); - // (face, outward normal, old offset, moved offset). - let planes: Vec<(usize, Vec3, f64, f64)> = at - .iter() - .map(|i| match (old.get(*i)?, new.get(*i)?) { - (Surf::Plane { n, d }, Surf::Plane { d: d2, .. }) => Some((*i, *n, *d, *d2)), - _ => None, - }) - .collect::>()?; - let normal = |fi: usize| planes.iter().find(|x| x.0 == fi).map(|x| x.1); - // Edge kinds round the corner: a face's loop runs counter-clockwise about its outward - // normal, so its inside is to the left; the edge is convex when the face beyond it falls - // away from there. - let mut sign = 0.0f64; - let mut mixed = false; - let mut pairs: Vec<(usize, usize)> = Vec::new(); - for &(fi, na, ..) in &planes { - for w in faces.get(fi)?.boundaries() { - for e in w.edge_iter() { - if e.front().id() != v.id() && e.back().id() != v.id() { - continue; - } - let fb = efaces.get(&e.id())?.iter().copied().find(|j| *j != fi)?; - pairs.push((fi, fb)); - let dir = (from_p3(e.back().point()) - from_p3(e.front().point())).normalized()?; - let s = normal(fb)?.dot(na.cross(dir)); - if s.abs() < 1e-9 { - continue; - } - if sign * s < 0.0 { - mixed = true; - } - sign = s.signum(); - } - } - } - if sign == 0.0 { - return None; - } - // Which triples of faces may meet at a new corner. All convex or all concave: any triple - // whose point is inside all the other moved planes. Mixed (a saddle, such as a box on a - // box that overhangs its side): the faces round the corner in order, and each new corner - // on three faces in a row (the two new edges on the middle face meet there). A saddle's - // faces bound no convex region, so a right corner can be outside another face's moved - // plane, and the inside-all-the-others test does not apply. What keeps a corner in place - // is that it is where its middle face's two new edges meet; a corner past the far end of - // one of the corner's edges turns that edge round, and a face whose loops cross after the - // move is refused (both checked in `offset_body`). - let triples: Vec<[usize; 3]> = if mixed { - let ring = face_ring(&pairs, planes.len())?; - let n = ring.len(); - (0..n).map(|i| [ring[(i + n - 1) % n], ring[i], ring[(i + 1) % n]]).collect() - } else { - let mut t = Vec::new(); - for ia in 0..planes.len() { - for ib in ia + 1..planes.len() { - for ic in ib + 1..planes.len() { - t.push([planes[ia].0, planes[ib].0, planes[ic].0]); - } - } - } - t - }; - let plane_of = |fi: usize| planes.iter().find(|x| x.0 == fi); - // Convex: the body's side, n·x ≤ d; concave: the outside's, n·x ≥ d. - let side = -sign; - let merge = size * 1e-6; - let mut nodes: Vec<(Vec3, Vec)> = Vec::new(); - for [fa, fb, fc] in triples { - let (a, b, c) = (plane_of(fa)?, plane_of(fb)?, plane_of(fc)?); - let den = a.1.dot(b.1.cross(c.1)); - if den.abs() < 1e-9 { - continue; - } - let x = (b.1.cross(c.1) * a.3 + c.1.cross(a.1) * b.3 + a.1.cross(b.1) * c.3) * (1.0 / den); - if !x.is_finite() || x.dist(p) > size || (!mixed && planes.iter().any(|q| side * (q.1.dot(x) - q.3) > merge)) { - continue; - } - let fs = [fa, fb, fc]; - match nodes.iter_mut().find(|(q, _)| q.dist(x) < merge) { - Some((_, nf)) => { - for f in fs { - if !nf.contains(&f) { - nf.push(f); - } - } - } - None => nodes.push((x, fs.to_vec())), - } - } - // Every face keeps a corner here, and every edge an end. - if planes.iter().any(|q| !nodes.iter().any(|(_, nf)| nf.contains(&q.0))) - || pairs.iter().any(|(x, y)| !nodes.iter().any(|(_, nf)| nf.contains(x) && nf.contains(y))) - { - return None; - } - // Each corner where its planes meet best (least squares, for planes meeting at one point - // to within the merge distance). - for (q, nf) in nodes.iter_mut() { - let (ns, ss): (Vec, Vec) = nf.iter().filter_map(|f| planes.iter().find(|x| x.0 == *f)).map(|x| (x.1, x.3 - x.2)).unzip(); - *q = p + span_step(&ns, &ss)?; - } - Some(nodes) -} - -/// The faces round a corner in order, from the pairs of faces on each of its edges: `None` -/// unless they form one simple ring of `count` faces (each face meets the corner once, between -/// exactly two neighbours). -fn face_ring(pairs: &[(usize, usize)], count: usize) -> Option> { - let mut next: HashMap> = HashMap::new(); - for &(a, b) in pairs { - for (x, y) in [(a, b), (b, a)] { - let ns = next.entry(x).or_default(); - if !ns.contains(&y) { - ns.push(y); - } - } - } - if next.len() != count || next.values().any(|ns| ns.len() != 2) { - return None; - } - let first = *next.keys().min()?; - let mut ring = vec![first]; - let mut prev = first; - let mut cur = *next.get(&first)?.first()?; - while cur != first { - if ring.len() >= count { - return None; - } - ring.push(cur); - let ns = next.get(&cur)?; - let to = if ns[0] == prev { ns[1] } else { ns[0] }; - prev = cur; - cur = to; - } - (ring.len() == count).then_some(ring) -} - -/// The corners of a split corner (see [`split_corner`]) on face `face`, in order from corner -/// `from` to corner `to`, along the new edges between them. -fn split_path(nodes: &[(Vec3, Vec)], face: usize, from: usize, to: usize) -> Option> { - let joined = |x: usize, y: usize| { - let (Some((_, a)), Some((_, b))) = (nodes.get(x), nodes.get(y)) else { return false }; - a.contains(&face) && b.contains(&face) && a.iter().filter(|f| b.contains(f)).count() >= 2 - }; - // Breadth first; `prev` leads back to `from`. - let mut prev: Vec> = vec![None; nodes.len()]; - let mut queue = std::collections::VecDeque::from([from]); - let mut seen = vec![false; nodes.len()]; - *seen.get_mut(from)? = true; - while let Some(x) = queue.pop_front() { - if x == to { - let mut path = vec![to]; - let mut cur = to; - while let Some(p) = prev.get(cur).copied().flatten() { - path.push(p); - cur = p; - } - path.reverse(); - return Some(path); - } - for y in 0..nodes.len() { - if !seen.get(y).copied().unwrap_or(true) && joined(x, y) { - *seen.get_mut(y)? = true; - *prev.get_mut(y)? = Some(x); - queue.push_back(y); - } - } - } - None -} - -/// A line or circular arc through an edge (by samples): `None` for other curves. -/// Maximum straight edges per face checked pairwise for crossings. -const MAX_CROSSING_EDGES: usize = 2000; - -/// Where the moved straight edges of a planar face cross each other (or a loop of straight -/// edges turns round), if they do. Faces next to a collapsed round are left to the other checks. -fn crossed_loops( - faces: &[mt::Face], - old: &[Surf], - pos: &dyn Fn(&mt::Vertex, &mt::Edge) -> Option, - edge_collapsed: &dyn Fn(&mt::Edge) -> bool, - size: f64, -) -> Option { - let eps = size * 1e-9; - for (f, sf) in faces.iter().zip(old) { - let Surf::Plane { n, .. } = *sf else { continue }; - if f.edge_iter().any(|e| edge_collapsed(&e)) { - continue; - } - let (u, w) = (n.any_perp(), n.cross(n.any_perp())); - let flat = |p: Vec3| (p.dot(u), p.dot(w)); - // Straight edges as (vertex ids, new ends in the plane, the plane's new offset). - let mut segs: Vec<([mt::VertexID; 2], [(f64, f64); 2], f64)> = Vec::new(); - for wire in f.absolute_boundaries() { - let (mut area_old, mut area_new, mut straight) = (0.0, 0.0, true); - for e in wire.edge_iter() { - let (v0, v1) = (e.front(), e.back()); - let (Some(q0), Some(q1)) = (pos(v0, e), pos(v1, e)) else { return None }; - let (o0, o1, n0, n1) = (flat(from_p3(v0.point())), flat(from_p3(v1.point())), flat(q0), flat(q1)); - area_old += o0.0 * o1.1 - o1.0 * o0.1; - area_new += n0.0 * n1.1 - n1.0 * n0.1; - if arc_mid(e, size * 1e-6) == Some(None) { - segs.push(([v0.id(), v1.id()], [n0, n1], n.dot(q0))); - } else { - straight = false; - } - } - if straight && area_old.abs() > eps && area_old * area_new <= 0.0 { - return wire.edge_iter().next().and_then(|e| pos(e.front(), e)); - } - } - if segs.len() > MAX_CROSSING_EDGES { - continue; - } - let side = |a: (f64, f64), c: (f64, f64), p: (f64, f64)| (c.0 - a.0) * (p.1 - a.1) - (c.1 - a.1) * (p.0 - a.0); - for (i, (ia, [a0, a1], d)) in segs.iter().enumerate() { - for (ib, [b0, b1], _) in segs.iter().skip(i + 1) { - if ia.iter().any(|v| ib.contains(v)) { - continue; - } - let (s0, s1) = (side(*a0, *a1, *b0), side(*a0, *a1, *b1)); - let (t0, t1) = (side(*b0, *b1, *a0), side(*b0, *b1, *a1)); - let tol = eps * size; - if ((s0 > tol && s1 < -tol) || (s0 < -tol && s1 > tol)) && ((t0 > tol && t1 < -tol) || (t0 < -tol && t1 > tol)) { - let k = t0 / (t0 - t1); - let (x, y) = (a0.0 + (a1.0 - a0.0) * k, a0.1 + (a1.1 - a0.1) * k); - return Some(u * x + w * y + n * *d); - } - } - } - } - None -} - -pub(crate) fn arc_mid(e: &mt::Edge, tol: f64) -> Option> { - use mt::{BoundedCurve, ParametricCurve}; - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - let pts: Vec = (0..=16).map(|k| from_p3(c.subs(t0 + (t1 - t0) * k as f64 / 16.0))).collect(); - let (a, b, m) = (*pts.first()?, *pts.last()?, *pts.get(8)?); - if a.dist(b) < tol { - return None; - } - if pts.iter().all(|p| p.dist_to_segment(a, b) < tol) { - return Some(None); - } - let (u, v) = (b - a, m - a); - let w = u.cross(v); - let d = 2.0 * w.len2(); - if d < 1e-300 { - return None; - } - let centre = a + (v.cross(w) * u.len2() + w.cross(u) * v.len2()) * (1.0 / d); - let r = centre.dist(a); - pts.iter().all(|p| (p.dist(centre) - r).abs() < tol && (*p - centre).dot(w.normalized().unwrap_or(Vec3::Z)).abs() < tol).then_some(Some(m)) -} - -/// The body with each face moved along its outward normal by `shift(face index, normal at a -/// face point)`, keeping the topology. Faces must be planes or cylinders. The result's history -/// is over `[b]`: each face is the face it was moved from, each edge the edge it was moved from; -/// faces moved to nothing are gone, and their neighbours meet along new edges. -pub(crate) fn offset_body(b: &Body, shift: impl Fn(usize, Vec3) -> f64) -> Result { - let faces: Vec = b.solid.face_iter().cloned().collect(); - let size = b.size(); - let tol = (size * 1e-7).max(1e-9); - let mut old = Vec::with_capacity(faces.len()); - let mut new = Vec::with_capacity(faces.len()); - let mut shifts = Vec::with_capacity(faces.len()); - // Faces moved to nothing (a round thinner than the move): they go, their neighbours meet. - let mut collapsed: Vec = Vec::with_capacity(faces.len()); - for (i, f) in faces.iter().enumerate() { - let sf = surf_of(f, tol * 100.0).ok_or_else(|| { - let at = samples(f).first().map(|(p, _)| format!(" (a face at [{:.2}, {:.2}, {:.2}])", p.x, p.y, p.z)).unwrap_or_default(); - fail(&format!("only bodies with planes, cylinders, cones, spheres and tori{at}")) - })?; - let n = match sf { - Surf::Plane { n, .. } => n, - Surf::Cylinder { a, .. } | Surf::Cone { a, .. } | Surf::Torus { a, .. } => a.any_perp(), - Surf::Sphere { .. } => Vec3::Z, - }; - let s = shift(i, n); - old.push(sf); - match sf.moved(s) { - Some(x) => { - new.push(x); - collapsed.push(false); - } - None => { - new.push(sf); - collapsed.push(true); - } - } - shifts.push(s); - } - let pick = |ids: &[usize]| -> (Vec, Vec, Vec) { - ( - ids.iter().filter_map(|i| old.get(*i).copied()).collect(), - ids.iter().filter_map(|i| shifts.get(*i).copied()).collect(), - ids.iter().filter_map(|i| new.get(*i).copied()).collect(), - ) - }; - // Vertex → its faces; edge → its faces. - let mut vfaces: HashMap> = HashMap::new(); - let mut efaces: HashMap> = HashMap::new(); - for (i, f) in faces.iter().enumerate() { - for v in f.vertex_iter() { - let e = vfaces.entry(v.id()).or_default(); - if !e.contains(&i) { - e.push(i); - } - } - for ed in f.edge_iter() { - let e = efaces.entry(ed.id()).or_default(); - if !e.contains(&i) { - e.push(i); - } - } - } - let is_collapsed = |i: usize| collapsed.get(i).copied().unwrap_or(false); - let any_collapsed = collapsed.iter().any(|c| *c); - // A collapsed face's place is taken by the faces around it (through other collapsed ones). - let mut nbrs: HashMap> = HashMap::new(); - for fs in efaces.values() { - for a in fs { - for b2 in fs { - if a != b2 { - let e = nbrs.entry(*a).or_default(); - if !e.contains(b2) { - e.push(*b2); - } - } - } - } - } - let expand = |fs: &[usize]| -> Vec { - let mut out: Vec = fs.iter().copied().filter(|i| !is_collapsed(*i)).collect(); - let mut queue: Vec = fs.iter().copied().filter(|i| is_collapsed(*i)).collect(); - let mut seen = queue.clone(); - while let Some(c) = queue.pop() { - for nb in nbrs.get(&c).into_iter().flatten() { - if is_collapsed(*nb) { - if !seen.contains(nb) { - seen.push(*nb); - queue.push(*nb); - } - } else if !out.contains(nb) { - out.push(*nb); - } - } - } - out - }; - // Each edge's ends and middle, and the faces either side. - let edge_pts: Vec<(Vec, [Vec3; 3])> = b - .solid - .edge_iter() - .filter_map(|e| { - use mt::{BoundedCurve, ParametricCurve}; - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - Some(( - efaces.get(&e.id())?.clone(), - [from_p3(e.absolute_front().point()), from_p3(e.absolute_back().point()), from_p3(c.subs((t0 + t1) / 2.0))], - )) +/// The record edges each face of `b` uses. +pub(crate) fn face_edges(b: &Brep, face: usize) -> Vec { + let mut out: Vec = b + .faces + .get(face) + .into_iter() + .flat_map(|f| &f.loops) + .flat_map(|l| match l { + Loop::Edges { edges } => edges.iter().map(|u| u.edge).collect(), + Loop::Vertex { .. } => Vec::new(), }) .collect(); - // Across the collapsed rounds next to edge `e` (its faces `fs`): a round is a strip, crossed - // to its side that shares no vertex with the edge, through further collapsed rounds. - let opposite_side = |e: &mt::Edge, fs: &[usize]| -> Vec { - let mut out: Vec = Vec::new(); - let mut seen: Vec = Vec::new(); - let mut queue: Vec<(usize, [mt::VertexID; 2])> = - fs.iter().copied().filter(|i| is_collapsed(*i)).map(|i| (i, [e.front().id(), e.back().id()])).collect(); - while let Some((cf, avoid)) = queue.pop() { - if seen.contains(&cf) { - continue; - } - seen.push(cf); - let Some(face) = faces.get(cf) else { continue }; - for side in face.edge_iter() { - if avoid.contains(&side.front().id()) || avoid.contains(&side.back().id()) { - continue; - } - for nb in efaces.get(&side.id()).into_iter().flatten().copied() { - if nb == cf || fs.contains(&nb) { - continue; - } - if is_collapsed(nb) { - queue.push((nb, [side.front().id(), side.back().id()])); - } else if !out.contains(&nb) { - out.push(nb); - } - } - } - } - out - }; - // For a point on a collapsed round touching the faces `at`: the faces it keeps (`at`'s - // own, not collapsed), and the faces along the rounds it is on, nearest `p` first. - let across = |at: &[usize], p: Vec3| -> (Vec, Vec) { - let own: Vec = at.iter().copied().filter(|i| !is_collapsed(*i)).collect(); - let mut cand: Vec<(f64, usize)> = expand(at) - .into_iter() - .filter(|nb| !own.contains(nb)) - .map(|nb| { - let d = edge_pts - .iter() - .filter(|(fs, _)| fs.contains(&nb) && fs.iter().any(|i| is_collapsed(*i))) - .flat_map(|(_, q)| q.iter().map(|x| x.dist(p))) - .fold(f64::INFINITY, f64::min); - (d, nb) - }) - .collect(); - cand.sort_by(|x, y| x.0.total_cmp(&y.0)); - (own, cand.into_iter().map(|(_, nb)| nb).collect()) - }; - let mut newpos: HashMap = HashMap::new(); - // Corners whose moved faces meet at several points (see `split_corner`). - let mut splits: HashMap)>> = HashMap::new(); - for v in b.solid.vertex_iter() { - let at = vfaces.get(&v.id()).ok_or_else(|| fail("vertex"))?; - let p = from_p3(v.point()); - let fs: Vec = if at.iter().any(|i| is_collapsed(*i)) { - // On a collapsed round: its own faces, then the faces along the rounds it is on, - // nearest first, until they fix a point. - let (mut own, cand) = across(at, p); - let rank = |ids: &[usize]| -> usize { - let mut basis: Vec = Vec::new(); - for i in ids { - let Some(nv) = old.get(*i).and_then(|sf| sf.normal(p)) else { continue }; - let mut w = nv; - for e in &basis { - w = w - *e * w.dot(*e); - } - if let Some(u) = w.normalized().filter(|_| w.len() > 1e-6) { - basis.push(u); - } - } - basis.len() - }; - for c in cand { - if rank(&own) >= 3 { - break; - } - own.push(c); - } - own - } else { - at.clone() - }; - let (o, s, n) = pick(&fs); - // A cone's apex goes with the cone (its normal is not defined there). - let apex = o.iter().zip(&n).find_map(|(a, b)| match (a, b) { - (Surf::Cone { v: va, .. }, Surf::Cone { v: vb, .. }) if va.dist(p) < size * 1e-6 => Some(*vb), - _ => None, - }); - let q = match apex { - Some(q) if n.iter().all(|sf| sf.dist(q).abs() < size * 1e-6) => q, - _ => match move_point(p, &o, &s, &n, size * 1e-6) { - Some(q) => q, - None => { - let nodes = (fs == *at) - .then(|| split_corner(&v, at, &faces, &efaces, &old, &new, size)) - .flatten() - .ok_or_else(|| fail("a corner whose faces don't meet the same way after the move"))?; - let q = nodes.first().map(|x| x.0).ok_or_else(|| fail("corner"))?; - splits.insert(v.id(), nodes); - q - } - }, - }; - newpos.insert(v.id(), q); - } - // Which of a split corner's new corners an edge ends at. - let node_of = |v: mt::VertexID, e: mt::EdgeID| -> Option { - let fs = efaces.get(&e)?; - splits.get(&v)?.iter().position(|(_, nf)| fs.iter().all(|i| nf.contains(i))) - }; - // Where an edge's end goes. - let end_pos = |v: &mt::Vertex, e: &mt::Edge| -> Option { - match splits.get(&v.id()) { - Some(nodes) => nodes.get(node_of(v.id(), e.id())?).map(|x| x.0), - None => newpos.get(&v.id()).copied(), - } - }; - // An edge turned round: faces crossed over (a wall thinner than the move), which would - // leave the body inside out. - let edge_collapsed = |e: &mt::Edge| efaces.get(&e.id()).is_some_and(|fs| fs.iter().any(|i| is_collapsed(*i))); - for e in b.solid.edge_iter() { - if edge_collapsed(&e) { - continue; - } - let (f0, f1) = (e.absolute_front(), e.absolute_back()); - let (Some(q0), Some(q1)) = (end_pos(f0, &e), end_pos(f1, &e)) else { continue }; - let (old_v, new_v) = (from_p3(f1.point()) - from_p3(f0.point()), q1 - q0); - if old_v.len() > size * 1e-6 && old_v.dot(new_v) < 0.0 { - return Err(fail("not supported yet: the move is larger than a wall or step is thick (faces would cross)")); - } - } - // A plane's loops crossing after the move: a rim or ledge narrower than the move (the hole - // in a top face sliding past its outer edge) turns part of the face inside out, though no - // edge turns round. - if let Some(at) = crossed_loops(&faces, &old, &end_pos, &edge_collapsed, size) { - return Err(fail(&format!( - "not supported yet: the move is larger than a rim or ledge near [{:.1}, {:.1}, {:.1}] is wide (a face would turn inside out)", - at.x, at.y, at.z - ))); - } - guard("offset", || { - // Vertices of collapsed faces that land together become one. - let on_collapsed: std::collections::HashSet = faces - .iter() - .enumerate() - .filter(|(i, _)| is_collapsed(*i)) - .flat_map(|(_, f)| f.vertex_iter().map(|v| v.id()).collect::>()) - .collect(); - let mut verts: HashMap = HashMap::new(); - let mut welded: Vec<(Vec3, mt::Vertex)> = Vec::new(); - for v in b.solid.vertex_iter() { - let Some(p) = newpos.get(&v.id()).copied() else { continue }; - let nv = if any_collapsed && on_collapsed.contains(&v.id()) { - match welded.iter().find(|(q, _)| q.dist(p) < size * 1e-6) { - Some((_, w)) => w.clone(), - None => { - let w = builder::vertex(p3(p)); - welded.push((p, w.clone())); - w - } - } - } else { - builder::vertex(p3(p)) - }; - verts.insert(v.id(), nv); - } - let node_verts: HashMap> = - splits.iter().map(|(id, nodes)| (*id, nodes.iter().map(|(q, _)| builder::vertex(p3(*q))).collect())).collect(); - let vert_at = |v: &mt::Vertex, e: &mt::Edge| -> Option<&mt::Vertex> { - match node_verts.get(&v.id()) { - Some(nv) => nv.get(node_of(v.id(), e.id())?), - None => verts.get(&v.id()), - } - }; - // New edges between a split corner's corners (stored from the lower index). - let mut links: HashMap<(mt::VertexID, usize, usize), mt::Edge> = HashMap::new(); - // Old edge → new edge, and whether it runs the other way (merged with its twin). - let mut edges: HashMap = HashMap::new(); - // Moved faces and edges; an edge where neighbours of a collapsed face meet is new. - let mut rec = crate::record::Rebuild::default(); - // New edges along collapsed rounds: ends and points along them, for their twins. - let mut merged: Vec<(mt::VertexID, mt::VertexID, Vec, mt::Edge)> = Vec::new(); - for e in b.solid.edge_iter() { - if edges.contains_key(&e.id()) { - continue; - } - let (Some(a), Some(c)) = (vert_at(e.absolute_front(), &e), vert_at(e.absolute_back(), &e)) else { return Err(fail("edge")) }; - let touches = edge_collapsed(&e); - if a == c || from_p3(a.point()).dist(from_p3(c.point())) < size * 1e-9 { - if touches { - continue; - } - return Err(fail("an edge vanishes (the offset is too large)")); - } - if efaces.get(&e.id()).is_some_and(|fs| fs.iter().all(|i| is_collapsed(*i))) { - continue; - } - if touches { - // Along a collapsed round: where the edge's own face meets the face across the - // round, between the edge's moved ends, through the edge's middle moved onto - // both: a line (planes, or a plane along a cylinder's axis) or an arc (a plane - // square to a coaxial cylinder); faces that meet in another curve are refused. - // Shared with its twin from the round's other side: the new edge with the same - // ends through the same middle (two arcs of one circle have the same ends). - use mt::{BoundedCurve, ParametricCurve}; - let fs = efaces.get(&e.id()).ok_or_else(|| fail("edge faces"))?; - let cv = e.curve(); - let (t0, t1) = cv.range_tuple(); - let mid = from_p3(cv.subs((t0 + t1) / 2.0)); - // The face across: the strip's far side (`opposite_side`), the nearest of them - // when several; the nearest along the rounds when the strip has none. - let (mut meet, cand) = across(fs, mid); - let far = opposite_side(&e, fs); - meet.extend(cand.iter().find(|c| far.contains(c)).or(cand.first())); - if meet.len() < 2 { - return Err(fail("an edge along a collapsed round with no face across it")); - } - let (o, s, n) = pick(&meet); - let m = move_point(mid, &o, &s, &n, size * 1e-6).ok_or_else(|| fail("faces that don't meet along a collapsed round"))?; - let near = size * 1e-5; - let twin = merged.iter().find(|(x, y, pts, _)| { - ((*x == a.id() && *y == c.id()) || (*x == c.id() && *y == a.id())) - && pts.windows(2).any(|w| w.first().zip(w.get(1)).is_some_and(|(p, q)| m.dist_to_segment(*p, *q) < near)) - }); - let ne = match twin { - Some((_, _, _, x)) => x.clone(), - None => { - let (pa, pc) = (from_p3(a.point()), from_p3(c.point())); - let x = if m.dist_to_segment(pa, pc) < near { builder::line(a, c) } else { builder::circle_arc(a, c, p3(m)) }; - let xc = x.curve(); - let (u0, u1) = xc.range_tuple(); - let pts: Vec = (0..=16).map(|j| from_p3(xc.subs(u0 + (u1 - u0) * j as f64 / 16.0))).collect(); - if !pts.iter().all(|p| n.iter().all(|sf| sf.dist(*p).abs() < near)) { - return Err(fail("not supported yet: faces meeting along a collapsed round in a curve other than a line or circle")); - } - merged.push((a.id(), c.id(), pts, x.clone())); - x - } - }; - let flipped = ne.front() != a; - edges.insert(e.id(), (ne, flipped)); - continue; - } - let Some(kind) = arc_mid(&e, size * 1e-6) else { - // Another curve (where two cylinders meet): its points moved onto the moved - // faces, through a smooth curve. - use mt::{BoundedCurve, ParametricCurve}; - let fs = efaces.get(&e.id()).ok_or_else(|| fail("edge faces"))?; - let (o, s, n) = pick(fs); - let cv = e.curve(); - let (t0, t1) = cv.range_tuple(); - let k = 16; - let mut pts = vec![from_p3(a.point())]; - for j in 1..k { - let p = from_p3(cv.subs(t0 + (t1 - t0) * j as f64 / k as f64)); - pts.push( - move_point(p, &o, &s, &n, size * 1e-6).ok_or_else(|| fail("an edge whose faces don't meet the same way after the move"))?, - ); - } - pts.push(from_p3(c.point())); - let curve = crate::build::interpolate_cubic(&pts).ok_or_else(|| fail("edge curve"))?; - let ne = mt::Edge::new(a, c, mt::Curve::BSplineCurve(curve)); - rec.piece(&ne, &e); - edges.insert(e.id(), (ne, false)); - continue; - }; - let ne = match kind { - None => builder::line(a, c), - Some(m) => { - let fs = efaces.get(&e.id()).ok_or_else(|| fail("edge faces"))?; - let (o, s, n) = pick(fs); - let m2 = - move_point(m, &o, &s, &n, size * 1e-6).ok_or_else(|| fail("an edge whose faces don't meet the same way after the move"))?; - // An arc turned round: its ends moved past its middle (next to a face it meets - // tangentially), so the arc through them goes the long way round its circle. - let (a0, c0, a1, c1) = - (from_p3(e.absolute_front().point()), from_p3(e.absolute_back().point()), from_p3(a.point()), from_p3(c.point())); - if (m - a0).cross(c0 - a0).dot((m2 - a1).cross(c1 - a1)) < 0.0 { - return Err(fail("not supported yet: the move is larger than a wall or step is thick (faces would cross)")); - } - builder::circle_arc(a, c, p3(m2)) - } - }; - rec.piece(&ne, &e); - edges.insert(e.id(), (ne, false)); - } - let mut out = Vec::new(); - for (i, f) in faces.iter().enumerate() { - if is_collapsed(i) { - continue; - } - let mut wires: Vec = Vec::new(); - for w in f.absolute_boundaries() { - let old_edges: Vec = w.edge_iter().cloned().collect(); - let mut wire: Vec = Vec::new(); - for (j, e) in old_edges.iter().enumerate() { - if let Some((ne, flip)) = edges.get(&e.id()) { - wire.push(if (e.front() == e.absolute_front()) != *flip { ne.clone() } else { ne.inverse() }); - } - // At a split corner, along the new edges from this edge's end to the next's. - let v = e.back(); - let (Some(nodes), Some(next)) = (splits.get(&v.id()), old_edges.get((j + 1) % old_edges.len())) else { continue }; - let (Some(from), Some(to)) = (node_of(v.id(), e.id()), node_of(v.id(), next.id())) else { return Err(fail("split corner")) }; - let path = split_path(nodes, i, from, to).ok_or_else(|| fail("split corner"))?; - for pair in path.windows(2) { - let (Some(&x), Some(&y)) = (pair.first(), pair.get(1)) else { continue }; - let key = (v.id(), x.min(y), x.max(y)); - let link = match links.get(&key) { - Some(l) => l.clone(), - None => { - let nv = node_verts.get(&v.id()).ok_or_else(|| fail("split corner"))?; - let (Some(va), Some(vb)) = (nv.get(key.1), nv.get(key.2)) else { return Err(fail("split corner")) }; - let l = builder::line(va, vb); - links.insert(key, l.clone()); - l - } - }; - wire.push(if x < y { link } else { link.inverse() }); - } - } - wires.push(wire.into()); - } - let (Some(o), Some(n)) = (old.get(i), new.get(i)) else { return Err(fail("face")) }; - let surface = match (o.map_to(n), *o, *n) { - (Some(mat), _, _) => mt::Transformed::transformed(&f.surface(), mat), - // A torus: its tube's circle scaled about the tube's centre, revolved again. - (None, Surf::Torus { o: to, a, big, h, r, .. }, Surf::Torus { r: r2, .. }) => { - use mt::{BoundedCurve, ParametricCurve}; - let mt::Surface::RevolutedCurve(rc) = f.surface() else { return Err(fail("torus surface")) }; - let curve = rc.entity().entity_curve().clone(); - let (t0, t1) = curve.range_tuple(); - let q = from_p3(curve.subs((t0 + t1) / 2.0)); - let c = tube_centre(to, a, big, h, q).ok_or_else(|| fail("torus"))?; - let k = r2 / r; - let t = c * (1.0 - k); - let mat = mt::Matrix4::from_translation(mt::Vector3::new(t.x, t.y, t.z)) * mt::Matrix4::from_scale(k); - let moved = mt::Transformed::transformed(&curve, mat); - let mut p = mt::Processor::new(mt::RevolutedCurve::by_revolution(moved, rc.entity().origin(), rc.entity().axis())); - if !rc.orientation() { - mt::Invertible::invert(&mut p); - } - mt::Surface::RevolutedCurve(p) - } - _ => return Err(fail("surface")), - }; - let mut nf = mt::Face::try_new(wires, surface).map_err(|e| fail(&e.to_string()))?; - if !f.orientation() { - nf.invert(); - } - rec.face(&nf, f); - out.push(nf); - } - // One shell per shell of the body (pieces, voids), less the collapsed faces. - let mut shells: Vec = Vec::new(); - let mut it = out.into_iter(); - let mut k = 0; - for sh in b.solid.boundaries() { - let keep = (k..k + sh.len()).filter(|i| !is_collapsed(*i)).count(); - k += sh.len(); - shells.push(it.by_ref().take(keep).collect::>().into()); - } - let solid = Solid::try_new(shells).map_err(|e| fail(&e.to_string()))?; - crate::record::rebuilt(solid, &[&b.solid], &rec) - }) + out.sort_unstable(); + out.dedup(); + out } -/// Draft walls parallel to `pull` (planes, and cylinders about axes along `pull`) by `angle` -/// about their line on the neutral plane: at height h along `pull` a wall moves along its -/// outward normal by −h·tan(angle), so planes tilt and cylinders become cones. The faces that -/// share a corner with a drafted wall must be caps square to `pull` or walls; the rest of the -/// body (a rounded edge elsewhere, say) is left as it is. The topology is kept, and the -/// result's history is over `[b]` (each face and edge the one it was moved from). -pub(crate) fn draft_walls(b: &Body, chosen: &[usize], neutral: &solidcraft_geom::Plane, pull: Vec3, angle: f64) -> Result { - let faces: Vec = b.solid.face_iter().cloned().collect(); - let size = b.size(); - let tol = (size * 1e-7).max(1e-9); - let nn = neutral.normal(); - let den = pull.dot(nn); - if den.abs() < 1e-9 { - return Err(fail("the neutral plane is parallel to the pull direction")); - } - let height = |p: Vec3| (p - neutral.origin).dot(nn) / den; - let tan = angle.tan(); - let mut vfaces: HashMap> = HashMap::new(); - let mut efaces: HashMap> = HashMap::new(); - for (i, f) in faces.iter().enumerate() { - for v in f.vertex_iter() { - let e = vfaces.entry(v.id()).or_default(); - if !e.contains(&i) { - e.push(i); - } - } - for ed in f.edge_iter() { - let e = efaces.entry(ed.id()).or_default(); - if !e.contains(&i) { - e.push(i); - } - } - } - // A corner moves when one of its faces is drafted; the faces round a moving corner must be - // walls or caps for the corner to follow them. Faces away from the drafted walls may be - // anything: they keep their surface and their edges. - let moves = |vid: &mt::VertexID| vfaces.get(vid).is_some_and(|fs| fs.iter().any(|i| chosen.contains(i))); - let touched: Vec = faces.iter().enumerate().map(|(i, f)| chosen.contains(&i) || f.vertex_iter().any(|v| moves(&v.id()))).collect(); - let mut old: Vec> = Vec::with_capacity(faces.len()); - for (i, f) in faces.iter().enumerate() { - if !touched.get(i).copied().unwrap_or(false) { - old.push(None); - continue; - } - let sf = surf_of(f, tol * 100.0).ok_or_else(|| fail("draft: the faces next to the drafted walls must be planes or cylinders"))?; - let wall = match sf { - Surf::Plane { n, .. } => n.dot(pull).abs() < 1e-9, - Surf::Cylinder { a, .. } => a.dot(pull).abs() > 1.0 - 1e-9, - Surf::Sphere { .. } | Surf::Cone { .. } | Surf::Torus { .. } => false, - }; - let cap = matches!(sf, Surf::Plane { n, .. } if n.dot(pull).abs() > 1.0 - 1e-9); - if chosen.contains(&i) && !wall { - return Err(fail("draft: a chosen face isn't parallel to the pull direction")); - } - if !chosen.contains(&i) && !cap && !wall { - return Err(fail("draft: faces next to the drafted walls must be square to the pull direction")); - } - old.push(Some(sf)); - } - // Shifts and moved surfaces at a height. - let at = |ids: &[usize], h: f64| -> Option<(Vec, Vec, Vec)> { - let mut o = Vec::new(); - let mut s = Vec::new(); - let mut n = Vec::new(); - for i in ids { - let sf = (*old.get(*i)?)?; - let sh = if chosen.contains(i) { -h * tan } else { 0.0 }; - o.push(sf); - s.push(sh); - n.push(sf.moved(sh)?); - } - Some((o, s, n)) - }; - let mut newpos: HashMap = HashMap::new(); - for v in b.solid.vertex_iter() { - let p = from_p3(v.point()); - if !moves(&v.id()) { - newpos.insert(v.id(), p); - continue; - } - let fs = vfaces.get(&v.id()).ok_or_else(|| fail("vertex"))?; - let (o, s, n) = at(fs, height(p)).ok_or_else(|| fail("draft: a wall shrinks to nothing"))?; - let q = move_point(p, &o, &s, &n, size * 1e-6).ok_or_else(|| fail("draft: a corner whose faces don't meet the same way after the draft"))?; - newpos.insert(v.id(), q); - } - // New surfaces for the drafted walls: planes through their hinge line, cylinders → cones. - let mut surfaces: Vec> = vec![None; faces.len()]; - for (i, sf) in old.iter().enumerate() { - let (true, Some(sf)) = (chosen.contains(&i), *sf) else { continue }; - let surface = match sf { - Surf::Plane { n, d } => { - let n2 = (n * angle.cos() + pull * angle.sin()).normalized().ok_or_else(|| fail("draft"))?; - // A point of the old plane on the neutral plane: the hinge. - let o = neutral.intersect_ray(n * d, pull).ok_or_else(|| fail("draft: hinge"))?; - let u = n2.cross(pull).normalized().ok_or_else(|| fail("draft"))?; - let w = n2.cross(u); - mt::Surface::Plane(mt::Plane::new(p3(o), p3(o + u), p3(o + w))) - } - Surf::Cylinder { o, a, r, convex } => { - // Generator: the wall at two heights along one radial direction. - let u = a.any_perp(); - // Over the face's heights (and a little beyond), short of the apex. - let hs: Vec = faces.get(i).map(|f| f.vertex_iter().map(|v| height(from_p3(v.point()))).collect()).unwrap_or_default(); - let (lo, hi) = hs.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |m, h| (m.0.min(*h), m.1.max(*h))); - if !(lo.is_finite() && hi.is_finite()) { - return Err(fail("draft: a wall without corners")); - } - let pad = (hi - lo).max(size * 1e-3) * 0.25; - let (mut h0, mut h1) = (lo - pad, hi + pad); - // Keep the radius positive along the generator. - let r_at = |h: f64| if convex { r - h * tan } else { r + h * tan }; - for h in [&mut h0, &mut h1] { - if r_at(*h) <= r * 1e-3 { - *h = if (*h - lo).abs() < (*h - hi).abs() { lo } else { hi }; - } - } - let base = |h: f64| { - let rr = if convex { r - h * tan } else { r + h * tan }; - o + pull * (h - height(o)) + u * rr - }; - let (pa, pb) = (base(h0), base(h1)); - let line = mt::Curve::Line(mt::Line(p3(pa), p3(pb))); - let rc = mt::RevolutedCurve::by_revolution(line, p3(o), mt::Vector3::new(a.x, a.y, a.z)); - mt::Surface::RevolutedCurve(mt::Processor::new(rc)) - } - Surf::Sphere { .. } | Surf::Cone { .. } | Surf::Torus { .. } => { - return Err(fail("draft: only planes and cylinders along the pull can be drafted")); - } - }; - if let Some(slot) = surfaces.get_mut(i) { - *slot = Some(surface); - } - } - guard("draft", || { - let verts: HashMap = newpos.iter().map(|(k, p)| (*k, builder::vertex(p3(*p)))).collect(); - let mut edges: HashMap = HashMap::new(); - let mut rec = crate::record::Rebuild::default(); - for e in b.solid.edge_iter() { - if edges.contains_key(&e.id()) { - continue; - } - let (Some(a), Some(c)) = (verts.get(&e.absolute_front().id()), verts.get(&e.absolute_back().id())) else { return Err(fail("edge")) }; - // An edge whose ends stay keeps its curve (it may be anything: a blend's spline). - if !moves(&e.absolute_front().id()) && !moves(&e.absolute_back().id()) { - let ne = mt::Edge::try_new(a, c, e.curve().clone()).map_err(|e| fail(&e.to_string()))?; - rec.piece(&ne, &e); - edges.insert(e.id(), ne); - continue; - } - let kind = arc_mid(&e, size * 1e-6).ok_or_else(|| fail("draft: edges next to the drafted walls must be lines or arcs"))?; - let ne = match kind { - None => builder::line(a, c), - Some(m) => { - let fs = efaces.get(&e.id()).ok_or_else(|| fail("edge faces"))?; - let (o, s, n) = at(fs, height(m)).ok_or_else(|| fail("draft"))?; - let m2 = move_point(m, &o, &s, &n, size * 1e-6).ok_or_else(|| fail("draft: an arc that can't follow its faces"))?; - builder::circle_arc(a, c, p3(m2)) - } - }; - rec.piece(&ne, &e); - edges.insert(e.id(), ne); - } - let mut out = Vec::new(); - for (i, f) in faces.iter().enumerate() { - let wires: Vec = f - .boundaries() - .iter() - .map(|w| { - w.edge_iter() - .filter_map(|e| edges.get(&e.id()).map(|ne| if e.front() == e.absolute_front() { ne.clone() } else { ne.inverse() })) - .collect::>() - .into() - }) - .collect(); - let nf = match surfaces.get(i).cloned().flatten() { - Some(mut surface) => { - // Outward like the old face (checked at a boundary point). - let probe = f.boundaries().first().and_then(|w| w.vertex_iter().next()).map(|v| from_p3(v.point())); - let want = probe.and_then(|p| old.get(i).copied().flatten().and_then(|s| s.normal(p))); - if let (Some(p), Some(want)) = (probe, want) { - use mt::{ParametricSurface3D, SearchNearestParameter}; - if let Some((u, v)) = surface.search_nearest_parameter(p3(p), None, 100) { - let nn = surface.normal(u, v); - if Vec3::new(nn.x, nn.y, nn.z).dot(want) < 0.0 { - surface = mt::Invertible::inverse(&surface); - } - } - } - mt::Face::try_new(wires, surface).map_err(|e| fail(&e.to_string()))? - } - None => { - // Unchanged surface: rebuild on the oriented boundary. - let mut nf = mt::Face::try_new( - f.absolute_boundaries() - .iter() - .map(|w| { - w.edge_iter() - .filter_map(|e| { - edges.get(&e.id()).map(|ne| if e.front() == e.absolute_front() { ne.clone() } else { ne.inverse() }) - }) - .collect::>() - .into() - }) - .collect(), - f.surface(), - ) - .map_err(|e| fail(&e.to_string()))?; - if !f.orientation() { - nf.invert(); - } - nf - } - }; - rec.face(&nf, f); - out.push(nf); - } - let shell: mt::Shell = out.into(); - let solid = Solid::try_new(vec![shell]).map_err(|e| fail(&e.to_string()))?; - crate::record::rebuilt(solid, &[&b.solid], &rec) - }) +/// Points along edge `e` of `b` (its ends and three inside), for comparing it with lines. +pub(crate) fn edge_points(b: &Brep, e: u32) -> Vec { + let Some(edge) = b.edges.get(e as usize) else { return Vec::new() }; + let Ok(c) = CurveEval::new(&edge.curve) else { return Vec::new() }; + let [t0, t1] = edge.interval; + (0..=4).filter_map(|k| c.point(t0 + (t1 - t0) * k as f64 / 4.0)).collect() } /// The chosen faces and every face on the same surface joined to them (the halves of a hole's /// wall), as face indices. Pieces of a face split on purpose (Split Face) stay apart. pub fn with_same_surface(b: &Body, chosen: &[usize]) -> Vec { - let faces: Vec = b.solid.face_iter().cloned().collect(); - let size = b.size(); - let tol = (size * 1e-7).max(1e-9) * 100.0; - let surfs: Vec> = faces.iter().map(|f| surf_of(f, tol)).collect(); - let same = |x: &Surf, y: &Surf| match (*x, *y) { - (Surf::Plane { n, d }, Surf::Plane { n: m, d: e }) => n.dot(m) > 1.0 - 1e-9 && (d - e).abs() < tol, - (Surf::Cylinder { o, a, r, convex }, Surf::Cylinder { o: o2, a: a2, r: r2, convex: c2 }) => { - a.dot(a2).abs() > 1.0 - 1e-9 && (r - r2).abs() < tol && convex == c2 && { (o2 - o - a * (o2 - o).dot(a)).len() < tol } - } - (Surf::Sphere { c, r, convex }, Surf::Sphere { c: c2, r: r2, convex: k2 }) => c.dist(c2) < tol && (r - r2).abs() < tol && convex == k2, - (Surf::Cone { v, a, half, convex }, Surf::Cone { v: v2, a: a2, half: h2, convex: k2 }) => { - v.dist(v2) < tol && a.dot(a2) > 1.0 - 1e-9 && (half - h2).abs() < 1e-9 && convex == k2 - } - (Surf::Torus { o, a, big, h, r, convex }, Surf::Torus { o: o2, a: a2, big: b2, h: h2, r: r2, convex: k2 }) => { - (o + a * h).dist(o2 + a2 * h2) < tol && a.dot(a2).abs() > 1.0 - 1e-9 && (big - b2).abs() < tol && (r - r2).abs() < tol && convex == k2 - } - _ => false, - }; + let Ok(record) = crate::native::brep_record(b) else { return chosen.to_vec() }; + let tol = (b.size() * 1e-7).max(1e-9) * 100.0; + let surfs: Vec> = (0..record.faces.len()).map(|i| surf_of(&record, i)).collect(); + let edges: Vec> = (0..record.faces.len()).map(|i| face_edges(&record, i)).collect(); let keep = b.split_keep(); let mut out: Vec = chosen.to_vec(); let mut grew = true; while grew { grew = false; - for (i, f) in faces.iter().enumerate() { + for i in 0..record.faces.len() { if out.contains(&i) { continue; } let Some(Some(si)) = surfs.get(i) else { continue }; + let mine = edges.get(i).map(Vec::as_slice).unwrap_or(&[]); let joins = out.iter().any(|j| { - surfs.get(*j).and_then(|x| x.as_ref()).is_some_and(|sj| same(si, sj)) - && faces.get(*j).is_some_and(|g| { - g.edge_iter().any(|e| { - f.edge_iter().any(|x| x.id() == e.id()) - && (keep.is_empty() || !crate::heal::on_split_line(&crate::heal::edge_points(&e), keep)) + surfs.get(*j).and_then(|x| x.as_ref()).is_some_and(|sj| si.same(sj, tol)) + && edges.get(*j).is_some_and(|theirs| { + theirs.iter().any(|e| { + mine.binary_search(e).is_ok() && (keep.is_empty() || !crate::heal::on_split_line(&edge_points(&record, *e), keep)) }) }) });