diff --git a/crates/kernel/src/matchsurf.rs b/crates/kernel/src/matchsurf.rs
index 8134ea341..623a1ef1f 100644
--- a/crates/kernel/src/matchsurf.rs
+++ b/crates/kernel/src/matchsurf.rs
@@ -16,15 +16,14 @@
//! of the target meet, with shapes that part company, is a seam the target itself does not hold
//! beyond that order, and no surface can be told to carry a condition the target has not got.
-use mt::{BoundedCurve, ParametricCurve, ParametricSurface, ParametricSurface3D, SearchNearestParameter};
use solidcraft_geom::Vec3;
-use truck_modeling as mt;
+use solidcraft_geom::brep::{self as b, eval::CurveEval, eval::SurfaceEval};
-use crate::body::{Body, from_p3, p3};
+use crate::body::Body;
use crate::bridge::{self, Continuity, Frame};
-use crate::record::Rebuild;
-use crate::surfaces::surface_body;
-use crate::{KernelError, Result, guard};
+use crate::history::{Change, EdgeProv, History};
+use crate::surfaces::Chain;
+use crate::{KernelError, Result};
/// Stations a match reads along the seam and along the boundary it keeps.
const STATIONS: usize = 33;
@@ -61,27 +60,31 @@ const SUPPLY_BEND_REL: f64 = 1e-1;
/// target's own shape along it up to `order` — position, tangent, curvature vector, and the
/// change of that curvature vector along the direction the match leaves in. The boundary
/// opposite keeps its place and the original surface's own frame, and the middle is shaped to
-/// stay as close to the original surface as the conditions allow.
+/// stay as close to the original surface as the conditions allow. Its history is over
+/// `[body, target]`: the face is the body's face, modified; its edges are new.
pub fn match_surface(body: &Body, faces: &[Vec3], target: &Body, target_pick: &[Vec3], order: Continuity) -> Result
{
body.require_brep("match")?;
target.require_brep("match")?;
if !body.is_surface() {
return Err(KernelError::Invalid("match rebuilds a surface body: this one is closed".into()));
}
- let face = face_near(body, faces)?;
+ let (record, target_record) = (body.record(), target.record());
+ let face = face_near(&record, faces, body.size() * 0.05 + 1e-6)?;
+ let original = Patch::of(&record, face)?;
let chain = bridge::chain(target, target_pick)?;
- let near = nearest_side(&face, &chain)?;
+ let line = chain_polyline(&target_record, &chain)?;
+ let near = nearest_side(&original, &line)?;
let far = near.opposite();
- let far_edges = side_edges(&face, far, body.size() * 1e-6 + 1e-9)?;
- let (mid_near, mid_far) = (chain_mid(&chain)?, Side::at(&face.surface(), &ranges(&face)?, far, 0.5));
+ let far_edges = side_edges(&record, face, &original, far, body.size() * 1e-6 + 1e-9)?;
+ let (mid_near, mid_far) = (chain_mid(&line)?, original.at(far, 0.5)?);
let leave = (mid_far - mid_near)
.normalized()
.filter(|l| l.is_finite())
.ok_or_else(|| KernelError::Invalid("the far boundary sits on the picked chain: there is nothing to match".into()))?;
// Which face of the target the match continues from, and how much of the requested order the
// target itself holds along that chain.
- let candidates = support_faces(target, &chain, leave)?;
- let supply = supply_order(&candidates, &chain, leave, target.size())?;
+ let candidates = support_faces(target, &chain, &line, leave)?;
+ let supply = supply_order(target, &candidates, &chain, leave)?;
if order.conditions() > supply.conditions() {
return Err(KernelError::Invalid(format!(
"the target's own surfaces part company at the picked edges: they hold only {} there, so a seam cannot hold {}",
@@ -89,13 +92,13 @@ pub fn match_surface(body: &Body, faces: &[Vec3], target: &Body, target_pick: &[
order.as_str()
)));
}
- let Some((target_face, _)) = candidates.first() else {
+ let Some(&(target_face, _)) = candidates.first() else {
return Err(KernelError::Invalid("no face of the target holds the picked edges".into()));
};
// The stations of the seam: what the target does there along the direction the match leaves
// in, and what the far boundary does coming back the other way.
- let mut near_frames = bridge::frames(target_face, &chain, leave, STATIONS)?;
- let far_frames = bridge::frames(&face, &far_edges, leave * -1.0, STATIONS)?;
+ let mut near_frames = bridge::frames(target, target_face, &chain, leave, STATIONS)?;
+ let far_frames = bridge::frames(body, face, &far_edges, leave * -1.0, STATIONS)?;
// The two chains are sampled from their own starts: turn one round when that pairs the
// stations better (a match is built station to station).
let direct: f64 = near_frames.iter().zip(&far_frames).map(|(a, b)| a.p.dist(b.p)).sum();
@@ -103,37 +106,36 @@ pub fn match_surface(body: &Body, faces: &[Vec3], target: &Body, target_pick: &[
if reversed < direct {
near_frames.reverse();
}
- guard("surface match", || {
- // The crown is the free knob: keep the one whose surface stays closest to the original.
- let mut best: Option<(f64, mt::Face)> = None;
- for crown_near in CROWNS {
- for crown_far in CROWNS {
- let made = bridge::bridge(&near_frames, &far_frames, [order, Continuity::G1], [crown_near, crown_far])?;
- let Some(made) = made.solid.face_iter().next().cloned() else {
- return Err(KernelError::Failed("match: the bridge made no face".into()));
- };
- let stray = deviation(&made, &face)?;
- if best.as_ref().is_none_or(|(b, _)| stray < *b) {
- best = Some((stray, made));
- }
+ // The crown is the free knob: keep the one whose surface stays closest to the original.
+ let mut best: Option<(f64, Body)> = None;
+ for crown_near in CROWNS {
+ for crown_far in CROWNS {
+ let made = bridge::bridge(&near_frames, &far_frames, [order, Continuity::G1], [crown_near, crown_far])?;
+ let stray = deviation(&Patch::of(&made.record(), 0)?, &original)?;
+ if best.as_ref().is_none_or(|(b, _)| stray < *b) {
+ best = Some((stray, made));
}
}
- let Some((_, made)) = best else {
- return Err(KernelError::Failed("match: no crown built a surface".into()));
- };
- let mut kept = made;
- // The rebuilt face takes the target's own sense at the seam: the two surfaces then meet
- // the same way round, which is what a stitch, a thicken or a display of the result reads.
- let seam = chain_mid(&chain)?;
- if let (Some((made_n, _)), Some((target_n, _))) = (normal_near(&kept, seam), normal_near(target_face, seam))
- && made_n.dot(target_n) < 0.0
- {
- kept.invert();
- }
- let mut rec = Rebuild::default();
- rec.face(&kept, &face);
- Ok(crate::record::rebuilt_body(surface_body(vec![kept]), &[&body.solid, &target.solid], &rec))
- })
+ }
+ let Some((_, made)) = best else {
+ return Err(KernelError::Failed("match: no crown built a surface".into()));
+ };
+ // The rebuilt face takes the target's own sense at the seam: the two surfaces then meet the
+ // same way round, which is what a stitch, a thicken or a display of the result reads.
+ let seam = chain_mid(&line)?;
+ let made_record = made.record();
+ let turn = match (Patch::of(&made_record, 0)?.normal_near(seam), Patch::of(&target_record, target_face)?.normal_near(seam)) {
+ (Some((m, _)), Some((t, _))) => m.dot(t) < 0.0,
+ _ => false,
+ };
+ let kept = crate::surfaces::Parts::of(&made_record, &[(0, turn)])?.canonical()?;
+ let sheet = crate::surfaces::surface_body(&kept.brep)?;
+ let history = History {
+ operands: 2,
+ faces: vec![crate::record::from_face(0, face, Change::Modified)],
+ edges: (0..sheet.edge_count()).map(|_| EdgeProv { faces: vec![0], origins: Vec::new() }).collect(),
+ };
+ sheet.with_history(history, &[body, target])
}
/// How well the rebuilt surface `made` meets `target` along the chain picked by `target_pick`:
@@ -143,68 +145,61 @@ pub fn match_surface(body: &Body, faces: &[Vec3], target: &Body, target_pick: &[
pub fn seam_continuity(made: &Body, target: &Body, target_pick: &[Vec3]) -> Result<(f64, f64, Continuity)> {
made.require_brep("match")?;
target.require_brep("match")?;
+ let (record, target_record) = (made.record(), target.record());
let chain = bridge::chain(target, target_pick)?;
- let poly = chain_polyline(&chain)?;
+ let poly = chain_polyline(&target_record, &chain)?;
// The face whose boundary runs along the chain: the one nearest it, so that a body that has
// not been matched yet — where the seam is still some way off — can be measured too.
- let mid = chain_mid(&chain)?;
- let face = made
- .solid
- .face_iter()
- .filter_map(|f| face_distance(f, mid).map(|d| (d, f)))
+ let mid = chain_mid(&poly)?;
+ let face = (0..record.faces.len())
+ .filter_map(|f| Patch::of(&record, f).ok().and_then(|p| p.normal_near(mid).map(|(_, d)| (d, p))))
.min_by(|a, b| a.0.total_cmp(&b.0))
- .map(|(_, f)| f.clone())
+ .map(|(_, p)| p)
.ok_or_else(|| KernelError::Failed("match: the body has no faces".into()))?;
- let near = nearest_side(&face, &chain)?;
+ let near = nearest_side(&face, &poly)?;
let far = near.opposite();
- let ranges = ranges(&face)?;
- let mid_far = Side::at(&face.surface(), &ranges, far, 0.5);
- let leave = (mid_far - chain_mid(&chain)?)
+ let leave = (face.at(far, 0.5)? - mid)
.normalized()
.ok_or_else(|| KernelError::Invalid("the seam and the far boundary coincide: there is nothing to measure".into()))?;
- let candidates = support_faces(target, &chain, leave)?;
- let Some((target_face, _)) = candidates.first() else {
+ let candidates = support_faces(target, &chain, &poly, leave)?;
+ let Some(&(target_face, _)) = candidates.first() else {
return Err(KernelError::Invalid("no face of the target holds the picked edges".into()));
};
- let frames = bridge::frames(target_face, &chain, leave, STATIONS)?;
+ let target_patch = Patch::of(&target_record, target_face)?;
+ let frames = bridge::frames(target, target_face, &chain, leave, STATIONS)?;
let size = target.size();
- guard("surface match", || {
- let surf = face.surface();
- let (mut gap, mut deg, mut curv, mut bend) = (0.0f64, 0.0f64, 0.0f64, 0.0f64);
- for i in 0..STATIONS {
- let t = i as f64 / (STATIONS - 1) as f64;
- let p = Side::at(&surf, &ranges, near, t);
- gap = gap.max(chain_distance(&poly, p));
- // What the target says there, and what the rebuilt surface actually does there.
- let Some(frame) = frames.iter().min_by(|a, b| a.p.dist(p).total_cmp(&b.p.dist(p))) else {
- return Err(KernelError::Failed("match: the target has no frames".into()));
- };
- let (_, t_made, bend_made, change_made) = seam_shape(&surf, &ranges, near, t)?;
- if let Some((n_made, _)) = normal_near(&face, p)
- && let Some((n_target, _)) = normal_near(target_face, p)
- {
- deg = deg.max(angle_deg(n_made, n_target));
- }
- let scale = frame.bend.len().max(bend_made.len()).max(1.0 / size);
- curv = curv.max((bend_made - frame.bend).len() / scale);
- // The change of curvature is what a surface can hold: only its normal part counts,
- // and it turns round with the direction of travel.
- let change = if t_made.dot(frame.leave) < 0.0 { change_made * -1.0 } else { change_made };
- let scale3 = frame.bend_change.len().max(change.len()).max(scale / size);
- bend = bend.max((change - frame.bend_change).len() / scale3);
+ let (mut gap, mut deg, mut curv, mut bend) = (0.0f64, 0.0f64, 0.0f64, 0.0f64);
+ for i in 0..STATIONS {
+ let t = i as f64 / (STATIONS - 1) as f64;
+ let p = face.at(near, t)?;
+ gap = gap.max(chain_distance(&poly, p));
+ // What the target says there, and what the rebuilt surface actually does there.
+ let Some(frame) = frames.iter().min_by(|a, b| a.p.dist(p).total_cmp(&b.p.dist(p))) else {
+ return Err(KernelError::Failed("match: the target has no frames".into()));
+ };
+ let (_, t_made, bend_made, change_made) = face.seam_shape(near, t)?;
+ if let (Some((n_made, _)), Some((n_target, _))) = (face.normal_near(p), target_patch.normal_near(p)) {
+ deg = deg.max(angle_deg(n_made, n_target));
}
- let mut order = Continuity::G0;
- if deg <= G1_DEG {
- order = Continuity::G1;
- if curv <= G2_REL {
- order = Continuity::G2;
- if bend <= G3_REL {
- order = Continuity::G3;
- }
+ let scale = frame.bend.len().max(bend_made.len()).max(1.0 / size);
+ curv = curv.max((bend_made - frame.bend).len() / scale);
+ // The change of curvature is what a surface can hold: only its normal part counts, and it
+ // turns round with the direction of travel.
+ let change = if t_made.dot(frame.leave) < 0.0 { change_made * -1.0 } else { change_made };
+ let scale3 = frame.bend_change.len().max(change.len()).max(scale / size);
+ bend = bend.max((change - frame.bend_change).len() / scale3);
+ }
+ let mut order = Continuity::G0;
+ if deg <= G1_DEG {
+ order = Continuity::G1;
+ if curv <= G2_REL {
+ order = Continuity::G2;
+ if bend <= G3_REL {
+ order = Continuity::G3;
}
}
- Ok((gap, deg, order))
- })
+ }
+ Ok((gap, deg, order))
}
/// Which side of a face's parameter rectangle a boundary runs along: the match reads its face as
@@ -251,58 +246,89 @@ impl Side {
}
/// The point at the normalized station `t` along the side.
- fn at(surf: &mt::Surface, ranges: &[(f64, f64); 2], side: Side, t: f64) -> Vec3 {
+ fn at(surf: &SurfaceEval, ranges: &[(f64, f64); 2], side: Side, t: f64) -> Result {
let (u, v) = (ranges[0], ranges[1]);
let (fixed, along) = side.fixed_and_along(u, v);
let t = along.0 + (along.1 - along.0) * t.clamp(0.0, 1.0);
- if side.is_u() { from_p3(surf.subs(fixed, t)) } else { from_p3(surf.subs(t, fixed)) }
+ surf.point(if side.is_u() { [fixed, t] } else { [t, fixed] }).ok_or_else(|| KernelError::Failed("match: a side has no point there".into()))
}
}
-/// The bounded parameter ranges of a face's surface.
-fn ranges(face: &mt::Face) -> Result<[(f64, f64); 2]> {
- let surf = face.surface();
- let (Some(u), Some(v)) = surf.try_range_tuple() else {
- return Err(KernelError::Failed("match: the face's surface is unbounded".into()));
- };
- Ok([u, v])
+/// A face read as a tensor patch: its record surface and its parameter box.
+struct Patch {
+ surface: SurfaceEval,
+ ranges: [(f64, f64); 2],
}
-/// How far `p` is from the face's own surface.
-fn face_distance(face: &mt::Face, p: Vec3) -> Option {
- let surf = face.surface();
- let (u, v) = surf.search_nearest_parameter(p3(p), None, 100)?;
- Some(from_p3(surf.subs(u, v)).dist(p))
+impl Patch {
+ fn of(r: &b::Brep, face: usize) -> Result {
+ let f = r.faces.get(face).ok_or_else(|| KernelError::Invalid(format!("no face {face}")))?;
+ let surface = SurfaceEval::new(&f.surface).map_err(|e| KernelError::Failed(format!("match: face {face}: {e}")))?;
+ let [[u0, u1], [v0, v1]] = f.domain;
+ Ok(Patch { surface, ranges: [(u0, u1), (v0, v1)] })
+ }
+
+ fn at(&self, side: Side, t: f64) -> Result {
+ Side::at(&self.surface, &self.ranges, side, t)
+ }
+
+ /// The surface's unit normal at the point nearest `p`, and how far `p` is from that point.
+ fn normal_near(&self, p: Vec3) -> Option<(Vec3, f64)> {
+ let uv = self.surface.project(p, None, f64::INFINITY)?;
+ let (q, su, sv) = self.surface.derivs(uv[0], uv[1])?;
+ Some((su.cross(sv).normalized()?, q.dist(p)))
+ }
+
+ /// The parameters of the point nearest `p`.
+ fn parameters(&self, p: Vec3) -> Option<[f64; 2]> {
+ self.surface.project(p, None, f64::INFINITY)
+ }
+
+ /// The shape of the surface along its cross direction at the station `t`, read inwards from
+ /// the boundary `near` over five one-sided samples: the point, the unit tangent, the
+ /// curvature vector and the change of that curvature. The same finite difference
+ /// [`crate::bridge::frames`] reads a support surface with, so that a rebuilt seam can be
+ /// compared with what it matched.
+ fn seam_shape(&self, near: Side, t: f64) -> Result<(Vec3, Vec3, Vec3, Vec3)> {
+ let ranges = self.ranges;
+ let (station, cross, at_start) = if near.is_u() {
+ (ranges[1].0 + (ranges[1].1 - ranges[1].0) * t, ranges[0], near == Side::U0)
+ } else {
+ (ranges[0].0 + (ranges[0].1 - ranges[0].0) * t, ranges[1], near == Side::V0)
+ };
+ let span = (cross.1 - cross.0).abs().max(1e-12);
+ let h = span * 1e-3;
+ let c0 = if at_start { cross.0 } else { cross.1 };
+ let sgn = if at_start { 1.0 } else { -1.0 };
+ let at = |x: f64| self.surface.point(if near.is_u() { [x, station] } else { [station, x] });
+ let q: Vec =
+ (0..5).map(|k| at(c0 + sgn * k as f64 * h)).collect::