From ce74cebdc2d2776d399165dd7ddd4a67dd7cb099 Mon Sep 17 00:00:00 2001 From: jyviko <2501648+jyviko@users.noreply.github.com> Date: Thu, 22 Oct 2026 07:15:40 -0400 Subject: [PATCH] Wave 165/509: kernel: bridges read their support faces on the record (and 3 more) 4 commits, squashed; the originals stay reachable from tag archive/merge-main-develop. - 9b5e0a8b4 jyviko: kernel: T-spline sheets as record faces; NURBS faces on the record - 5c1b335e1 jyviko: kernel: bridges read their support faces on the record - b5a7d52b7 jyviko: kernel: bridges and surfaces read the body's own record - c83bd8f94 jyviko: kernel: T-spline and offset tests read the body's record Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ --- crates/kernel/src/boundary_tests.rs | 7 +- crates/kernel/src/bridge.rs | 402 ++++++++++++++-------------- crates/kernel/src/bridge_tests.rs | 62 ++--- crates/kernel/src/surface_offset.rs | 2 +- crates/kernel/src/surfaces.rs | 150 ++++++++--- crates/kernel/src/tspline.rs | 142 ++++++---- 6 files changed, 431 insertions(+), 334 deletions(-) diff --git a/crates/kernel/src/boundary_tests.rs b/crates/kernel/src/boundary_tests.rs index ce7abfcb0..f1091173d 100644 --- a/crates/kernel/src/boundary_tests.rs +++ b/crates/kernel/src/boundary_tests.rs @@ -3,8 +3,6 @@ //! approximation. use super::*; -use crate::body::from_p3; -use truck_modeling::ParametricSurface; /// The angle between two vectors, in degrees. fn angle_deg(a: Vec3, b: Vec3) -> f64 { @@ -28,9 +26,8 @@ fn shape_of(d1: Vec3, d2: Vec3, d3: Vec3) -> (Vec3, Vec3, Vec3) { /// read back as the position, the unit tangent, the curvature vector and the change of curvature /// along that inward direction. fn across(body: &Body, uv: (f64, f64), into: (f64, f64), h: f64) -> (Vec3, Vec3, Vec3, Vec3) { - let face = body.solid.face_iter().next().unwrap(); - let surf = face.surface(); - let q: Vec = (0..5).map(|k| from_p3(surf.subs(uv.0 + k as f64 * h * into.0, uv.1 + k as f64 * h * into.1))).collect(); + let (surf, _) = crate::bridge::the_face(body).unwrap(); + let q: Vec = (0..5).map(|k| surf.point([uv.0 + k as f64 * h * into.0, uv.1 + k as f64 * h * into.1]).unwrap()).collect(); let (f0, f1, f2, f3, f4) = (q[0], q[1], q[2], q[3], q[4]); let d1 = (f0 * -25.0 + f1 * 48.0 + f2 * -36.0 + f3 * 16.0 + f4 * -3.0) * (1.0 / (12.0 * h)); let d2 = (f0 * 35.0 + f1 * -104.0 + f2 * 114.0 + f3 * -56.0 + f4 * 11.0) * (1.0 / (12.0 * h * h)); diff --git a/crates/kernel/src/bridge.rs b/crates/kernel/src/bridge.rs index d13685cfb..4f66db2b6 100644 --- a/crates/kernel/src/bridge.rs +++ b/crates/kernel/src/bridge.rs @@ -16,14 +16,14 @@ //! speed) by finite differences: the second derivative of a surface curve with a unit tangent is //! its curvature vector, and the third is the arclength derivative of that curvature vector. -use mt::{BoundedCurve, ParametricCurve, ParametricSurface, ParametricSurface3D, SearchNearestParameter}; use solidcraft_geom::Vec3; +use solidcraft_geom::brep::Brep; +use solidcraft_geom::brep::eval::{CurveEval, SurfaceEval}; use solidcraft_geom::bspline::{CurveN, HPoint, NurbsSurface}; -use truck_modeling as mt; -use crate::body::{Body, from_p3, p3}; -use crate::surfaces::surface_body; -use crate::{KernelError, Result, guard}; +use crate::body::Body; +use crate::surfaces::Chain; +use crate::{KernelError, Result}; /// How much of a support surface a bridge repeats along its boundary. #[derive(Clone, Copy, PartialEq, Eq, Debug, Default, serde::Serialize, serde::Deserialize)] @@ -89,41 +89,40 @@ pub struct Frame { } /// The edges of `body` picked by points on them, chained: each runs on from the last, and the -/// chain may close. Used with [`frames`], whose chain must be a chain of one face's own edges. -pub fn chain(body: &Body, at: &[Vec3]) -> Result> { +/// chain may close. Each is an edge of the body's record (its index) with whether the chain runs +/// along it. Used with [`frames`], whose chain must be a chain of one face's own edges. +pub fn chain(body: &Body, at: &[Vec3]) -> Result { body.require_brep("blend")?; if at.is_empty() || at.len() > 10_000 || at.iter().any(|p| !p.is_finite()) { return Err(KernelError::Invalid("pick 1 to 10000 points on the edges of a chain".into())); } - let mut pool: Vec = Vec::new(); + let r = body.record(); + let mut pool: Vec = Vec::new(); for p in at { let e = crate::surfaces::edge_near(body, *p).ok_or_else(|| KernelError::Invalid("no edge near a picked point".to_string()))?; - if !pool.iter().any(|x| x.id() == e.id()) { + if !pool.contains(&e) { pool.push(e); } } + let ends = |e: usize| r.edges.get(e).map(|x| x.vertices).ok_or_else(|| KernelError::Invalid("an edge reference".into())); let first = pool.remove(0); - let mut chain = vec![first]; + let mut chain = vec![(first, true)]; // The picks need not be given in order: run forward from the first edge, then backwards. - let mut end = match chain.first() { - Some(e) => e.back().clone(), - None => return Err(KernelError::Invalid("pick at least one edge".into())), - }; - while let Some(k) = pool.iter().position(|e| e.front().id() == end.id() || e.back().id() == end.id()) { + let mut end = ends(first)?[1]; + while let Some(k) = pool.iter().position(|e| ends(*e).is_ok_and(|v| v.contains(&end))) { let e = pool.remove(k); - let e = if e.front().id() == end.id() { e } else { e.inverse() }; - end = e.back().clone(); - chain.push(e); + let [a, z] = ends(e)?; + let forward = a == end; + end = if forward { z } else { a }; + chain.push((e, forward)); } - let mut start = match chain.first() { - Some(e) => e.front().clone(), - None => return Err(KernelError::Invalid("pick at least one edge".into())), - }; - while let Some(k) = pool.iter().position(|e| e.front().id() == start.id() || e.back().id() == start.id()) { + let mut start = ends(first)?[0]; + while let Some(k) = pool.iter().position(|e| ends(*e).is_ok_and(|v| v.contains(&start))) { let e = pool.remove(k); - let e = if e.back().id() == start.id() { e } else { e.inverse() }; - start = e.front().clone(); - chain.insert(0, e); + let [a, z] = ends(e)?; + let forward = z == start; + start = if forward { a } else { z }; + chain.insert(0, (e, forward)); } if !pool.is_empty() { return Err(KernelError::Invalid("the picked edges do not run on from one another".into())); @@ -131,14 +130,20 @@ pub fn chain(body: &Body, at: &[Vec3]) -> Result> { Ok(chain) } -/// Whether a chain of edges closes back on itself. -pub fn chain_closes(chain: &[mt::Edge]) -> bool { +/// Whether a chain of `body`'s edges closes back on itself. +pub fn chain_closes(body: &Body, chain: &Chain) -> bool { + closes(body.record(), chain) +} + +fn closes(r: &Brep, chain: &Chain) -> bool { + let end = |(e, forward): (usize, bool), head: bool| r.edges.get(e).map(|x| if forward == head { x.vertices[1] } else { x.vertices[0] }); let (Some(first), Some(last)) = (chain.first(), chain.last()) else { return false }; - first.front().id() == last.back().id() + end(*first, false).is_some() && end(*first, false) == end(*last, true) } /// A point of a [`ChainLine`]'s polyline: where it is, its arclength along the chain, the chain -/// edge (its index) the segment from it runs along, and that edge's curve parameter there. +/// edge (its index in the chain) the segment from it runs along, and that edge's curve parameter +/// there. #[derive(Clone, Copy)] struct Sample { p: Vec3, @@ -148,40 +153,42 @@ struct Sample { } /// A chain of edges measured by arclength through a fine polyline on it, so that a station is read -/// on the edge's own curve, not on a chord. A chain that closes ends back on its first point. +/// on the edge's own curve, not on a chord. A chain that closes ends back on its first point. Each +/// edge's curve is walked the way the chain runs along it. struct ChainLine { - curves: Vec, + curves: Vec<(CurveEval, [f64; 2])>, samples: Vec, closed: bool, } impl ChainLine { - fn of(edges: &[mt::Edge]) -> Result { + fn of(body: &Body, chain: &Chain) -> Result { /// Samples per edge used for the length table. const PER_EDGE: usize = 64; - let mut samples: Vec = Vec::with_capacity(edges.len() * (PER_EDGE + 1) + 1); - let mut curves = Vec::with_capacity(edges.len()); + let r = body.record(); + let mut samples: Vec = Vec::with_capacity(chain.len() * (PER_EDGE + 1) + 1); + let mut curves = Vec::with_capacity(chain.len()); let push = |samples: &mut Vec, p: Vec3, edge: usize, t: f64| { let s = samples.last().map_or(0.0, |last| last.s + last.p.dist(p)); samples.push(Sample { p, s, edge, t }); }; - for (i, e) in edges.iter().enumerate() { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - if !(t1 > t0) || ![t0, t1].into_iter().all(f64::is_finite) { - return Err(KernelError::Invalid("an edge has no parameter range".into())); - } + let fail = || KernelError::Failed("bridge: an edge has no point".into()); + for (i, &(e, forward)) in chain.iter().enumerate() { + let edge = r.edges.get(e).ok_or_else(|| KernelError::Invalid("an edge reference".into()))?; + let c = CurveEval::new(&edge.curve).map_err(|err| KernelError::Failed(format!("bridge: {err}")))?; + let [t0, t1] = edge.interval; + let (a, z) = if forward { (t0, t1) } else { (t1, t0) }; for k in 0..=PER_EDGE { // The segment that starts at this point: along this edge, or the zero-length join // to the next edge. - let t = t0 + (t1 - t0) * k as f64 / PER_EDGE as f64; - push(&mut samples, from_p3(c.subs(t)), i, t); + let t = a + (z - a) * k as f64 / PER_EDGE as f64; + push(&mut samples, c.point(t).ok_or_else(fail)?, i, t); } - curves.push(c); + curves.push((c, [a, z])); } - let closed = chain_closes(edges); + let closed = closes(&r, chain); if closed && let Some(first) = samples.first().copied() { - push(&mut samples, first.p, edges.len().saturating_sub(1), first.t); + push(&mut samples, first.p, chain.len().saturating_sub(1), first.t); } let line = ChainLine { curves, samples, closed }; let total = line.length(); @@ -195,6 +202,10 @@ impl ChainLine { self.samples.last().map_or(0.0, |x| x.s) } + fn point(&self, edge: usize, t: f64) -> Result { + self.curves.get(edge).and_then(|(c, _)| c.point(t)).ok_or_else(|| KernelError::Failed("bridge: sample".into())) + } + /// The point at arclength `s` (wrapped round a closed chain, clamped on an open one), on its /// edge's own curve, and the chain edge it is on. fn at(&self, s: f64) -> Result<(Vec3, usize)> { @@ -203,14 +214,13 @@ impl ChainLine { let hi = self.samples.partition_point(|x| x.s < s).clamp(1, self.samples.len().saturating_sub(1)); let fail = || KernelError::Failed("bridge: sample".into()); let (lo, hi) = (self.samples.get(hi - 1).ok_or_else(fail)?, self.samples.get(hi).ok_or_else(fail)?); - let curve = self.curves.get(lo.edge).ok_or_else(fail)?; let span = hi.s - lo.s; if !(span > 1e-12) { // The zero-length join between two edges: the end of the edge it belongs to. - return Ok((from_p3(curve.subs(lo.t)), lo.edge)); + return Ok((self.point(lo.edge, lo.t)?, lo.edge)); } let f = ((s - lo.s) / span).clamp(0.0, 1.0); - Ok((from_p3(curve.subs(lo.t + (hi.t - lo.t) * f)), lo.edge)) + Ok((self.point(lo.edge, lo.t + (hi.t - lo.t) * f)?, lo.edge)) } /// `count` stations evenly along the chain, from arclength `start` (a closed chain's seam; an @@ -234,11 +244,10 @@ impl ChainLine { fn edges_at(&self, p: Vec3, edge: usize) -> [Option; 3] { let count = self.curves.len(); let tol = self.length() * 1e-9 + 1e-12; - let Some(curve) = self.curves.get(edge) else { return [Some(edge), None, None] }; - let (t0, t1) = curve.range_tuple(); - let at = |t: f64| from_p3(curve.subs(t)).dist(p) <= tol; - let before = at(t0).then(|| edge.checked_sub(1).or(self.closed.then(|| count.saturating_sub(1)))).flatten(); - let after = at(t1).then(|| Some(edge + 1).filter(|e| *e < count).or(self.closed.then_some(0))).flatten(); + let Some((curve, [a, z])) = self.curves.get(edge) else { return [Some(edge), None, None] }; + let at = |t: f64| curve.point(t).is_some_and(|q| q.dist(p) <= tol); + let before = at(*a).then(|| edge.checked_sub(1).or(self.closed.then(|| count.saturating_sub(1)))).flatten(); + let after = at(*z).then(|| Some(edge + 1).filter(|e| *e < count).or(self.closed.then_some(0))).flatten(); [Some(edge), before, after] } @@ -250,23 +259,33 @@ impl ChainLine { } /// The arclength of the chain's point nearest `p`, and how far `p` is from the chain: the - /// nearest point of the fine polyline, then refined on that edge's own curve. + /// nearest point of the fine polyline, then refined on that edge's own curve between the + /// samples either side (golden-section search). fn nearest_with_distance(&self, p: Vec3) -> (f64, f64) { - let mut best = (f64::INFINITY, 0.0, 0usize, 0.0); + let mut best = (f64::INFINITY, 0.0, 0usize, 0.0, 0.0); for w in self.samples.windows(2) { let (Some(a), Some(b)) = (w.first(), w.get(1)) else { continue }; let len = a.p.dist(b.p); let f = if len > 1e-12 { ((p - a.p).dot(b.p - a.p) / (len * len)).clamp(0.0, 1.0) } else { 0.0 }; let d = p.dist(a.p + (b.p - a.p) * f); - if d < best.0 { - best = (d, a.s + len * f, a.edge, a.t + (b.t - a.t) * f); + if d < best.0 && a.edge == b.edge { + best = (d, a.s + len * f, a.edge, a.t, b.t); } } - let (chord, s, edge, hint) = best; - let on_curve = self.curves.get(edge).and_then(|c| { - let (t0, t1) = c.range_tuple(); - let t = c.search_nearest_parameter(p3(p), Some(hint), 100)?; - (t0..=t1).contains(&t).then(|| from_p3(c.subs(t)).dist(p)) + let (chord, s, edge, ta, tb) = best; + let on_curve = self.curves.get(edge).and_then(|(c, _)| { + let d = |t: f64| c.point(t).map_or(f64::INFINITY, |q| q.dist(p)); + let (mut lo, mut hi) = (ta.min(tb), ta.max(tb)); + let g = 0.5 * (5f64.sqrt() - 1.0); + for _ in 0..80 { + let (x, y) = (hi - g * (hi - lo), lo + g * (hi - lo)); + if d(x) < d(y) { + hi = y; + } else { + lo = x; + } + } + Some(d(0.5 * (lo + hi))).filter(|x| x.is_finite()) }); (s, on_curve.map_or(chord, |d| d.min(chord))) } @@ -294,24 +313,25 @@ impl ChainLine { } } -/// The support surface's frames along `edges` (a chain of its own edges), for a bridge that -/// leaves in direction `leave` (projected into the tangent plane at each station). -pub fn frames(face: &mt::Face, edges: &[mt::Edge], leave: Vec3, count: usize) -> Result> { +/// The support surface's frames along `chain` (a chain of edges of `body`'s face `face`), for a +/// bridge that leaves in direction `leave` (projected into the tangent plane at each station). +pub fn frames(body: &Body, face: usize, chain: &Chain, leave: Vec3, count: usize) -> Result> { if !(2..=4097).contains(&count) { return Err(KernelError::Invalid("a bridge needs 2 to 4097 stations".into())); } - let line = ChainLine::of(edges)?; + let line = ChainLine::of(body, chain)?; let stations = line.stations(count, 0.0, false)?; - frames_on(&vec![face.clone(); edges.len()], &stations, &line, leave) + let r = body.record(); + frames_on(&r, &vec![face; chain.len()], &stations, &line, leave) } /// The frames at `stations` (points on `line`, each with the index of the chain edge it is on), -/// each read on the support face of its own edge (`faces`, one per chain edge): a chain may run -/// along the boundaries of several faces, a tube's rim along the halves of its wall. A station on -/// the vertex where two of those faces meet sits at a corner of one face's parameters, where the -/// shape may not be readable along the leave direction; it is then read on the other face, which -/// holds the same point. -fn frames_on(faces: &[mt::Face], stations: &[(Vec3, usize)], line: &ChainLine, leave: Vec3) -> Result> { +/// each read on the support face of its own edge (`faces`, faces of `r`, one per chain edge): a +/// chain may run along the boundaries of several faces, a tube's rim along the halves of its wall. +/// A station on the vertex where two of those faces meet sits at a corner of one face's +/// parameters, where the shape may not be readable along the leave direction; it is then read on +/// the other face, which holds the same point. +fn frames_on(r: &Brep, faces: &[usize], stations: &[(Vec3, usize)], line: &ChainLine, leave: Vec3) -> Result> { let leave = leave.normalized().filter(|l| l.is_finite()).ok_or_else(|| KernelError::Invalid("the leave direction must be a finite vector".into()))?; let along = |n: Vec3| -> Result { @@ -322,22 +342,21 @@ fn frames_on(faces: &[mt::Face], stations: &[(Vec3, usize)], line: &ChainLine, l let length = line.length(); // One support per distinct face, each with its own walk (a parameter hint means nothing on // another surface). - let mut supports: Vec<(mt::FaceID, Support, Walk)> = Vec::new(); + let mut supports: Vec<(usize, Support, Walk)> = Vec::new(); let mut out = Vec::with_capacity(stations.len()); 'stations: for (p, edge) in stations { - let mut tried: Vec = Vec::with_capacity(2); + let mut tried: Vec = Vec::with_capacity(2); let mut refusal: Option = None; for e in line.edges_at(*p, *edge).into_iter().flatten() { - let Some(face) = faces.get(e) else { continue }; - let id = face.id(); - if tried.contains(&id) { + let Some(&face) = faces.get(e) else { continue }; + if tried.contains(&face) { continue; } - tried.push(id); - let k = match supports.iter().position(|(f, _, _)| *f == id) { + tried.push(face); + let k = match supports.iter().position(|(f, _, _)| *f == face) { Some(k) => k, None => { - supports.push((id, Support::of(face, length)?, Walk::new(length))); + supports.push((face, Support::of(r, face, length)?, Walk::new(length))); supports.len() - 1 } }; @@ -359,21 +378,22 @@ fn frames_on(faces: &[mt::Face], stations: &[(Vec3, usize)], line: &ChainLine, l Ok(out) } -/// The frames of `face` at stations on its own boundary, each leaving the face straight across -/// that boundary: `stations` are points on the boundary with the boundary's direction there *as -/// the face's own boundary runs* (its wires as [`mt::Face::boundaries`] gives them), and the leave -/// direction is that direction × the face's outward normal — in the face's tangent plane, at -/// right angles to the boundary, away from the face. `length` is the size of the boundary the -/// stations are on (it sets how closely a station must lie on the surface and the step the shape -/// is read with). Each frame comes with the face's unit normal there (as the face is oriented). -/// With `shape` false only the leave direction and the normal are read (`bend` and -/// `bend_change` are zero), which needs no room on the surface beside the station. -pub fn frames_across(face: &mt::Face, stations: &[(Vec3, Vec3)], length: f64, shape: bool) -> Result> { +/// The frames of `body`'s face `face` at stations on its own boundary, each leaving the face +/// straight across that boundary: `stations` are points on the boundary with the boundary's +/// direction there *as the face's own boundary runs* (counter-clockwise about its outward normal), +/// and the leave direction is that direction × the face's outward normal — in the face's tangent +/// plane, at right angles to the boundary, away from the face. `length` is the size of the boundary +/// the stations are on (it sets how closely a station must lie on the surface and the step the +/// shape is read with). Each frame comes with the face's outward unit normal there. With `shape` +/// false only the leave direction and the normal are read (`bend` and `bend_change` are zero), +/// which needs no room on the surface beside the station. +pub fn frames_across(body: &Body, face: usize, stations: &[(Vec3, Vec3)], length: f64, shape: bool) -> Result> { if stations.len() > 1 << 16 || !(length.is_finite() && length > 0.0) { return Err(KernelError::Invalid("frames across a boundary need at most 65536 stations on a boundary of finite size".into())); } - let support = Support::of(face, length)?; - let outward = if face.orientation() { 1.0 } else { -1.0 }; + let r = body.record(); + let support = Support::of(&r, face, length)?; + let outward = if support.forward { 1.0 } else { -1.0 }; let mut walk = Walk::new(length); let mut out = Vec::with_capacity(stations.len()); for (p, tangent) in stations { @@ -389,12 +409,13 @@ pub fn frames_across(face: &mt::Face, stations: &[(Vec3, Vec3)], length: f64, sh Ok(out) } -/// A support surface read at stations: the surface, its parameter box, and how close a station -/// must lie to it. +/// A support surface read at stations: the surface, where its parameters run (a periodic +/// direction without bound), whether its face is used along its natural normal, and how close a +/// station must lie to it. struct Support { - surf: mt::Surface, - range_u: (f64, f64), - range_v: (f64, f64), + surf: SurfaceEval, + range: [(f64, f64); 2], + forward: bool, tol: f64, } @@ -402,7 +423,7 @@ struct Support { /// next projection, which keeps the search on the same side of a periodic or split surface) and /// the finite-difference step that worked. struct Walk { - hint: Option<(f64, f64)>, + hint: Option<[f64; 2]>, step: f64, } @@ -415,45 +436,46 @@ impl Walk { } impl Support { - fn of(face: &mt::Face, length: f64) -> Result { - let surf = face.surface(); - let (Some(range_u), Some(range_v)) = surf.try_range_tuple() else { - return Err(KernelError::Failed("bridge: the support surface is unbounded".into())); - }; - // A face's own edges may sit a fit tolerance off its surface (a cylinder's wall as a NURBS - // next to its exact ring), so the projection is only asked to be close, not exact. + fn of(r: &Brep, face: usize, length: f64) -> Result { + let f = r.faces.get(face).ok_or_else(|| KernelError::Invalid("no such face".into()))?; + let surf = SurfaceEval::new(&f.surface).map_err(|e| KernelError::Failed(format!("bridge: {e}")))?; + let dom = surf.domain(); + let range = [0, 1].map(|d| match (dom.period[d], dom.range[d]) { + (None, Some(r)) => r, + _ => (f64::NEG_INFINITY, f64::INFINITY), + }); + let forward = r + .shells + .iter() + .find_map(|s| match s { + solidcraft_geom::brep::Shell::Faces { faces, .. } => faces.iter().find(|o| o.face as usize == face).map(|o| o.forward), + _ => None, + }) + .unwrap_or(true); + // A face's own edges may sit a fit tolerance off its surface, so the projection is only + // asked to be close, not exact. let tol = (length * 1e-4).max(1e-6); - Ok(Support { surf, range_u, range_v, tol }) + Ok(Support { surf, range, forward, tol }) } - /// The frame at `p`, leaving in `leave(n)` (`n` the surface's unit normal there), and that - /// normal. Without `read_shape`, the frame's shape is left at zero. + /// The frame at `p`, leaving in `leave(n)` (`n` the surface's natural unit normal there), and + /// that normal. Without `read_shape`, the frame's shape is left at zero. fn station(&self, p: Vec3, leave: &dyn Fn(Vec3) -> Result, walk: &mut Walk, read_shape: bool) -> Result<(Frame, Vec3)> { - let (surf, range_u, range_v, tol) = (&self.surf, self.range_u, self.range_v, self.tol); - let project = |hint: Option<(f64, f64)>| surf.search_nearest_parameter(p3(p), hint, 100); - let close = |uv: (f64, f64)| from_p3(surf.subs(uv.0, uv.1)).dist(p) <= tol; + let (surf, [range_u, range_v], tol) = (&self.surf, self.range, self.tol); // The station before this one is the hint where it lands close; a chain that wraps the // surface (or a periodic one) falls back to a free search. - let (u, v) = match project(walk.hint).filter(|uv| close(*uv)).or_else(|| project(None).filter(|uv| close(*uv))) { - Some(uv) => uv, - None => return Err(KernelError::Invalid("a picked edge is not on the support surface".into())), - }; - walk.hint = Some((u, v)); - let at = from_p3(surf.subs(u, v)); - if at.dist(p) > tol { + let Some([u, v]) = surf.project(p, walk.hint, tol).or_else(|| surf.project(p, None, tol)) else { return Err(KernelError::Invalid("a picked edge is not on the support surface".into())); - } - let normal = surf.normal(u, v); - let n = Vec3::new(normal.x, normal.y, normal.z) - .normalized() - .ok_or_else(|| KernelError::Failed("bridge: the support surface has no normal".into()))?; + }; + walk.hint = Some([u, v]); + let fail = || KernelError::Failed("bridge: the support surface has no point there".into()); + let (_, su, sv) = surf.derivs(u, v).ok_or_else(fail)?; + let n = su.cross(sv).normalized().ok_or_else(|| KernelError::Failed("bridge: the support surface has no normal".into()))?; let w = leave(n)?; if !read_shape { return Ok((Frame { p, leave: w, bend: Vec3::ZERO, bend_change: Vec3::ZERO }, n)); } // Parameter-space direction that leaves in `w` at unit 3D speed: S_u·du + S_v·dv = w. - let su = tangent(surf, u, v, range_u, true); - let sv = tangent(surf, u, v, range_v, false); let (a, b, c) = (su.dot(su), su.dot(sv), sv.dot(sv)); let det = a * c - b * b; let scale = a.max(c).max(1e-30); @@ -463,8 +485,8 @@ impl Support { let du = (c * w.dot(su) - b * w.dot(sv)) / det; let dv = (a * w.dot(sv) - b * w.dot(su)) / det; // The samples of the parameter line. A station sits on the support surface's own - // boundary, so the line usually leaves the surface: the shape is then read from the - // samples of the one side that is still on it, which is the surface's own extension past + // boundary, so the line usually leaves the face: the shape is then read from the samples + // of the one side that is still on the surface, which is the surface's own extension past // that boundary (exact for a plane and a cylinder, what a blend continues from). let slack = 1e-9; let on = |t: f64, h: f64| { @@ -497,7 +519,7 @@ impl Support { let Some(offsets) = chosen else { return Err(KernelError::Invalid("the support surface is too small around a picked edge to read its shape".into())); }; - let q: Vec = offsets.iter().map(|t| from_p3(surf.subs(u + t * h * du, v + t * h * dv))).collect(); + let q: Vec = offsets.iter().map(|t| surf.point([u + t * h * du, v + t * h * dv]).ok_or_else(fail)).collect::>()?; let (Some(&f0), Some(&f1), Some(&f2), Some(&f3), Some(&f4)) = (q.first(), q.get(1), q.get(2), q.get(3), q.get(4)) else { return Err(KernelError::Failed("bridge: samples".into())); }; @@ -529,22 +551,6 @@ impl Support { } } -/// A first derivative of the surface in one parameter, by central differences (one-sided where -/// the parameter is at the edge of the domain). -fn tangent(surf: &mt::Surface, u: f64, v: f64, range: (f64, f64), along_u: bool) -> Vec3 { - let span = (range.1 - range.0).max(1e-12); - let h = (span * 1e-5).max(1e-12); - let at = |x: f64| if along_u { from_p3(surf.subs(x, v)) } else { from_p3(surf.subs(u, x)) }; - let x = if along_u { u } else { v }; - if x - h >= range.0 && x + h <= range.1 { - (at(x + h) - at(x - h)) * (0.5 / h) - } else if x + h <= range.1 { - (at(x + h) - at(x)) * (1.0 / h) - } else { - (at(x.min(range.1)) - at((x - h).max(range.0))) * (1.0 / h) - } -} - /// The geometric shape of a surface curve at a point from its first three derivatives along the /// curve: the unit tangent, the curvature vector and the arclength derivative of that curvature /// vector. All three are what a surface-to-surface continuity condition is stated with. @@ -721,71 +727,68 @@ pub fn bridge(a: &[Frame], b: &[Frame], orders: [Continuity; 2], crown: [f64; 2] knots_v.extend(std::iter::repeat_n(1.0, n + 1)); let points: Vec = ctrl.iter().map(|p| HPoint::weighted(*p, 1.0)).collect(); let nurbs = NurbsSurface::from_homogeneous([degree, n], [knots_u, knots_v], points).map_err(|e| KernelError::Failed(format!("bridge: {e}")))?; - guard("bridge surface", || crate::spline_conv::tensor_face(&nurbs).map(|f| surface_body(vec![f]))) + crate::surfaces::tensor_sheet(&nurbs) } -/// The surface of a bridge face as a grid of points, for callers that measure the result. +/// The one face of a bridge body: its surface and its parameter box. +pub(crate) fn the_face(body: &Body) -> Result<(SurfaceEval, [[f64; 2]; 2])> { + let r = body.record(); + let face = r.faces.first().ok_or_else(|| KernelError::Failed("bridge: no face".into()))?; + let surf = SurfaceEval::new(&face.surface).map_err(|e| KernelError::Failed(format!("bridge: {e}")))?; + Ok((surf, face.domain)) +} + +/// The surface of a bridge face as a grid of points over its parameter box, for callers that +/// measure the result. pub fn sample_grid(body: &Body, along: usize, across: usize) -> Result>> { if !(2..=1025).contains(&along) || !(2..=1025).contains(&across) { return Err(KernelError::Invalid("a grid needs 2 to 1025 samples each way".into())); } - let face = body.solid.face_iter().next().ok_or_else(|| KernelError::Failed("bridge: no face".into()))?; - let surf = face.surface(); - let (Some((u0, u1)), Some((v0, v1))) = surf.try_range_tuple() else { - return Err(KernelError::Failed("bridge: the surface is unbounded".into())); - }; - let mut out = Vec::with_capacity(along); - for i in 0..along { - let u = u0 + (u1 - u0) * i as f64 / (along - 1) as f64; - let mut row = Vec::with_capacity(across); - for j in 0..across { - let v = v0 + (v1 - v0) * j as f64 / (across - 1) as f64; - row.push(from_p3(surf.subs(u, v))); - } - out.push(row); - } - Ok(out) + let (surf, [[u0, u1], [v0, v1]]) = the_face(body)?; + let fail = || KernelError::Failed("bridge: the surface has no point there".into()); + (0..along) + .map(|i| { + let u = u0 + (u1 - u0) * i as f64 / (along - 1) as f64; + (0..across).map(|j| surf.point([u, v0 + (v1 - v0) * j as f64 / (across - 1) as f64]).ok_or_else(fail)).collect() + }) + .collect() } /// The most any point of a bridge's boundary row is from the chain it was built on — the row at /// `v0` for the first boundary, at `v1` for the second: what a stitch would have to close up. fn boundary_gap(made: &Body, line: &ChainLine, at_end: bool) -> Result { - let face = made.solid.face_iter().next().ok_or_else(|| KernelError::Failed("bridge: no face".into()))?; - let surf = face.surface(); - let (Some((u0, u1)), Some((v0, v1))) = surf.try_range_tuple() else { - return Err(KernelError::Failed("bridge: the surface is unbounded".into())); - }; + let (surf, [[u0, u1], [v0, v1]]) = the_face(made)?; let v = if at_end { v1 } else { v0 }; let mut worst: f64 = 0.0; for i in 0..=256 { - let u = u0 + (u1 - u0) * i as f64 / 256.0; - worst = worst.max(line.nearest_with_distance(from_p3(surf.subs(u, v))).1); + let q = + surf.point([u0 + (u1 - u0) * i as f64 / 256.0, v]).ok_or_else(|| KernelError::Failed("bridge: the surface has no point there".into()))?; + worst = worst.max(line.nearest_with_distance(q).1); } Ok(worst) } /// Which face of `body` the blend continues from along each edge of a chain (one per edge, in -/// chain order): of the faces each edge bounds, the one whose tangent plane holds as much of -/// `leave` as possible there. A chain may run along several faces (a tube's rim along the halves -/// of its wall). -fn support_faces(body: &Body, chain: &[mt::Edge], leave: Vec3) -> Result> { +/// chain order, by its index in the body's record): of the faces each edge bounds, the one whose +/// tangent plane holds as much of `leave` as possible there. A chain may run along several faces +/// (a tube's rim along the halves of its wall). +fn support_faces(r: &Brep, chain: &Chain, leave: Vec3, size: f64) -> Result> { let mut out = Vec::with_capacity(chain.len()); - for edge in chain { - let curve = edge.curve(); - let (t0, t1) = curve.range_tuple(); - let mid = from_p3(curve.subs(0.5 * (t0 + t1))); - let mut best: Option<(f64, mt::Face)> = None; - for face in body.solid.face_iter() { - if !face.edge_iter().any(|f| f.id() == edge.id()) { - continue; - } - let Some((q, n, _)) = crate::curveblend::project(face, mid, None) else { continue }; - if q.dist(mid) > body.size() * 1e-6 + 1e-9 { - continue; - } + for &(e, _) in chain { + let edge = r.edges.get(e).ok_or_else(|| KernelError::Invalid("an edge reference".into()))?; + let mid = CurveEval::new(&edge.curve) + .ok() + .and_then(|c| c.point(0.5 * (edge.interval[0] + edge.interval[1]))) + .ok_or_else(|| KernelError::Failed("bridge: an edge has no point".into()))?; + let mut best: Option<(f64, usize)> = None; + for u in &edge.uses { + let face = u.face as usize; + let Some(surf) = r.faces.get(face).and_then(|f| SurfaceEval::new(&f.surface).ok()) else { continue }; + let Some(uv) = surf.project(mid, None, size * 1e-6 + 1e-9) else { continue }; + let Some(n) = surf.derivs(uv[0], uv[1]).and_then(|(_, su, sv)| su.cross(sv).normalized()) else { continue }; let score = (leave - n * leave.dot(n)).len(); - if best.as_ref().is_none_or(|(b, _)| score > *b) { - best = Some((score, face.clone())); + if best.is_none_or(|(b, _)| score > b) { + best = Some((score, face)); } } let (score, face) = best.ok_or_else(|| KernelError::Invalid("no face of the body holds a picked edge".into()))?; @@ -898,7 +901,8 @@ pub fn blend_between( } let chain_a = chain(a, picks_a)?; let chain_b = chain(b, picks_b)?; - let (line_a, line_b) = (ChainLine::of(&chain_a)?, ChainLine::of(&chain_b)?); + let (line_a, line_b) = (ChainLine::of(a, &chain_a)?, ChainLine::of(b, &chain_b)?); + let (record_a, record_b) = (a.record(), b.record()); if line_a.closed != line_b.closed { return Err(KernelError::Invalid("a closed chain blends only to a closed chain, and an open one only to an open one".into())); } @@ -913,21 +917,17 @@ pub fn blend_between( (mid_a - mid_b).normalized().ok_or_else(|| KernelError::Invalid("the two boundaries coincide: there is nothing to blend".into()))?, ), }; - let faces_a = support_faces(a, &chain_a, leave_a)?; - let faces_b = support_faces(b, &chain_b, leave_b)?; + let faces_a = support_faces(&record_a, &chain_a, leave_a, a.size())?; + let faces_b = support_faces(&record_b, &chain_b, leave_b, b.size())?; let (start_a, backwards_a) = seam.map_or((0.0, false), |[p, _]| line_a.start_at_seam(p)); let stations_a = line_a.stations(samples, start_a, backwards_a)?; let stations_b = pair_with(&stations_a, &line_b, seam.map(|[_, q]| q))?; - let frames_a = frames_on(&faces_a, &stations_a, &line_a, leave_a)?; - let frames_b = frames_on(&faces_b, &stations_b, &line_b, leave_b)?; + let frames_a = frames_on(&record_a, &faces_a, &stations_a, &line_a, leave_a)?; + let frames_b = frames_on(&record_b, &faces_b, &stations_b, &line_b, leave_b)?; let made = bridge(&frames_a, &frames_b, orders, crown)?; let gap = boundary_gap(&made, &line_a, false)?.max(boundary_gap(&made, &line_b, true)?); - let faces: Vec = made.solid.face_iter().cloned().collect(); - let mut rec = crate::record::Rebuild::default(); - for f in &faces { - rec.made(f, Vec::new()); - } - let blend = crate::record::rebuilt_body(surface_body(faces), &[&a.solid, &b.solid], &rec); + // The blend's face is new to the operation over `[a, b]`. + let blend = crate::surfaces::all_new(made, &[a, b])?; if !stitch { return Ok((blend, gap)); } diff --git a/crates/kernel/src/bridge_tests.rs b/crates/kernel/src/bridge_tests.rs index 82966612b..54bb13115 100644 --- a/crates/kernel/src/bridge_tests.rs +++ b/crates/kernel/src/bridge_tests.rs @@ -9,11 +9,9 @@ use crate::{box_solid, cylinder}; /// of that curvature vector at the start of the cross-section. The samples run inwards from the /// boundary, so nothing is asked of the surface outside its own domain. fn section_at(body: &Body, u: f64) -> (Vec3, Vec3, Vec3, Vec3) { - let face = body.solid.face_iter().next().unwrap(); - let surf = face.surface(); - let (Some(_), Some((v0, _))) = surf.try_range_tuple() else { panic!("unbounded") }; + let (surf, [_, [v0, _]]) = the_face(body).unwrap(); let h = 1e-3; - let q: Vec = (0..5).map(|k| from_p3(surf.subs(u, v0 + k as f64 * h))).collect(); + let q: Vec = (0..5).map(|k| surf.point([u, v0 + k as f64 * h]).unwrap()).collect(); let (f0, f1, f2, f3, f4) = (q[0], q[1], q[2], q[3], q[4]); let d1 = (f0 * -25.0 + f1 * 48.0 + f2 * -36.0 + f3 * 16.0 + f4 * -3.0) * (1.0 / (12.0 * h)); let d2 = (f0 * 35.0 + f1 * -104.0 + f2 * 114.0 + f3 * -56.0 + f4 * 11.0) * (1.0 / (12.0 * h * h)); @@ -25,11 +23,9 @@ fn section_at(body: &Body, u: f64) -> (Vec3, Vec3, Vec3, Vec3) { /// The same at the end of the cross-section (`v = v1`), with the samples running back inwards and /// the odd derivatives turned round. fn section_end_at(body: &Body, u: f64) -> (Vec3, Vec3, Vec3, Vec3) { - let face = body.solid.face_iter().next().unwrap(); - let surf = face.surface(); - let (Some(_), Some((_, v1))) = surf.try_range_tuple() else { panic!("unbounded") }; + let (surf, [_, [_, v1]]) = the_face(body).unwrap(); let h = 1e-3; - let q: Vec = (0..5).map(|k| from_p3(surf.subs(u, v1 - k as f64 * h))).collect(); + let q: Vec = (0..5).map(|k| surf.point([u, v1 - k as f64 * h]).unwrap()).collect(); let (f0, f1, f2, f3, f4) = (q[0], q[1], q[2], q[3], q[4]); let d1 = (f0 * -25.0 + f1 * 48.0 + f2 * -36.0 + f3 * 16.0 + f4 * -3.0) * (-1.0 / (12.0 * h)); let d2 = (f0 * 35.0 + f1 * -104.0 + f2 * 114.0 + f3 * -56.0 + f4 * 11.0) * (1.0 / (12.0 * h * h)); @@ -81,28 +77,17 @@ fn valley_between_cylinders(count: usize, r: f64) -> (Vec, Vec) { (a, b) } -/// The edges of `face` chained into one loop. -fn loop_of(face: &mt::Face) -> Vec { - let mut pool: Vec = face.edge_iter().collect(); - let mut out = vec![pool.remove(0)]; - let mut end = out[0].back().clone(); - while !pool.is_empty() { - let k = pool.iter().position(|e| e.front().id() == end.id() || e.back().id() == end.id()).unwrap(); - let e = pool.remove(k); - let e = if e.front().id() == end.id() { e } else { e.inverse() }; - end = e.back().clone(); - out.push(e); - } - out +/// The edges of `body`'s face `face` chained into one loop (its outer loop, as it runs). +fn loop_of(body: &Body, face: usize) -> Chain { + let r = body.record(); + let solidcraft_geom::brep::Loop::Edges { edges } = &r.faces[face].loops[0] else { panic!("a vertex loop") }; + edges.iter().map(|u| (u.edge as usize, u.forward)).collect() } -/// The face of `body` that contains `at`. -fn face_at(body: &Body, at: Vec3) -> mt::Face { - body.solid - .face_iter() - .find(|f| f.surface().search_nearest_parameter(p3(at), None, 100).is_some_and(|(u, v)| from_p3(f.surface().subs(u, v)).dist(at) < 1e-6)) - .unwrap() - .clone() +/// The face of `body` (its index) whose surface contains `at`. +fn face_at(body: &Body, at: Vec3) -> usize { + let r = body.record(); + r.faces.iter().position(|f| SurfaceEval::new(&f.surface).unwrap().project(at, None, 1e-6).is_some()).unwrap() } #[test] @@ -110,9 +95,9 @@ fn frames_read_a_plane_and_a_cylinder_wall() { // A 40 x 30 x 20 box: the top face's rim leaves along +x, a plane with no curvature. let b = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 20.0)).unwrap(); let top = face_at(&b, Vec3::new(20.0, 15.0, 20.0)); - let rim = loop_of(&top); - assert!(chain_closes(&rim)); - let f = frames(&top, &rim, Vec3::new(1.0, 0.0, 0.0), 9).unwrap(); + let rim = loop_of(&b, top); + assert!(chain_closes(&b, &rim)); + let f = frames(&b, top, &rim, Vec3::new(1.0, 0.0, 0.0), 9).unwrap(); assert_eq!(f.len(), 9); for s in &f { assert!((s.p.z - 20.0).abs() < 1e-9, "{s:?}"); @@ -127,15 +112,15 @@ fn frames_read_a_plane_and_a_cylinder_wall() { // has no tangent plane to work in. let c = cylinder(Vec3::ZERO, Vec3::new(0.0, 0.0, 1.0), 10.0, 30.0).unwrap(); let wall = face_at(&c, Vec3::new(10.0, 0.0, 15.0)); - let ring = loop_of(&wall); - let f = frames(&wall, &ring, Vec3::new(0.0, 0.0, 1.0), 5).unwrap(); + let ring = loop_of(&c, wall); + let f = frames(&c, wall, &ring, Vec3::new(0.0, 0.0, 1.0), 5).unwrap(); for s in &f { assert!(s.bend.len() < 1e-6, "the axis direction is straight: {s:?}"); } // A leave direction that is normal to the support surface has no tangent plane to work in. - assert!(frames(&top, &rim, Vec3::new(0.0, 0.0, 1.0), 9).is_err(), "a face's own normal is no direction to leave in"); + assert!(frames(&b, top, &rim, Vec3::new(0.0, 0.0, 1.0), 9).is_err(), "a face's own normal is no direction to leave in"); // On the cylinder's wall only a direction with a tangential part is usable. - assert!(frames(&wall, &ring, Vec3::new(1.0, 0.0, 0.0), 5).is_ok()); + assert!(frames(&c, wall, &ring, Vec3::new(1.0, 0.0, 0.0), 5).is_ok()); } #[test] @@ -332,13 +317,12 @@ fn a_blend_between_offset_strips_is_the_cubic_hermite_strip() { } } // G1 at both seams: the blend's normal is the top faces' (±z) all along each rim. - let face = made.solid.face_iter().next().unwrap(); - let surf = face.surface(); - let (Some((u0, u1)), Some((v0, v1))) = surf.try_range_tuple() else { panic!("unbounded") }; + let (surf, [[u0, u1], [v0, v1]]) = the_face(&made).unwrap(); for i in 0..=16 { let u = u0 + (u1 - u0) * i as f64 / 16.0; for v in [v0, v1] { - let n = surf.normal(u, v); + let (_, su, sv) = surf.derivs(u, v).unwrap(); + let n = su.cross(sv); let worst = angle_deg(Vec3::new(n.x, n.y, n.z), Vec3::Z).min(angle_deg(Vec3::new(n.x, n.y, n.z), Vec3::Z * -1.0)); assert!(worst < 0.01, "at u = {u}, v = {v}: the normal is {worst}° off the top faces'"); } diff --git a/crates/kernel/src/surface_offset.rs b/crates/kernel/src/surface_offset.rs index a19d34fa9..a87ef7bdd 100644 --- a/crates/kernel/src/surface_offset.rs +++ b/crates/kernel/src/surface_offset.rs @@ -111,7 +111,7 @@ mod tests { let z = |x: f64| 50.0 - (1600.0 - x * x).sqrt(); let rim = [Vec3::new(14.0, 0.0, z(14.0)), Vec3::new(0.0, 14.0, z(0.0)), Vec3::new(-14.0, 0.0, z(-14.0)), Vec3::new(0.0, -14.0, z(0.0))]; let cover = crate::patch_edges(&cup, &rim).unwrap(); - let record = crate::native::brep_record(&cover).unwrap(); + let record = cover.record(); let s = solidcraft_geom::brep::eval::SurfaceEval::new(&record.faces[0].surface).unwrap(); let out = offset_surface(&cover, &[0], 1.5, 0.01).unwrap(); let mesh = out.mesh(&crate::MeshTolerance::chord(0.05)).unwrap(); diff --git a/crates/kernel/src/surfaces.rs b/crates/kernel/src/surfaces.rs index 0a059e744..11b337ff5 100644 --- a/crates/kernel/src/surfaces.rs +++ b/crates/kernel/src/surfaces.rs @@ -19,6 +19,7 @@ use std::collections::BTreeSet; use solidcraft_geom::brep::eval::CurveEval; use solidcraft_geom::brep::{self as b, Brep, Curve2}; +use solidcraft_geom::bspline::{HPoint, NurbsSurface}; use solidcraft_geom::{Plane, Region2, Seg2, Vec2, Vec3}; use crate::body::Body; @@ -28,7 +29,7 @@ use crate::{KernelError, Result, record}; impl Body { /// A surface body: some shell does not close (an edge bounds a face on one side only). pub fn is_surface(&self) -> bool { - !self.is_mesh() && crate::native::brep_record(self).is_ok_and(|r| r.edges.iter().any(|e| e.uses.len() == 1)) + !self.is_mesh() && self.record().edges.iter().any(|e| e.uses.len() == 1) } } @@ -338,9 +339,9 @@ fn uv_box(loops: &[b::Loop]) -> Option<[[f64; 2]; 2]> { } /// A body of a record this module built, and whether it numbers its faces and edges as the -/// record does (so a history in the record's order is the body's). +/// record does (so a history in the record's order is the body's): the record is the body's own. fn record_body(r: &Brep) -> Result<(Body, bool)> { - imp::record_body(r) + Ok((Body::from_record(r.clone())?, true)) } /// `body` with the history `h` over operands of `counts` faces and edges when its order is the @@ -354,6 +355,15 @@ pub(crate) fn surface_body(r: &Brep) -> Result { record_body(r).map(|(body, _)| body.without_history()) } +/// `body` (made by an operation on `operands`) with the history that every face and edge is new to +/// it. +pub(crate) fn all_new(body: Body, operands: &[&Body]) -> Result { + let r = body.record(); + let faces = vec![record::generated(Vec::new()); r.faces.len()]; + let h = record_history(&r, operands.len(), faces, |_, _, _| Vec::new()); + body.with_history_counts(h, &record::counts(operands)) +} + /// The faces `picked` of `body` (its record `r`; each with whether to turn it over) as their own /// body, each the body's face (Kept), every edge the body's. fn taken(body: &Body, r: &Brep, picked: &[(usize, bool)]) -> Result { @@ -364,6 +374,73 @@ fn taken(body: &Body, r: &Brep, picked: &[(usize, bool)]) -> Result { with_history(result, same, h, &record::counts(&[body])) } +// ---- NURBS faces -------------------------------------------------------------------------- + +/// A NURBS surface as a record surface (a plain B-spline where every weight is 1). +pub(crate) fn spline_surface(n: &NurbsSurface) -> b::Surface { + let [nu, nv] = n.count(); + let [ku, kv] = n.knots().clone(); + if n.homogeneous().iter().all(|h| h.w == 1.0) { + let points = (0..nu).map(|i| (0..nv).map(|j| a3(n.point(i, j).xyz())).collect()).collect(); + return b::Surface::Spline { u_knots: ku, v_knots: kv, points }; + } + let homogeneous = (0..nu).map(|i| (0..nv).map(|j| n.point(i, j)).map(|h| [h.x, h.y, h.z, h.w]).collect()).collect(); + b::Surface::RationalSpline { u_knots: ku, v_knots: kv, homogeneous } +} + +/// The NURBS curve of homogeneous control points `ctrl` on `knots` as a record curve, and its +/// parameter interval. +pub(crate) fn spline_curve(ctrl: &[HPoint], knots: Vec) -> Result<(b::Curve, [f64; 2])> { + let degree = knots.len().checked_sub(ctrl.len() + 1).filter(|d| *d >= 1).ok_or_else(|| invalid("a spline's knots"))?; + let interval = [*knots.get(degree).ok_or_else(|| invalid("knots"))?, *knots.get(ctrl.len()).ok_or_else(|| invalid("knots"))?]; + let curve = if ctrl.iter().all(|h| h.w == 1.0) { + b::Curve::Spline { knots, points: ctrl.iter().map(|h| a3(h.xyz())).collect() } + } else { + b::Curve::RationalSpline { knots, homogeneous: ctrl.iter().map(|h| [h.x, h.y, h.z, h.w]).collect() } + }; + Ok((curve, interval)) +} + +/// The pcurve of an edge along a straight line of its face's parameters: from `a` at the +/// interval's start to `z` at its end. +pub(crate) fn uv_line(a: [f64; 2], z: [f64; 2], [t0, t1]: [f64; 2]) -> Curve2 { + Curve2::Spline { knots: vec![t0, t0, t1, t1], points: vec![a, z] } +} + +/// One face: the whole of the NURBS surface `n`, bounded by its four boundary curves (each the +/// boundary row or column of its net on its knots, exact for a clamped surface), as a surface +/// body with no history. +pub(crate) fn tensor_sheet(n: &NurbsSurface) -> Result { + let [nu, nv] = n.count(); + if nu < 2 || nv < 2 { + return Err(invalid("a face needs at least 2 x 2 control points")); + } + let [ku, kv] = n.knots().clone(); + let [[u0, u1], [v0, v1]] = n.domain(); + let corner = |i: usize, j: usize| n.point(i, j).project().ok_or_else(|| failed("a corner of the surface has no position")); + let corners = [corner(0, 0)?, corner(nu - 1, 0)?, corner(nu - 1, nv - 1)?, corner(0, nv - 1)?]; + let mut parts = Parts { tolerance: tolerance_of(corners.into_iter()), ..Parts::default() }; + parts.vertices = corners.iter().map(|p| b::Vertex { point: a3(*p), tolerance: parts.tolerance }).collect(); + let row = |j: usize| (0..nu).map(|i| n.point(i, j)).collect::>(); + let column = |i: usize| (0..nv).map(|j| n.point(i, j)).collect::>(); + // Bottom (v0) and top (v1) run along u, left (u0) and right (u1) along v; the loop goes bottom, + // right, top backwards, left backwards: counter-clockwise in (u, v). + let sides = [ + (row(0), ku.clone(), [0, 1], [[u0, v0], [u1, v0]], true), + (column(nu - 1), kv.clone(), [1, 2], [[u1, v0], [u1, v1]], true), + (row(nv - 1), ku, [3, 2], [[u0, v1], [u1, v1]], false), + (column(0), kv, [0, 3], [[u0, v0], [u0, v1]], false), + ]; + let mut uses = Vec::with_capacity(4); + for (i, (ctrl, knots, [a, z], [pa, pz], forward)) in sides.into_iter().enumerate() { + let (curve, interval) = spline_curve(&ctrl, knots)?; + parts.edges.push(b::Edge { curve, interval, vertices: [index(a)?, index(z)?], tolerance: parts.tolerance, uses: Vec::new() }); + uses.push(b::OrientedEdge { edge: index(i)?, forward, pcurve: uv_line(pa, pz, interval) }); + } + parts.faces.push((b::Face { surface: spline_surface(n), domain: n.domain(), loops: vec![b::Loop::Edges { edges: uses }] }, true)); + surface_body(&parts.canonical()?.brep) +} + // ---- Patches ---------------------------------------------------------------------------- /// A planar surface filling a sketch region. Its history has no operands: the face is new. @@ -418,7 +495,7 @@ fn sketch_loop(parts: &mut Parts, plane: &Plane, segs: &[Seg2]) -> Result Option { - let r = crate::native::brep_record(body).ok()?; + let r = body.record(); let mut best: Option<(f64, usize)> = None; for (i, e) in r.edges.iter().enumerate() { let Ok(c) = CurveEval::new(&e.curve) else { continue }; @@ -448,7 +525,7 @@ pub fn patch_edges(body: &Body, at: &[Vec3]) -> Result { if at.is_empty() || at.len() > 10_000 { return Err(invalid("pick the edges of a closed loop")); } - let r = crate::native::brep_record(body)?; + let r = body.record(); let chain = picked_loop(body, at)?; let Some(plane) = chain_plane(&r, &chain, crate::fill::planarity_tolerance(body))? else { return crate::fill::fill_loop(body, &chain); @@ -548,7 +625,7 @@ pub(crate) fn picked_loop(body: &Body, at: &[Vec3]) -> Result { /// chain runs from the free end met first in pick order. Edges that branch, or form more than one /// chain, are refused. pub(crate) fn picked_chain(body: &Body, at: &[Vec3]) -> Result<(Chain, bool)> { - let r = crate::native::brep_record(body)?; + let r = body.record(); let mut edges: Vec = Vec::new(); for p in at { let e = edge_near(body, *p).ok_or_else(|| invalid(format!("no edge at {p:?}")))?; @@ -638,7 +715,7 @@ pub fn copy_faces(body: &Body, at: &[Vec3]) -> Result { return Err(invalid("pick the faces to copy")); } let chosen = picked_faces(body, at)?; - let r = crate::native::brep_record(body)?; + let r = body.record(); taken(body, &r, &chosen.into_iter().map(|f| (f, false)).collect::>()) } @@ -647,7 +724,7 @@ pub fn copy_faces(body: &Body, at: &[Vec3]) -> Result { /// surfaces. Histories are over `[body]`: each face is the body's. pub fn unstitch(body: &Body, at: &[Vec3]) -> Result<(Vec, Option)> { body.require_brep("unstitch")?; - let r = crate::native::brep_record(body)?; + let r = body.record(); if r.faces.len() < 2 { return Err(invalid("the body has one face: nothing to unstitch")); } @@ -667,7 +744,7 @@ pub fn reverse_faces(body: &Body, at: &[Vec3]) -> Result { return Err(invalid("a solid's faces face out: unstitch it into surfaces first")); } let chosen = picked_faces(body, at)?; - let r = crate::native::brep_record(body)?; + let r = body.record(); taken(body, &r, &(0..r.faces.len()).map(|f| (f, chosen.contains(&f))).collect::>()) } @@ -679,7 +756,7 @@ pub fn remove_faces(body: &Body, faces: &[usize]) -> Result { if faces.is_empty() { return Err(invalid("no faces given")); } - let r = crate::native::brep_record(body)?; + let r = body.record(); let left: Vec<(usize, bool)> = (0..r.faces.len()).filter(|f| !faces.contains(f)).map(|f| (f, false)).collect(); if left.is_empty() { return Err(invalid("that would delete every face of the body")); @@ -736,8 +813,8 @@ pub fn stitch(bodies: &[&Body], tol: f64) -> Result { } let size = bodies.iter().map(|b| b.size()).fold(0.0, f64::max); let tol = if tol.is_finite() && tol > 0.0 { tol } else { size * 1e-6 + 1e-6 }; - let records = bodies.iter().map(|b| crate::native::brep_record(b)).collect::>>()?; - let (parts, offsets) = Parts::joined(&records.iter().collect::>())?; + let records: Vec<&Brep> = bodies.iter().map(|b| b.record()).collect(); + let (parts, offsets) = Parts::joined(&records)?; let c = parts.canonical()?; let (body, h) = imp::stitched(&c.brep, tol)?; let h = h.and_then(|h| carried(&h, &c, &offsets, bodies.len(), |operand, face| FaceOrigin::Face { operand, face })); @@ -758,7 +835,7 @@ pub fn thicken(body: &Body, thickness: f64, symmetric: bool) -> Result { /// apart): see [`crate::offset_surface`]. A distance of zero copies the faces. Each face is the /// offset of the one it came from. pub(crate) fn offset_faces(body: &Body, picked: &[usize], distance: f64, tolerance: f64) -> Result { - let r = crate::native::brep_record(body)?; + let r = body.record(); if distance == 0.0 { return taken(body, &r, &picked.iter().map(|f| (*f, false)).collect::>()); } @@ -770,7 +847,7 @@ pub(crate) fn offset_faces(body: &Body, picked: &[usize], distance: f64, toleran let faces = h .and_then(|h| carried(&h, &c, &offsets, 1, offset)) .map(|h| h.faces.into_iter().map(|f| FaceProv { change: Change::Generated, ..f }).collect::>()); - let rec = crate::native::brep_record(&result)?; + let rec = result.record(); let h = faces.map(|faces| record_history(&rec, 1, faces, |_, between, faces| record::meeting(between, faces))); Ok(result.with_checked_history(h, &record::counts(&[body]))) } @@ -783,7 +860,7 @@ pub fn extend(body: &Body, at: &[Vec3], distance: f64) -> Result { if !(distance.is_finite() && distance > 0.0) { return Err(invalid("the extension distance must be positive")); } - let r = crate::native::brep_record(body)?; + let r = body.record(); let [face] = r.faces.as_slice() else { return Err(invalid("not supported yet: extending a surface of more than one face")) }; let (origin, du, dv) = match face.surface { b::Surface::Plane { origin, u_axis, v_axis } => (v3(origin), v3(u_axis), v3(v_axis)), @@ -935,7 +1012,7 @@ fn sheet_of(pieces: Vec<(Brep, Vec)>, stitch: bool) -> Result { let faces: Option> = c.faces.iter().map(|p| prov(*p)).collect(); if !stitch { let (body, same) = record_body(&c.brep)?; - return record::attach(body, &[], faces.filter(|_| same), Default::default()); + return Ok(record::attach(body, &[], faces.filter(|_| same), &[])); } let (body, h) = imp::stitched(&c.brep, c.brep.tolerance * 10.0)?; // A stitched face keeps the tag of the joined record's face it was. @@ -948,7 +1025,7 @@ fn sheet_of(pieces: Vec<(Brep, Vec)>, stitch: bool) -> Result { }) .collect::>>() }); - record::attach(body, &[], sewn, Default::default()) + Ok(record::attach(body, &[], sewn, &[])) } /// A surface extruded from chains of sketch segments on `plane`: each chain (open, or closed such @@ -1195,25 +1272,37 @@ mod imp { r.to_native().map_err(|e| failed(format!("SMLib {what}: {e}"))) } - pub(super) fn record_body(r: &Brep) -> Result<(Body, bool)> { - let (brep, order) = crate::native::smlib_record_ordered(r)?; - let (body, kept) = crate::native::body_from_smlib_ordered(&brep)?; - Ok((body, order.is_some() && kept.is_some())) + /// Whether two records of one body number its faces, edges and vertices alike: the same + /// loops of the same edges, run the same ways, and each edge between the same vertices. + fn same_numbering(a: &Brep, b: &Brep) -> bool { + let loops = |f: &b::Face| -> Vec> { + f.loops + .iter() + .map(|l| match l { + b::Loop::Edges { edges } => edges.iter().map(|u| (u.edge, u.forward)).collect(), + b::Loop::Vertex { vertex } => vec![(*vertex, true)], + }) + .collect() + }; + a.faces.len() == b.faces.len() + && a.edges.len() == b.edges.len() + && a.vertices.len() == b.vertices.len() + && a.faces.iter().zip(&b.faces).all(|(x, y)| loops(x) == loops(y)) + && a.edges.iter().zip(&b.edges).all(|(x, y)| x.vertices == y.vertices) } /// The record `r` sewn by SMLib at `tol` (`smlib_stitch`), with its history over `[r]` (faces - /// and edges by their index in `r`); none where the orders cannot be matched. + /// and edges by their index in `r`); none where SMLib's import of `r` does not number it as + /// `r` does. pub(super) fn stitched(r: &Brep, tol: f64) -> Result<(Body, Option)> { - let (brep, order) = crate::native::smlib_record_ordered(r)?; + let brep = SmBrep::from_record(r, true).map_err(sm("stitch"))?; + let (back, order) = brep.to_native_ordered().map_err(|e| failed(format!("SMLib stitch: {e}")))?; let tagged = brep.tagged(0).map_err(sm("stitch"))?; let (sewn, _closed) = tagged.stitch(tol).map_err(sm("stitch"))?; checked(&sewn, "stitch")?; - let (body, kept) = crate::native::body_from_smlib_ordered(&sewn)?; - let h = match (order, kept) { - (Some(o), Some(k)) => sewn.history().ok().and_then(|raw| raw.history(&[o], &k).ok()), - _ => None, - }; - Ok((body, h)) + let (record, kept) = sewn.to_native_ordered().map_err(|e| failed(format!("SMLib stitch: {e}")))?; + let h = if same_numbering(r, &back) { sewn.history().ok().and_then(|raw| raw.history(&[order], &kept).ok()) } else { None }; + Ok((Body::from_smlib_record(sewn, record)?, h)) } pub(super) fn thicken(body: &Body, thickness: f64, symmetric: bool) -> Result { @@ -1415,9 +1504,6 @@ mod imp { pub(super) fn refuse(what: &str) -> KernelError { crate::smlib_sweeps::refuse(what) } - pub(super) fn record_body(_: &Brep) -> Result<(Body, bool)> { - Err(not_built()) - } pub(super) fn stitched(_: &Brep, _: f64) -> Result<(Body, Option)> { Err(not_built()) } diff --git a/crates/kernel/src/tspline.rs b/crates/kernel/src/tspline.rs index 485ab575c..88c77c787 100644 --- a/crates/kernel/src/tspline.rs +++ b/crates/kernel/src/tspline.rs @@ -2,29 +2,29 @@ //! faces. A T-mesh without T-junctions becomes one clamped tensor face; otherwise each Bézier //! element is a face, and the faces share their edges and vertices — a side that meets two //! neighbours is split at the T-point between them — so the sheet is one sewn open shell. +//! +//! Every edge is an exact piece of its patch's side (a Bézier segment of the side's control +//! points) and its pcurve on each face it bounds a straight line in that patch's parameters. -use std::collections::hash_map::Entry; use std::collections::{BTreeMap, BTreeSet, HashMap}; +use solidcraft_geom::brep as b; use solidcraft_geom::bspline::{BezierPatch, HPoint, NurbsSurface, SplineError, bezier_segment}; use solidcraft_geom::tspline::TSpline; -use truck_modeling as mt; use crate::body::Body; -use crate::spline_conv::{h4, nurbs_curve, nurbs_surface}; -use crate::{KernelError, Result, guard}; +use crate::surfaces::{Parts, spline_curve, spline_surface, surface_body, uv_line}; +use crate::{KernelError, Result}; /// A T-spline as a surface body (an open shell of NURBS faces whose normals follow /// `∂S/∂s × ∂S/∂t`). pub fn tspline_sheet(ts: &TSpline) -> Result { - let faces = if ts.mesh().is_regular() { + if ts.mesh().is_regular() { let n = ts.to_nurbs().and_then(|n| n.clamped()).map_err(spline_err)?; - guard("t-spline sheet", || tensor_face(&n).map(|f| vec![f]))? - } else { - let patches = ts.bezier_elements().map_err(spline_err)?; - guard("t-spline sheet", || patch_faces(&patches))? - }; - Ok(crate::surfaces::surface_body(faces)) + return crate::surfaces::tensor_sheet(&n); + } + let patches = ts.bezier_elements().map_err(spline_err)?; + surface_body(&patch_faces(&patches)?.canonical()?.brep) } fn spline_err(e: SplineError) -> KernelError { @@ -35,14 +35,8 @@ fn fail(m: impl std::fmt::Display) -> KernelError { KernelError::Failed(format!("t-spline sheet: {m}")) } -fn vertex(h: HPoint) -> Result { - let p = h.project().ok_or_else(|| fail("a corner has no position"))?; - Ok(mt::builder::vertex(crate::body::p3(p))) -} - -/// One face from a clamped tensor surface, bounded by its four boundary curves. -fn tensor_face(n: &NurbsSurface) -> Result { - crate::spline_conv::tensor_face(n) +fn index(i: usize) -> Result { + u32::try_from(i).map_err(|_| KernelError::TooLarge("t-spline sheet: too many patches".into())) } /// A parameter point, exact (knot values are shared, so equal points have equal bits). @@ -52,9 +46,13 @@ fn key(s: f64, t: f64) -> Key { ((s + 0.0).to_bits(), (t + 0.0).to_bits()) } -/// One face per Bézier patch, sharing vertices and edges; sides are split where a -/// neighbour's corner lands on them. -fn patch_faces(patches: &[BezierPatch]) -> Result> { +fn st(k: Key) -> [f64; 2] { + [f64::from_bits(k.0), f64::from_bits(k.1)] +} + +/// One face per Bézier patch, sharing vertices and edges; sides are split where a neighbour's +/// corner lands on them. +fn patch_faces(patches: &[BezierPatch]) -> Result { // Corner parameters on each line of constant t (their s values) and of constant s. let mut on_t: BTreeMap> = BTreeMap::new(); let mut on_s: BTreeMap> = BTreeMap::new(); @@ -67,14 +65,21 @@ fn patch_faces(patches: &[BezierPatch]) -> Result> { } } } - let mut verts: HashMap = HashMap::new(); - let mut edges: HashMap<(Key, Key), mt::Edge> = HashMap::new(); - let mut faces = Vec::with_capacity(patches.len()); + let mut parts = Parts::default(); + let mut verts: HashMap = HashMap::new(); + // Each edge by its ends' parameters, in the direction it was made. + let mut edges: HashMap<(Key, Key), u32> = HashMap::new(); + let mut corners: Vec<[f64; 3]> = Vec::new(); for p in patches { - let mut wire: Vec = Vec::new(); + // The patch's own (u, v) on [0, 1]² of a global (s, t). + let local = |k: Key| { + let [s, t] = st(k); + [(s - p.s[0]) / (p.s[1] - p.s[0]), (t - p.t[0]) / (p.t[1] - p.t[0])] + }; + let mut uses: Vec = Vec::new(); for side in 0..4 { - // Side 0: t = t₀, 1: s = s₁, 2: t = t₁, 3: s = s₀; each runs with its parameter - // rising, sides 2 and 3 are walked backwards. + // Side 0: t = t0, 1: s = s1, 2: t = t1, 3: s = s0; each runs with its parameter rising, + // sides 2 and 3 are walked backwards. let (along_s, fixed, [lo, hi]) = match side { 0 => (true, p.t[0], p.s), 1 => (false, p.s[1], p.t), @@ -91,39 +96,62 @@ fn patch_faces(patches: &[BezierPatch]) -> Result> { for w in breaks.windows(2) { let &[x0, x1] = w else { continue }; let (ka, kb) = (at(x0), at(x1)); - let e = if let Some(e) = edges.get(&(ka, kb)) { - e.clone() - } else if let Some(e) = edges.get(&(kb, ka)) { - e.inverse() - } else { - let seg = bezier_segment(&ctrl, (x0 - lo) / (hi - lo), (x1 - lo) / (hi - lo)).map_err(spline_err)?; - let (Some(&first), Some(&last)) = (seg.first(), seg.last()) else { return Err(fail("an empty side")) }; - let mut corner = |k: Key, h: HPoint| -> Result { - Ok(match verts.entry(k) { - Entry::Occupied(e) => e.get().clone(), - Entry::Vacant(e) => e.insert(vertex(h)?).clone(), - }) - }; - let (va, vb) = (corner(ka, first)?, corner(kb, last)?); - let curve = nurbs_curve(mt::KnotVec::bezier_knot(seg.len() - 1), &seg)?; - let e = mt::Edge::try_new(&va, &vb, curve).map_err(fail)?; - edges.insert((ka, kb), e.clone()); - e + // The edge as made (a to b with its parameter rising), and whether this side runs + // along it. + let (edge, made) = match (edges.get(&(ka, kb)), edges.get(&(kb, ka))) { + (Some(e), _) => (*e, (ka, kb)), + (None, Some(e)) => (*e, (kb, ka)), + (None, None) => { + let seg = bezier_segment(&ctrl, (x0 - lo) / (hi - lo), (x1 - lo) / (hi - lo)).map_err(spline_err)?; + let (Some(&first), Some(&last)) = (seg.first(), seg.last()) else { return Err(fail("an empty side")) }; + let mut corner = |k: Key, h: HPoint| -> Result { + if let Some(v) = verts.get(&k) { + return Ok(*v); + } + let q = h.project().ok_or_else(|| fail("a corner has no position"))?; + let v = index(corners.len())?; + corners.push([q.x, q.y, q.z]); + verts.insert(k, v); + Ok(v) + }; + let vertices = [corner(ka, first)?, corner(kb, last)?]; + let degree = seg.len().saturating_sub(1); + let knots = std::iter::repeat_n(0.0, degree + 1).chain(std::iter::repeat_n(1.0, degree + 1)).collect(); + let (curve, interval) = spline_curve(&seg, knots)?; + let e = index(parts.edges.len())?; + parts.edges.push(b::Edge { curve, interval, vertices, tolerance: 0.0, uses: Vec::new() }); + edges.insert((ka, kb), e); + (e, (ka, kb)) + } }; - pieces.push(e); + let pcurve = uv_line(local(made.0), local(made.1), [0.0, 1.0]); + pieces.push(b::OrientedEdge { edge, forward: made == (ka, kb), pcurve }); } if side >= 2 { pieces.reverse(); - pieces.iter_mut().for_each(|e| *e = e.inverse()); + pieces.iter_mut().for_each(|u| u.forward = !u.forward); } - wire.extend(pieces); + uses.extend(pieces); } let [ps, pt] = p.degree; - let rows: Vec> = (0..=ps).map(|i| (0..=pt).map(|j| h4(p.point(i, j))).collect()).collect(); - let surf = nurbs_surface((mt::KnotVec::bezier_knot(ps), mt::KnotVec::bezier_knot(pt)), rows)?; - faces.push(mt::Face::try_new(vec![wire.into()], surf).map_err(fail)?); + let knots = |d: usize| std::iter::repeat_n(0.0, d + 1).chain(std::iter::repeat_n(1.0, d + 1)).collect::>(); + let ctrl: Vec = (0..=pt).flat_map(|j| (0..=ps).map(move |i| (i, j))).map(|(i, j)| p.point(i, j)).collect(); + let surface = NurbsSurface::from_homogeneous([ps, pt], [knots(ps), knots(pt)], ctrl).map_err(spline_err)?; + parts.faces.push(( + b::Face { surface: spline_surface(&surface), domain: [[0.0, 1.0], [0.0, 1.0]], loops: vec![b::Loop::Edges { edges: uses }] }, + true, + )); } - Ok(faces) + let mut bounds = solidcraft_geom::Aabb3::EMPTY; + for c in &corners { + bounds.add(solidcraft_geom::Vec3::new(c[0], c[1], c[2])); + } + parts.tolerance = (bounds.diagonal() * 1e-6).max(1e-5); + parts.vertices = corners.into_iter().map(|point| b::Vertex { point, tolerance: parts.tolerance }).collect(); + for e in &mut parts.edges { + e.tolerance = parts.tolerance; + } + Ok(parts) } #[cfg(test)] @@ -131,7 +159,6 @@ mod tests { use solidcraft_geom::Vec3; use solidcraft_geom::bspline::NurbsSurface; use solidcraft_geom::tspline::{Cut, TSpline}; - use truck_modeling as mt; use super::tspline_sheet; use crate::fuzz::Rng; @@ -187,8 +214,11 @@ mod tests { assert!(body.is_surface()); assert_eq!(body.shell_count(), 1); assert_eq!(body.face_count(), faces); - let shell = &body.solid.boundaries()[0]; - assert_eq!(shell.shell_condition(), mt::ShellCondition::Oriented, "neighbours share edges, run opposite ways"); + let record = body.record(); + assert!( + record.edges.iter().all(|e| e.uses.len() == 1 || (e.uses.len() == 2 && e.uses[0].upper != e.uses[1].upper)), + "neighbours share edges, run opposite ways" + ); let euler = body.vertex_count() as i64 - body.edge_count() as i64 + body.face_count() as i64; assert_eq!(euler, 1, "one sewn sheet (a disc)"); let mesh = body.mesh(&crate::MeshTolerance::chord(0.01)).unwrap();