surface.boundary: surfaces through boundary curves and curve networks (#763) (#2129)

* feat(geom): surfaces through curve networks, and spline spaces to build them

Adds spline_space (clamped B-spline spaces, Hermite interpolation, exact
embedding by Bézier degree elevation and knot insertion, a monotone cubic
for reparameterising) and network (loft, Coons and Gordon surfaces through
curves in one or two directions, with G1/G2 cross-boundary conditions
against a neighbouring face). Part of #763.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(kernel): boundary surfaces from sketch curves, 3D curves and edges

kernel::boundary_network turns sketch chains, 3D sketch polylines and edge chains
into network curves, gives G1 frames of the faces along open edges
(EdgeFaces), builds the B-spline face (sides split at chain vertices so a
join shares the body's edges) and joins it into a surface body by stitching.
G2 is refused for now (not supported yet). Part of #763.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(kernel): second derivatives of B-spline surfaces in the vendored truck-geometry

BSplineSurface::uuder and vvder multiplied the second differences by p
instead of p·(p − 1), as BSplineCurve::der2 does, so every surface of
degree p ≥ 3 (NURBS too, through its homogeneous surface) reported
1/(p − 1) of its second derivative: a cubic surface's curvature read as
half. This is why a G2 boundary surface on a cylinder measured half the
curvature it carries (#763). New tests hold both to finite differences
for degrees 2 to 5.

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

* feat(kernel): G2 boundary surfaces against a body's face

The network always carried the face's curvature across a G2 edge; the
refusal came from measuring it with truck's halved surface second
derivatives (fixed in the previous commit). EdgeFaces now reads the
face's second fundamental form from the exact second derivatives
instead of differencing the normal. A new test holds the curvature
across a cylinder's edge to the cylinder's within 0.1%, also with a
sheared far curve; G3 is refused (a network holds up to G2).

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

* test(kernel): a boundary patch with straight corners measures its own area

A stadium's arcs meet its lines at 180°, so the Coons patch is singular
at its corners. From such a corner the reference mesher's boundary walk
ran onto the B-spline's extrapolation past its domain (a planar spline
passes through every point of its plane there), and the face measured
289 mm² for its 158.5 (#763). The vendored mesher's bounded projection
(nearest_projection, #2043) keeps the walk on the domain; this holds it
there, by the faces, the measuring mesh and the display mesh. The
display path (#1653) was never affected.

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

* feat(geom,kernel): three-sided boundary surfaces (one side collapsed to a point)

A network curve may be a PointCurve: the apex where the two sides beside
it meet. The curves through it cross it at the point itself, its row of
the net collapses there, and the kernel's face leaves that side out of
its loop (three edges, one vertex at the apex). One point per patch, as
a side; refused elsewhere, when it moves, or with a continuity
condition. Tests: a triangle and a quarter disc filled flat with their
analytic areas (40 mm², 25π), by geom and by the kernel's faces and
meshes.

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

* feat(doc): boundary surfaces through curve networks and loops of three or four

FeatureKind::SurfaceNetwork saves a network as `u` and `v` curves, each
a sketch chain (planar or 3D), a chain of a body's edges with an
optional G1/G2 continuity, or a point (the apex of a three-sided
patch), and an `operation` that can join the surface into the body of
its edges. A SurfaceBoundary of three or four sketch curves, refused
until now, builds as the flat Coons patch of its loop (three collapse
the side opposite the first curve). The format change is one pending
file; feature-walk goldens record the new variant's sketches, bodies
and points.

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

* feat(engine): surface.boundary through loops of three or four and curve networks

The command keeps its loop form (two to four curves of one sketch; three
and four now build the flat patch of the loop, crown refused there) and
gains a network form: `u` and `v`, each curve a sketch curve id, a
{sketch?, curves} chain (planar or 3D), a {body, edges, continuity?}
edge chain (g1/g2 with the face beside it) or a {point} for a
three-sided patch, with `operation` new or join. Edits may move between
the two forms (timeline.redefine accepts the command now that it has a
dialog).

Tests: analytic areas of loop patches and of a hyperbolic paraboloid
bounded by four 3D lines (every mesh vertex on z = xy/10), a loft
across two sketches, G1 and G2 measured across a cylinder's edge with
inspect.continuity (angle < 0.1°; curvature jump 1e-16 with G2 against
0.027 with G1), 26 hostile networks refused without panicking, and u/v
added to hostile_params_never_panic.

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

* feat(ui): Boundary Surface dialog

Curves and Cross curves take sketch curves and edges (picks that meet
end to end in one sketch or body are one chain); Continuity and
Operation (New Body or Join). Two to four sketch curves of one sketch
with nothing across are the loop patch; anything else is a network.
Edit Feature brings either back (per-side orders, crown and stations
the dialog does not show are kept). Strings in en, ja and zh.

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

* docs: ROADMAP M8 and the bridge patch's notes for boundary networks (#763)

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

* test(oracle): a boundary surface through a loop, thickened (#763)

Case 83: four sketch curves (a square's three sides and a half circle
for its top) make one boundary surface, thickened 2 mm; analytic values
from tools/oracle-analytic/cases_surfaces.py (V = 2A, area 2A + 2P,
centroid by moments). Recipes gain boundary_surface, thicken and remove.

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

* refactor: boundary surfaces, review cleanups

Project onto the face once per derivative evaluation (the frame is
passed to natural() and reused by scale()), keep each track's
finite-difference step instead of rescanning its table, export the
kernel's edge-pick and chain caps and the default station count for
the engine, doc and dialog to share, map TooLarge spline errors to
KernelError::TooLarge, reuse the engine's operation parser, and skip
the dialog's sketch lookup when the picks are no loop.

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

---------

Co-authored-by: jyviko <2501648+jyviko@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: bherbruck <brennen.herbruck@gmail.com>
This commit is contained in:
authored and GitHub committed 2026-10-17 21:47:38 -04:00
1 parent ae6a33bf96
commit 83c31d77c4
37 files changed
+4358 -44

No files matched your search

+40 -3
View File
@@ -1465,6 +1465,19 @@ pub enum FeatureKind {
#[serde(default = "boundary_samples")]
samples: usize,
},
/// One surface through a curve network (`surface.boundary` with `u` and `v`, issue #763): the
/// curves `u` run one way (two or more: the surface lofts through them) and `v` cross them the
/// other way (two each way: a Coons patch; more: a Gordon surface through every curve). A side
/// may be a point (a three-sided patch). A curve that is a chain of a surface's open edges may
/// carry G1 or G2 with the face beside it. `operation` join sews the surface into the body of
/// its first edge curve (a solid when it closes the gap there).
SurfaceNetwork {
u: Vec<NetworkCurve>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
v: Vec<NetworkCurve>,
#[serde(default)]
operation: Operation,
},
/// One face of a surface body rebuilt against another body (`surface.match`): the rebuilt
/// boundary nearest the chain of `edges` on `target` takes that chain's place and repeats the
/// target's own shape along the seam up to `order`, while the boundary opposite it, and the
@@ -1692,6 +1705,27 @@ pub struct BlendSide {
pub edges: Vec<Position>,
}
/// One curve of a boundary surface's network ([`FeatureKind::SurfaceNetwork`]): a chain of a
/// sketch's `curves` (planar or 3D, meeting end to end), a chain of `body`'s edges picked by points
/// on them (`edges`), or a side collapsed to the point `point` (the apex of a three-sided patch).
/// A chain of a surface's open edges may carry `continuity` with the face beside it (G0, the
/// default, G1 or G2).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)]
pub struct NetworkCurve {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sketch: Option<SketchId>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub curves: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub body: Option<BodyName>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub edges: Vec<Position>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub point: Option<Position>,
#[serde(default = "patch_g0", skip_serializing_if = "is_g0")]
pub continuity: Continuity,
}
/// How a patch on a loop of edges meets the faces beside the loop: every edge with `all`, but the
/// edges picked in `edges` with their own.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)]
@@ -1733,9 +1767,12 @@ fn is_g0(g: &Continuity) -> bool {
/// The continuity a blend repeats by default: the tangent plane on both sides.
/// The stations a boundary patch carries by default.
fn boundary_samples() -> usize {
25
BOUNDARY_SAMPLES
}
/// The stations a boundary patch carries when a design does not say.
pub const BOUNDARY_SAMPLES: usize = 25;
fn blend_orders() -> [Continuity; 2] {
[Continuity::G1, Continuity::G1]
}
@@ -2088,7 +2125,7 @@ impl FeatureKind {
FeatureKind::SurfaceSweep { .. } => "SurfaceSweepFeature",
FeatureKind::SurfaceLoft { .. } => "SurfaceLoftFeature",
FeatureKind::SurfaceBlend { .. } => "BlendFeature",
FeatureKind::SurfaceBoundary { .. } => "BoundaryFeature",
FeatureKind::SurfaceBoundary { .. } | FeatureKind::SurfaceNetwork { .. } => "BoundaryFeature",
FeatureKind::SurfaceMatch { .. } => "MatchFeature",
FeatureKind::SurfaceFair { .. } => "FairFeature",
FeatureKind::Stitch { .. } => "StitchFeature",
@@ -2168,7 +2205,7 @@ impl FeatureKind {
FeatureKind::SurfaceSweep { .. } => "SurfaceSweep",
FeatureKind::SurfaceLoft { .. } => "SurfaceLoft",
FeatureKind::SurfaceBlend { .. } => "Blend",
FeatureKind::SurfaceBoundary { .. } => "Boundary",
FeatureKind::SurfaceBoundary { .. } | FeatureKind::SurfaceNetwork { .. } => "Boundary",
FeatureKind::SurfaceMatch { .. } => "Match",
FeatureKind::SurfaceFair { .. } => "Fair",
FeatureKind::Stitch { .. } => "Stitch",
+15
View File
@@ -1035,6 +1035,20 @@ fn placement_digest(doc: &Document, f: &Feature) -> u64 {
}
return hash.finish();
}
// A network through 3D sketch curves reads their points through the components the
// feature and those sketches are placed in, as a sweep's wired path does.
if let FeatureKind::SurfaceNetwork { u, v, .. } = &f.kind {
let sketches: Vec<crate::SketchId> = u.iter().chain(v).filter_map(|c| c.sketch).collect();
if sketches.iter().any(wired) {
let mut hash = std::collections::hash_map::DefaultHasher::new();
doc.component_transform(f.component).iter().flatten().for_each(|value| value.to_bits().hash(&mut hash));
for sketch in &sketches {
let owner = doc.feature(sketch.0).map(|feature| feature.component).unwrap_or(0);
doc.component_transform(owner).iter().flatten().for_each(|value| value.to_bits().hash(&mut hash));
}
return hash.finish();
}
}
// To / From Object finds its target where that target's component is placed (#928).
let to_object = match &f.kind {
FeatureKind::Extrude { extent, .. } => extent.to.is_some() || extent.from.is_some(),
@@ -4691,6 +4705,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st:
| FeatureKind::SurfaceLoft { .. }
| FeatureKind::SurfaceBlend { .. }
| FeatureKind::SurfaceBoundary { .. }
| FeatureKind::SurfaceNetwork { .. }
| FeatureKind::SurfaceMatch { .. }
| FeatureKind::SurfaceFair { .. }
| FeatureKind::SurfaceOffset { .. }
+168 -2
View File
@@ -151,12 +151,49 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature,
st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?,
f.component,
)?;
let boundaries = boundary_frames(&ss, curves, orders, *samples)?;
let body = kernel::boundary_patch(&boundaries, *crown, *samples)?;
// Two curves are the two sides of a bridge. Three or four run round a loop: the Coons
// patch of the loop, which lies in the sketch's plane with them, so every order holds.
let body = if curves.len() >= 3 {
if *crown != 0.0 {
return Err(DocError::Invalid(
"not supported yet: crown on a patch through three or four curves (it is the flat patch of its sides)".into(),
));
}
loop_patch(&ss, curves)?
} else {
let boundaries = boundary_frames(&ss, curves, orders, *samples)?;
kernel::boundary_patch(&boundaries, *crown, *samples)?
};
let name = new_name(st, f, 0);
st.bodies.push(ModelBody::new(name, body, f.id));
Ok(())
}
FeatureKind::SurfaceNetwork { u, v, operation } => {
if !matches!(operation, crate::Operation::NewBody | crate::Operation::Join) {
return Err(DocError::Invalid("a boundary surface is a new body or joins the body of its edges".into()));
}
let us = network_sources(doc, st, f, u, "U")?;
let vs = network_sources(doc, st, f, v, "V")?;
let made = kernel::boundary_surface(&network_curves(&us), &network_curves(&vs))?;
if *operation == crate::Operation::Join {
// Into the body of the first curve picked on a body's edges.
let target = u
.iter()
.chain(v)
.find_map(|c| c.body.clone())
.ok_or_else(|| DocError::Invalid("join needs a curve on a body's edges: the surface is sewn into that body".into()))?;
let i = st.bodies.iter().position(|b| b.name == target).ok_or_else(|| DocError::Unknown(format!("body `{target}`")))?;
let Some(mb) = st.bodies.get(i).cloned() else { return Err(DocError::Invalid("body".into())) };
let joined = kernel::boundary_join(&mb.body, &made)?;
if let Some(slot) = st.bodies.get_mut(i) {
*slot = ModelBody::new(mb.name, joined, mb.feature);
}
return Ok(());
}
let name = new_name(st, f, 0);
st.bodies.push(ModelBody::new(name, made, f.id));
Ok(())
}
FeatureKind::SurfaceMatch { body, faces, target, edges, order } => {
let i = st.bodies.iter().position(|b| &b.name == body).ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?;
let Some(mb) = st.bodies.get(i).cloned() else { return Err(DocError::Invalid("body".into())) };
@@ -439,6 +476,135 @@ fn push_sheet(st: &mut ModelState, f: &Feature, traced: crate::lineage::Traced)
st.bodies.push(ModelBody::traced_new(name, traced, f.id));
}
/// The most curves one direction of a network may list (the kernel's own cap).
const MAX_NETWORK_CURVES: usize = solidcraft_geom::network::MAX_NETWORK_CURVES;
/// A loop of three or four sketch curves as one patch: four give the Coons patch of opposite pairs
/// (the first and third one way, the second and fourth the other); three collapse the side
/// opposite the first curve to the corner where the other two meet.
fn loop_patch(ss: &SolvedSketch, curves: &[String]) -> Result<kernel::Body> {
let mut chains: Vec<Vec<Seg2>> = Vec::with_capacity(curves.len());
for id in curves {
let ci = ss.sketch.curve_index(id).ok_or_else(|| DocError::Unknown(format!("sketch curve `{id}`")))?;
let segs = ss.sketch.exact_segs(ci).unwrap_or_else(|| ss.sketch.segs(ci));
if segs.is_empty() {
return Err(DocError::Invalid(format!("curve `{id}` has no geometry to build on")));
}
chains.push(segs);
}
let side = |k: usize| -> Result<kernel::BoundaryCurve<'static>> {
let (Some(id), Some(segs)) = (curves.get(k), chains.get(k)) else { return Err(DocError::Invalid("a boundary curve is missing".into())) };
Ok(kernel::BoundaryCurve {
label: format!("curve `{id}`"),
source: kernel::CurveSource::Sketch { plane: ss.plane, segs: segs.clone() },
continuity: kernel::Continuity::G0,
})
};
match curves.len() {
4 => Ok(kernel::boundary_surface(&[side(0)?, side(2)?], &[side(1)?, side(3)?])?),
3 => {
// The corner the second and third curves share, whichever way each was drawn.
let ends = |k: usize| -> Option<[Vec2; 2]> {
let c = chains.get(k)?;
Some([c.first()?.start(), c.last()?.end()])
};
let (Some(b), Some(c)) = (ends(1), ends(2)) else { return Err(DocError::Invalid("a boundary curve is missing".into())) };
let mut best = (f64::INFINITY, Vec2::new(0.0, 0.0));
for p in b {
for q in c {
if p.dist(q) < best.0 {
best = (p.dist(q), (p + q) * 0.5);
}
}
}
let apex = kernel::BoundaryCurve {
label: "the corner opposite the first curve".into(),
source: kernel::CurveSource::Point(ss.plane.to_world(best.1)),
continuity: kernel::Continuity::G0,
};
Ok(kernel::boundary_surface(&[side(0)?, apex], &[side(1)?, side(2)?])?)
}
_ => Err(DocError::Invalid("a loop patch takes three or four curves".into())),
}
}
/// A network curve resolved in the feature's frame, owning what it is built from.
enum NetSource {
Sketch(solidcraft_geom::Plane, Vec<Seg2>),
Points(Vec<Vec3>),
Edges(kernel::Body, Vec<Vec3>),
Point(Vec3),
}
/// The curves of one direction of a network, resolved: each one sketch chain, 3D sketch chain,
/// edge chain or point, labelled `U1`, `U2`, … (with `dir` "U") for messages.
fn network_sources(
doc: &Document,
st: &ModelState,
f: &Feature,
list: &[crate::NetworkCurve],
dir: &str,
) -> Result<Vec<(String, NetSource, kernel::Continuity)>> {
if list.len() > MAX_NETWORK_CURVES {
return Err(DocError::Invalid(format!("at most {MAX_NETWORK_CURVES} curves each way")));
}
let mut out = Vec::with_capacity(list.len());
for (k, c) in list.iter().enumerate() {
let label = format!("{dir}{}", k + 1);
let given = [c.sketch.is_some() || !c.curves.is_empty(), c.body.is_some() || !c.edges.is_empty(), c.point.is_some()];
if given.iter().filter(|g| **g).count() != 1 {
return Err(DocError::Invalid(format!("{label} must be sketch curves, a body's edges or a point")));
}
let source = if let Some(p) = c.point {
NetSource::Point(p.0)
} else if let Some(name) = &c.body {
if c.edges.is_empty() {
return Err(DocError::Invalid(format!("{label} needs points on the edges of {name}")));
}
let b = st.body(name).ok_or_else(|| DocError::Unknown(format!("body `{name}`")))?;
NetSource::Edges(b.body.clone(), crate::plain(&c.edges))
} else {
let sk = c.sketch.ok_or_else(|| DocError::Invalid(format!("{label} needs the sketch its curves are in")))?;
if c.curves.is_empty() || c.curves.len() > MAX_CHAIN_CURVES {
return Err(DocError::Invalid(format!("{label} needs 1 to {MAX_CHAIN_CURVES} curves of its sketch")));
}
let raw = st.sketch(sk.0).ok_or_else(|| DocError::Unknown(format!("sketch {sk} (it must come earlier in the timeline)")))?;
// 3D sketch curves are followed through their points; planar ones exactly.
let mapped = path_in_frame(doc, raw, f.component)?;
match path_points(&mapped, &c.curves, Vec3::new(f64::NAN, f64::NAN, f64::NAN))? {
Some(pts) => NetSource::Points(pts),
None => {
let ss = sketch_in_feature_frame(doc, raw, f.component)?;
let mut chains = curve_chains(&ss, &c.curves)?.into_iter();
let (Some(chain), None) = (chains.next(), chains.next()) else {
return Err(DocError::Invalid(format!("{label}: its curves must meet end to end in one chain")));
};
NetSource::Sketch(ss.plane, chain)
}
}
};
out.push((label, source, c.continuity));
}
Ok(out)
}
/// The kernel's curves over resolved sources (borrowing their bodies).
fn network_curves(sources: &[(String, NetSource, kernel::Continuity)]) -> Vec<kernel::BoundaryCurve<'_>> {
sources
.iter()
.map(|(label, src, g)| kernel::BoundaryCurve {
label: label.clone(),
source: match src {
NetSource::Sketch(plane, segs) => kernel::CurveSource::Sketch { plane: *plane, segs: segs.clone() },
NetSource::Points(pts) => kernel::CurveSource::Points(pts.clone()),
NetSource::Edges(body, at) => kernel::CurveSource::Edges { body, at: at.clone() },
NetSource::Point(p) => kernel::CurveSource::Point(*p),
},
continuity: *g,
})
.collect()
}
/// The boundaries `surface.boundary` builds its patch from: each picked curve's own stations in
/// the sketch's frame, every one of them leaving the boundary square into the loop — the direction
/// from the curve towards the middle of the loop, taken across its tangent — over the plane the
@@ -164,6 +164,10 @@ pub(super) fn fixtures() -> Vec<(&'static str, Value)> {
// The Class-A surface family (surface.blend/boundary/match/fair).
("surface_blend", json!({"type": "surface_blend", "from": {"body": "B", "edges": [o]}, "to": {"body": "C", "edges": [o]}, "align": [o, o]})),
("surface_boundary", json!({"type": "surface_boundary", "sketch": 1, "curves": ["l1", "l2"]})),
(
"surface_network",
json!({"type": "surface_network", "u": [{"sketch": 1, "curves": ["l1"]}, {"body": "B", "edges": [o], "continuity": "g1"}], "v": [{"sketch": 2, "curves": ["l1"]}, {"point": o}], "operation": "join"}),
),
("surface_match", json!({"type": "surface_match", "body": "B", "faces": [o], "target": "C", "edges": [o]})),
("surface_fair", json!({"type": "surface_fair", "body": "B", "faces": [o], "tolerance": "sfair.tolerance"})),
("unstitch", json!({"type": "unstitch", "body": "B"})),
@@ -342,6 +342,7 @@ surface_offset
expressions: soff.distance, soff.tolerance
surface_blend
surface_boundary
surface_network
surface_match
surface_fair
inputs:
@@ -157,6 +157,8 @@ surface_offset
surface_blend
moves: align[0][0], align[0][1], align[0][2], align[1][0], align[1][1], align[1][2], from.edges[0][0], from.edges[0][1], from.edges[0][2], to.edges[0][0], to.edges[0][1], to.edges[0][2]
surface_boundary
surface_network
moves: u[1].edges[0][0], u[1].edges[0][1], u[1].edges[0][2], v[1].point[0], v[1].point[1], v[1].point[2]
surface_match
moves: edges[0][0], edges[0][1], edges[0][2], faces[0][0], faces[0][1], faces[0][2]
face points: [0, 0, 0]
@@ -182,6 +182,10 @@ surface_blend
surface_boundary
sketches: [1]
remap_refs: sketch
surface_network
sketches: [1, 2]
remap_refs: u[0].sketch, v[0].sketch
remap_bodies: u[1].body
surface_match
remap_bodies: body
surface_fair
@@ -0,0 +1,7 @@
//! A `SurfaceNetwork` (Boundary Surface through a curve network, #763) saves `u` and `v`, each a
//! list of curves: a `sketch` and its `curves`, a `body` and points on its `edges`, or a `point`
//! (the apex of a three-sided patch), with an optional `continuity` (`g1` or `g2` with the face
//! beside an edge chain), and an `operation` (`new_body`, or `join` into the body of its edges).
//! A `SurfaceBoundary` of three or four curves, which older builds refused, now builds and saves
//! as it always did. Older designs need no transformation; the last release asks for an update
//! instead of meeting a feature it can't read.
+5 -1
View File
@@ -978,6 +978,7 @@ fn redefine(s: &mut Session, p: &Value) -> Result<Value> {
.chain(super::features_more::COMMANDS)
.chain(super::construct::COMMANDS)
.chain(super::surface::COMMANDS)
.chain(super::surface_boundary::COMMANDS)
.any(|candidate| candidate.id == spec.id)
|| matches!(
spec.id,
@@ -1049,7 +1050,10 @@ fn redefine(s: &mut Session, p: &Value) -> Result<Value> {
{
*after = before.clone();
}
if std::mem::discriminant(&new.kind) != std::mem::discriminant(&old.kind) {
// A boundary surface's loop of sketch curves and its curve network are one command's two
// forms: an edit may turn one into the other.
let boundary = |k: &FeatureKind| matches!(k, FeatureKind::SurfaceBoundary { .. } | FeatureKind::SurfaceNetwork { .. });
if std::mem::discriminant(&new.kind) != std::mem::discriminant(&old.kind) && !(boundary(&new.kind) && boundary(&old.kind)) {
return Err(bad(cmd, format!("{} is not a {} feature", old.name, cid)));
}
// Optional inputs can move other inputs' positions (e.g. Distance 2 goes before Taper).
+165 -25
View File
@@ -1,38 +1,56 @@
//! Boundary surfaces: one patch through a network of two to four sketch curves (`surface.boundary`,
//! issue #763). The kernel builds the face from the curves' own frames; this is the command's
//! parameters and its checks, so that a loop it cannot hold is refused before anything is built.
//! Boundary surfaces (`surface.boundary`, issue #763): one patch through two to four sketch
//! curves in loop order, or one surface through a network of curves in two directions (sketch
//! curves, 3D sketch curves, a body's edges, or a point for a three-sided patch). The kernel
//! builds the face; this is the command's parameters and its checks, so that what it cannot hold
//! is refused before anything is built.
use serde_json::Value;
use solidcraft_doc::{FeatureKind, SketchId};
use solidcraft_doc::{BodyName, FeatureKind, NetworkCurve, Operation, Position, SketchId};
use solidcraft_kernel::Continuity;
use super::CommandSpec;
use super::features::{add_feature, feature_sketch};
use crate::params::{bad, string_list};
use super::features::{add_feature, feature_sketch, sketch_id};
use crate::params::{bad, str_, string_list, vec3};
use crate::{Result, Session};
/// The stations a boundary carries by default (the patch's resolution along the loop).
const DEFAULT_SAMPLES: usize = 25;
const DEFAULT_SAMPLES: usize = solidcraft_doc::BOUNDARY_SAMPLES;
/// The fewest stations a patch can hold the widest continuity pair with: a G3 side needs four rows
/// at each of two opposite sides, so eight.
const MIN_SAMPLES: usize = 8;
/// The most stations a boundary may carry (the kernel's own cap).
const MAX_SAMPLES: usize = 512;
/// The most curves one direction of a network may list (the kernel's own cap).
const MAX_NETWORK_CURVES: usize = solidcraft_geom::network::MAX_NETWORK_CURVES;
/// The most sketch curves one network curve may chain, and points picking one chain of edges
/// (the kernel's own caps).
use solidcraft_kernel::{MAX_CHAIN_CURVES as MAX_CHAIN, MAX_EDGE_PICKS as MAX_PICKS};
pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("surface.boundary", "Boundary Surface", boundary)
.at("SURFACE", "CREATE")
.icon("surface_boundary")
.params(
"sketch?: id|name (default: the sketch being edited); curves: [2 to 4 sketch curve ids in loop order] (each one ends where the next begins and the last where the first does; the patch runs through them and leaves each boundary along the tangent across it); continuity?: g0|g1|g2|g3 | [one per curve] (default g1: how much of the surface across each boundary the patch repeats — a sketch curve's own plane, so g1 and up hold exactly and g0 lets the middle bow); crown?: number -0.9…3 (default 0: how full the middle is, without touching a boundary); samples?: 8…512 stations per boundary (default 25); name?, body_name? (a surface body)",
"Either a loop of one sketch's curves — sketch?: id|name (default: the sketch being edited); curves: [2 to 4 sketch curve ids in loop order] (each one ends where the next begins and the last where the first does; two: the patch spans between them and leaves each boundary along the tangent across it; three or four: the flat patch of the loop, three collapsing the side opposite the first curve to the corner there); continuity?: g0|g1|g2|g3 | [one per curve] (default g1: how much of the surface across each boundary the patch repeats — a sketch curve's own plane, so g1 and up hold exactly and g0 lets the middle bow); crown?: number -0.9…3 (default 0: how full the middle is, without touching a boundary; two curves only); samples?: 8…512 stations per boundary (default 25) — or a curve network — u: [curve] (two or more one way: the surface lofts through them), v?: [curve] (crossing every u-curve once: two each way give a Coons patch, more a Gordon surface through every curve; a curve that misses another by more than 0.01 mm is refused, naming the pair), each curve \"id\" (a curve of `sketch`) | {sketch?: id|name, curves: [ids meeting end to end]} (planar or 3D sketch curves) | {body: name, edges: [[x,y,z]] (points on a chain of its edges), continuity?: g0|g1|g2 (default g0; g1 the surface leaves tangent to the face beside a surface's open edges, g2 with its curvature too; on curves of one direction only)} | {point: [x,y,z]} (a side collapsed to a point: a three-sided patch); operation?: new|join (default new; join sews the surface into the body of its first edge curve, a solid when it closes the gap). name?, body_name? (a surface body)",
)];
/// `surface.boundary`: one patch through a network of two to four sketch curves.
/// `surface.boundary`: a loop of sketch curves, or a network when `u` is given.
fn boundary(s: &mut Session, p: &Value) -> Result<Value> {
if p.get("u").is_some_and(|v| !v.is_null()) {
return network(s, p);
}
loop_patch(s, p)
}
/// `surface.boundary` with `curves`: one patch through two to four sketch curves in loop order.
fn loop_patch(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "surface.boundary";
if p.get("v").is_some_and(|v| !v.is_null()) || p.get("operation").is_some_and(|v| !v.is_null()) {
return Err(bad(cmd, "`v` and `operation` belong to a curve network: give its curves as `u` and `v`"));
}
let sketch = feature_sketch(s, p, cmd)?;
let curves = string_list(p, "curves");
if !(2..=4).contains(&curves.len()) {
return Err(bad(cmd, "`curves` must list 2 to 4 sketch curves in loop order"));
return Err(bad(cmd, "`curves` must list 2 to 4 sketch curves in loop order (or give a network as `u` and `v`)"));
}
// The curves must be the sketch's own, and they must run on into one another: the last station
// of each is the first of the next, and the last boundary's end is the first one's start.
@@ -98,9 +116,134 @@ fn boundary(s: &mut Session, p: &Value) -> Result<Value> {
.ok_or_else(|| bad(cmd, format!("`samples` must be a whole number of stations between {MIN_SAMPLES} and {MAX_SAMPLES}")))?
}
};
if crown != 0.0 && curves.len() >= 3 {
return Err(bad(cmd, "not supported yet: `crown` on a patch through three or four curves (it is the flat patch of its sides)"));
}
add_feature(s, p, FeatureKind::SurfaceBoundary { sketch: SketchId(sketch), curves, orders, crown, samples })
}
/// `surface.boundary` with `u` (and `v`): one surface through a curve network.
fn network(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "surface.boundary";
for key in ["curves", "continuity", "crown", "samples"] {
if p.get(key).is_some_and(|v| !v.is_null()) {
return Err(bad(cmd, format!("`{key}` belongs to a loop of sketch curves: a network gives each curve its own continuity")));
}
}
let operation = super::features::operation(p, cmd)?;
if !matches!(operation, Operation::NewBody | Operation::Join) {
return Err(bad(cmd, "`operation` must be new or join"));
}
// The sketch a bare curve id belongs to, found only when one is used.
let mut default_sketch: Option<u64> = None;
let u = network_curves(s, p, "u", &mut default_sketch)?;
let v = network_curves(s, p, "v", &mut default_sketch)?;
if u.is_empty() {
return Err(bad(cmd, "`u` must list the curves of one direction"));
}
if u.len() + v.len() < 2 {
return Err(bad(cmd, "a boundary surface needs two curves in one direction, or crossing curves"));
}
if operation == Operation::Join && !u.iter().chain(&v).any(|c| c.body.is_some()) {
return Err(bad(cmd, "`operation` join needs a curve on a body's edges: the surface is sewn into that body"));
}
add_feature(s, p, FeatureKind::SurfaceNetwork { u, v, operation })
}
/// One direction of a network (`key` is `u` or `v`), checked: each curve sketch curves that exist
/// (planar or 3D), a body's edges with points on them, or a point; a continuity only on edges.
fn network_curves(s: &Session, p: &Value, key: &str, default_sketch: &mut Option<u64>) -> Result<Vec<NetworkCurve>> {
let cmd = "surface.boundary";
let list = match p.get(key) {
None | Some(Value::Null) => return Ok(Vec::new()),
Some(Value::Array(a)) => a,
Some(_) => return Err(bad(cmd, format!("`{key}` must list curves"))),
};
if list.len() > MAX_NETWORK_CURVES {
return Err(bad(cmd, format!("`{key}` may list at most {MAX_NETWORK_CURVES} curves")));
}
let mut out = Vec::with_capacity(list.len());
for (k, item) in list.iter().enumerate() {
let name = format!("{key}[{k}]");
let mut curve = NetworkCurve { sketch: None, curves: Vec::new(), body: None, edges: Vec::new(), point: None, continuity: Continuity::G0 };
let obj = match item {
Value::String(id) => {
curve.curves = vec![id.clone()];
None
}
Value::Object(_) => Some(item),
_ => return Err(bad(cmd, format!("{name} must be a curve id or {{sketch?, curves}}, {{body, edges}} or {{point}}"))),
};
if let Some(o) = obj {
let has = |k: &str| o.get(k).is_some_and(|v| !v.is_null());
let kinds = [has("curves"), has("body") || has("edges"), has("point")];
if kinds.iter().filter(|x| **x).count() != 1 {
return Err(bad(cmd, format!("{name} must be one of {{sketch?, curves}}, {{body, edges}} or {{point}}")));
}
if has("point") {
curve.point = Some(Position(o.get("point").and_then(vec3).ok_or_else(|| bad(cmd, format!("{name}.point must be [x, y, z]")))?));
} else if kinds[1] {
let body = str_(o, "body").ok_or_else(|| bad(cmd, format!("{name}.body must name a body")))?;
if s.model.state().body(body).is_none() {
return Err(bad(cmd, format!("no body `{body}`")));
}
let edges =
o.get("edges").and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("{name}.edges must list points on the edges")))?;
if edges.is_empty() || edges.len() > MAX_PICKS {
return Err(bad(cmd, format!("{name}.edges must list 1 to {MAX_PICKS} points on a chain of edges")));
}
let pts: Vec<Position> = edges
.iter()
.map(|e| vec3(e).map(Position).ok_or_else(|| bad(cmd, format!("{name}.edges: a point must be [x, y, z]"))))
.collect::<Result<_>>()?;
curve.body = Some(BodyName::from(body.to_string()));
curve.edges = pts;
} else {
curve.curves = string_list(o, "curves");
if o.get("sketch").is_some_and(|v| !v.is_null()) {
curve.sketch = Some(SketchId(sketch_id(s, o.get("sketch"), cmd, &format!("{name}.sketch"))?));
}
}
if let Some(g) = o.get("continuity").filter(|v| !v.is_null()) {
let g = g.as_str().and_then(Continuity::parse).ok_or_else(|| bad(cmd, format!("{name}.continuity must be g0, g1 or g2")))?;
if g == Continuity::G3 {
return Err(bad(cmd, format!("not supported yet: G3 on {name} (a curve network holds up to g2)")));
}
if g != Continuity::G0 && curve.body.is_none() {
return Err(bad(cmd, format!("{name}: g1 and g2 apply to a curve on a body's edges (a surface's open edges)")));
}
curve.continuity = g;
}
}
if curve.point.is_none() && curve.body.is_none() {
if curve.curves.is_empty() || curve.curves.len() > MAX_CHAIN {
return Err(bad(cmd, format!("{name} must list 1 to {MAX_CHAIN} sketch curves")));
}
let sketch = match curve.sketch {
Some(id) => id.0,
None => match *default_sketch {
Some(id) => id,
None => {
let id = feature_sketch(s, p, cmd)?;
*default_sketch = Some(id);
id
}
},
};
let state = s.model.state();
let sk = state.sketch(sketch).ok_or_else(|| bad(cmd, "the sketch has not been solved"))?;
for id in &curve.curves {
if sk.sketch.curve_index(id).is_none() && sk.sketch.wire_index(id).is_none() {
return Err(bad(cmd, format!("{name}: no sketch curve `{id}`")));
}
}
curve.sketch = Some(SketchId(sketch));
}
out.push(curve);
}
Ok(out)
}
#[cfg(test)]
mod tests {
use serde_json::{Value, json};
@@ -154,27 +297,19 @@ mod tests {
}
#[test]
fn a_boundary_patch_refuses_a_loop_and_values_it_cannot_hold() {
fn a_boundary_patch_refuses_values_it_cannot_hold() {
let mut s = new_sketch();
let curves = two_walls(&mut s);
let extra = ids(&run(&mut s, "sketch.line", json!({"points": [[30, 30], [40, 40]]}))["created"]["curves"])[0].clone();
// A loop of three or four: the kernel refuses it with its own reason (a tensor-product patch
// cannot hold two sides' data at a corner, issue #763) rather than building it approximately.
let triangle = ["l1", "l2", "l3"].map(|id| {
let _ = id;
String::new()
});
let _ = triangle;
// A loop of three: the crown is the bridge's, not the flat loop patch's.
let a = ids(&run(&mut s, "sketch.line", json!({"points": [[0, 0], [20, 0]]}))["created"]["curves"])[0].clone();
let b = ids(&run(&mut s, "sketch.line", json!({"points": [[20, 0], [10, 15]]}))["created"]["curves"])[0].clone();
let c = ids(&run(&mut s, "sketch.line", json!({"points": [[10, 15], [0, 0]]}))["created"]["curves"])[0].clone();
let e = s.execute("surface.boundary", &json!({"curves": [a, b, c], "continuity": "g2"})).unwrap_err().to_string();
assert!(e.contains("not supported yet") && e.contains("#763"), "three boundaries: {e}");
// A closed square of four lines, in loop order.
let sq = [[[0, 0], [10, 0]], [[10, 0], [10, 10]], [[10, 10], [0, 10]], [[0, 10], [0, 0]]];
let square: Vec<String> = sq.iter().map(|p| ids(&run(&mut s, "sketch.line", json!({"points": p}))["created"]["curves"])[0].clone()).collect();
let e = s.execute("surface.boundary", &json!({"curves": square})).unwrap_err().to_string();
assert!(e.contains("not supported yet") && e.contains("#763"), "four boundaries: {e}");
let e = s.execute("surface.boundary", &json!({"curves": [a, b, c], "crown": 1})).unwrap_err().to_string();
assert!(e.contains("not supported yet") && e.contains("crown"), "three boundaries with a crown: {e}");
// Curves out of loop order.
let e = s.execute("surface.boundary", &json!({"curves": [curves[0], curves[1], extra]})).unwrap_err().to_string();
assert!(e.contains("loop order"), "{e}");
// Parameters and curves that make no sense.
let cases: Vec<(Value, &str)> = vec![
(json!({"curves": [curves[0]]}), "2 to 4"),
@@ -186,6 +321,7 @@ mod tests {
(json!({"curves": curves, "crown": "full"}), "crown"),
(json!({"curves": curves, "samples": 3}), "samples"),
(json!({"curves": curves, "samples": 2.5}), "samples"),
(json!({"curves": curves, "operation": "join"}), "network"),
];
for (params, want) in cases {
let e = s.execute("surface.boundary", &params).unwrap_err().to_string();
@@ -195,3 +331,7 @@ mod tests {
assert!(s.model.state().bodies.is_empty(), "a refused patch left a body behind");
}
}
#[cfg(test)]
#[path = "surface_boundary_tests.rs"]
mod network_tests;
@@ -0,0 +1,267 @@
//! `surface.boundary` through loops of three or four sketch curves and through curve networks
//! (#763): analytic areas and shapes, G1 and G2 measured across the edge a surface shares with a
//! body (`inspect.continuity`), and refusals of hostile networks that never panic.
use serde_json::{Value, json};
use crate::Session;
fn run(s: &mut Session, id: &str, p: Value) -> Value {
match s.execute(id, &p) {
Ok(v) => v,
Err(e) => panic!("{id} {p}: {e}"),
}
}
fn first(v: &Value) -> String {
v.as_array().and_then(|a| a.first()).and_then(Value::as_str).map(str::to_string).unwrap_or_default()
}
/// A sketch line's id.
fn line(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> String {
first(&run(s, "sketch.line", json!({"points": [a, b]}))["created"]["curves"])
}
/// A 3D sketch line's id (the active sketch must have 3D Sketch on).
fn line3d(s: &mut Session, a: [f64; 3], b: [f64; 3]) -> String {
first(&run(s, "sketch.line3d", json!({"points": [a, b]}))["curves"])
}
/// The area of the one face of `body`, and the area `inspect.measure` gives for the whole model.
fn areas(s: &mut Session, body: &str) -> (f64, f64) {
let f = run(s, "model.faces", json!({"body": body}));
let faces = f["faces"].as_array().cloned().unwrap_or_default();
assert_eq!(faces.len(), 1, "one face: {f}");
let face = faces[0]["area"].as_f64().unwrap_or(f64::NAN);
let m = run(s, "inspect.measure", json!({}));
(face, m["total"]["area_mm2"].as_f64().unwrap_or(f64::NAN))
}
/// Three and four sketch curves in loop order: the flat patch of the loop. A triangle and a square
/// of lines, and a square whose top is a half circle bulging out, each measure their own area.
#[test]
fn three_and_four_curve_loops_are_flat_patches() {
use std::f64::consts::PI;
let cases: Vec<(Vec<[[f64; 2]; 2]>, f64, f64)> = vec![
(vec![[[0.0, 0.0], [20.0, 0.0]], [[20.0, 0.0], [10.0, 15.0]], [[10.0, 15.0], [0.0, 0.0]]], 150.0, 1e-6),
(vec![[[0.0, 0.0], [10.0, 0.0]], [[10.0, 0.0], [10.0, 10.0]], [[10.0, 10.0], [0.0, 10.0]], [[0.0, 10.0], [0.0, 0.0]]], 100.0, 1e-6),
];
for (lines, want, tol) in cases {
for continuity in [json!("g0"), json!("g1"), json!("g3")] {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
let curves: Vec<String> = lines.iter().map(|[a, b]| line(&mut s, *a, *b)).collect();
let r = run(&mut s, "surface.boundary", json!({"curves": curves, "continuity": continuity}));
let body = first(&r["created_bodies"]);
let (face, total) = areas(&mut s, &body);
assert!(
(face - want).abs() < tol * want && (total - want).abs() < tol * want,
"{} sides, {continuity}: {face} / {total} vs {want}",
lines.len()
);
}
}
// A square with a half circle for its top, bulging out: 100 + 12.5π.
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
let bottom = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
let right = line(&mut s, [10.0, 0.0], [10.0, 10.0]);
let arc = first(&run(&mut s, "sketch.arc.three_point", json!({"start": [10, 10], "end": [0, 10], "through": [5, 15]}))["created"]["curves"]);
let left = line(&mut s, [0.0, 10.0], [0.0, 0.0]);
let r = run(&mut s, "surface.boundary", json!({"curves": [bottom, right, arc, left]}));
let (face, total) = areas(&mut s, &first(&r["created_bodies"]));
let want = 100.0 + 12.5 * PI;
assert!((face - want).abs() < 2e-3 * want && (total - want).abs() < 2e-3 * want, "{face} / {total} vs {want}");
}
/// Simpson's rule over [0, a] × [0, a] with n (even) intervals each way.
fn simpson2(f: impl Fn(f64, f64) -> f64, a: f64, n: usize) -> f64 {
let h = a / n as f64;
let w = |k: usize| {
if k == 0 || k == n {
1.0
} else if k % 2 == 1 {
4.0
} else {
2.0
}
};
let mut sum = 0.0;
for i in 0..=n {
for j in 0..=n {
sum += w(i) * w(j) * f(i as f64 * h, j as f64 * h);
}
}
sum * h * h / 9.0
}
/// Four straight 3D sketch lines bounding the hyperbolic paraboloid z = x·y/10 over the 10 × 10
/// square: the network's Coons patch is that surface (every vertex of its mesh on it), and its
/// area is the paraboloid's, ∫∫ √(1 + (x/10)² + (y/10)²).
#[test]
fn a_network_of_3d_lines_is_a_hyperbolic_paraboloid() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.options", json!({"sketch_3d": true}));
let a = line3d(&mut s, [0.0, 0.0, 0.0], [10.0, 0.0, 0.0]);
let c = line3d(&mut s, [0.0, 10.0, 0.0], [10.0, 10.0, 10.0]);
let d = line3d(&mut s, [0.0, 0.0, 0.0], [0.0, 10.0, 0.0]);
let b = line3d(&mut s, [10.0, 0.0, 0.0], [10.0, 10.0, 10.0]);
let r = run(&mut s, "surface.boundary", json!({"u": [a, c], "v": [d, b]}));
let body = first(&r["created_bodies"]);
let want = simpson2(|x, y| (1.0 + (x / 10.0).powi(2) + (y / 10.0).powi(2)).sqrt(), 10.0, 200);
let (face, total) = areas(&mut s, &body);
// The face's own area comes from the coarse reference mesh (a chord of a fiftieth of a per
// cent of the body); the measuring mesh is refined onto the surface.
assert!((face - want).abs() < 1e-2 * want && (total - want).abs() < 1e-3 * want, "{face} / {total} vs {want}");
let st = s.world_state();
let mesh = st.body(&body).map(|b| b.body.tessellate(0.01)).and_then(Result::ok).unwrap_or_default();
assert!(!mesh.positions.is_empty());
for p in &mesh.positions {
assert!((p.z - p.x * p.y / 10.0).abs() < 1e-6, "{p:?} is off the paraboloid");
}
}
/// Curves of two planar sketches, one picked by a bare id in the sketch being edited: the loft
/// between a line on the ground and one 10 mm across and 5 mm up is the flat strip between them.
#[test]
fn a_network_takes_curves_from_several_sketches() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Low"}));
let low = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "sketch.create", json!({"plane": "XY", "offset": 5, "name": "High"}));
let high = line(&mut s, [0.0, 10.0], [10.0, 10.0]);
let r = run(&mut s, "surface.boundary", json!({"u": [{"sketch": "Low", "curves": [low]}, high]}));
let (face, _) = areas(&mut s, &first(&r["created_bodies"]));
let want = 10.0 * 125f64.sqrt();
assert!((face - want).abs() < 1e-6 * want, "{face} vs {want}");
}
/// A quarter cylinder sheet (R = 10, axis along x, its straight top edge at y = 10, z = 0 open)
/// and a line 3D-sketched above it; returns the sheet's name and the line's id.
fn cylinder_and_line(s: &mut Session) -> (String, String) {
run(s, "sketch.create", json!({"plane": "YZ", "name": "Arc"}));
let h = 10.0 * std::f64::consts::FRAC_1_SQRT_2;
let arc = first(&run(s, "sketch.arc.three_point", json!({"start": [0, -10], "end": [10, 0], "through": [h, -h]}))["created"]["curves"]);
run(s, "sketch.finish", json!({}));
let sheet = first(&run(s, "surface.extrude", json!({"sketch": "Arc", "curves": [arc], "distance": 10}))["created_bodies"]);
run(s, "sketch.create", json!({"plane": "XY", "name": "Top"}));
run(s, "sketch.options", json!({"sketch_3d": true}));
let top = line3d(s, [0.0, 3.0, 12.0], [10.0, 3.0, 12.0]);
run(s, "sketch.finish", json!({}));
(sheet, top)
}
/// The edge a surface built from the cylinder's top edge shares with it, measured with
/// `inspect.continuity`: (normal angle in degrees, curvature jump per mm).
fn seam(s: &mut Session, body: &str) -> (f64, f64) {
let v = run(s, "inspect.continuity", json!({"body": body, "edges": [[5.0, 10.0, 0.0]]}));
let e = v["bodies"][0]["edges"].as_array().and_then(|a| a.first()).cloned().unwrap_or_default();
(e["normal_angle_deg"]["value"].as_f64().unwrap_or(f64::NAN), e["curvature_jump_per_mm"]["value"].as_f64().unwrap_or(f64::NAN))
}
/// G1 and G2 against a body: a network from the cylinder's open top edge to a line above, joined
/// into the cylinder. Across the shared edge the normals agree within 0.1° for G1 and G2; the
/// curvature jumps by much of the cylinder's 1/R with G1 and by under 1% of it with G2.
#[test]
fn g1_and_g2_networks_meet_a_body_across_its_edge() {
let mut jumps = Vec::new();
for g in ["g1", "g2"] {
let mut s = Session::default();
let (sheet, top) = cylinder_and_line(&mut s);
let r = run(
&mut s,
"surface.boundary",
json!({"u": [{"body": sheet, "edges": [[5.0, 10.0, 0.0]], "continuity": g}, {"sketch": "Top", "curves": [top]}], "operation": "join"}),
);
assert!(r["created_bodies"].as_array().is_none_or(Vec::is_empty), "a join makes no new body: {r}");
let f = run(&mut s, "model.faces", json!({"body": sheet}));
assert_eq!(f["faces"].as_array().map(Vec::len), Some(2), "the surface is sewn into the sheet: {f}");
let (angle, jump) = seam(&mut s, &sheet);
assert!(angle < 0.1, "{g}: normals {angle}° apart across the edge");
jumps.push(jump);
}
let r = 10.0;
assert!(jumps[0] > 0.2 / r, "G1 leaves the curvature behind: jump {}", jumps[0]);
assert!(jumps[1] < 0.01 / r, "G2 carries the cylinder's curvature across: jump {}", jumps[1]);
}
/// Networks that cannot be built are refused with a reason — by the command's own checks or by the
/// kernel — and leave nothing behind; none of them panics.
#[test]
fn hostile_networks_are_refused() {
let mut s = Session::default();
let (sheet, top) = cylinder_and_line(&mut s);
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [40, 40, 0]}));
let boxed = s.world_state().bodies.last().map(|b| b.name.clone()).unwrap_or_default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Flat"}));
let a = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
let b = line(&mut s, [0.0, 5.0], [10.0, 5.0]);
let far = line(&mut s, [0.0, 20.0], [10.0, 20.0]);
let ring = first(&run(&mut s, "sketch.circle.center", json!({"center": [50, 50], "radius": 3}))["created"]["curves"]);
let bodies = s.world_state().bodies.len();
let edge = |g: &str| json!({"body": sheet, "edges": [[5.0, 10.0, 0.0]], "continuity": g});
let many: Vec<Value> = (0..33).map(|_| json!(a)).collect();
let cases: Vec<(Value, &str)> = vec![
(json!({"u": "l1"}), "list"),
(json!({"u": [42, a]}), "curve id"),
(json!({"u": [{}, a]}), "one of"),
(json!({"u": [{"curves": [], "sketch": "Flat"}, a]}), "sketch curves"),
(json!({"u": [{"curves": ["nope"]}, a]}), "no sketch curve"),
(json!({"u": [{"curves": [a], "sketch": "Nope"}, b]}), "no sketch"),
(json!({"u": [{"body": "Nope", "edges": [[0, 0, 0]]}, a]}), "no body"),
(json!({"u": [{"body": sheet, "edges": []}, a]}), "edges"),
(json!({"u": [{"body": sheet, "edges": [["x", 0, 0]]}, a]}), "[x, y, z]"),
(json!({"u": [{"body": sheet, "edges": [[1e300, 0, 0]]}, a]}), "[x, y, z]"),
(json!({"u": [{"point": [0, 0]}, a]}), "point"),
(json!({"u": [{"curves": [a], "body": sheet, "edges": [[5, 10, 0]]}, b]}), "one of"),
(json!({"u": [{"curves": [a], "continuity": "g1"}, b]}), "body's edges"),
(json!({"u": [edge("g3"), {"sketch": "Top", "curves": [top]}]}), "not supported yet"),
(json!({"u": [edge("g9"), {"sketch": "Top", "curves": [top]}]}), "continuity"),
(json!({"u": many}), "at most"),
(json!({"u": [a, b], "curves": [a, b]}), "loop"),
(json!({"u": [a, b], "crown": 1}), "loop"),
(json!({"u": [a, b], "operation": "cut"}), "operation"),
(json!({"u": [a, b], "operation": "join"}), "join"),
(json!({"u": [a]}), "two curves"),
(json!({"u": [], "v": [a, b]}), "`u`"),
// The kernel's refusals: curves that miss, a closed curve, G1 on an edge between two faces.
(json!({"u": [a, b], "v": [{"curves": [far]}, {"curves": [a]}]}), "don't meet"),
(json!({"u": [{"curves": [ring]}, b]}), "closed"),
(json!({"u": [{"body": boxed, "edges": [[45, 40, 0]], "continuity": "g1"}, b]}), "open edge"),
(json!({"u": [a, {"point": [5, 2, 0]}, b]}), "point"),
];
for (params, want) in cases {
let e = match s.execute("surface.boundary", &params) {
Ok(v) => panic!("{params} was built: {v}"),
Err(e) => e,
};
assert!(!matches!(e, crate::EngineError::Internal(..)), "{params}: {e}");
assert!(e.to_string().contains(want), "{params}: {e}");
}
assert_eq!(s.world_state().bodies.len(), bodies, "a refused network left a body behind");
}
/// An edit (`timeline.redefine`) may turn a loop of sketch curves into the network of the same
/// curves and back: the feature keeps its place and its name, and the surface its area.
#[test]
fn an_edit_turns_a_loop_into_a_network_and_back() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Square"}));
let sides: Vec<String> = [[[0.0, 0.0], [10.0, 0.0]], [[10.0, 0.0], [10.0, 10.0]], [[10.0, 10.0], [0.0, 10.0]], [[0.0, 10.0], [0.0, 0.0]]]
.iter()
.map(|[a, b]| line(&mut s, *a, *b))
.collect();
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "surface.boundary", json!({"sketch": "Square", "curves": sides, "name": "Patch"}));
let network = json!({"sketch": "Square", "u": [sides[0], sides[2]], "v": [sides[1], sides[3]]});
run(&mut s, "timeline.redefine", json!({"feature": "Patch", "command": "surface.boundary", "params": network}));
let kind = |s: &Session| s.doc.find_feature("Patch").map(|f| f.kind.clone());
assert!(matches!(kind(&s), Some(solidcraft_doc::FeatureKind::SurfaceNetwork { .. })), "{:?}", kind(&s));
let body = s.world_state().bodies.first().map(|b| b.name.clone()).unwrap_or_default();
assert!((areas(&mut s, &body).0 - 100.0).abs() < 1e-6);
run(&mut s, "timeline.redefine", json!({"feature": "Patch", "command": "surface.boundary", "params": {"sketch": "Square", "curves": sides}}));
assert!(matches!(kind(&s), Some(solidcraft_doc::FeatureKind::SurfaceBoundary { .. })), "{:?}", kind(&s));
assert!((areas(&mut s, &body).0 - 100.0).abs() < 1e-6);
}
+2
View File
@@ -807,6 +807,8 @@ fn hostile_params_never_panic() {
"continuity",
"crown",
"faces",
"u",
"v",
];
// Commands are independent; worker threads take them one at a time (their costs vary a lot).
let ids: Vec<&str> = command_specs()
+5 -2
View File
@@ -1,7 +1,8 @@
//! Geometry foundation for SolidCraft: 2D/3D vectors, sketch planes, axis-aligned boxes,
//! triangle meshes with their measures (volume, area, centroid), and freeform surface maths
//! (B-spline basis and NURBS surfaces in [`bspline`], one-surface fills of closed loops in
//! [`fill`], T-splines in [`tspline`]). Units are millimetres.
//! (B-spline basis and NURBS surfaces in [`bspline`], spline spaces and the operators that make
//! splines compatible in [`spline_space`], one-surface fills of closed loops in [`fill`],
//! surfaces through curve networks in [`network`], T-splines in [`tspline`]). Units are millimetres.
//!
//! This crate has no knowledge of sketches, documents or a modelling backend; every other crate
//! builds on it.
@@ -19,8 +20,10 @@ pub mod fill;
pub mod fill_general;
mod mesh;
pub mod mesh_distance;
pub mod network;
mod plane;
mod profile;
pub mod spline_space;
pub mod tess;
pub mod tspline;
mod vec;
File diff suppressed because it is too large. Load diff
+584
View File
@@ -0,0 +1,584 @@
//! Spline function spaces and the linear operators surface construction is built from: a clamped
//! B-spline space ([`Space`]), interpolation in it with derivative (Hermite) conditions
//! ([`Interpolant`]), carrying a spline into a larger space that contains it ([`embed`]: Bézier
//! degree elevation and Boehm knot insertion, exact), and a monotone piecewise cubic through
//! increasing data ([`Monotone`], for reparameterising curves).
//!
//! These are the pieces that make several splines *compatible* (one degree, one knot vector) so
//! that their control points can be combined linearly: lofting, Coons and Gordon surfaces, and
//! cross-boundary derivative conditions all reduce to them.
//!
//! References: Piegl & Tiller, *The NURBS Book* (2nd ed.) — §2.2–2.3 (basis functions and
//! their derivatives), §5.2 (knot insertion), §5.5 (degree elevation; the Bézier case), §9.2.1
//! (global interpolation, knots by averaging the parameters) and §9.2.2 (interpolation with
//! end derivatives); Fritsch & Carlson 1980, "Monotone piecewise cubic interpolation" (SIAM J.
//! Numer. Anal. 17), with the weighted harmonic-mean slopes of Fritsch & Butland 1984.
//!
//! Input is hostile: constructors check sizes and finiteness and return [`SplineError`]; no
//! function here panics.
use crate::Vec3;
use crate::bspline::{HPoint, MAX_SPLINE_DEGREE, Side, SplineError, SplineResult, check_knots, find_span, insert_knot, invalid, local_basis};
/// Most basis functions a space used for interpolation may have (its systems are solved densely).
pub const MAX_SPACE_DIMENSION: usize = 2048;
/// Values a spline can carry: numbers and points (vectors).
pub trait Linear: Copy {
fn zero() -> Self;
fn plus(self, o: Self) -> Self;
fn times(self, s: f64) -> Self;
/// The value as a homogeneous point of weight one (knot insertion works on those).
fn to_h(self) -> HPoint;
fn from_h(h: HPoint) -> Self;
fn is_finite(self) -> bool;
}
impl Linear for f64 {
fn zero() -> Self {
0.0
}
fn plus(self, o: Self) -> Self {
self + o
}
fn times(self, s: f64) -> Self {
self * s
}
fn to_h(self) -> HPoint {
HPoint { x: self, y: 0.0, z: 0.0, w: 1.0 }
}
fn from_h(h: HPoint) -> Self {
h.x
}
fn is_finite(self) -> bool {
f64::is_finite(self)
}
}
impl Linear for Vec3 {
fn zero() -> Self {
Vec3::ZERO
}
fn plus(self, o: Self) -> Self {
self + o
}
fn times(self, s: f64) -> Self {
self * s
}
fn to_h(self) -> HPoint {
HPoint::weighted(self, 1.0)
}
fn from_h(h: HPoint) -> Self {
h.xyz()
}
fn is_finite(self) -> bool {
Vec3::is_finite(self)
}
}
/// A clamped B-spline space: a degree and a knot vector whose first and last `degree + 1` knots
/// are the domain's ends, interior knots repeated at most `degree` times (the space's splines
/// are continuous).
#[derive(Clone, Debug, PartialEq)]
pub struct Space {
degree: usize,
knots: Vec<f64>,
}
impl Space {
pub fn new(degree: usize, knots: Vec<f64>) -> SplineResult<Space> {
if degree == 0 || degree > MAX_SPLINE_DEGREE {
return Err(SplineError::Unsupported(format!("degree {degree} (1 to {MAX_SPLINE_DEGREE})")));
}
check_knots(&knots)?;
let n = knots.len().checked_sub(degree + 1).filter(|n| *n > degree).ok_or_else(|| SplineError::Invalid("too few knots".into()))?;
if n > MAX_SPACE_DIMENSION {
return Err(SplineError::TooLarge(format!("{n} basis functions (at most {MAX_SPACE_DIMENSION})")));
}
let (a, b) = (knots[0], knots[knots.len() - 1]);
if !(a < b) || knots[..=degree].iter().any(|k| *k != a) || knots[n..].iter().any(|k| *k != b) {
return invalid("the knot vector must be clamped on a non-empty domain");
}
let inner = &knots[degree + 1..n];
let mut run = 0;
for w in inner.windows(2) {
run = if w[0] == w[1] { run + 1 } else { 0 };
if run + 1 > degree {
return invalid("an interior knot is repeated more often than the degree");
}
}
if inner.first().is_some_and(|k| *k == a) || inner.last().is_some_and(|k| *k == b) {
return invalid("an interior knot lies on a domain end");
}
Ok(Space { degree, knots })
}
/// Polynomials of `degree` on `[a, b]` (one Bézier piece).
pub fn polynomial(degree: usize, a: f64, b: f64) -> SplineResult<Space> {
let mut knots = vec![a; degree + 1];
knots.extend(std::iter::repeat_n(b, degree + 1));
Space::new(degree, knots)
}
/// Splines of `degree` with a simple knot at every interior break: `breaks` increase
/// strictly, the first and last are the domain's ends.
pub fn with_breaks(degree: usize, breaks: &[f64]) -> SplineResult<Space> {
let (Some(&a), Some(&b)) = (breaks.first(), breaks.last()) else { return invalid("no breaks") };
if breaks.len() > MAX_SPACE_DIMENSION || breaks.windows(2).any(|w| !(w[0] < w[1])) {
return invalid("the breaks must increase");
}
let mut knots = vec![a; degree + 1];
knots.extend(breaks.iter().skip(1).take(breaks.len().saturating_sub(2)).copied());
knots.extend(std::iter::repeat_n(b, degree + 1));
Space::new(degree, knots)
}
pub fn degree(&self) -> usize {
self.degree
}
pub fn knots(&self) -> &[f64] {
&self.knots
}
/// The number of basis functions (control points of a spline in the space).
pub fn count(&self) -> usize {
self.knots.len() - self.degree - 1
}
/// The domain `[a, b]`.
pub fn domain(&self) -> [f64; 2] {
[self.knots[0], self.knots[self.knots.len() - 1]]
}
/// The `der`-th derivatives at `t` (clamped to the domain) of the basis functions that do not
/// vanish there: the index of the first one and their values.
pub fn basis(&self, t: f64, der: usize) -> SplineResult<(usize, Vec<f64>)> {
let [a, b] = self.domain();
if !t.is_finite() {
return invalid("a parameter is not a finite number");
}
let t = t.clamp(a, b);
let (p, n) = (self.degree, self.count());
let span = find_span(&self.knots, p, n, t).ok_or_else(|| SplineError::Invalid(format!("{t} is outside the domain")))?;
let side = if t >= b { Side::Left } else { Side::Right };
let first = span - p;
let values =
(first..=span).map(|i| self.knots.get(i..i + p + 2).map_or(0.0, |k| local_basis(k, t, side, der).get(der).copied().unwrap_or(0.0)));
Ok((first, values.collect()))
}
/// The `der`-th derivative at `t` of the spline with control values `ctrl`.
pub fn eval<T: Linear>(&self, ctrl: &[T], t: f64, der: usize) -> SplineResult<T> {
if ctrl.len() != self.count() {
return invalid(format!("{} control values for {} basis functions", ctrl.len(), self.count()));
}
let (first, values) = self.basis(t, der)?;
Ok(values.iter().zip(ctrl.iter().skip(first)).fold(T::zero(), |acc, (n, c)| acc.plus(c.times(*n))))
}
/// The splines of this space with `breaks` added as simple knots (those already knots are
/// left as they are). The result contains this space.
pub fn refined(&self, breaks: &[f64]) -> SplineResult<Space> {
let [a, b] = self.domain();
let mut knots = self.knots.clone();
for &x in breaks {
if x > a && x < b && !knots.contains(&x) {
knots.push(x);
}
}
knots.sort_by(f64::total_cmp);
Space::new(self.degree, knots)
}
}
/// A condition on a spline: the value (`der` = 0) or a derivative at `t`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Cond {
pub t: f64,
pub der: usize,
}
/// Interpolation in a space: the spline whose values and derivatives at the conditions are given
/// (as many conditions as the space has basis functions). The system is factored once; each
/// [`Interpolant::fit`] solves it for new data, so one interpolant serves many curves and the
/// rows of a surface alike (the operator is linear).
#[derive(Clone, Debug)]
pub struct Interpolant {
space: Space,
conds: Vec<Cond>,
lu: Lu,
}
impl Interpolant {
pub fn new(space: Space, conds: Vec<Cond>) -> SplineResult<Interpolant> {
let n = space.count();
if conds.len() != n {
return invalid(format!("{} conditions for {n} basis functions", conds.len()));
}
let mut a = vec![0.0; n * n];
for (r, c) in conds.iter().enumerate() {
let (first, values) = space.basis(c.t, c.der)?;
for (k, v) in values.iter().enumerate() {
if let Some(x) = a.get_mut(r * n + first + k) {
*x = *v;
}
}
}
let lu = Lu::new(n, a).map_err(|_| SplineError::Invalid("the interpolation conditions do not determine a spline".into()))?;
Ok(Interpolant { space, conds, lu })
}
/// Interpolation by a single polynomial piece of the lowest degree that meets `conds` (degree
/// one less than their number, at least one: a lone value is held constant), on `[a, b]`;
/// with more than four conditions, a cubic spline whose interior knots average the
/// conditions' parameters (taken as a sequence with one entry per condition, NURBS Book eq.
/// 9.8 applied to that confluent sequence, which keeps every basis function's support over
/// the condition it is matched with).
pub fn lowest(conds: Vec<Cond>, a: f64, b: f64) -> SplineResult<Interpolant> {
let mut conds = conds;
if conds.iter().any(|c| !c.t.is_finite() || c.t < a || c.t > b) {
return invalid("an interpolation parameter is outside the domain");
}
if conds.len() == 1
&& let Some(c) = conds.first().copied()
{
// A constant: the value and a zero slope (the caller supplies zero data for it).
conds.push(Cond { t: c.t, der: 1 });
}
let k = conds.len();
if k <= 4 {
return Interpolant::new(Space::polynomial(k.saturating_sub(1).max(1), a, b)?, conds);
}
let mut tau: Vec<f64> = conds.iter().map(|c| c.t).collect();
tau.sort_by(f64::total_cmp);
let mut breaks = vec![a];
for j in 1..k - 3 {
breaks.push((tau[j] + tau[j + 1] + tau[j + 2]) / 3.0);
}
breaks.push(b);
if breaks.windows(2).any(|w| !(w[0] < w[1])) {
return invalid("the interpolation parameters repeat too often");
}
Interpolant::new(Space::with_breaks(3, &breaks)?, conds)
}
pub fn space(&self) -> &Space {
&self.space
}
pub fn conds(&self) -> &[Cond] {
&self.conds
}
/// The control values of the spline meeting the conditions with `data` (one per condition).
pub fn fit<T: Linear>(&self, data: &[T]) -> SplineResult<Vec<T>> {
if data.len() != self.conds.len() {
return invalid(format!("{} values for {} conditions", data.len(), self.conds.len()));
}
let out = self.lu.solve(data);
if out.iter().any(|x| !x.is_finite()) {
return invalid("interpolation did not give finite control values");
}
Ok(out)
}
}
/// An LU factorisation with partial pivoting of a dense square matrix (row-major).
#[derive(Clone, Debug)]
struct Lu {
n: usize,
a: Vec<f64>,
piv: Vec<usize>,
}
impl Lu {
fn new(n: usize, mut a: Vec<f64>) -> SplineResult<Lu> {
if a.len() != n * n {
return invalid("matrix size");
}
let scale = a.iter().fold(0.0f64, |m, x| m.max(x.abs()));
if !(scale > 0.0 && scale.is_finite()) {
return invalid("singular system");
}
let mut piv = vec![0; n];
for k in 0..n {
let (mut best, mut big) = (k, 0.0);
for r in k..n {
let x = a[r * n + k].abs();
if x > big {
(best, big) = (r, x);
}
}
if !(big > scale * 1e-13) {
return invalid("singular system");
}
piv[k] = best;
if best != k {
for c in 0..n {
a.swap(k * n + c, best * n + c);
}
}
let d = a[k * n + k];
for r in k + 1..n {
let f = a[r * n + k] / d;
a[r * n + k] = f;
if f != 0.0 {
for c in k + 1..n {
a[r * n + c] -= f * a[k * n + c];
}
}
}
}
Ok(Lu { n, a, piv })
}
fn solve<T: Linear>(&self, b: &[T]) -> Vec<T> {
let n = self.n;
let mut x = b.to_vec();
if x.len() != n {
return x;
}
for (k, &p) in self.piv.iter().enumerate() {
x.swap(k, p);
}
for r in 0..n {
let row = &self.a[r * n..r * n + r];
let acc = row.iter().zip(&x[..r]).fold(x[r], |acc, (l, xc)| acc.plus(xc.times(-l)));
x[r] = acc;
}
for r in (0..n).rev() {
let row = &self.a[r * n + r + 1..(r + 1) * n];
let acc = row.iter().zip(&x[r + 1..]).fold(x[r], |acc, (u, xc)| acc.plus(xc.times(-u)));
x[r] = acc.times(1.0 / self.a[r * n + r]);
}
x
}
}
/// The control values in `to` of the spline with control values `ctrl` in `from`, which `to`
/// contains: the same domain, a degree at least as high, and every knot of `from` among those of
/// `to` (with a polynomial `from` when the degree rises). Exact: Bézier degree elevation (NURBS
/// Book §5.5) to the target degree, then Boehm knot insertion (§5.2) of the knots `to` adds.
pub fn embed<T: Linear>(from: &Space, ctrl: &[T], to: &Space) -> SplineResult<Vec<T>> {
if ctrl.len() != from.count() {
return invalid("control values do not match the space");
}
let ([a0, b0], [a1, b1]) = (from.domain(), to.domain());
if a0 != a1 || b0 != b1 {
return invalid("the spaces' domains differ");
}
let mut p = from.degree();
let mut knots = from.knots().to_vec();
let mut pts: Vec<T> = ctrl.to_vec();
if p > to.degree() {
return invalid("the target space's degree is lower");
}
if p < to.degree() {
if from.count() != p + 1 {
return Err(SplineError::Unsupported("raising the degree of a spline with interior knots".into()));
}
while p < to.degree() {
pts = elevate_bezier(&pts);
p += 1;
}
knots = vec![a0; p + 1];
knots.extend(std::iter::repeat_n(b0, p + 1));
}
// The knots `to` adds: a merge of the two sorted vectors.
let target = to.knots();
let mut missing = Vec::new();
let mut j = 0;
for &x in target {
match knots.get(j) {
Some(&k) if k == x => j += 1,
Some(&k) if k < x => return invalid("a knot of the spline is not in the target space"),
_ => missing.push(x),
}
}
if j != knots.len() {
return invalid("a knot of the spline is not in the target space");
}
let mut h: Vec<HPoint> = pts.iter().map(|x| x.to_h()).collect();
for x in missing {
(knots, h) = insert_knot(p, &knots, &h, x)?;
}
if knots.as_slice() != target {
return invalid("knot insertion did not reach the target space");
}
Ok(h.into_iter().map(T::from_h).collect())
}
/// A Bézier piece's control values one degree higher, the same polynomial (NURBS Book eq. 5.36):
/// `Qᵢ = (i/(p+1))·Pᵢ₋₁ + (1 − i/(p+1))·Pᵢ`.
fn elevate_bezier<T: Linear>(pts: &[T]) -> Vec<T> {
let p = pts.len().saturating_sub(1);
let at = |i: usize| pts.get(i).copied().unwrap_or_else(T::zero);
(0..=p + 1)
.map(|i| {
let a = i as f64 / (p + 1) as f64;
let prev = if i == 0 { T::zero() } else { at(i - 1).times(a) };
prev.plus(at(i).times(1.0 - a))
})
.collect()
}
/// A monotone piecewise cubic Hermite function through `(xₖ, yₖ)`, both strictly increasing
/// (Fritsch & Carlson): slopes are the weighted harmonic means of the neighbouring secants
/// (Fritsch & Butland), the secant at the ends. Its slope is positive everywhere, and through two
/// points it is the straight line.
#[derive(Clone, Debug, PartialEq)]
pub struct Monotone {
x: Vec<f64>,
y: Vec<f64>,
m: Vec<f64>,
}
impl Monotone {
pub fn new(x: Vec<f64>, y: Vec<f64>) -> SplineResult<Monotone> {
let n = x.len();
if n < 2 || y.len() != n {
return invalid("a monotone cubic needs two points or more");
}
let increasing = |v: &[f64]| v.iter().all(|t| t.is_finite()) && v.windows(2).all(|w| w[0] < w[1]);
if !increasing(&x) || !increasing(&y) {
return invalid("the points of a monotone cubic must increase");
}
let h: Vec<f64> = x.windows(2).map(|w| w[1] - w[0]).collect();
let d: Vec<f64> = y.windows(2).zip(&h).map(|(w, h)| (w[1] - w[0]) / h).collect();
let mut m = Vec::with_capacity(n);
m.push(d[0]);
for k in 1..n - 1 {
let (w1, w2) = (2.0 * h[k] + h[k - 1], h[k] + 2.0 * h[k - 1]);
m.push((w1 + w2) / (w1 / d[k - 1] + w2 / d[k]));
}
m.push(d[n - 2]);
Ok(Monotone { x, y, m })
}
/// The value and the first two derivatives at `t` (clamped to the points' range).
pub fn eval(&self, t: f64) -> [f64; 3] {
let n = self.x.len();
let t = t.clamp(self.x[0], self.x[n - 1]);
let k = self.x.partition_point(|x| *x <= t).saturating_sub(1).min(n - 2);
let (x0, x1, y0, y1, m0, m1) = (self.x[k], self.x[k + 1], self.y[k], self.y[k + 1], self.m[k], self.m[k + 1]);
let h = x1 - x0;
let s = (t - x0) / h;
let (s2, s3) = (s * s, s * s * s);
let value = (2.0 * s3 - 3.0 * s2 + 1.0) * y0 + (s3 - 2.0 * s2 + s) * h * m0 + (-2.0 * s3 + 3.0 * s2) * y1 + (s3 - s2) * h * m1;
let d1 = ((6.0 * s2 - 6.0 * s) * y0 + (3.0 * s2 - 4.0 * s + 1.0) * h * m0 + (-6.0 * s2 + 6.0 * s) * y1 + (3.0 * s2 - 2.0 * s) * h * m1) / h;
let d2 = ((12.0 * s - 6.0) * y0 + (6.0 * s - 4.0) * h * m0 + (-12.0 * s + 6.0) * y1 + (6.0 * s - 2.0) * h * m1) / (h * h);
[value, d1, d2]
}
}
#[cfg(test)]
mod tests {
use super::*;
fn close(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-10
}
/// Hermite interpolation reproduces a cubic from its values and end derivatives, and the
/// lowest-degree interpolant through two values is the straight line.
#[test]
fn interpolation_meets_values_and_derivatives() {
let f = |t: f64| 1.0 + 2.0 * t - 3.0 * t * t + 0.5 * t * t * t;
let df = |t: f64| 2.0 - 6.0 * t + 1.5 * t * t;
let d2f = |t: f64| -6.0 + 3.0 * t;
let conds = vec![Cond { t: 0.0, der: 0 }, Cond { t: 0.0, der: 1 }, Cond { t: 0.0, der: 2 }, Cond { t: 2.0, der: 0 }];
let it = Interpolant::lowest(conds, 0.0, 2.0).unwrap();
let c = it.fit(&[f(0.0), df(0.0), d2f(0.0), f(2.0)]).unwrap();
for k in 0..=10 {
let t = k as f64 * 0.2;
assert!(close(it.space().eval(&c, t, 0).unwrap(), f(t)), "{t}");
}
let line = Interpolant::lowest(vec![Cond { t: 0.0, der: 0 }, Cond { t: 1.0, der: 0 }], 0.0, 1.0).unwrap();
let c = line.fit(&[2.0, 5.0]).unwrap();
assert!(close(line.space().eval(&c, 0.25, 0).unwrap(), 2.75));
let constant = Interpolant::lowest(vec![Cond { t: 0.3, der: 0 }], 0.0, 1.0).unwrap();
let c = constant.fit(&[4.0, 0.0]).unwrap();
assert!(close(constant.space().eval(&c, 0.9, 0).unwrap(), 4.0));
}
/// Many conditions: a cubic spline with averaged knots through samples of a smooth function
/// with derivative conditions at both ends (values exact at the samples).
#[test]
fn spline_interpolation_with_end_derivatives() {
let f = |t: f64| (2.0 * t).sin();
let df = |t: f64| 2.0 * (2.0 * t).cos();
let ts: Vec<f64> = (0..=8).map(|k| k as f64 / 8.0).collect();
let mut conds: Vec<Cond> = ts.iter().map(|&t| Cond { t, der: 0 }).collect();
conds.push(Cond { t: 0.0, der: 1 });
conds.push(Cond { t: 1.0, der: 1 });
let it = Interpolant::lowest(conds, 0.0, 1.0).unwrap();
let mut data: Vec<f64> = ts.iter().map(|&t| f(t)).collect();
data.push(df(0.0));
data.push(df(1.0));
let c = it.fit(&data).unwrap();
for &t in &ts {
assert!(close(it.space().eval(&c, t, 0).unwrap(), f(t)));
}
assert!(close(it.space().eval(&c, 0.0, 1).unwrap(), df(0.0)));
assert!(close(it.space().eval(&c, 1.0, 1).unwrap(), df(1.0)));
assert!((it.space().eval(&c, 0.53, 0).unwrap() - f(0.53)).abs() < 1e-4);
}
/// Embedding is exact: a quadratic polynomial raised to a cubic with knots inserted, and a
/// cubic spline refined, evaluate the same everywhere; a space that does not contain the
/// spline is refused.
#[test]
fn embedding_keeps_the_spline() {
let from = Space::polynomial(2, 0.0, 1.0).unwrap();
let ctrl = [Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 2.0, 0.0), Vec3::new(3.0, -1.0, 1.0)];
let to = Space::with_breaks(3, &[0.0, 0.2, 0.5, 0.7, 1.0]).unwrap();
let out = embed(&from, &ctrl, &to).unwrap();
let spline = Space::with_breaks(3, &[0.0, 0.5, 1.0]).unwrap();
let sctrl: Vec<f64> = (0..spline.count()).map(|i| (i as f64 * 1.7).sin()).collect();
let finer = spline.refined(&[0.25, 0.5, 0.8]).unwrap();
let sout = embed(&spline, &sctrl, &finer).unwrap();
for k in 0..=20 {
let t = k as f64 / 20.0;
assert!(from.eval(&ctrl, t, 0).unwrap().dist(to.eval(&out, t, 0).unwrap()) < 1e-12);
assert!(close(spline.eval(&sctrl, t, 0).unwrap(), finer.eval(&sout, t, 0).unwrap()));
}
assert!(embed(&finer, &sout, &spline).is_err(), "a coarser space");
assert!(embed(&spline, &sctrl, &Space::with_breaks(3, &[0.0, 0.4, 1.0]).unwrap()).is_err(), "a knot missing");
assert!(embed(&spline, &sctrl, &Space::with_breaks(3, &[0.0, 0.5, 2.0]).unwrap()).is_err(), "another domain");
}
#[test]
fn monotone_cubic_is_monotone_and_straight_through_two_points() {
let m = Monotone::new(vec![0.0, 0.3, 0.5, 1.0], vec![0.0, 0.05, 0.9, 1.0]).unwrap();
let mut last = -1.0;
for k in 0..=200 {
let [y, d, _] = m.eval(k as f64 / 200.0);
assert!(y >= last && d >= 0.0, "{k}");
last = y;
}
assert!(close(m.eval(0.3)[0], 0.05) && close(m.eval(0.5)[0], 0.9));
let line = Monotone::new(vec![0.0, 1.0], vec![2.0, 4.0]).unwrap();
assert!(close(line.eval(0.25)[0], 2.5) && close(line.eval(0.7)[1], 2.0) && close(line.eval(0.7)[2], 0.0));
assert!(Monotone::new(vec![0.0, 0.0], vec![0.0, 1.0]).is_err());
assert!(Monotone::new(vec![0.0, 1.0], vec![1.0, 0.0]).is_err());
assert!(Monotone::new(vec![0.0, f64::NAN], vec![0.0, 1.0]).is_err());
}
#[test]
fn hostile_spaces_are_refused() {
assert!(Space::new(3, vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]).is_ok());
assert!(Space::new(3, vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]).is_err(), "too few knots");
assert!(Space::new(3, vec![0.0, 0.0, 0.0, 0.1, 1.0, 1.0, 1.0, 1.0]).is_err(), "not clamped");
assert!(Space::new(1, vec![0.0, 0.0, 0.5, 0.5, 1.0, 1.0]).is_err(), "a discontinuous space");
assert!(Space::new(0, vec![0.0, 1.0]).is_err());
assert!(Space::with_breaks(3, &[0.0, 0.5, 0.5, 1.0]).is_err());
assert!(Space::with_breaks(3, &[0.0, f64::NAN, 1.0]).is_err());
let s = Space::with_breaks(3, &[0.0, 1.0]).unwrap();
assert!(s.eval(&[1.0, 2.0], 0.5, 0).is_err(), "wrong control count");
assert!(s.basis(f64::NAN, 0).is_err());
// Repeated conditions do not determine a spline.
assert!(Interpolant::new(s.clone(), vec![Cond { t: 0.5, der: 0 }; 4]).is_err());
assert!(Interpolant::lowest(vec![Cond { t: 2.0, der: 0 }], 0.0, 1.0).is_err());
}
}
+8 -5
View File
@@ -6,13 +6,16 @@
//! surface — its tangent plane, its curvature, the change of that curvature — as the side's order
//! asks for, with `crown` shaping the middle without touching a boundary condition.
//!
//! A patch through *three or four* boundaries is refused rather than built approximately. At a
//! corner two sides prescribe the same entries of the control net from two different surfaces, and
//! a tensor-product patch can hold both only where those two prescriptions already agree (one wall
//! carrying every side, say). Where they do not — the general case — the requested order would
//! A patch through *three or four* boundaries is refused here rather than built approximately. At
//! a corner two sides prescribe the same entries of the control net from two different surfaces,
//! and a tensor-product patch can hold both only where those two prescriptions already agree (one
//! wall carrying every side, say). Where they do not — the general case — the requested order would
//! silently drop near the corner, or the boundary curve would visibly leave its stations, and a
//! Gregory-type corner (a rational blend of the sides' own data) is needed to hold them instead
//! (issue #763). Everything this module refuses is an error, never a quietly worse surface.
//! (issue #763). A loop of one sketch's curves is the case where they agree: it lies in the
//! sketch's plane, and its flat Coons patch ([`crate::boundary_network`]) holds every order
//! exactly; the network there refuses G1/G2 on two sides that meet at a corner for the same
//! reason. Everything this module refuses is an error, never a quietly worse surface.
use solidcraft_geom::Vec3;
+744
View File
@@ -0,0 +1,744 @@
//! Boundary surfaces (Surface › Boundary): one B-spline face through curves in one or two
//! directions (`solidcraft_geom::network`: a loft between curves, a Coons patch inside four, a
//! Gordon surface through a network), made from sketch curves, 3D sketch curves or a body's
//! edges. A boundary curve that is a chain of open edges of a surface may carry a continuity
//! condition with the face beside it: G1 (tangent) or G2 (curvature).
//!
//! The reusable pieces: [`CurveSource`] turns each kind of curve into a curve the network can
//! measure, [`EdgeFaces`] gives the frame and second fundamental form of the faces along a chain
//! of edges (what a G1 or G2 condition needs), and [`boundary_surface`] builds the face.
//!
//! The two-curve bridge with G0–G3 against a sketch's plane is [`crate::boundary`]; this is the
//! general case: three or four sides, interior curves, 3D curves and edges.
use std::collections::HashSet;
use mt::{BoundedCurve, Cut, InnerSpace, ParametricCurve, ParametricSurface, SearchNearestParameter};
use solidcraft_geom::bspline::{CurveN, NurbsSurface, SplineError};
use solidcraft_geom::network::{self, CrossFace, FaceFrame, NetCurve, NetworkCurve, PointCurve, Tolerances};
use solidcraft_geom::{Plane, Seg2, Vec3};
use truck_modeling as mt;
use crate::body::{Body, from_p3, p3};
use crate::bridge::Continuity;
use crate::plane_fit::EdgeSampler;
use crate::record::Rebuild;
use crate::{KernelError, Result, guard};
/// How far apart curves of the two directions may pass and still cross (mm).
pub const CROSS_TOLERANCE: f64 = 0.01;
/// How far the surface may stray from its curves (mm).
pub const FIT_TOLERANCE: f64 = 1e-4;
/// Most points of a 3D sketch curve a boundary surface follows (longer ones are resampled).
const MAX_WIRE_POINTS: usize = 400;
/// Most points picking the edges of one curve.
pub const MAX_EDGE_PICKS: usize = 10_000;
/// Most sketch curves one curve of a boundary surface chains.
pub const MAX_CHAIN_CURVES: usize = 1000;
/// The network's continuity for a curve's: G3 is refused (a network holds up to G2).
fn net_order(c: &BoundaryCurve) -> Result<network::Continuity> {
match c.continuity {
Continuity::G0 => Ok(network::Continuity::G0),
Continuity::G1 => Ok(network::Continuity::G1),
Continuity::G2 => Ok(network::Continuity::G2),
Continuity::G3 => Err(KernelError::Invalid(format!("not supported yet: G3 continuity on {} (a curve network holds up to G2)", c.label))),
}
}
/// Where a curve of a boundary surface comes from.
pub enum CurveSource<'a> {
/// Sketch segments on a plane, each starting where the one before it ends.
Sketch { plane: Plane, segs: Vec<Seg2> },
/// A 3D sketch curve's points: followed smoothly through them (a cubic spline).
Points(Vec<Vec3>),
/// A chain of a body's edges, each picked by a point on it.
Edges { body: &'a Body, at: Vec<Vec3> },
/// A side collapsed to a point: the apex of a three-sided patch, where the sides beside it
/// meet.
Point(Vec3),
}
/// A curve of a boundary surface: a name for messages, where it comes from, and (for edges of a
/// surface) its continuity with the face beside it.
pub struct BoundaryCurve<'a> {
pub label: String,
pub source: CurveSource<'a>,
pub continuity: Continuity,
}
/// One B-spline face through curves `u` (two or more; or one with a continuity condition, crossed
/// by `v`) and `v` (none: a loft through `u`; two each way and no more: a Coons patch; more: a
/// Gordon surface through the network). A surface body; its history has no operands (the face
/// and its edges are new). Refused, naming the curves: curves that miss each other (by more than
/// [`CROSS_TOLERANCE`]) or cross twice, curves out of order, closed curves, a continuity
/// condition on anything but an open edge of a surface, or on curves of both directions.
pub fn boundary_surface(u: &[BoundaryCurve], v: &[BoundaryCurve]) -> Result<Body> {
for c in u.iter().chain(v) {
if let CurveSource::Edges { body, .. } = &c.source {
body.require_brep("boundary surface")?;
}
}
guard("boundary surface", || {
let mut corners: Vec<Vec3> = Vec::new();
let mut to_net = |c: &BoundaryCurve| -> Result<NetworkCurve<'static>> {
let (curve, face): (Box<dyn NetCurve>, Option<EdgeFaces>) = match &c.source {
CurveSource::Sketch { plane, segs } => (Box::new(SketchChain::new(&c.label, plane, segs)?), None),
CurveSource::Points(pts) => (Box::new(Polyline::new(&c.label, pts)?), None),
CurveSource::Point(p) => {
if !p.is_finite() {
return Err(KernelError::Invalid(format!("{} is not a finite point", c.label)));
}
(Box::new(PointCurve(*p)), None)
}
CurveSource::Edges { body, at } => {
if at.is_empty() || at.len() > MAX_EDGE_PICKS || at.iter().any(|p| !p.is_finite()) {
return Err(KernelError::Invalid(format!("{}: pick 1 to {MAX_EDGE_PICKS} points on its edges", c.label)));
}
let (chain, closed) = crate::surfaces::picked_chain(body, at)?;
if closed {
return Err(KernelError::Invalid(format!("not supported yet: {} is a closed chain of edges", c.label)));
}
// The chain's inner vertices: the face's sides are split there, so that a
// join shares the body's edges one for one.
corners.extend(chain.iter().skip(1).map(|e| from_p3(e.front().point())));
let face = match c.continuity {
Continuity::G0 => None,
_ => Some(EdgeFaces::new(&c.label, body, &chain)?),
};
(Box::new(EdgeChain::new(&c.label, &chain)?), face)
}
};
if c.continuity != Continuity::G0 && face.is_none() {
return Err(KernelError::Invalid(format!("{}: G1 and G2 apply only to a body's edges", c.label)));
}
let order = net_order(c)?;
Ok(NetworkCurve { label: c.label.clone(), curve, condition: face.map(|f| (order, Box::new(f) as Box<dyn CrossFace>)) })
};
let nu: Vec<NetworkCurve> = u.iter().map(&mut to_net).collect::<Result<_>>()?;
let nv: Vec<NetworkCurve> = v.iter().map(&mut to_net).collect::<Result<_>>()?;
let surface = network::network_surface(nu, nv, Tolerances { cross: CROSS_TOLERANCE, fit: FIT_TOLERANCE }).map_err(|e| match e {
SplineError::Unsupported(m) => KernelError::Invalid(format!("not supported yet: {m}")),
SplineError::TooLarge(m) => KernelError::TooLarge(m),
SplineError::Invalid(m) => KernelError::Invalid(m),
})?;
let face = face_of(&surface, &corners)?;
let mut rec = Rebuild::default();
rec.made(&face, Vec::new());
crate::surfaces::body_of(vec![face], &[], &rec)
})
}
/// `made` (a boundary surface) sewn into `target` along the edges they share: one body, a solid
/// when it closes the gap. Refused when they share no edge.
pub fn boundary_join(target: &Body, made: &Body) -> Result<Body> {
target.require_brep("join")?;
let edges = |b: &Body| b.solid.edge_iter().map(|e| e.id()).collect::<HashSet<_>>().len();
let joined = crate::surfaces::stitch(&[target, made], CROSS_TOLERANCE)?;
if edges(&joined) == edges(target) + edges(made) {
return Err(KernelError::Invalid("the surface shares no edge with the body it joins".into()));
}
Ok(joined)
}
/// Sketch segments on a plane, run end to end by arc length.
struct SketchChain {
plane: Plane,
segs: Vec<Seg2>,
/// Cumulative length at the start of each segment, and the total.
starts: Vec<f64>,
total: f64,
}
impl SketchChain {
fn new(label: &str, plane: &Plane, segs: &[Seg2]) -> Result<SketchChain> {
if segs.is_empty() || segs.len() > MAX_CHAIN_CURVES {
return Err(KernelError::Invalid(format!("{label} has no curves, or too many")));
}
if segs.windows(2).any(|w| w[0].end().dist(w[1].start()) > 1e-6) {
return Err(KernelError::Invalid(format!("{label}: its curves don't meet end to end")));
}
let mut starts = Vec::with_capacity(segs.len());
let mut total = 0.0;
for s in segs {
starts.push(total);
total += s.length();
}
if !(total > 0.0 && total.is_finite()) {
return Err(KernelError::Invalid(format!("{label} has no length")));
}
Ok(SketchChain { plane: *plane, segs: segs.to_vec(), starts, total })
}
}
impl NetCurve for SketchChain {
fn point(&mut self, t: f64) -> Option<Vec3> {
let at = t.clamp(0.0, 1.0) * self.total;
let k = self.starts.partition_point(|s| *s <= at).saturating_sub(1);
let (seg, start) = (self.segs.get(k)?, self.starts.get(k)?);
let len = seg.length();
let local = if len > 0.0 { ((at - start) / len).clamp(0.0, 1.0) } else { 0.0 };
let p = self.plane.to_world(seg.point_at(local));
p.is_finite().then_some(p)
}
}
/// A 3D polyline followed smoothly: a cubic through its points by chord length (fewer points, a
/// lower degree; a long one resampled first).
struct Polyline {
curve: CurveN<3>,
end: f64,
}
impl Polyline {
fn new(label: &str, pts: &[Vec3]) -> Result<Polyline> {
let mut clean: Vec<Vec3> = Vec::with_capacity(pts.len());
for p in pts {
if !p.is_finite() {
return Err(KernelError::Invalid(format!("{label} has a point that is not a finite number")));
}
if clean.last().is_none_or(|q: &Vec3| q.dist(*p) > 1e-9) {
clean.push(*p);
}
}
let pts = resample(&clean, MAX_WIRE_POINTS);
if pts.len() < 2 {
return Err(KernelError::Invalid(format!("{label} has no length")));
}
let mut params = vec![0.0];
for w in pts.windows(2) {
params.push(params.last().copied().unwrap_or(0.0) + w[0].dist(w[1]));
}
let end = params.last().copied().unwrap_or(0.0);
let data: Vec<[f64; 3]> = pts.iter().map(|p| [p.x, p.y, p.z]).collect();
let curve = CurveN::interpolate(&params, &data, (pts.len() - 1).min(3))
.map_err(|e| KernelError::Invalid(format!("{label} can't be followed smoothly: {e}")))?;
Ok(Polyline { curve, end })
}
}
impl NetCurve for Polyline {
fn point(&mut self, t: f64) -> Option<Vec3> {
let ([x, y, z], _) = self.curve.eval(t.clamp(0.0, 1.0) * self.end)?;
Some(Vec3::new(x, y, z))
}
}
/// At most `max` points evenly along a polyline by arc length, its ends kept.
fn resample(pts: &[Vec3], max: usize) -> Vec<Vec3> {
if pts.len() <= max || max < 2 {
return pts.to_vec();
}
let mut cum = vec![0.0];
for w in pts.windows(2) {
cum.push(cum.last().copied().unwrap_or(0.0) + w[0].dist(w[1]));
}
let total = cum.last().copied().unwrap_or(0.0);
(0..max)
.filter_map(|k| {
let at = total * k as f64 / (max - 1) as f64;
let i = cum.partition_point(|c| *c <= at).saturating_sub(1).min(pts.len().saturating_sub(2));
let (c0, c1) = (cum.get(i)?, cum.get(i + 1)?);
let w = if c1 > c0 { ((at - c0) / (c1 - c0)).clamp(0.0, 1.0) } else { 0.0 };
Some(pts.get(i)?.lerp(*pts.get(i + 1)?, w))
})
.collect()
}
/// A chain of edges (each turned to run along it), by their lengths.
struct EdgeChain {
edges: Vec<EdgeSampler>,
starts: Vec<f64>,
total: f64,
}
impl EdgeChain {
fn new(label: &str, chain: &[mt::Edge]) -> Result<EdgeChain> {
let mut edges = Vec::with_capacity(chain.len());
let mut starts = Vec::with_capacity(chain.len());
let mut total = 0.0;
for e in chain {
let mut s = EdgeSampler::new(e).ok_or_else(|| KernelError::Invalid(format!("{label}: an edge has no parameter range")))?;
let mut len = 0.0;
let mut last: Option<Vec3> = None;
for k in 0..=16 {
let p = s.at(k as f64 / 16.0).ok_or_else(|| KernelError::Invalid(format!("{label}: an edge can't be evaluated")))?;
if let Some(q) = last {
len += p.dist(q);
}
last = Some(p);
}
starts.push(total);
total += len;
edges.push(s);
}
if !(total > 0.0 && total.is_finite()) {
return Err(KernelError::Invalid(format!("{label} has no length")));
}
Ok(EdgeChain { edges, starts, total })
}
}
impl NetCurve for EdgeChain {
fn point(&mut self, t: f64) -> Option<Vec3> {
let at = t.clamp(0.0, 1.0) * self.total;
let k = self.starts.partition_point(|s| *s <= at).saturating_sub(1);
let start = *self.starts.get(k)?;
let end = self.starts.get(k + 1).copied().unwrap_or(self.total);
let local = if end > start { ((at - start) / (end - start)).clamp(0.0, 1.0) } else { 0.0 };
self.edges.get_mut(k)?.at(local)
}
}
/// The faces along a chain of edges, each edge an open edge of one face of its body: their
/// frames and second fundamental forms where a boundary surface meets them (G1 and G2
/// conditions).
pub(crate) struct EdgeFaces {
sides: Vec<EdgeSide>,
}
/// One edge of the chain: points along it (to find the edge nearest a point), the surface of
/// its face, whether the face's boundary runs along the chain (`along`), and the surface
/// parameters found last (the next search starts there).
struct EdgeSide {
pts: Vec<Vec3>,
surface: mt::Surface,
along: bool,
hint: Option<(f64, f64)>,
}
impl EdgeFaces {
pub(crate) fn new(label: &str, body: &Body, chain: &[mt::Edge]) -> Result<EdgeFaces> {
let mut sides = Vec::with_capacity(chain.len());
for e in chain {
let mut faces = body.solid.face_iter().filter(|f| f.boundaries().iter().flatten().any(|x| x.id() == e.id()));
let (Some(face), None) = (faces.next(), faces.next()) else {
return Err(KernelError::Invalid(format!(
"{label}: G1 and G2 need an open edge of a surface (an edge with a face on one side only)"
)));
};
// How the face's own (absolute) boundary runs this edge.
let in_wire = face.absolute_boundaries().iter().flatten().find(|x| x.id() == e.id()).cloned();
let in_wire = in_wire.ok_or_else(|| KernelError::Failed("boundary surface: an edge's face".into()))?;
let along = in_wire.front().id() == e.front().id();
let mut sampler = EdgeSampler::new(e).ok_or_else(|| KernelError::Invalid(format!("{label}: an edge has no parameter range")))?;
let pts = (0..=16).map(|k| sampler.at(k as f64 / 16.0)).collect::<Option<Vec<_>>>();
let pts = pts.ok_or_else(|| KernelError::Invalid(format!("{label}: an edge can't be evaluated")))?;
sides.push(EdgeSide { pts, surface: face.surface(), along, hint: None });
}
Ok(EdgeFaces { sides })
}
}
impl CrossFace for EdgeFaces {
fn frame(&mut self, at: Vec3, tangent: Vec3) -> Option<FaceFrame> {
// The edge nearest the point, and the chain's direction along it there.
let near = |s: &EdgeSide| s.pts.windows(2).map(|w| at.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min);
let k = (0..self.sides.len()).min_by(|a, b| near(&self.sides[*a]).total_cmp(&near(&self.sides[*b])))?;
let side = self.sides.get_mut(k)?;
let seg = side.pts.windows(2).min_by(|a, b| at.dist_to_segment(a[0], a[1]).total_cmp(&at.dist_to_segment(b[0], b[1])))?;
let chain_dir = seg[1] - seg[0];
let s = &side.surface;
let (u, v) = s.search_nearest_parameter(p3(at), side.hint, 100).or_else(|| s.search_nearest_parameter(p3(at), None, 100))?;
side.hint = Some((u, v));
let (su, sv) = (s.uder(u, v), s.vder(u, v));
let n = su.cross(sv);
if !(n.magnitude2() > 0.0) {
return None;
}
let n = n.normalize();
let normal = Vec3::new(n.x, n.y, n.z);
// The face's boundary runs counter-clockwise about its surface's normal, so the face lies
// to the left of it: outward is the boundary's direction × the normal.
let wire = if side.along { chain_dir } else { -chain_dir };
let outward = wire.cross(normal).normalized()?;
// The second fundamental form, in the basis of the tangent asked about and outward.
let t = (tangent - normal * tangent.dot(normal)).normalized()?;
let b = (outward - t * outward.dot(t)).normalized()?;
let (e, f, g) = (su.dot(su), su.dot(sv), sv.dot(sv));
let det = e * g - f * f;
if !(det.abs() > 1e-24) {
return None;
}
// II(w, w) = L·α² + 2M·αβ + N·β² for w = α·S_u + β·S_v, with L, M, N the surface's
// second derivatives along its unit normal (do Carmo, §3-3): exact, rational surfaces
// included, and with nothing sampled beyond the edge, where the face's domain ends.
let nv = mt::Vector3::new(normal.x, normal.y, normal.z);
let (l, m, nn) = (s.uuder(u, v).dot(nv), s.uvder(u, v).dot(nv), s.vvder(u, v).dot(nv));
let ii = |w: Vec3| -> Option<f64> {
let wv = mt::Vector3::new(w.x, w.y, w.z);
let (p, q) = (wv.dot(su), wv.dot(sv));
let (alpha, beta) = ((p * g - q * f) / det, (q * e - p * f) / det);
let out = l * alpha * alpha + 2.0 * m * alpha * beta + nn * beta * beta;
out.is_finite().then_some(out)
};
let (tt, bb) = (ii(t)?, ii(b)?);
let tb = (ii(t + b)? - tt - bb) / 2.0;
let form = [tt, tb, bb];
form.iter().all(|x| x.is_finite()).then_some(FaceFrame { normal, outward: b, form })
}
}
/// The face of a network surface: its four sides from the surface's boundary rows, each split
/// at the `corners` that lie on it (inner vertices of edge chains). Refused when a side shrinks to
/// a point.
fn face_of(s: &NurbsSurface, corners: &[Vec3]) -> Result<mt::Face> {
let fail = |m: &str| KernelError::Failed(format!("boundary surface: {m}"));
let [nu, nv] = s.count();
let [ku, kv] = s.knots();
let rows: Vec<Vec<mt::Point3>> = (0..nu).map(|i| (0..nv).map(|j| p3(s.point(i, j).xyz())).collect()).collect();
let (uk, vk) = (mt::KnotVec::from(ku.clone()), mt::KnotVec::from(kv.clone()));
let surface = mt::BSplineSurface::try_new((uk.clone(), vk.clone()), rows.clone()).map_err(|e| fail(&e.to_string()))?;
let row = |pts: Vec<mt::Point3>, k: &mt::KnotVec| mt::BSplineCurve::try_new(k.clone(), pts).map_err(|e| fail(&e.to_string()));
let (Some(first), Some(last)) = (rows.first(), rows.last()) else { return Err(fail("control net")) };
let bottom = row(rows.iter().filter_map(|r| r.first().copied()).collect(), &uk)?;
let top = row(rows.iter().filter_map(|r| r.last().copied()).collect(), &uk)?;
let left = row(first.clone(), &vk)?;
let right = row(last.clone(), &vk)?;
let corner = |c: &mt::BSplineCurve<mt::Point3>, end: bool| {
let (t0, t1) = c.range_tuple();
c.subs(if end { t1 } else { t0 })
};
let (c00, c10, c11, c01) = (corner(&bottom, false), corner(&bottom, true), corner(&top, true), corner(&top, false));
let size = [c00, c10, c11, c01].iter().map(|p| from_p3(*p).dist(from_p3(c00))).fold(0.0, f64::max).max(1.0);
// A side collapsed to a point (a three-sided patch) is left out of the loop: the two sides
// beside it meet at one vertex there.
let sides = [(c00, c10), (c10, c11), (c01, c11), (c00, c01)];
let collapsed: Vec<bool> = sides.iter().map(|(a, b)| from_p3(*a).dist(from_p3(*b)) <= size * 1e-9).collect();
match collapsed.iter().filter(|c| **c).count() {
0 | 1 => {}
_ => return Err(KernelError::Invalid("not supported yet: a boundary surface with more than one side shrunk to a point".into())),
}
let mut verts: Vec<mt::Vertex> = Vec::with_capacity(4);
for c in [c00, c10, c11, c01] {
let same = verts.iter().find(|v| from_p3(v.point()).dist(from_p3(c)) <= size * 1e-9).cloned();
verts.push(same.unwrap_or_else(|| mt::Vertex::new(c)));
}
let (Some(v00), Some(v10), Some(v11), Some(v01)) = (verts.first(), verts.get(1), verts.get(2), verts.get(3)) else {
return Err(fail("corners"));
};
let is = |k: usize| collapsed.get(k).copied().unwrap_or(false);
let mut wire: Vec<mt::Edge> = Vec::new();
if !is(0) {
wire.extend(side_edges(bottom, v00, v10, corners));
}
if !is(1) {
wire.extend(side_edges(right, v10, v11, corners));
}
if !is(2) {
wire.extend(side_edges(top, v01, v11, corners).into_iter().rev().map(|e| e.inverse()));
}
if !is(3) {
wire.extend(side_edges(left, v00, v01, corners).into_iter().rev().map(|e| e.inverse()));
}
// u along the bottom, v up the left: counter-clockwise in (u, v).
mt::Face::try_new(vec![wire.into()], mt::Surface::BSplineSurface(surface)).map_err(|e| fail(&e.to_string()))
}
/// The edges of one side from `a` to `b`, split at the points of `corners` that lie on it
/// (within [`CROSS_TOLERANCE`]) strictly between its ends.
fn side_edges(mut curve: mt::BSplineCurve<mt::Point3>, a: &mt::Vertex, b: &mt::Vertex, corners: &[Vec3]) -> Vec<mt::Edge> {
let (t0, t1) = curve.range_tuple();
let margin = (t1 - t0) * 1e-6;
let mut cuts: Vec<f64> = corners
.iter()
.filter_map(|c| {
let t = curve.search_nearest_parameter(p3(*c), None, 100)?;
(t > t0 + margin && t < t1 - margin && from_p3(curve.subs(t)).dist(*c) <= CROSS_TOLERANCE).then_some(t)
})
.collect();
cuts.sort_by(f64::total_cmp);
cuts.dedup_by(|x, y| (*x - *y).abs() <= margin);
let mut edges = Vec::with_capacity(cuts.len() + 1);
let mut from = a.clone();
// Cut from the far end back, so the earlier parameters stay on the part kept.
let mut tails = Vec::with_capacity(cuts.len());
for &t in cuts.iter().rev() {
tails.push(curve.cut(t));
}
let mut pieces = vec![curve];
pieces.extend(tails.into_iter().rev());
let count = pieces.len();
for (k, piece) in pieces.into_iter().enumerate() {
let to = if k + 1 == count { b.clone() } else { mt::Vertex::new(piece.subs(piece.range_tuple().1)) };
edges.push(mt::Edge::new(&from, &to, mt::Curve::BSplineCurve(piece)));
from = to;
}
edges
}
#[cfg(test)]
mod tests {
use super::*;
use crate::patch_region;
use mt::ParametricSurface3D;
use solidcraft_geom::{Loop2, Region2, Vec2};
fn sketch(label: &str, plane: Plane, segs: Vec<Seg2>) -> BoundaryCurve<'static> {
BoundaryCurve { label: label.into(), source: CurveSource::Sketch { plane, segs }, continuity: Continuity::G0 }
}
fn line3(label: &str, a: Vec3, b: Vec3) -> BoundaryCurve<'static> {
BoundaryCurve { label: label.into(), source: CurveSource::Points(vec![a, b]), continuity: Continuity::G0 }
}
fn face_surface(b: &Body) -> mt::Surface {
b.solid.face_iter().next().unwrap().surface()
}
/// The flat sheet y ∈ [−10, 0], x ∈ [0, 10] in z = 0, its edge along y = 0 open.
fn sheet() -> Body {
let sq = Loop2::polygon(&[Vec2::new(0.0, -10.0), Vec2::new(10.0, -10.0), Vec2::new(10.0, 0.0), Vec2::new(0.0, 0.0)]);
patch_region(&Plane::XY, &Region2 { outer: sq, holes: vec![] }).unwrap()
}
/// A Coons patch of four lines bounding the hyperbolic paraboloid z = x·y/10: every point of
/// the face lies on it, and its area is the paraboloid's over the square.
#[test]
fn coons_patch_of_lines_is_a_hyperbolic_paraboloid() {
let p = |x: f64, y: f64| Vec3::new(x, y, x * y / 10.0);
let body = boundary_surface(
&[line3("u0", p(0.0, 0.0), p(10.0, 0.0)), line3("u1", p(0.0, 10.0), p(10.0, 10.0))],
&[line3("v0", p(0.0, 0.0), p(0.0, 10.0)), line3("v1", p(10.0, 0.0), p(10.0, 10.0))],
)
.unwrap();
assert!(body.is_surface() && body.face_count() == 1);
let s = face_surface(&body);
for i in 0..=10 {
for j in 0..=10 {
let q = from_p3(s.subs(i as f64 / 10.0, j as f64 / 10.0));
assert!((q.z - q.x * q.y / 10.0).abs() < 1e-9, "{q:?}");
}
}
}
/// Sketch curves: a patch inside two arcs and two lines on one plane lies in that plane.
#[test]
fn coplanar_sketch_curves_give_a_plane() {
use std::f64::consts::PI;
// Two half-discs' arcs over [0, 10] (radius 5) facing out, joined by the lines x = 0, 10.
let low = Seg2::Arc { center: Vec2::new(5.0, 0.0), radius: 5.0, start: PI, sweep: PI };
let high = Seg2::Arc { center: Vec2::new(5.0, 8.0), radius: 5.0, start: PI, sweep: -PI };
let left = Seg2::Line { a: Vec2::new(0.0, 0.0), b: Vec2::new(0.0, 8.0) };
let right = Seg2::Line { a: Vec2::new(10.0, 0.0), b: Vec2::new(10.0, 8.0) };
let pl = Plane::XY.offset(3.0);
let body = boundary_surface(
&[sketch("low", pl, vec![low]), sketch("high", pl, vec![high])],
&[sketch("left", pl, vec![left]), sketch("right", pl, vec![right])],
)
.unwrap();
let s = face_surface(&body);
for i in 0..=8 {
for j in 0..=8 {
assert!((s.subs(i as f64 / 8.0, j as f64 / 8.0).z - 3.0).abs() < 1e-9);
}
}
}
/// A stadium: two half-circle arcs (radius 5) bulging out of the 10 × 8 rectangle between two
/// lines. Each arc meets its lines at 180°, so the patch is singular at its corners, and the
/// reference mesher's walk round the boundary used to run from such a corner onto the
/// surface's extrapolation past its domain (a planar spline passes through every point of its
/// plane there): the face measured 289 mm² for its 158.5. The vendored mesher's bounded
/// projection (`nearest_projection`, vendor/README.md) keeps the walk on the domain. Its area
/// is the stadium's, 80 + 25π, by the faces, the measuring mesh and the display mesh.
#[test]
fn a_patch_with_straight_corners_measures_its_own_area() {
use std::f64::consts::PI;
let low = Seg2::Arc { center: Vec2::new(5.0, 0.0), radius: 5.0, start: PI, sweep: PI };
let high = Seg2::Arc { center: Vec2::new(5.0, 8.0), radius: 5.0, start: PI, sweep: -PI };
let left = Seg2::Line { a: Vec2::new(0.0, 0.0), b: Vec2::new(0.0, 8.0) };
let right = Seg2::Line { a: Vec2::new(10.0, 0.0), b: Vec2::new(10.0, 8.0) };
let pl = Plane::XY.offset(3.0);
let body = boundary_surface(
&[sketch("low", pl, vec![low]), sketch("high", pl, vec![high])],
&[sketch("left", pl, vec![left]), sketch("right", pl, vec![right])],
)
.unwrap();
let want = 80.0 + 25.0 * PI;
// Chords of the arcs at 0.01 mm sag cut off up to (2/3)·sag·length ≈ 0.21 mm².
let near = |a: f64| (a - want).abs() < 0.25;
let faces = body.faces(0.01).unwrap();
assert!(faces.len() == 1 && near(faces[0].area), "faces: {faces:?}");
let tess = body.tessellate(0.01).unwrap().measure().area;
assert!(near(tess), "measuring mesh: {tess}");
let display = body.display_mesh(0.01).unwrap().measure().area;
assert!(near(display), "display mesh: {display}");
}
/// Three sides: a quarter disc of radius 10 (two radii and the arc) is one face with three
/// edges, the collapsed side left out of its loop, and measures 25π by its faces and both
/// meshes.
#[test]
fn a_three_sided_patch_is_one_face_with_three_edges() {
use std::f64::consts::{FRAC_PI_2, PI};
let r = 10.0;
let arc = Seg2::Arc { center: Vec2::new(0.0, 0.0), radius: r, start: 0.0, sweep: FRAC_PI_2 };
let x = Seg2::Line { a: Vec2::new(0.0, 0.0), b: Vec2::new(r, 0.0) };
let y = Seg2::Line { a: Vec2::new(0.0, r), b: Vec2::new(0.0, 0.0) };
let pl = Plane::XY;
let apex = BoundaryCurve { label: "centre".into(), source: CurveSource::Point(Vec3::ZERO), continuity: Continuity::G0 };
let body = boundary_surface(&[sketch("arc", pl, vec![arc]), apex], &[sketch("x", pl, vec![x]), sketch("y", pl, vec![y])]).unwrap();
assert!(body.is_surface() && body.face_count() == 1);
let edges: std::collections::HashSet<_> = body.solid.edge_iter().map(|e| e.id()).collect();
assert_eq!(edges.len(), 3, "the collapsed side is no edge");
let want = PI * r * r / 4.0;
let near = |a: f64| (a - want).abs() < 0.2;
let faces = body.faces(0.01).unwrap();
assert!(near(faces[0].area), "faces: {faces:?}");
let tess = body.tessellate(0.01).unwrap().measure().area;
assert!(near(tess), "measuring mesh: {tess}");
let display = body.display_mesh(0.01).unwrap().measure().area;
assert!(near(display), "display mesh: {display}");
// Two collapsed sides are no patch.
let p = |l: &str, q: Vec3| BoundaryCurve { label: l.into(), source: CurveSource::Point(q), continuity: Continuity::G0 };
assert!(
boundary_surface(&[sketch("arc", pl, vec![arc]), p("o", Vec3::ZERO)], &[p("a", Vec3::new(r, 0.0, 0.0)), sketch("y", pl, vec![y])])
.is_err()
);
assert!(boundary_surface(&[sketch("arc", pl, vec![arc]), p("nan", Vec3::new(f64::NAN, 0.0, 0.0))], &[]).is_err());
}
/// The angle between the two faces' normals across the edge at `p`.
fn normal_angle(a: &mt::Surface, b: &mt::Surface, p: Vec3) -> f64 {
let n = |s: &mt::Surface| {
let (u, v) = s.search_nearest_parameter(p3(p), None, 100).unwrap();
let n = s.normal(u, v);
Vec3::new(n.x, n.y, n.z)
};
n(a).dot(n(b)).abs().clamp(0.0, 1.0).acos().to_degrees()
}
/// G1 against a flat sheet's open edge: a loft from the edge to a line above, and a patch
/// whose sides are arcs leaving the sheet tangent to it. The normals across the shared edge
/// agree within 0.1°; the patch joins the sheet into one surface body.
#[test]
fn g1_meets_the_sheet_tangent() {
let base = sheet();
let edge =
|g| BoundaryCurve { label: "edge".into(), source: CurveSource::Edges { body: &base, at: vec![Vec3::new(5.0, 0.0, 0.0)] }, continuity: g };
let far = || line3("far", Vec3::new(0.0, 10.0, 5.0), Vec3::new(10.0, 10.0, 5.0));
let loft = boundary_surface(&[edge(Continuity::G1), far()], &[]).unwrap();
let plain = boundary_surface(&[edge(Continuity::G0), far()], &[]).unwrap();
let (sb, sl, sp) = (face_surface(&base), face_surface(&loft), face_surface(&plain));
for k in 0..=10 {
let p = Vec3::new(k as f64, 0.0, 0.0);
let a = normal_angle(&sb, &sl, p);
assert!(a < 0.1, "G1 at x = {k}: {a}°");
}
assert!(normal_angle(&sb, &sp, Vec3::new(5.0, 0.0, 0.0)) > 10.0, "G0 has a crease");
// Arcs in x = 0 and x = 10 from the edge, tangent to the sheet, up to the far line.
let arc_plane = |x: f64| Plane::new(Vec3::new(x, 0.0, 0.0), Vec3::Y, Vec3::Z).unwrap();
let arc = Seg2::Arc { center: Vec2::new(0.0, 12.5), radius: 12.5, start: -std::f64::consts::FRAC_PI_2, sweep: 0.927_295_218_001_612_2 };
let patch = boundary_surface(
&[edge(Continuity::G1), far()],
&[sketch("left", arc_plane(0.0), vec![arc]), sketch("right", arc_plane(10.0), vec![arc])],
)
.unwrap();
let spa = face_surface(&patch);
for k in 0..=10 {
let a = normal_angle(&sb, &spa, Vec3::new(k as f64, 0.0, 0.0));
assert!(a < 0.1, "G1 patch at x = {k}: {a}°");
}
let joined = boundary_join(&base, &patch).unwrap();
assert_eq!(joined.face_count(), 2);
assert!(
boundary_join(&base, &boundary_surface(&[far(), line3("other", Vec3::new(0.0, 20.0, 5.0), Vec3::new(10.0, 20.0, 5.0))], &[]).unwrap())
.is_err()
);
}
/// Normal curvature of `s` at the point nearest `p` in the direction `w` (projected into the
/// tangent plane), signed against the unit normal `n`.
fn normal_curvature(s: &mt::Surface, p: Vec3, w: Vec3, n: Vec3) -> f64 {
let (u, v) = s.search_nearest_parameter(p3(p), None, 100).unwrap();
let v3 = |x: mt::Vector3| Vec3::new(x.x, x.y, x.z);
let (su, sv) = (v3(s.uder(u, v)), v3(s.vder(u, v)));
let (suu, suv, svv) = (v3(s.uuder(u, v)), v3(s.uvder(u, v)), v3(s.vvder(u, v)));
let (e, f, g) = (su.dot(su), su.dot(sv), sv.dot(sv));
let (l, m, nn) = (suu.dot(n), suv.dot(n), svv.dot(n));
let (p1, q1) = (w.dot(su), w.dot(sv));
let det = e * g - f * f;
let (a, b) = ((p1 * g - q1 * f) / det, (q1 * e - p1 * f) / det);
(l * a * a + 2.0 * m * a * b + nn * b * b) / (e * a * a + 2.0 * f * a * b + g * b * b)
}
/// G2 against a real cylinder's open edge (R = 10, the face below the edge): across the edge
/// the surface's normal curvature is the cylinder's, −1/R about its outward normal, within
/// 0.1 % — also when the far curve is sheared along the edge, so that the surface's own
/// cross direction leans. With G1 alone it is not.
#[test]
fn g2_matches_a_cylinder_across_its_edge() {
let r = 10.0;
let pl = Plane::new(Vec3::ZERO, Vec3::Y, Vec3::Z).unwrap();
let arc = Seg2::Arc { center: Vec2::new(0.0, 0.0), radius: r, start: -std::f64::consts::FRAC_PI_2, sweep: std::f64::consts::FRAC_PI_2 };
let cyl = crate::extrude_sheet(&pl, &[vec![arc]], 0.0, 10.0).unwrap();
let sc = face_surface(&cyl);
let made = |g, shear: f64| {
let edge =
BoundaryCurve { label: "rim".into(), source: CurveSource::Edges { body: &cyl, at: vec![Vec3::new(5.0, r, 0.0)] }, continuity: g };
let top = line3("top", Vec3::new(shear, 3.0, 12.0), Vec3::new(10.0 + shear, 3.0, 12.0));
face_surface(&boundary_surface(&[edge, top], &[]).unwrap())
};
for shear in [0.0, 5.0] {
let sm = made(Continuity::G2, shear);
for k in 1..=9 {
let p = Vec3::new(k as f64, r, 0.0);
let kc = normal_curvature(&sc, p, Vec3::Z, Vec3::Y);
assert!((kc + 1.0 / r).abs() < 1e-9, "the cylinder's own curvature: {kc}");
let km = normal_curvature(&sm, p, Vec3::Z, Vec3::Y);
assert!((km - kc).abs() < 1e-3 / r, "shear {shear}, x = {k}: {km} across the edge where the cylinder has {kc}");
// Along the edge both are straight.
assert!(normal_curvature(&sm, p, Vec3::X, Vec3::Y).abs() < 1e-6);
assert!(normal_angle(&sc, &sm, p) < 0.1);
}
}
let g1 = made(Continuity::G1, 0.0);
let k1 = normal_curvature(&g1, Vec3::new(5.0, r, 0.0), Vec3::Z, Vec3::Y);
assert!((k1 + 1.0 / r).abs() > 0.1 / r, "G1 alone does not carry the curvature: {k1}");
}
/// G3 is more than a network holds: refused, never a panic.
#[test]
fn g3_is_not_supported() {
let base = sheet();
let edge = BoundaryCurve {
label: "edge".into(),
source: CurveSource::Edges { body: &base, at: vec![Vec3::new(5.0, 0.0, 0.0)] },
continuity: Continuity::G3,
};
let e = boundary_surface(&[edge, line3("far", Vec3::new(0.0, 10.0, 5.0), Vec3::new(10.0, 10.0, 5.0))], &[]).unwrap_err();
assert!(e.to_string().contains("not supported yet"), "{e}");
}
/// Refusals: G1 on a sketch curve, on an edge between two faces, curves that miss.
#[test]
fn bad_boundaries_are_refused() {
let cube = crate::box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap();
let edge = BoundaryCurve {
label: "edge".into(),
source: CurveSource::Edges { body: &cube, at: vec![Vec3::new(5.0, 0.0, 0.0)] },
continuity: Continuity::G1,
};
let far = line3("far", Vec3::new(0.0, 10.0, 15.0), Vec3::new(10.0, 10.0, 15.0));
let e = boundary_surface(&[edge, far], &[]).unwrap_err();
assert!(e.to_string().contains("open edge"), "{e}");
let mut tangent = line3("t", Vec3::ZERO, Vec3::X);
tangent.continuity = Continuity::G1;
assert!(boundary_surface(&[tangent, line3("b", Vec3::Y, Vec3::new(1.0, 1.0, 0.0))], &[]).is_err());
let miss = boundary_surface(
&[line3("a", Vec3::ZERO, Vec3::X * 10.0), line3("b", Vec3::Y * 10.0, Vec3::new(10.0, 10.0, 0.0))],
&[line3("c", Vec3::ZERO, Vec3::Y * 10.0), line3("d", Vec3::new(10.0, 0.0, 2.0), Vec3::new(10.0, 10.0, 2.0))],
)
.unwrap_err();
assert!(miss.to_string().contains("don't meet"), "{miss}");
let pts = BoundaryCurve { label: "p".into(), source: CurveSource::Points(vec![Vec3::ZERO; 3]), continuity: Continuity::G0 };
assert!(boundary_surface(&[pts, line3("b", Vec3::Y, Vec3::new(1.0, 1.0, 0.0))], &[]).is_err());
let nan = BoundaryCurve {
label: "n".into(),
source: CurveSource::Points(vec![Vec3::ZERO, Vec3::new(f64::NAN, 0.0, 0.0)]),
continuity: Continuity::G0,
};
assert!(boundary_surface(&[nan, line3("b", Vec3::Y, Vec3::new(1.0, 1.0, 0.0))], &[]).is_err());
}
}
+4
View File
@@ -25,6 +25,7 @@ mod boolean_guard;
mod boolean_record;
mod bore_guard;
mod boundary;
mod boundary_network;
mod bridge;
mod build;
mod clearance;
@@ -121,6 +122,8 @@ mod surface_extend;
mod surface_kind;
mod surface_offset;
mod surface_ruled;
#[cfg(test)]
mod surface_second_derivative_tests;
mod surface_untrim;
mod surfaces;
mod sweep_path;
@@ -145,6 +148,7 @@ pub use blend_variable::{RadiusSpline, Taper, fillet_chord, fillet_tapered, fill
pub use body::{Body, CapSignature, DISPLAY_ANGLE, EdgeInfo, FaceInfo, FacePaint, FaceSource, Paint};
pub use boolean_diagnostics::{BooleanDiagnostics, BooleanFallback, BooleanStrategy, capture_boolean_diagnostics};
pub use boundary::{Boundary, boundary_patch};
pub use boundary_network::{BoundaryCurve, CurveSource, MAX_CHAIN_CURVES, MAX_EDGE_PICKS, boundary_join, boundary_surface};
pub use bridge::{Continuity, Frame, blend_between, bridge, chain, chain_closes, frames, frames_across, sample_grid};
pub use build::{
PathSeg, box_solid, canonical_revolve_axis, cylinder, extrude, extrude_tapered, extrude_tapered_between, loft, path_polyline, revolve,
@@ -0,0 +1,96 @@
//! The vendored truck-geometry's second derivatives of B-spline and NURBS surfaces (`uuder`,
//! `vvder`) against finite differences of the surface itself, for degrees 2 to 5. Upstream's
//! were short of the factor p − 1, so every curvature read from a cubic surface came out half its
//! value (#763: a G2 boundary surface measured half the cylinder's curvature it does carry).
//! These pin the vendored fix, so a refresh of the crate can't quietly bring the error back.
use solidcraft_geom::Vec3;
use truck_modeling as mt;
use truck_modeling::ParametricSurface;
use crate::body::from_p3;
/// A degree-`p` × degree-`q` surface on a 5 × 6 net with an interior knot each way, bent in z.
fn surface(p: usize, q: usize) -> mt::BSplineSurface<mt::Point3> {
let knots = |d: usize, n: usize| {
let inner: Vec<f64> = (1..n - d).map(|k| k as f64 / (n - d) as f64).collect();
let mut k = vec![0.0; d + 1];
k.extend(inner);
k.extend(vec![1.0; d + 1]);
mt::KnotVec::from(k)
};
let (nu, nv) = (p + 3, q + 3);
let rows: Vec<Vec<mt::Point3>> = (0..nu)
.map(|i| {
(0..nv)
.map(|j| {
let (x, y) = (i as f64 * 2.0, j as f64 * 1.5);
mt::Point3::new(x + 0.3 * y, y, 0.4 * x * x - 0.2 * y * y + 0.1 * x * y)
})
.collect()
})
.collect();
mt::BSplineSurface::new((knots(p, nu), knots(q, nv)), rows)
}
/// Second differences of `f` along the parameter line, central inside and one-sided at the ends.
fn second(f: impl Fn(f64) -> Vec3, t: f64) -> Vec3 {
let h = 1e-4;
if t < 2.0 * h {
(f(t) * 2.0 - f(t + h) * 5.0 + f(t + 2.0 * h) * 4.0 - f(t + 3.0 * h)) / (h * h)
} else if t > 1.0 - 2.0 * h {
(f(t) * 2.0 - f(t - h) * 5.0 + f(t - 2.0 * h) * 4.0 - f(t - 3.0 * h)) / (h * h)
} else {
(f(t - h) - f(t) * 2.0 + f(t + h)) / (h * h)
}
}
fn v3(x: mt::Vector3) -> Vec3 {
Vec3::new(x.x, x.y, x.z)
}
#[test]
fn bspline_surface_second_derivatives_match_finite_differences() {
for p in 2..=5 {
for q in 2..=5 {
let s = surface(p, q);
for (u, v) in [(0.0, 0.0), (0.37, 0.0), (0.5, 0.61), (1.0, 0.2), (0.13, 1.0)] {
let uu = second(|t| from_p3(s.subs(t, v)), u);
let vv = second(|t| from_p3(s.subs(u, t)), v);
let scale = uu.len().max(vv.len()).max(1.0);
assert!(v3(s.uuder(u, v)).dist(uu) < 1e-4 * scale, "degree ({p}, {q}) uuder at ({u}, {v}): {:?} vs {uu:?}", s.uuder(u, v));
assert!(v3(s.vvder(u, v)).dist(vv) < 1e-4 * scale, "degree ({p}, {q}) vvder at ({u}, {v}): {:?} vs {vv:?}", s.vvder(u, v));
}
}
}
}
/// A rational surface's second derivatives come from its homogeneous B-spline's: they are right
/// too.
#[test]
fn nurbs_surface_second_derivatives_match_finite_differences() {
let b = surface(3, 3);
let (ku, kv) = b.knot_vecs().clone();
let rows: Vec<Vec<mt::Vector4>> = b
.control_points()
.iter()
.enumerate()
.map(|(i, row)| {
row.iter()
.enumerate()
.map(|(j, p)| {
let w = 1.0 + 0.3 * ((i + 2 * j) % 3) as f64;
mt::Vector4::new(p.x * w, p.y * w, p.z * w, w)
})
.collect()
})
.collect();
let s = mt::NurbsSurface::new(mt::BSplineSurface::new((ku, kv), rows));
for (u, v) in [(0.0, 0.0), (0.37, 0.0), (0.5, 0.61), (1.0, 0.2)] {
let uu = second(|t| from_p3(s.subs(t, v)), u);
let vv = second(|t| from_p3(s.subs(u, t)), v);
let scale = uu.len().max(vv.len()).max(1.0);
assert!(v3(s.uuder(u, v)).dist(uu) < 1e-4 * scale, "uuder at ({u}, {v}): {:?} vs {uu:?}", s.uuder(u, v));
assert!(v3(s.vvder(u, v)).dist(vv) < 1e-4 * scale, "vvder at ({u}, {v}): {:?} vs {vv:?}", s.vvder(u, v));
}
}
+1 -1
View File
@@ -48,7 +48,7 @@ fn surface_of(shell: mt::Shell) -> Body {
/// A body from faces: a solid when they close, else a surface; with the history of the
/// operation that made the faces from `operands` as `rec` records.
fn body_of(faces: Vec<mt::Face>, operands: &[&mt::Solid], rec: &Rebuild) -> Result<Body> {
pub(crate) fn body_of(faces: Vec<mt::Face>, operands: &[&mt::Solid], rec: &Rebuild) -> Result<Body> {
let shell = mt::Shell::from(faces);
if shell.shell_condition() == mt::ShellCondition::Closed {
crate::record::rebuilt(mt::Solid::new_unchecked(vec![shell]), operands, rec)
+127
View File
@@ -0,0 +1,127 @@
//! The Boundary Surface dialog (#763): a loop of sketch curves becomes the loop patch, edges and
//! curves across become a network with its continuity and operation, curves that meet end to end
//! are one chain, and Edit Feature brings a network back as it was.
use crate::dialogs::Kind;
use crate::dialogs_surface::Surf;
use crate::scenario::Harness;
use serde_json::{Map, json};
use solidcraft_engine::Sel;
use solidcraft_engine::doc::{FeatureKind, Operation, kernel::Continuity};
use solidcraft_engine::geom::Vec3;
fn ok(h: &mut Harness) {
h.frames(2);
h.step(&json!({"widget":"OK"})).unwrap();
// An edit is applied off the UI thread: give it the frames it takes.
for _ in 0..200 {
if h.app.dialog.is_none() {
break;
}
h.frames(1);
}
assert!(h.app.dialog.is_none(), "{:?} {:?} {:?}", h.app.preview.error, h.app.dialog.as_ref().map(|d| (&d.error, &d.inputs)), h.app.session.log);
}
#[test]
fn a_loop_of_sketch_curves_is_the_loop_patch() {
let mut h = Harness::new();
h.app.run("sketch.create", json!({"plane":"XY","name":"Loop"})).unwrap();
for (id, a, b) in [("s1", [0, 0], [10, 0]), ("s2", [10, 0], [10, 10]), ("s3", [10, 10], [0, 10]), ("s4", [0, 10], [0, 0])] {
h.app.run("sketch.line", json!({"points":[a, b],"ids":[id]})).unwrap();
}
h.app.run("sketch.finish", json!({})).unwrap();
h.step(&json!({"call":"ui.start","params":{"command":"surface.boundary"}})).unwrap();
h.frames(3);
assert!(h.widget("Cross curves").is_some() && h.widget("Continuity").is_some() && h.widget("Operation").is_some());
let d = h.app.dialog.as_mut().unwrap();
d.inputs[0].items = ["s1", "s2", "s3", "s4"].iter().map(|id| Sel::SketchCurve { id: (*id).into() }).collect();
ok(&mut h);
let f = h.app.session.doc.features.last().unwrap();
let FeatureKind::SurfaceBoundary { curves, orders, .. } = &f.kind else { panic!("{:?}", f.kind) };
assert_eq!(curves, &["s1", "s2", "s3", "s4"]);
assert!(orders.iter().all(|o| *o == Continuity::G1), "{orders:?}");
assert_eq!(h.app.session.world_state().bodies.len(), 1);
}
/// A quarter cylinder sheet (its top edge open at y = 10, z = 0) and a 3D line above it.
fn cylinder_and_line(h: &mut Harness) -> String {
h.app.run("sketch.create", json!({"plane":"YZ","name":"Arc"})).unwrap();
let c = 10.0 * std::f64::consts::FRAC_1_SQRT_2;
let r = h.app.run("sketch.arc.three_point", json!({"start":[0,-10],"end":[10,0],"through":[c,-c]})).unwrap();
let arc = r["created"]["curves"][0].as_str().unwrap().to_string();
h.app.run("sketch.finish", json!({})).unwrap();
h.app.run("surface.extrude", json!({"sketch":"Arc","curves":[arc],"distance":10})).unwrap();
h.app.run("sketch.create", json!({"plane":"XY","name":"Top"})).unwrap();
h.app.run("sketch.options", json!({"sketch_3d": true})).unwrap();
let r = h.app.run("sketch.line3d", json!({"points":[[0,3,12],[10,3,12]]})).unwrap();
h.app.run("sketch.finish", json!({})).unwrap();
r["curves"][0].as_str().unwrap().to_string()
}
#[test]
fn edges_and_curves_make_a_network_and_come_back_in_an_edit() {
let mut h = Harness::new();
let top = cylinder_and_line(&mut h);
let rim = crate::dialogs::edge_sel(&h.app.session, Vec3::new(5.0, 10.0, 0.0)).unwrap();
let Sel::Edge { body, .. } = &rim else { panic!("{rim:?}") };
let body = body.clone();
h.step(&json!({"call":"ui.start","params":{"command":"surface.boundary"}})).unwrap();
h.frames(3);
let d = h.app.dialog.as_mut().unwrap();
d.inputs[0].items = vec![rim.clone(), Sel::SketchCurve { id: top.clone() }];
let Kind::Surface(Surf::Boundary { continuity, join }) = &mut d.kind else { panic!("{:?}", d.kind) };
*continuity = 2;
*join = true;
ok(&mut h);
let name = h.app.session.doc.features.last().unwrap().name.clone();
let network = |h: &Harness| match &h.app.session.doc.find_feature(&name).unwrap().kind {
FeatureKind::SurfaceNetwork { u, v, operation } => (u.clone(), v.clone(), *operation),
k => panic!("{k:?}"),
};
let (u, v, operation) = network(&h);
assert_eq!((u.len(), v.len(), operation), (2, 0, Operation::Join));
assert_eq!(u[0].body.as_ref().map(|b| b.to_string()), Some(body.clone()));
assert_eq!(u[0].continuity, Continuity::G2);
assert_eq!(u[1].curves, vec![top.clone()]);
// Joined into the sheet: one body, two faces.
let st = h.app.session.world_state();
assert_eq!(st.bodies.len(), 1);
assert_eq!(st.body(&body).map(|b| b.body.face_count()), Some(2));
drop(st);
h.step(&json!({"call":"ui.editFeature","params":{"feature":name}})).unwrap();
h.frames(8);
let d = h.app.dialog.as_ref().unwrap();
assert!(matches!(d.kind, Kind::Surface(Surf::Boundary { continuity: 2, join: true })), "{:?}", d.kind);
assert_eq!(d.inputs[0].items.len(), 2, "{:?}", d.inputs[0].items);
ok(&mut h);
let (u2, v2, op2) = network(&h);
assert_eq!((u2.len(), v2.len(), op2), (2, 0, Operation::Join));
assert_eq!((u2[0].continuity, &u2[1].curves), (Continuity::G2, &vec![top]));
}
/// Picks that meet end to end in one sketch are one curve of the network; a pick elsewhere is
/// another.
#[test]
fn curves_that_meet_are_one_chain() {
let mut h = Harness::new();
h.app.run("sketch.create", json!({"plane":"XY","name":"Net"})).unwrap();
h.app.run("sketch.line", json!({"points":[[0,0],[5,0]],"ids":["a1"]})).unwrap();
h.app.run("sketch.line", json!({"points":[[5,0],[10,0]],"ids":["a2"]})).unwrap();
h.app.run("sketch.line", json!({"points":[[0,8],[10,8]],"ids":["b"]})).unwrap();
h.app.run("sketch.line", json!({"points":[[0,0],[0,8]],"ids":["c"]})).unwrap();
h.app.run("sketch.line", json!({"points":[[10,0],[10,8]],"ids":["d"]})).unwrap();
h.app.run("sketch.finish", json!({})).unwrap();
let sketch = h.app.session.doc.find_feature("Net").unwrap().id;
let k = Surf::Boundary { continuity: 0, join: false };
let (_, mut inputs) = crate::dialogs_surface::start(&h.app, "surface.boundary").unwrap();
inputs[0].items = ["a2", "b", "a1"].iter().map(|id| Sel::SketchCurve { id: (*id).into() }).collect();
inputs[1].items = ["c", "d"].iter().map(|id| Sel::SketchCurve { id: (*id).into() }).collect();
let cmds = crate::dialogs_surface::commands(&h.app, &k, &inputs, &Map::new()).unwrap();
let (id, p) = &cmds[0];
assert_eq!(id, "surface.boundary");
assert_eq!(p["u"], json!([{"sketch": sketch, "curves": ["a2", "a1"]}, {"sketch": sketch, "curves": ["b"]}]), "{p}");
assert_eq!(p["v"], json!([{"sketch": sketch, "curves": ["c"]}, {"sketch": sketch, "curves": ["d"]}]), "{p}");
// And it builds: the chain a1–a2 is one boundary of the patch.
h.app.run("surface.boundary", p.clone()).unwrap();
assert_eq!(h.app.session.world_state().bodies.len(), 1);
}
+199 -1
View File
@@ -1,5 +1,6 @@
//! Dialogs for the surface tools and face splitting (#19): Surface Extrude, Revolve, Sweep and
//! Loft, Offset and Ruled Surface, Patch, Stitch, Thicken, Extend, Trim, Untrim and Split Face. Each has a live preview and Edit Feature.
//! Loft, Offset and Ruled Surface, Boundary Surface, Patch, Stitch, Thicken, Extend, Trim, Untrim
//! and Split Face. Each has a live preview and Edit Feature.
use serde_json::{Map, Value, json};
use solidcraft_engine::Sel;
@@ -27,6 +28,13 @@ pub enum Surf {
},
Sweep(crate::dialogs_sweep::SweepOpts),
Loft,
/// `continuity`: an index into [`PATCH_CONTINUITY`] (for a loop of sketch curves, how much of
/// the sketch's plane each side repeats; for picked edges, how the surface meets the faces
/// beside them); `join`: sew the surface into the body of its edges.
Boundary {
continuity: usize,
join: bool,
},
/// `continuity`: an index into [`PATCH_CONTINUITY`] (how a patch on edges meets the faces
/// beside its loop).
Patch {
@@ -74,6 +82,7 @@ impl Surf {
Surf::Revolve { .. } => "SURFACE REVOLVE",
Surf::Sweep(_) => "SURFACE SWEEP",
Surf::Loft => "SURFACE LOFT",
Surf::Boundary { .. } => "BOUNDARY SURFACE",
Surf::Patch { .. } => "PATCH",
Surf::Unstitch => "UNSTITCH",
Surf::ReverseNormal => "REVERSE NORMAL",
@@ -104,6 +113,9 @@ impl Surf {
/// How a patch on edges meets the faces beside its loop (labels, and the `continuity` parameter).
const PATCH_CONTINUITY: [(&str, &str); 3] = [("Position (G0)", "g0"), ("Tangent (G1)", "g1"), ("Curvature (G2)", "g2")];
/// What a boundary surface becomes: a body of its own, or part of the body of its edges.
const BOUNDARY_OPS: [&str; 2] = ["New Body", "Join"];
/// Which holes Untrim takes away: every one, the picked ones, or none (the outer boundary only).
const UNTRIM_HOLES: [&str; 3] = ["All", "Picked", "None"];
@@ -128,6 +140,7 @@ fn inputs(k: &Surf) -> Vec<SelInput> {
]
}
Surf::Loft => vec![SelInput::new("Sections (one sketch each)", PROFILES | CURVES, true)],
Surf::Boundary { .. } => vec![SelInput::new("Curves", CURVES | EDGES, true), SelInput::new("Cross curves", CURVES | EDGES, true)],
Surf::Patch { .. } => vec![SelInput::new("Boundary", PROFILES | EDGES, true), SelInput::new("Pass through", VERTICES | FACES, true)],
Surf::Unstitch => vec![SelInput::new("Body, or faces to take out", BODIES | FACES, true)],
Surf::ReverseNormal => vec![SelInput::new("Surface, or faces to turn over", BODIES | FACES, true)],
@@ -155,6 +168,7 @@ pub fn start(_app: &SolveApp, id: &str) -> Option<(Kind, Vec<SelInput>)> {
"surface.revolve" => Surf::Revolve { angle: "360 deg".into(), symmetric: false, axis: None },
"surface.sweep" => Surf::Sweep(crate::dialogs_sweep::SweepOpts::default()),
"surface.loft" => Surf::Loft,
"surface.boundary" => Surf::Boundary { continuity: 1, join: false },
"surface.patch" => Surf::Patch { continuity: 0 },
"surface.unstitch" => Surf::Unstitch,
"surface.reverse_normal" => Surf::ReverseNormal,
@@ -264,6 +278,16 @@ pub fn rows(ui: &mut egui::Ui, k: &mut Surf) -> bool {
combo(ui, "pa_cont", &PATCH_CONTINUITY.map(|(label, _)| label), continuity);
ui.end_row();
}
Surf::Boundary { continuity, join } => {
row_label(ui, "Continuity");
combo(ui, "bo_cont", &PATCH_CONTINUITY.map(|(label, _)| label), continuity);
ui.end_row();
row_label(ui, "Operation");
let mut op = usize::from(*join);
combo(ui, "bo_op", &BOUNDARY_OPS, &mut op);
*join = op == 1;
ui.end_row();
}
Surf::Sweep(opts) => enter |= crate::dialogs_sweep::rows(ui, opts, "ss"),
Surf::Trim | Surf::SplitFace | Surf::Unstitch | Surf::ReverseNormal | Surf::Loft => {}
}
@@ -342,6 +366,98 @@ fn tool(app: &SolveApp, sel: Option<&Sel>) -> Result<(&'static str, Value), Stri
}
}
/// One curve of a boundary surface as the dialog picks it: sketch curves of one sketch, or edges
/// of one body, that meet end to end.
#[derive(Clone, Debug, PartialEq)]
enum Chain {
Sketch { sketch: u64, ids: Vec<String> },
Edges { body: String, points: Vec<Vec3> },
}
/// The picks grouped into curves: picks of one sketch (or one body) whose ends meet run on into
/// one chain, in the order they were first picked; anything else is a curve of its own.
fn chains(app: &SolveApp, picks: &[Sel]) -> Result<Vec<Chain>, String> {
let st = app.session.world_state();
// Each pick: what it belongs to (a sketch or a body), its ends, and how it joins a chain.
let mut parts: Vec<(Chain, [Vec3; 2])> = Vec::with_capacity(picks.len());
for x in picks {
match x {
Sel::SketchCurve { id } => {
let sketch = crate::dialogs::curves_sketch(app, std::slice::from_ref(id), None).ok_or("a picked curve is no longer in a sketch")?;
let ss = st.sketch(sketch).ok_or("a picked curve's sketch has not been solved")?;
let ends = if let Some(ci) = ss.sketch.curve_index(id) {
let segs = ss.sketch.segs(ci);
match (segs.first(), segs.last()) {
(Some(a), Some(b)) => [ss.plane.to_world(a.start()), ss.plane.to_world(b.end())],
_ => return Err(format!("curve `{id}` has no geometry")),
}
} else {
let w = ss.sketch.wire_index(id).and_then(|wi| ss.sketch.wires.get(wi)).ok_or("a picked curve is no longer in a sketch")?;
match (w.pts.first(), w.pts.last()) {
(Some(a), Some(b)) => [*a, *b],
_ => return Err(format!("curve `{id}` has no geometry")),
}
};
parts.push((Chain::Sketch { sketch, ids: vec![id.clone()] }, ends));
}
Sel::Edge { body, index, point } => {
let b = st.body(body).ok_or("a picked edge's body is gone")?;
let m = b.mesh();
let e = m.edges.get(*index).ok_or("a picked edge is gone")?;
let (Some(a), Some(z)) = (e.first(), e.last()) else { return Err("a picked edge has no points".into()) };
parts.push((Chain::Edges { body: body.clone(), points: vec![*point] }, [*a, *z]));
}
_ => return Err("pick sketch curves or edges".into()),
}
}
let same_source = |a: &Chain, b: &Chain| match (a, b) {
(Chain::Sketch { sketch: x, .. }, Chain::Sketch { sketch: y, .. }) => x == y,
(Chain::Edges { body: x, .. }, Chain::Edges { body: y, .. }) => x == y,
_ => false,
};
let meet = |a: &[Vec3; 2], b: &[Vec3; 2]| a.iter().any(|p| b.iter().any(|q| p.dist(*q) <= 1e-6 * (1.0 + p.len())));
// Union the picks that meet, keeping the first pick of each chain in front.
let mut group: Vec<usize> = (0..parts.len()).collect();
fn root(group: &[usize], mut i: usize) -> usize {
while let Some(&g) = group.get(i) {
if g == i {
break;
}
i = g;
}
i
}
for i in 0..parts.len() {
for j in 0..i {
let (Some((ci, ei)), Some((cj, ej))) = (parts.get(i), parts.get(j)) else { continue };
if same_source(ci, cj) && meet(ei, ej) {
let (ri, rj) = (root(&group, i), root(&group, j));
if let Some(g) = group.get_mut(ri.max(rj)) {
*g = ri.min(rj);
}
}
}
}
let mut out: Vec<(usize, Chain)> = Vec::new();
for (i, (part, _)) in parts.into_iter().enumerate() {
let r = root(&group, i);
match out.iter_mut().find(|(k, _)| *k == r) {
Some((_, Chain::Sketch { ids, .. })) => {
if let Chain::Sketch { ids: more, .. } = part {
ids.extend(more);
}
}
Some((_, Chain::Edges { points, .. })) => {
if let Chain::Edges { points: more, .. } = part {
points.extend(more);
}
}
None => out.push((r, part)),
}
}
Ok(out.into_iter().map(|(_, c)| c).collect())
}
/// The command a surface dialog makes.
pub fn commands(app: &SolveApp, k: &Surf, inputs: &[SelInput], extra: &Map<String, Value>) -> Result<Vec<(String, Value)>, String> {
let need = |i: usize, what: &str| if items(inputs, i).is_empty() { Err(format!("select {what} first")) } else { Ok(()) };
@@ -407,6 +523,48 @@ pub fn commands(app: &SolveApp, k: &Surf, inputs: &[SelInput], extra: &Map<Strin
.collect::<Result<_, String>>()?;
("surface.loft", json!({ "sections": sections }))
}
Surf::Boundary { continuity, join } => {
need(0, "the curves (sketch curves or edges)")?;
let word = PATCH_CONTINUITY.get(*continuity).map_or("g0", |(_, w)| *w);
let across = items(inputs, 1);
let picks = items(inputs, 0);
let sketch_ids: Vec<String> =
picks.iter().filter_map(|x| if let Sel::SketchCurve { id } = x { Some(id.clone()) } else { None }).collect();
// Two to four sketch curves of one sketch and nothing across: the loop patch.
let looped = across.is_empty() && !*join && sketch_ids.len() == picks.len() && (2..=4).contains(&picks.len());
match looped.then(|| crate::dialogs::curves_sketch(app, &sketch_ids, None)).flatten() {
Some(sk) => {
let mut p = json!({"sketch": sk, "curves": sketch_ids});
// Orders that differ from side to side (kept from the feature) stand as they are.
if !extra.contains_key("continuity") {
p["continuity"] = json!(word);
}
("surface.boundary", p)
}
None => {
let curve = |c: &Chain| match c {
Chain::Sketch { sketch, ids } => json!({"sketch": sketch, "curves": ids}),
Chain::Edges { body, points } => {
let mut v = json!({"body": body, "edges": points.iter().map(|p| pt(*p)).collect::<Vec<_>>()});
if *continuity > 0 {
v["continuity"] = json!(word);
}
v
}
};
let u: Vec<Value> = chains(app, picks)?.iter().map(curve).collect();
let v: Vec<Value> = chains(app, across)?.iter().map(curve).collect();
let mut p = json!({"u": u});
if !v.is_empty() {
p["v"] = json!(v);
}
if *join {
p["operation"] = json!("join");
}
("surface.boundary", p)
}
}
}
Surf::Patch { continuity } => {
need(0, "a boundary (sketch profiles or a loop of edges)")?;
let profiles: Vec<(u64, usize)> =
@@ -629,6 +787,46 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K
],
)
}
FeatureKind::SurfaceBoundary { curves, orders, crown, samples, .. } => {
let first = orders.first().copied().unwrap_or(solidcraft_engine::doc::kernel::Continuity::G1);
let index = PATCH_CONTINUITY.iter().position(|(_, w)| *w == first.as_str());
// What the dialog does not show is kept as it was: a crown, the stations, and orders
// that differ from side to side or that the list does not offer (G3).
let mut extra = Map::new();
if *crown != 0.0 {
extra.insert("crown".into(), json!(crown));
}
if *samples != solidcraft_engine::doc::BOUNDARY_SAMPLES {
extra.insert("samples".into(), json!(samples));
}
if index.is_none() || orders.iter().any(|o| *o != first) {
extra.insert("continuity".into(), json!(orders.iter().map(|o| o.as_str()).collect::<Vec<_>>()));
}
let k = Surf::Boundary { continuity: index.unwrap_or(1), join: false };
let mut ins = inputs(&k);
if let Some(inp) = ins.first_mut() {
inp.items = curves.iter().map(|id| Sel::SketchCurve { id: id.clone() }).collect();
}
return Some((Kind::Surface(k), ins, extra));
}
FeatureKind::SurfaceNetwork { u, v, operation } => {
// A network with a point for a side has nothing to pick it with here.
if u.iter().chain(v).any(|c| c.point.is_some()) {
return None;
}
let sels = |list: &[solidcraft_engine::doc::NetworkCurve]| -> Vec<Sel> {
list.iter()
.flat_map(|c| {
let mut out: Vec<Sel> = c.curves.iter().map(|id| Sel::SketchCurve { id: id.clone() }).collect();
out.extend(c.edges.iter().filter_map(edge));
out
})
.collect()
};
let g = u.iter().chain(v).find(|c| c.body.is_some()).map_or(solidcraft_engine::doc::kernel::Continuity::G0, |c| c.continuity);
let index = PATCH_CONTINUITY.iter().position(|(_, w)| *w == g.as_str()).unwrap_or(0);
(Surf::Boundary { continuity: index, join: *operation == solidcraft_engine::doc::Operation::Join }, vec![sels(u), sels(v)])
}
FeatureKind::SurfaceLoft { sections, .. } => {
(Surf::Loft, vec![sections.iter().flat_map(|sec| sheet_sels(app, sec.sketch.0, sec.profiles.as_ref(), &sec.curves)).collect()])
}
+2
View File
@@ -106,6 +106,8 @@ mod history_off_thread_tests;
pub use file_picker::FilePickerFuture;
#[cfg(test)]
mod blend_arrow_tests;
#[cfg(test)]
mod boundary_dialog_tests;
pub(crate) mod display_lod;
#[cfg(test)]
mod file_load_ui_tests;
+2 -1
View File
@@ -25,7 +25,7 @@ pub(crate) fn icon_of(k: &FeatureKind) -> &'static str {
FeatureKind::SurfaceRuled { .. } => "surface_ruled",
FeatureKind::SurfaceUntrim { .. } => "surface_untrim",
FeatureKind::SurfaceBlend { .. } => "surface_blend",
FeatureKind::SurfaceBoundary { .. } => "surface_boundary",
FeatureKind::SurfaceBoundary { .. } | FeatureKind::SurfaceNetwork { .. } => "surface_boundary",
FeatureKind::SurfaceMatch { .. } => "continuity",
FeatureKind::SurfaceFair { .. } => "surface_fair",
FeatureKind::Revolve { .. } => "revolve",
@@ -549,6 +549,7 @@ mod tests {
("surface.reverse_normal", json!({"type":"reverse_normal", "body":"A"})),
("surface.blend", json!({"type":"surface_blend", "from":{"body":"A", "edges":[]}, "to":{"body":"B", "edges":[]}})),
("surface.boundary", json!({"type":"surface_boundary", "sketch":0, "curves":[]})),
("surface.boundary", json!({"type":"surface_network", "u":[]})),
("surface.match", json!({"type":"surface_match", "body":"A", "target":"B", "edges":[]})),
("surface.fair", json!({"type":"surface_fair", "body":"A", "tolerance":"0.001"})),
("solid.rib", json!({"type":"rib", "sketch":0, "curves":[], "thickness":"2"})),