Wave 318/509: geom, kernel: the patch fill meets its neighbours with G0 to G4, on rational edges too

1 commits, squashed; the originals stay reachable from tag archive/merge-main-develop.

- 99297495b jyviko: geom, kernel: the patch fill meets its neighbours with G0 to G4, on rational edges too

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ
This commit is contained in:
jyviko
2026-10-27 19:56:01 -04:00
parent 0cae7f871c
commit 0d3e1eac82
11 changed files with 1239 additions and 202 deletions
+78 -50
View File
@@ -5,11 +5,14 @@
//! parameters are plane coordinates, so each edge's pcurve is its exact projection onto the
//! plane.
//!
//! The general fill, which also meets the faces beside the loop with G1 or G2, passes through
//! The general fill, which also meets the faces beside the loop with G1 … G4, passes through
//! given points, and fills loops that bound no height field, is a patch whose boundary rows are
//! the loop's own edges (`solidcraft_geom::fill_iso`): each edge's pcurve is a straight line in
//! (u, v). It takes loops of three or four line or spline edges; the frames across each edge are
//! read off the neighbouring face's record surface (exact second derivatives for G2).
//! (u, v), affine in the edge's own parameter. It takes loops of three to sixteen line, spline or
//! rational edges (a circle's arc on the NURBS form SMLib holds it as); the frames across each
//! edge are read off the neighbouring face's record surface, with its exact derivatives to the
//! order asked: the neighbour as a height over its tangent plane to that order
//! (`solidcraft_geom::linkage`).
use solidcraft_geom::Vec3;
use solidcraft_geom::brep::eval::SurfaceEval;
@@ -25,7 +28,7 @@ use crate::history::{Change, EdgeOrigin, EdgeProv, FaceProv, History};
use crate::sew::{PartEdge, PartFace, PartUse, Parts, assemble};
use crate::{KernelError, Result};
/// How far (degrees) a G1 or G2 patch's normal may turn from its neighbour's along the loop.
/// How far (degrees) a G1 … G4 patch's normal may turn from its neighbour's along the loop.
pub const PATCH_ANGLE_TOL_DEG: f64 = 0.05;
/// A spline error as the patch reports it.
@@ -39,7 +42,7 @@ fn spline_error(e: SplineError) -> KernelError {
/// What a patch on a loop of edges must do besides filling it.
#[derive(Clone, Debug, PartialEq)]
pub struct PatchSpec {
/// How every edge's neighbour is met (G0, G1 or G2).
/// How every edge's neighbour is met (G0 … G4).
pub continuity: Continuity,
/// Edges met otherwise: a point on the edge and its continuity.
pub edges: Vec<(Vec3, Continuity)>,
@@ -77,9 +80,11 @@ pub struct PatchReport {
/// corners where the neighbours themselves disagree, and anywhere.
pub normal_deviation_deg: f64,
pub normal_deviation_all_deg: f64,
/// The largest difference (1/mm) between the patch's normal curvature across a G2 edge and
/// the neighbour's.
pub curvature_mismatch: f64,
/// `jumps[k]`, k = 2 … 4: the largest jump across the edges asked for order k or more, clear
/// of the loop's corners, of the k-th derivative of the linkage curves' height above the
/// neighbour (1/mmᵏ⁻¹): the normal curvature (k = 2), its rate of change
/// (3) and that rate's (4) (`solidcraft_geom::fill_iso::Achieved::jumps`).
pub jumps: [f64; solidcraft_geom::linkage::MAX_CONTINUITY + 1],
/// The farthest point from the surface.
pub point_gap: f64,
}
@@ -100,10 +105,6 @@ pub fn patch_edges_report(body: &Body, at: &[Vec3], spec: &PatchSpec) -> Result<
if !(solidcraft_geom::fill::MIN_CROWN..=solidcraft_geom::fill::MAX_CROWN).contains(&spec.crown) {
return Err(KernelError::Invalid("a patch's crown must be between -0.9 and 3".into()));
}
let g3 = |g: Continuity| g == Continuity::G3;
if g3(spec.continuity) || spec.edges.iter().any(|(_, g)| g3(*g)) {
return Err(KernelError::Invalid("not supported yet: a patch meets its neighbours with g0, g1 or g2".into()));
}
if spec.edges.len() > 10_000 || spec.edges.iter().any(|(p, _)| !p.is_finite()) {
return Err(KernelError::Invalid("pick at most 10000 edges, each by a finite point, for their continuity".into()));
}
@@ -125,7 +126,7 @@ pub fn patch_edges_report(body: &Body, at: &[Vec3], spec: &PatchSpec) -> Result<
}
}
if spec.crown != 0.0 && orders.iter().all(|g| *g == Continuity::G0) {
return Err(KernelError::Invalid("not supported yet: a crown on a patch through points with no g1 or g2 edge".into()));
return Err(KernelError::Invalid("not supported yet: a crown on a patch through points with no g1 or higher edge".into()));
}
general_fill(body, &record, &chain, &orders, &spec.points, spec.crown)
}
@@ -151,7 +152,7 @@ fn general_fill(
let size = body.size().max(solidcraft_geom::LINEAR_TOL);
let mut beside: Vec<Option<Beside>> = Vec::with_capacity(chain.len());
for (&(e, forward), order) in chain.iter().zip(orders) {
beside.push(if *order == Continuity::G0 { None } else { Some(Beside::new(record, e, forward, *order == Continuity::G2, size)?) });
beside.push(if *order == Continuity::G0 { None } else { Some(Beside::new(record, e, forward, *order, size)?) });
}
// Where a G1/G2 edge's neighbour and the one before disagree at their corner.
let n = chain.len();
@@ -181,7 +182,7 @@ fn general_fill(
gap: 0.0,
normal_deviation_deg: a.normal_deviation.to_degrees(),
normal_deviation_all_deg: a.normal_deviation_all.to_degrees(),
curvature_mismatch: a.curvature_mismatch,
jumps: a.jumps,
point_gap: a.point_deviation,
};
Ok((made, report))
@@ -208,7 +209,7 @@ pub(crate) fn matched_patch(body: &Body, chain: &[(usize, bool)], curvature_tol:
let mut beside = Vec::with_capacity(chain.len());
for &(e, forward) in chain {
sides.push(Side::new(&record, e, forward)?);
beside.push(Beside::new(&record, e, forward, true, size)?);
beside.push(Beside::new(&record, e, forward, Continuity::G2, size)?);
}
// A vertex of the loop is a corner where the loop turns there: the edge arriving and the one
// leaving go different ways.
@@ -241,44 +242,44 @@ pub(crate) fn matched_patch(body: &Body, chain: &[(usize, bool)], curvature_tol:
Ok((made, fill))
}
/// A loop edge as the patch takes it: a non-rational B-spline on the edge's interval, running
/// the loop's way, its ends on the edge's vertices. Conics and traced curves have no such form
/// in their own parameter (an arc's angle is no rational function of a NURBS parameter), and a
/// rational edge none the Coons sum can blend: refused by name.
/// A loop edge as the patch takes it: a B-spline on the edge's interval, rational when the edge
/// is (a circle or ellipse on the NURBS form SMLib holds it as, whose parameter the edge's interval
/// and pcurves are in), running the loop's way, its ends on the edge's vertices. A traced curve
/// has no such form in its own parameter and is refused by name.
fn iso_edge(record: &b::Brep, e: usize, forward: bool) -> Result<IsoEdge> {
let edge = record.edges.get(e).ok_or_else(|| KernelError::Failed("patch: edge reference".into()))?;
let v3 = |p: &[f64; 3]| Vec3::new(p[0], p[1], p[2]);
let [a, z] = edge.interval;
let (degree, knots, points): (usize, Vec<f64>, Vec<Vec3>) = match &edge.curve {
let (degree, knots, h): (usize, Vec<f64>, Vec<HPoint>) = match edge.parameters() {
b::Curve::Line { start, end } => {
let (s, t) = (v3(start), v3(end));
(1, vec![a, a, z, z], vec![s + (t - s) * a, s + (t - s) * z])
(1, vec![a, a, z, z], vec![HPoint::weighted(s + (t - s) * a, 1.0), HPoint::weighted(s + (t - s) * z, 1.0)])
}
b::Curve::Polyline { points } => {
let mut knots = vec![0.0];
knots.extend((0..points.len()).map(|i| i as f64));
knots.push(points.len().saturating_sub(1) as f64);
(1, knots, points.iter().map(v3).collect())
(1, knots, points.iter().map(|p| HPoint::weighted(v3(p), 1.0)).collect())
}
b::Curve::Spline { knots, points } => (knots.len().saturating_sub(points.len() + 1), knots.clone(), points.iter().map(v3).collect()),
b::Curve::RationalSpline { knots, homogeneous } if homogeneous.windows(2).all(|w| w[0][3] == w[1][3]) => (
b::Curve::Spline { knots, points } => {
(knots.len().saturating_sub(points.len() + 1), knots.clone(), points.iter().map(|p| HPoint::weighted(v3(p), 1.0)).collect())
}
b::Curve::RationalSpline { knots, homogeneous } => (
knots.len().saturating_sub(homogeneous.len() + 1),
knots.clone(),
homogeneous.iter().map(|h| Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3])).collect(),
homogeneous.iter().map(|h| HPoint { x: h[0], y: h[1], z: h[2], w: h[3] }).collect(),
),
_ => {
return Err(KernelError::Invalid(format!(
"not supported yet: a general patch on edge {e}, a circle, ellipse, rational or traced curve (its pcurve on the patch has no exact form in its own parameter)"
"not supported yet: a general patch on edge {e}, a circle or ellipse with no NURBS form, or a traced curve (its pcurve on the patch has no exact form in its own parameter)"
)));
}
};
// The piece on the edge's interval, then run the loop's way.
let h: Vec<HPoint> = points.iter().map(|p| HPoint::weighted(*p, 1.0)).collect();
let (mut knots, h) = solidcraft_geom::bspline::segment(degree, &knots, &h, a, z).map_err(spline_error)?;
let mut points: Vec<Vec3> = h.iter().map(|p| p.xyz()).collect();
let (mut knots, mut h) = solidcraft_geom::bspline::segment(degree, &knots, &h, a, z).map_err(spline_error)?;
if !forward {
knots = knots.iter().rev().map(|k| a + z - k).collect();
points.reverse();
h.reverse();
// The interval's ends exactly (the reflection's rounding), so a piece's ends name them.
let n = knots.len();
for (i, k) in knots.iter_mut().enumerate() {
@@ -289,6 +290,12 @@ fn iso_edge(record: &b::Brep, e: usize, forward: bool) -> Result<IsoEdge> {
}
}
}
let rational = h.iter().any(|q| q.w != 1.0);
let mut points = h
.iter()
.map(|q| q.project().filter(|_| q.w > 0.0))
.collect::<Option<Vec<Vec3>>>()
.ok_or_else(|| KernelError::Invalid(format!("not supported yet: a general patch on edge {e}, whose weights are not all positive")))?;
// Its ends exactly on the loop's vertices.
let vertex = |end: usize| record.vertices.get(edge.vertices[end] as usize).map(|v| v3(&v.point));
let (first, last) = if forward { (vertex(0), vertex(1)) } else { (vertex(1), vertex(0)) };
@@ -298,27 +305,28 @@ fn iso_edge(record: &b::Brep, e: usize, forward: bool) -> Result<IsoEdge> {
*l = q;
}
}
Ok(IsoEdge { degree, knots, points })
let weights = rational.then(|| h.iter().map(|q| q.w).collect());
Ok(IsoEdge { degree, knots, points, weights })
}
/// The face beside a G1/G2 edge, read at points of the edge: its record surface, which side of
/// it is outward, whether its boundary runs the edge the loop's way, and whether its curvature
/// is read (G2).
/// The face beside a G1 … G4 edge, read at points of the edge: its record surface, which side of
/// it is outward, whether its boundary runs the edge the loop's way, and how much of it is read
/// (`order`: its tangent plane for G1, and its jet to that order above).
struct Beside {
surface: SurfaceEval,
side: f64,
along: bool,
edge: usize,
forward: bool,
curvature: bool,
order: Continuity,
reach: f64,
}
impl Beside {
fn new(record: &b::Brep, e: usize, forward: bool, curvature: bool, size: f64) -> Result<Beside> {
fn new(record: &b::Brep, e: usize, forward: bool, order: Continuity, size: f64) -> Result<Beside> {
let edge = record.edges.get(e).ok_or_else(|| KernelError::Failed("patch: edge reference".into()))?;
let [u] = edge.uses.as_slice() else {
return Err(KernelError::Invalid("an edge of the loop lies between two faces: g1 and g2 need the one face beside it".into()));
return Err(KernelError::Invalid("an edge of the loop lies between two faces: g1 and up need the one face beside it".into()));
};
let face = record.faces.get(u.face as usize).ok_or_else(|| KernelError::Failed("patch: face reference".into()))?;
let surface = SurfaceEval::new(face.parameters())
@@ -345,15 +353,17 @@ impl Beside {
along: runs_forward == forward,
edge: e,
forward,
curvature,
order,
reach: (size * 1e-4).max(1e-6),
})
}
/// The neighbour's conditions at parameter `t` of the loop's edge (its `IsoEdge`, run the
/// loop's way, whose parameter is the edge's reversed where the loop runs against it):
/// its normal, the direction it leaves the edge in, away from it, and for G2 its curvature
/// vector along that direction. `None` where the edge has no tangent there.
/// its normal, the direction it leaves the edge in, away from it, and for G2 and up its
/// curvature vector along that direction and its jet to the order asked
/// (`solidcraft_geom::linkage::surface_jet`, on the frame of the boundary and the leave
/// direction). `None` where the edge has no tangent there.
fn across(&self, record: &b::Brep, t: f64) -> Result<Option<Across>> {
let edge = record.edges.get(self.edge).ok_or_else(|| KernelError::Failed("patch: edge reference".into()))?;
let [a, z] = edge.interval;
@@ -370,11 +380,23 @@ impl Beside {
// Away from the face: its boundary's direction × its outward normal.
let boundary = if self.along { tangent } else { tangent * -1.0 };
let leave = boundary.cross(normal).normalized().ok_or_else(|| KernelError::Invalid("the boundary runs along the face's normal".into()))?;
let bend = if self.curvature { Some(normal * normal_curvature(&self.surface, uv, normal, leave)?) } else { None };
Ok(Some(Across { leave, normal, bend }))
let order = continuity_order(self.order);
if order < 2 {
return Ok(Some(Across { leave, normal, bend: None, jet: None }));
}
let bend = Some(normal * normal_curvature(&self.surface, uv, normal, leave)?);
let jet = solidcraft_geom::linkage::surface_jet(&self.surface, uv, normal, leave, order).ok_or_else(|| {
KernelError::Invalid(format!("not supported yet: g{order} to a face whose surface has no derivatives of order {order} there"))
})?;
Ok(Some(Across { leave, normal, bend, jet: Some(jet) }))
}
}
/// The continuity order a [`Continuity`] asks: 0 (G0) … n, the one place it is read as a number.
fn continuity_order(g: Continuity) -> usize {
g.conditions().saturating_sub(1)
}
/// The normal curvature of a surface at `uv` along the unit tangent `w`: `n·r''` of the unit-speed
/// curve on it leaving that way (the second fundamental form, exact second derivatives).
fn normal_curvature(s: &SurfaceEval, uv: [f64; 2], n: Vec3, w: Vec3) -> Result<f64> {
@@ -783,7 +805,9 @@ fn quilt_body(body: &Body, record: &b::Brep, chain: &[(usize, bool)], fill: &Iso
};
}
let id = index(edges.len())?;
edges.push(PartEdge { curve: edge.curve.clone(), interval: [lo, hi], vertices: ends });
// The curve the interval and the pcurve's parameter are on: a conic's
// NURBS form.
edges.push(PartEdge { curve: edge.parameters().clone(), interval: [lo, hi], vertices: ends });
origin.push(Some(e));
piece_of.insert(key, id);
id
@@ -802,12 +826,16 @@ fn quilt_body(body: &Body, record: &b::Brep, chain: &[(usize, bool)], fill: &Iso
let start = middle(&mut vertices, &mut middle_of, spoke, edge, 0.5 * (edge.interval[0] + edge.interval[1]))?;
let end = centre.ok_or_else(|| fail("centre"))?;
let id = index(edges.len())?;
let points = curve.points.iter().map(|p| [p.x, p.y, p.z]).collect();
edges.push(PartEdge {
curve: b::Curve::Spline { knots: curve.knots.clone(), points },
interval: [0.0, 1.0],
vertices: [start, end],
});
let spline = match &curve.weights {
Some(w) => b::Curve::RationalSpline {
knots: curve.knots.clone(),
homogeneous: curve.points.iter().zip(w).map(|(p, w)| [p.x * w, p.y * w, p.z * w, *w]).collect(),
},
None => {
b::Curve::Spline { knots: curve.knots.clone(), points: curve.points.iter().map(|p| [p.x, p.y, p.z]).collect() }
}
};
edges.push(PartEdge { curve: spline, interval: [0.0, 1.0], vertices: [start, end] });
origin.push(None);
spoke_of.insert(spoke, id);
id
+1 -1
View File
@@ -195,7 +195,7 @@ fn spec(g: Continuity) -> PatchSpec {
fn report(name: &str, r: &PatchReport) {
eprintln!(
"{name}: fill reports gap {:e}, normals within {:.4}° ({:.4}° near clashing corners), curvature mismatch {:e}, points within {:e}",
r.gap, r.normal_deviation_deg, r.normal_deviation_all_deg, r.curvature_mismatch, r.point_gap
r.gap, r.normal_deviation_deg, r.normal_deviation_all_deg, r.jumps[2], r.point_gap
);
}