refactor: geom::Grid for control nets; one surface fit through a grid of samples (#2331)
Thanks @jijinbei.
This commit is contained in:
@@ -532,6 +532,10 @@ impl NurbsSurface {
|
||||
pub fn homogeneous(&self) -> &[HPoint] {
|
||||
&self.ctrl
|
||||
}
|
||||
/// The control net.
|
||||
pub fn net(&self) -> crate::Grid<HPoint> {
|
||||
crate::Grid::checked(self.count, self.ctrl.clone())
|
||||
}
|
||||
/// Control point `(i, j)`.
|
||||
pub fn point(&self, i: usize, j: usize) -> HPoint {
|
||||
self.ctrl.get(j * self.count[0] + i).copied().unwrap_or(HPoint::ZERO)
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
//! A rectangular net of values: a surface's control points, a sample grid. Rectangular by
|
||||
//! construction, so code that walks it never meets a missing cell: a grid is made from a
|
||||
//! function of `(i, j)`, from one row, or from rows checked once ([`Grid::from_u_rows`]).
|
||||
|
||||
/// `count[0]` values along u by `count[1]` along v; value `(i, j)` (i along u) is stored at
|
||||
/// `j·count[0] + i`, u fastest.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Grid<T> {
|
||||
count: [usize; 2],
|
||||
cells: Vec<T>,
|
||||
}
|
||||
|
||||
impl<T> Grid<T> {
|
||||
/// A grid of `f(i, j)` for every cell; `None` when `count[0]·count[1]` overflows.
|
||||
pub fn from_fn(count: [usize; 2], mut f: impl FnMut(usize, usize) -> T) -> Option<Grid<T>> {
|
||||
let total = count[0].checked_mul(count[1])?;
|
||||
let cu = count[0].max(1);
|
||||
Some(Grid { count, cells: (0..total).map(|k| f(k % cu, k / cu)).collect() })
|
||||
}
|
||||
|
||||
/// One row of values along u: `count` is `[cells.len(), 1]` (a curve's control points seen
|
||||
/// as a net).
|
||||
pub fn row(cells: Vec<T>) -> Grid<T> {
|
||||
Grid { count: [cells.len(), 1], cells }
|
||||
}
|
||||
|
||||
/// A grid whose caller already holds `count[0]·count[1]` cells (a checked surface's net).
|
||||
pub(crate) fn checked(count: [usize; 2], cells: Vec<T>) -> Grid<T> {
|
||||
Grid { count, cells }
|
||||
}
|
||||
|
||||
/// Values along u and along v.
|
||||
pub fn count(&self) -> [usize; 2] {
|
||||
self.count
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.cells.is_empty()
|
||||
}
|
||||
|
||||
/// Value `(i, j)`, i along u.
|
||||
pub fn get(&self, i: usize, j: usize) -> Option<&T> {
|
||||
if i < self.count[0] { self.cells.get(j * self.count[0] + i) } else { None }
|
||||
}
|
||||
|
||||
/// The values, u fastest.
|
||||
pub fn cells(&self) -> &[T] {
|
||||
&self.cells
|
||||
}
|
||||
|
||||
/// The runs along u, one per v index: run `j` holds values `(0, j)`, `(1, j)`, ….
|
||||
pub fn lines(&self) -> std::slice::Chunks<'_, T> {
|
||||
self.cells.chunks(self.count[0].max(1))
|
||||
}
|
||||
|
||||
/// The grid with u and v swapped: value `(i, j)` becomes value `(j, i)`.
|
||||
pub fn transposed(&self) -> Grid<T>
|
||||
where
|
||||
T: Clone,
|
||||
{
|
||||
let [cu, cv] = self.count;
|
||||
let cells = (0..self.cells.len()).filter_map(|k| self.get(k / cv.max(1), k % cv.max(1)).cloned()).collect();
|
||||
Grid { count: [cv, cu], cells }
|
||||
}
|
||||
|
||||
/// The values to change in place; the grid keeps its shape.
|
||||
pub fn cells_mut(&mut self) -> &mut [T] {
|
||||
&mut self.cells
|
||||
}
|
||||
|
||||
pub fn into_cells(self) -> Vec<T> {
|
||||
self.cells
|
||||
}
|
||||
|
||||
pub fn map<U>(self, f: impl FnMut(T) -> U) -> Grid<U> {
|
||||
Grid { count: self.count, cells: self.cells.into_iter().map(f).collect() }
|
||||
}
|
||||
|
||||
/// [`Grid::map`] with a step that can fail: the first failure.
|
||||
pub fn try_map<U, E>(self, f: impl FnMut(T) -> Result<U, E>) -> Result<Grid<U>, E> {
|
||||
Ok(Grid { count: self.count, cells: self.cells.into_iter().map(f).collect::<Result<_, _>>()? })
|
||||
}
|
||||
|
||||
/// The grid as rows, one per u index: `rows[i][j]` is value `(i, j)` (truck's layout).
|
||||
pub fn into_u_rows(self) -> Vec<Vec<T>> {
|
||||
let cu = self.count[0];
|
||||
let mut rows: Vec<Vec<T>> = (0..cu).map(|_| Vec::with_capacity(self.count[1])).collect();
|
||||
for (k, v) in self.cells.into_iter().enumerate() {
|
||||
if let Some(row) = rows.get_mut(k % cu) {
|
||||
row.push(v);
|
||||
}
|
||||
}
|
||||
rows
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Clone> Grid<T> {
|
||||
/// A grid from rows, one per u index: `rows[i][j]` is value `(i, j)` (truck's layout).
|
||||
/// `None` when the rows differ in length, the one check rows from elsewhere need.
|
||||
pub fn from_u_rows<R: AsRef<[T]>>(rows: &[R]) -> Option<Grid<T>> {
|
||||
let cv = rows.first().map_or(0, |r| r.as_ref().len());
|
||||
if rows.iter().any(|r| r.as_ref().len() != cv) {
|
||||
return None;
|
||||
}
|
||||
let cells = (0..cv).flat_map(|j| rows.iter().filter_map(move |r| r.as_ref().get(j).cloned())).collect();
|
||||
Some(Grid { count: [rows.len(), cv], cells })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rows_go_in_and_come_back_out() {
|
||||
// rows[i][j]: two along u, three along v.
|
||||
let rows = vec![vec![(0, 0), (0, 1), (0, 2)], vec![(1, 0), (1, 1), (1, 2)]];
|
||||
let g = Grid::from_u_rows(&rows).unwrap();
|
||||
assert_eq!(g.count(), [2, 3]);
|
||||
assert_eq!(g.cells(), &[(0, 0), (1, 0), (0, 1), (1, 1), (0, 2), (1, 2)]);
|
||||
assert_eq!(g.get(1, 2), Some(&(1, 2)));
|
||||
assert_eq!(g.get(2, 0), None);
|
||||
assert_eq!(g.into_u_rows(), rows);
|
||||
assert_eq!(Grid::row(vec![1, 2, 3]).count(), [3, 1]);
|
||||
let g = Grid::from_fn([3, 2], |i, j| (i, j)).unwrap();
|
||||
assert_eq!(g.lines().collect::<Vec<_>>(), vec![&[(0, 0), (1, 0), (2, 0)][..], &[(0, 1), (1, 1), (2, 1)][..]]);
|
||||
let t = g.transposed();
|
||||
assert_eq!(t.count(), [2, 3]);
|
||||
assert!((0..3).all(|i| (0..2).all(|j| t.get(j, i) == g.get(i, j))));
|
||||
assert!(Grid::from_fn([usize::MAX, 2], |_, _| 0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_rectangles_are_grids() {
|
||||
assert!(Grid::from_u_rows(&[vec![1, 2], vec![3]]).is_none());
|
||||
let empty: [Vec<u8>; 0] = [];
|
||||
assert!(Grid::from_u_rows(&empty).is_some_and(|g| g.is_empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn try_map_stops_at_the_first_failure() {
|
||||
assert_eq!(Grid::row(vec![1, -1, -2]).try_map(|x| if x > 0 { Ok(x) } else { Err(x) }), Err(-1));
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ pub mod compare;
|
||||
pub mod env;
|
||||
pub mod fill;
|
||||
pub mod fill_general;
|
||||
mod grid;
|
||||
mod mesh;
|
||||
pub mod mesh_distance;
|
||||
pub mod network;
|
||||
@@ -33,6 +34,7 @@ mod vec;
|
||||
pub use arcfit::MAX_FIT_PIECES;
|
||||
pub use blend::hermite_bezier;
|
||||
pub use bvh::{Bvh, MeshIndex};
|
||||
pub use grid::Grid;
|
||||
pub use mesh::{Aabb3, BoxedTriangle, InsideIndex, MassProperties, Mesh, MeshMeasure, find_close_pair};
|
||||
pub use plane::Plane;
|
||||
pub use profile::{Loop2, MAX_BEZIER_CTRL, MAX_BEZIER_DEGREE, MAX_DERIVATIVE_ORDER, Region2, Seg2, bezier, regions_apart};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Building bodies: extrude and revolve planar regions, primitives.
|
||||
|
||||
use mt::builder;
|
||||
use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3};
|
||||
use solidcraft_geom::{Grid, Loop2, Plane, Region2, Seg2, Vec2, Vec3};
|
||||
use truck_modeling as mt;
|
||||
|
||||
use crate::body::{Body, Solid, from_p3, p3, v3};
|
||||
@@ -2155,6 +2155,36 @@ pub(crate) fn interpolate_cubic(pts: &[Vec3]) -> Option<mt::BSplineCurve<mt::Poi
|
||||
interpolate_cubic_at(pts, &u)
|
||||
}
|
||||
|
||||
/// A cubic B-spline surface through a grid of samples at uniform parameters: cubics across v
|
||||
/// through each u index's samples, then cubics across u through their control points.
|
||||
pub(crate) struct NetFit {
|
||||
pub surface: mt::BSplineSurface<mt::Point3>,
|
||||
/// The surface's edges at the first and the last u (curves across v).
|
||||
pub u_ends: [mt::BSplineCurve<mt::Point3>; 2],
|
||||
/// The surface's edges at the first and the last v (curves across u).
|
||||
pub v_ends: [mt::BSplineCurve<mt::Point3>; 2],
|
||||
}
|
||||
|
||||
/// [`NetFit`] through `samples`; `None` with fewer than four samples across either direction.
|
||||
pub(crate) fn interpolate_net(samples: &Grid<Vec3>) -> Option<NetFit> {
|
||||
let across_v: Vec<mt::BSplineCurve<mt::Point3>> = samples.transposed().lines().map(interpolate_cubic).collect::<Option<_>>()?;
|
||||
let across_u: Vec<mt::BSplineCurve<mt::Point3>> =
|
||||
control_net(&across_v)?.lines().map(|run| interpolate_cubic(&run.iter().map(|&p| from_p3(p)).collect::<Vec<_>>())).collect::<Option<_>>()?;
|
||||
let net = control_net(&across_u)?.transposed().into_u_rows();
|
||||
let knots = (across_u.first()?.knot_vec().clone(), across_v.first()?.knot_vec().clone());
|
||||
let surface = mt::BSplineSurface::try_new(knots, net).ok()?;
|
||||
let u_ends = [across_v.first()?.clone(), across_v.last()?.clone()];
|
||||
let v_ends = [across_u.first()?.clone(), across_u.last()?.clone()];
|
||||
Some(NetFit { surface, u_ends, v_ends })
|
||||
}
|
||||
|
||||
/// The control points of `curves` as a grid: value `(i, j)` is control point `j` of curve `i`.
|
||||
/// `None` unless every curve has as many control points.
|
||||
fn control_net(curves: &[mt::BSplineCurve<mt::Point3>]) -> Option<Grid<mt::Point3>> {
|
||||
let rows: Vec<&[mt::Point3]> = curves.iter().map(|c| c.control_points().as_slice()).collect();
|
||||
Grid::from_u_rows(&rows)
|
||||
}
|
||||
|
||||
/// [`interpolate_cubic`] by chord length: the parameters (0 to 1) in proportion to the distance
|
||||
/// along the points. Points closer together toward an end (where a curve leaves another
|
||||
/// tangentially) then don't slow the curve to a stop there, where a uniform parameter lets it
|
||||
|
||||
+112
-142
@@ -43,8 +43,8 @@
|
||||
//! control point that does not change the geometry at all — is reported as an error and the
|
||||
//! geometry is left alone.
|
||||
|
||||
use solidcraft_geom::Vec3;
|
||||
use solidcraft_geom::bspline::{HPoint, MAX_SPLINE_DEGREE, NurbsSurface, Side, SplineError, check_knots, local_basis};
|
||||
use solidcraft_geom::{Grid, Vec3};
|
||||
use truck_modeling as mt;
|
||||
|
||||
use crate::body::Body;
|
||||
@@ -167,16 +167,15 @@ pub struct FairCurve<const N: usize> {
|
||||
pub report: FairReport,
|
||||
}
|
||||
|
||||
/// A faired B-spline control net: the input's degrees, knots and counts, the moved control points
|
||||
/// (u fastest) and the run's report.
|
||||
/// A faired B-spline control net: the input's degrees and knots, the moved control points and the
|
||||
/// run's report.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct FairNet<const N: usize> {
|
||||
pub degree: [usize; 2],
|
||||
pub knots: [Vec<f64>; 2],
|
||||
pub count: [usize; 2],
|
||||
/// The faired control points, u fastest; the held boundary layers are bit-identical to the
|
||||
/// input.
|
||||
pub ctrl: Vec<[f64; N]>,
|
||||
/// The faired control points, as many as the input's; the held boundary layers are
|
||||
/// bit-identical to the input.
|
||||
pub ctrl: Grid<[f64; N]>,
|
||||
pub report: FairReport,
|
||||
}
|
||||
|
||||
@@ -274,23 +273,23 @@ impl Gram {
|
||||
/// A control net to fair: a tensor-product B-spline with the terms of its fairness energy. A
|
||||
/// direction of one control point (degree 0, knots `[0, 1]`) makes the net a curve, whose energy
|
||||
/// is the one-direction [`CURVE_ENERGY`].
|
||||
struct Net {
|
||||
struct Net<'a, const N: usize> {
|
||||
degree: [usize; 2],
|
||||
count: [usize; 2],
|
||||
/// The number of control points, `count[0] · count[1]`.
|
||||
total: usize,
|
||||
/// The control points as the design has them; the run moves copies.
|
||||
ctrl: &'a Grid<[f64; N]>,
|
||||
gram: [Gram; 2],
|
||||
terms: &'static [(usize, usize, f64)],
|
||||
}
|
||||
|
||||
impl Net {
|
||||
impl<'a, const N: usize> Net<'a, N> {
|
||||
/// Check the degrees, knots and counts and build the Gram matrices: an error, never a panic,
|
||||
/// for a degree above [`MAX_SPLINE_DEGREE`], too few control points for the degree, a knot
|
||||
/// vector of the wrong length, unusable knots or an empty parameter range.
|
||||
fn new(degree: [usize; 2], knots: [Vec<f64>; 2], count: [usize; 2], terms: &'static [(usize, usize, f64)]) -> Result<Net> {
|
||||
let Some(total) = count[0].checked_mul(count[1]).filter(|&n| n <= MAX_FAIR_POINTS) else {
|
||||
fn new(degree: [usize; 2], knots: [Vec<f64>; 2], ctrl: &'a Grid<[f64; N]>, terms: &'static [(usize, usize, f64)]) -> Result<Net<'a, N>> {
|
||||
let count = ctrl.count();
|
||||
if ctrl.cells().len() > MAX_FAIR_POINTS {
|
||||
return Err(KernelError::TooLarge(format!("fairing {} × {} control points (at most {MAX_FAIR_POINTS} in all)", count[0], count[1])));
|
||||
};
|
||||
}
|
||||
for d in 0..2 {
|
||||
let (p, c, kn) = (degree[d], count[d], &knots[d]);
|
||||
if p > MAX_SPLINE_DEGREE {
|
||||
@@ -316,18 +315,28 @@ impl Net {
|
||||
return Err(KernelError::Invalid("a fairness term does not fit the net's degrees".into()));
|
||||
}
|
||||
let gram = [Gram::new(degree[0], &knots[0], count[0])?, Gram::new(degree[1], &knots[1], count[1])?];
|
||||
Ok(Net { degree, count, total, gram, terms })
|
||||
Ok(Net { degree, ctrl, gram, terms })
|
||||
}
|
||||
|
||||
/// Control points along u and along v.
|
||||
fn count(&self) -> [usize; 2] {
|
||||
self.ctrl.count()
|
||||
}
|
||||
|
||||
/// The number of control points, `count[0] · count[1]`.
|
||||
fn total(&self) -> usize {
|
||||
self.ctrl.cells().len()
|
||||
}
|
||||
|
||||
/// The index of control point `(i, j)` in the flattened net (u fastest).
|
||||
fn index(&self, i: usize, j: usize) -> usize {
|
||||
j * self.count[0] + i
|
||||
j * self.count()[0] + i
|
||||
}
|
||||
|
||||
/// The fairness energy `Pᵀ·G·P` of the net `ctrl` (u fastest) and, in `grad`, `G·P`. One
|
||||
/// banded sweep gives both, since `E = Σ Pₚ·(G·P)ₚ`.
|
||||
fn energy_gradient<const N: usize>(&self, ctrl: &[[f64; N]], grad: &mut [[f64; N]]) -> f64 {
|
||||
let [cu, cv] = self.count;
|
||||
fn energy_gradient(&self, ctrl: &[[f64; N]], grad: &mut [[f64; N]]) -> f64 {
|
||||
let [cu, cv] = self.count();
|
||||
let (pu, pv) = (self.degree[0], self.degree[1]);
|
||||
let mut energy = 0.0;
|
||||
for j in 0..cv {
|
||||
@@ -365,7 +374,7 @@ impl Net {
|
||||
/// step). In the u-fastest order two unknowns couple within `degree_u + degree_v · cols`:
|
||||
/// `degree_u` along a row, `degree_v` rows apart.
|
||||
fn system(&self, interior: &Interior) -> Result<Band> {
|
||||
let [cu, cv] = self.count;
|
||||
let [cu, cv] = self.count();
|
||||
let (pu, pv) = (self.degree[0], self.degree[1]);
|
||||
let rows = if cv > 1 { interior.rows.saturating_sub(1).min(pv) } else { 0 };
|
||||
let mut band = Band::new(interior.points.len(), pu + rows * interior.cols)?;
|
||||
@@ -383,20 +392,18 @@ impl Net {
|
||||
band.factorised()
|
||||
}
|
||||
|
||||
/// Fair `ctrl` (u fastest) with checked `opts`: see the module docs. The result is the input
|
||||
/// with the interior control points moved; the held ones are bit-identical.
|
||||
fn fair<const N: usize>(&self, ctrl: &[[f64; N]], opts: &FairOptions) -> Result<(Vec<[f64; N]>, FairReport)> {
|
||||
if ctrl.len() != self.total {
|
||||
return Err(KernelError::Invalid(format!("{} control points, expected {}", ctrl.len(), self.total)));
|
||||
}
|
||||
/// Fair the net with checked `opts`: see the module docs. The result is the input with the
|
||||
/// interior control points moved; the held ones are bit-identical.
|
||||
fn fair(&self, opts: &FairOptions) -> Result<(Grid<[f64; N]>, FairReport)> {
|
||||
let ctrl = self.ctrl.cells();
|
||||
if ctrl.iter().flatten().any(|x| !x.is_finite()) {
|
||||
return Err(KernelError::Invalid("a control point is not a finite number".into()));
|
||||
}
|
||||
let interior = Interior::new(self, if opts.keep_edges { 2 } else { 1 })?;
|
||||
let system = self.system(&interior)?;
|
||||
let mut current: Vec<[f64; N]> = ctrl.to_vec();
|
||||
let mut grad = vec![[0.0; N]; self.total];
|
||||
let energy_before = self.energy_gradient(¤t, &mut grad);
|
||||
let mut current = self.ctrl.clone();
|
||||
let mut grad = vec![[0.0; N]; self.total()];
|
||||
let energy_before = self.energy_gradient(ctrl, &mut grad);
|
||||
if !energy_before.is_finite() {
|
||||
return Err(KernelError::Invalid("the fairness energy of this net is not a finite number".into()));
|
||||
}
|
||||
@@ -409,7 +416,7 @@ impl Net {
|
||||
let mut b = vec![0.0; interior.points.len()];
|
||||
let mut report = FairReport { energy_before, energy_after: energy_before, steps: 0, movement: 0.0, energy_trace: Vec::new() };
|
||||
for _ in 0..opts.iterations {
|
||||
let e_now = self.energy_gradient(¤t, &mut grad);
|
||||
let e_now = self.energy_gradient(current.cells(), &mut grad);
|
||||
if !e_now.is_finite() {
|
||||
break;
|
||||
}
|
||||
@@ -431,7 +438,7 @@ impl Net {
|
||||
}
|
||||
// The largest fraction of the step that keeps every control point within the
|
||||
// tolerance of where the design put it, and never more than the whole step.
|
||||
let mut s = opts.strength.min(interior.limit(ctrl, ¤t, &step, opts.tolerance));
|
||||
let mut s = opts.strength.min(interior.limit(ctrl, current.cells(), &step, opts.tolerance));
|
||||
if !(s > 0.0) {
|
||||
break;
|
||||
}
|
||||
@@ -444,7 +451,7 @@ impl Net {
|
||||
let mut taken = false;
|
||||
for _ in 0..MAX_HALVINGS {
|
||||
let candidate = interior.apply(¤t, &step, s);
|
||||
let e = self.energy_gradient(&candidate, &mut grad);
|
||||
let e = self.energy_gradient(candidate.cells(), &mut grad);
|
||||
if e < e_now {
|
||||
current = candidate;
|
||||
report.steps += 1;
|
||||
@@ -464,7 +471,7 @@ impl Net {
|
||||
}
|
||||
}
|
||||
report.energy_after = report.energy_trace.last().copied().unwrap_or(energy_before);
|
||||
report.movement = interior.movement(ctrl, ¤t);
|
||||
report.movement = interior.movement(ctrl, current.cells());
|
||||
Ok((current, report))
|
||||
}
|
||||
}
|
||||
@@ -483,13 +490,13 @@ struct Interior {
|
||||
impl Interior {
|
||||
/// The interior of `net` with `keep` layers held at each end of each direction (1 without
|
||||
/// [`FairOptions::keep_edges`], 2 with it).
|
||||
fn new(net: &Net, keep: usize) -> Result<Interior> {
|
||||
let [cu, cv] = net.count;
|
||||
fn new<const N: usize>(net: &Net<N>, keep: usize) -> Result<Interior> {
|
||||
let [cu, cv] = net.count();
|
||||
let (i0, i1) = free_span(cu, keep)?;
|
||||
let (j0, j1) = free_span(cv, keep)?;
|
||||
let (cols, rows) = (i1 - i0, j1 - j0);
|
||||
let mut points = Vec::with_capacity(cols * rows);
|
||||
let mut slot = vec![None; net.total];
|
||||
let mut slot = vec![None; net.total()];
|
||||
for j in j0..j1 {
|
||||
for i in i0..i1 {
|
||||
if let Some(s) = slot.get_mut(net.index(i, j)) {
|
||||
@@ -509,10 +516,10 @@ impl Interior {
|
||||
|
||||
/// `current` with `s` times the step `d` added to the interior control points; the held ones
|
||||
/// are copied as they are, bit for bit.
|
||||
fn apply<const N: usize>(&self, current: &[[f64; N]], d: &[[f64; N]], s: f64) -> Vec<[f64; N]> {
|
||||
let mut out = current.to_vec();
|
||||
fn apply<const N: usize>(&self, current: &Grid<[f64; N]>, d: &[[f64; N]], s: f64) -> Grid<[f64; N]> {
|
||||
let mut out = current.clone();
|
||||
for (slot, &at) in self.points.iter().enumerate() {
|
||||
let (Some(p), Some(v)) = (out.get_mut(at), d.get(slot)) else { continue };
|
||||
let (Some(p), Some(v)) = (out.cells_mut().get_mut(at), d.get(slot)) else { continue };
|
||||
for (x, dx) in p.iter_mut().zip(v) {
|
||||
*x += s * dx;
|
||||
}
|
||||
@@ -697,28 +704,20 @@ impl Band {
|
||||
/// wire in space, 2 for a sketch curve.
|
||||
pub fn fair_curve<const N: usize>(degree: usize, knots: &[f64], ctrl: &[[f64; N]], opts: &FairOptions) -> Result<FairCurve<N>> {
|
||||
let opts = opts.checked()?;
|
||||
let net = Net::new([degree, 0], [knots.to_vec(), TRIVIAL_KNOTS.to_vec()], [ctrl.len(), 1], &CURVE_ENERGY)?;
|
||||
let (faired, report) = net.fair(ctrl, &opts)?;
|
||||
Ok(FairCurve { degree, knots: knots.to_vec(), ctrl: faired, report })
|
||||
let row = Grid::row(ctrl.to_vec());
|
||||
let (faired, report) = Net::new([degree, 0], [knots.to_vec(), TRIVIAL_KNOTS.to_vec()], &row, &CURVE_ENERGY)?.fair(&opts)?;
|
||||
Ok(FairCurve { degree, knots: knots.to_vec(), ctrl: faired.into_cells(), report })
|
||||
}
|
||||
|
||||
/// Fair the interior of a B-spline control net with the thin-plate energy
|
||||
/// `∫∫ ‖S_uu‖² + 2‖S_uv‖² + ‖S_vv‖² du dv` in the net's own parameters (see the module docs).
|
||||
/// `count[0]` control points lie along u and `count[1]` along v, `ctrl` is u fastest, and the
|
||||
/// boundary layers (see [`FairOptions::keep_edges`]) are held. The generic core behind
|
||||
/// The boundary layers (see [`FairOptions::keep_edges`]) are held. The generic core behind
|
||||
/// [`fair_surface`], [`fair_bspline_surface`] and their rational counterparts, for a caller with
|
||||
/// its own control net.
|
||||
pub fn fair_net<const N: usize>(
|
||||
degree: [usize; 2],
|
||||
knots: [&[f64]; 2],
|
||||
count: [usize; 2],
|
||||
ctrl: &[[f64; N]],
|
||||
opts: &FairOptions,
|
||||
) -> Result<FairNet<N>> {
|
||||
pub fn fair_net<const N: usize>(degree: [usize; 2], knots: [&[f64]; 2], ctrl: &Grid<[f64; N]>, opts: &FairOptions) -> Result<FairNet<N>> {
|
||||
let opts = opts.checked()?;
|
||||
let net = Net::new(degree, [knots[0].to_vec(), knots[1].to_vec()], count, &SURFACE_ENERGY)?;
|
||||
let (faired, report) = net.fair(ctrl, &opts)?;
|
||||
Ok(FairNet { degree, knots: [knots[0].to_vec(), knots[1].to_vec()], count, ctrl: faired, report })
|
||||
let (faired, report) = Net::new(degree, [knots[0].to_vec(), knots[1].to_vec()], ctrl, &SURFACE_ENERGY)?.fair(&opts)?;
|
||||
Ok(FairNet { degree, knots: [knots[0].to_vec(), knots[1].to_vec()], ctrl: faired, report })
|
||||
}
|
||||
|
||||
/// Fair a truck B-spline curve's control points: [`fair_curve`] on its three-dimensional points,
|
||||
@@ -762,64 +761,55 @@ pub fn fair_nurbs_curve(curve: &mt::NurbsCurve<mt::Vector4>, opts: &FairOptions)
|
||||
/// of the same knots, with the boundary rows held. Guarded like [`fair_bspline_curve`].
|
||||
pub fn fair_bspline_surface(surface: &mt::BSplineSurface<mt::Point3>, opts: &FairOptions) -> Result<(mt::BSplineSurface<mt::Point3>, FairReport)> {
|
||||
guard("fair a B-spline surface", || {
|
||||
let rows = surface.control_points();
|
||||
let count = [rows.len(), rows.first().map_or(0, Vec::len)];
|
||||
if count[0] == 0 || count[1] == 0 {
|
||||
return Err(KernelError::Invalid("the surface has no control points".into()));
|
||||
}
|
||||
if rows.iter().any(|r| r.len() != count[1]) {
|
||||
return Err(KernelError::Invalid("the surface's control net is not rectangular".into()));
|
||||
}
|
||||
// truck keeps the net as control_points()[i][j] with i along u; fair_net wants u fastest.
|
||||
let mut ctrl = Vec::with_capacity(count[0] * count[1]);
|
||||
for j in 0..count[1] {
|
||||
for i in 0..count[0] {
|
||||
let Some(p) = rows.get(i).and_then(|r| r.get(j)) else { continue };
|
||||
ctrl.push([p.x, p.y, p.z]);
|
||||
}
|
||||
}
|
||||
let net = truck_net(surface.control_points())?;
|
||||
let (ku, kv) = surface.knot_vecs();
|
||||
let (pu, pv) = surface.degrees();
|
||||
let faired = fair_net([pu, pv], [ku, kv], count, &ctrl, opts)?;
|
||||
let mut net: Vec<Vec<mt::Point3>> = Vec::with_capacity(count[0]);
|
||||
for i in 0..count[0] {
|
||||
let mut row = Vec::with_capacity(count[1]);
|
||||
for j in 0..count[1] {
|
||||
let Some(c) = faired.ctrl.get(j * count[0] + i) else {
|
||||
return Err(KernelError::Failed("fairing lost a control point".into()));
|
||||
};
|
||||
row.push(mt::Point3::new(c[0], c[1], c[2]));
|
||||
}
|
||||
net.push(row);
|
||||
}
|
||||
let faired = fair_net([pu, pv], [ku, kv], &net.map(|p| [p.x, p.y, p.z]), opts)?;
|
||||
let net = faired.ctrl.map(|[x, y, z]| mt::Point3::new(x, y, z)).into_u_rows();
|
||||
let surface = mt::BSplineSurface::try_new((ku.clone(), kv.clone()), net).map_err(|e| KernelError::Failed(format!("fair: {e}")))?;
|
||||
Ok((surface, faired.report))
|
||||
})
|
||||
}
|
||||
|
||||
/// A truck surface's control net (`rows[i][j]`, i along u) as a grid: refused when it is empty
|
||||
/// or not rectangular.
|
||||
fn truck_net<P: Clone>(rows: &[Vec<P>]) -> Result<Grid<P>> {
|
||||
let net = Grid::from_u_rows(rows).ok_or_else(|| KernelError::Invalid("the surface's control net is not rectangular".into()))?;
|
||||
if net.is_empty() {
|
||||
return Err(KernelError::Invalid("the surface has no control points".into()));
|
||||
}
|
||||
Ok(net)
|
||||
}
|
||||
|
||||
/// A homogeneous control net's Cartesian points; refused when a weight is zero (the point has no
|
||||
/// position).
|
||||
fn positions(net: &Grid<HPoint>) -> Result<Grid<[f64; 3]>> {
|
||||
net.clone().try_map(|h| {
|
||||
let p = h.project().ok_or_else(|| KernelError::Invalid("a control point has no position: its weight is zero".into()))?;
|
||||
Ok([p.x, p.y, p.z])
|
||||
})
|
||||
}
|
||||
|
||||
/// `net` moved to the faired `points`, each keeping its weight.
|
||||
fn reweighted(mut net: Grid<HPoint>, points: &Grid<[f64; 3]>) -> Grid<HPoint> {
|
||||
for (h, &[x, y, z]) in net.cells_mut().iter_mut().zip(points.cells()) {
|
||||
*h = HPoint::weighted(Vec3::new(x, y, z), h.w);
|
||||
}
|
||||
net
|
||||
}
|
||||
|
||||
/// Fair a geom NURBS surface's control net: [`fair_net`] on its Cartesian control points, with
|
||||
/// the weights kept as they are (a fairing moves points, not weights) and the boundary rows held.
|
||||
/// A rational surface's geometry then stays within the tolerance too, by the same convex-hull
|
||||
/// bound as the non-rational case.
|
||||
pub fn fair_surface(surface: &NurbsSurface, opts: &FairOptions) -> Result<(NurbsSurface, FairReport)> {
|
||||
let [cu, cv] = surface.count();
|
||||
let mut ctrl = Vec::with_capacity(cu * cv);
|
||||
let mut weights = Vec::with_capacity(cu * cv);
|
||||
for j in 0..cv {
|
||||
for i in 0..cu {
|
||||
let h = surface.point(i, j);
|
||||
let Some(p) = h.project() else {
|
||||
return Err(KernelError::Invalid("a control point has no position: its weight is zero".into()));
|
||||
};
|
||||
ctrl.push([p.x, p.y, p.z]);
|
||||
weights.push(h.w);
|
||||
}
|
||||
}
|
||||
let net = surface.net();
|
||||
let [ku, kv] = surface.knots();
|
||||
let degree = surface.degree();
|
||||
let faired = fair_net(degree, [ku, kv], [cu, cv], &ctrl, opts)?;
|
||||
let points: Vec<HPoint> = faired.ctrl.iter().zip(&weights).map(|(p, w)| HPoint::weighted(Vec3::new(p[0], p[1], p[2]), *w)).collect();
|
||||
let out = NurbsSurface::from_homogeneous(degree, surface.knots().clone(), points).map_err(|e| spline_error("fairing the surface", e))?;
|
||||
let faired = fair_net(degree, [ku, kv], &positions(&net)?, opts)?;
|
||||
let net = reweighted(net, &faired.ctrl);
|
||||
let out =
|
||||
NurbsSurface::from_homogeneous(degree, surface.knots().clone(), net.into_cells()).map_err(|e| spline_error("fairing the surface", e))?;
|
||||
Ok((out, faired.report))
|
||||
}
|
||||
|
||||
@@ -829,40 +819,11 @@ pub fn fair_surface(surface: &NurbsSurface, opts: &FairOptions) -> Result<(Nurbs
|
||||
pub fn fair_nurbs_surface(surface: &mt::NurbsSurface<mt::Vector4>, opts: &FairOptions) -> Result<(mt::NurbsSurface<mt::Vector4>, FairReport)> {
|
||||
guard("fair a NURBS surface", || {
|
||||
let bsp = surface.non_rationalized();
|
||||
let rows = bsp.control_points();
|
||||
let count = [rows.len(), rows.first().map_or(0, Vec::len)];
|
||||
if count[0] == 0 || count[1] == 0 {
|
||||
return Err(KernelError::Invalid("the surface has no control points".into()));
|
||||
}
|
||||
if rows.iter().any(|r| r.len() != count[1]) {
|
||||
return Err(KernelError::Invalid("the surface's control net is not rectangular".into()));
|
||||
}
|
||||
let mut ctrl = Vec::with_capacity(count[0] * count[1]);
|
||||
let mut weights = Vec::with_capacity(count[0] * count[1]);
|
||||
for j in 0..count[1] {
|
||||
for i in 0..count[0] {
|
||||
let Some(h) = rows.get(i).and_then(|r| r.get(j)) else { continue };
|
||||
let Some(p) = (HPoint { x: h.x, y: h.y, z: h.z, w: h.w }).project() else {
|
||||
return Err(KernelError::Invalid("a control point has no position: its weight is zero".into()));
|
||||
};
|
||||
ctrl.push([p.x, p.y, p.z]);
|
||||
weights.push(h.w);
|
||||
}
|
||||
}
|
||||
let net = truck_net(bsp.control_points())?.map(|h| HPoint { x: h.x, y: h.y, z: h.z, w: h.w });
|
||||
let (ku, kv) = bsp.knot_vecs();
|
||||
let (pu, pv) = bsp.degrees();
|
||||
let faired = fair_net([pu, pv], [ku, kv], count, &ctrl, opts)?;
|
||||
let mut net: Vec<Vec<mt::Vector4>> = Vec::with_capacity(count[0]);
|
||||
for i in 0..count[0] {
|
||||
let mut row = Vec::with_capacity(count[1]);
|
||||
for j in 0..count[1] {
|
||||
let (Some(c), Some(w)) = (faired.ctrl.get(j * count[0] + i), weights.get(j * count[0] + i)) else {
|
||||
return Err(KernelError::Failed("fairing lost a control point".into()));
|
||||
};
|
||||
row.push(mt::Vector4::new(c[0] * w, c[1] * w, c[2] * w, *w));
|
||||
}
|
||||
net.push(row);
|
||||
}
|
||||
let faired = fair_net([pu, pv], [ku, kv], &positions(&net)?, opts)?;
|
||||
let net = reweighted(net, &faired.ctrl).map(|h| mt::Vector4::new(h.x, h.y, h.z, h.w)).into_u_rows();
|
||||
let bsp = mt::BSplineSurface::try_new((ku.clone(), kv.clone()), net).map_err(|e| KernelError::Failed(format!("fair: {e}")))?;
|
||||
Ok((mt::NurbsSurface::new(bsp), faired.report))
|
||||
})
|
||||
@@ -1167,18 +1128,18 @@ mod tests {
|
||||
rough[j * cu + i][2] += d;
|
||||
}
|
||||
let opts = FairOptions::new(1.0, 6, false, 100.0).unwrap();
|
||||
let faired = fair_net(degree, [&ku, &kv], [cu, cv], &rough, &opts).unwrap();
|
||||
let faired = fair_net(degree, [&ku, &kv], &Grid::from_fn([cu, cv], |i, j| rough[j * cu + i]).unwrap(), &opts).unwrap();
|
||||
for j in 0..cv {
|
||||
for i in [0, cu - 1] {
|
||||
assert_eq!(faired.ctrl[j * cu + i], rough[j * cu + i], "column {i}, row {j} moved");
|
||||
assert_eq!(faired.ctrl.get(i, j), Some(&rough[j * cu + i]), "column {i}, row {j} moved");
|
||||
}
|
||||
}
|
||||
for i in 0..cu {
|
||||
for j in [0, cv - 1] {
|
||||
assert_eq!(faired.ctrl[j * cu + i], rough[j * cu + i], "row {j}, column {i} moved");
|
||||
assert_eq!(faired.ctrl.get(i, j), Some(&rough[j * cu + i]), "row {j}, column {i} moved");
|
||||
}
|
||||
}
|
||||
let near = (0..cu * cv).map(|k| dist(&faired.ctrl[k], &smooth[k])).fold(0.0, f64::max);
|
||||
let near = faired.ctrl.cells().iter().zip(&smooth).map(|(a, b)| dist(a, b)).fold(0.0, f64::max);
|
||||
let far = (0..cu * cv).map(|k| dist(&rough[k], &smooth[k])).fold(0.0, f64::max);
|
||||
eprintln!("net: perturbation {far} mm, faired to {near:e} mm, energy {:e} → {:e}", faired.report.energy_before, faired.report.energy_after);
|
||||
assert!(near < 1e-6, "{near:e}");
|
||||
@@ -1191,16 +1152,16 @@ mod tests {
|
||||
inner[j * cu + i][2] += d;
|
||||
}
|
||||
let kept = FairOptions::new(1.0, 6, true, 100.0).unwrap();
|
||||
let faired = fair_net(degree, [&ku, &kv], [cu, cv], &inner, &kept).unwrap();
|
||||
let faired = fair_net(degree, [&ku, &kv], &Grid::from_fn([cu, cv], |i, j| inner[j * cu + i]).unwrap(), &kept).unwrap();
|
||||
let shell = |i: usize, j: usize| i < 2 || i + 2 >= cu || j < 2 || j + 2 >= cv;
|
||||
for j in 0..cv {
|
||||
for i in 0..cu {
|
||||
if shell(i, j) {
|
||||
assert_eq!(faired.ctrl[j * cu + i], inner[j * cu + i], "({i}, {j}) is a boundary layer and moved");
|
||||
assert_eq!(faired.ctrl.get(i, j), Some(&inner[j * cu + i]), "({i}, {j}) is a boundary layer and moved");
|
||||
}
|
||||
}
|
||||
}
|
||||
let near = (0..cu * cv).filter(|&k| !shell(k % cu, k / cu)).map(|k| dist(&faired.ctrl[k], &smooth[k])).fold(0.0, f64::max);
|
||||
let near = (0..cu * cv).filter(|&k| !shell(k % cu, k / cu)).map(|k| dist(&faired.ctrl.cells()[k], &smooth[k])).fold(0.0, f64::max);
|
||||
eprintln!("net with keep_edges: interior faired to {near:e} mm, energy {:e} → {:e}", faired.report.energy_before, faired.report.energy_after);
|
||||
assert!(near < 1e-6 && faired.report.energy_after < faired.report.energy_before);
|
||||
}
|
||||
@@ -1376,10 +1337,13 @@ mod tests {
|
||||
let flat = [0.0, 0.0, 1.0, 2.0, 2.0];
|
||||
let grid = [[0.0, 0.0, 0.0]; 9];
|
||||
let kept = FairOptions::new(1.0, 4, true, 1.0).unwrap();
|
||||
assert!(fair_net([1, 1], [&flat, &flat], [3, 3], &grid, &kept).is_err(), "keep_edges on a 3 × 3 net");
|
||||
assert!(
|
||||
fair_net([1, 1], [&flat, &flat], &Grid::from_fn([3, 3], |i, j| grid[j * 3 + i]).unwrap(), &kept).is_err(),
|
||||
"keep_edges on a 3 × 3 net"
|
||||
);
|
||||
// A net too large to fair, refused before anything is allocated for it.
|
||||
let line = [0.0, 0.0, 1.0, 1.0];
|
||||
assert!(fair_net([1, 1], [&line, &line], [65, 65], &vec![[0.0; 3]; 65 * 65], &ok).is_err(), "4225 control points");
|
||||
assert!(fair_net([1, 1], [&line, &line], &Grid::from_fn([65, 65], |_, _| [0.0; 3]).unwrap(), &ok).is_err(), "4225 control points");
|
||||
// A singular system: a cubic whose last control points lie past the end of its domain
|
||||
// (0.5), where they do not move the curve at all, so the interior equations have no
|
||||
// unique solution and the run must refuse rather than move anything.
|
||||
@@ -1405,14 +1369,20 @@ mod tests {
|
||||
for &(i, j, d) in &[(1usize, 2usize, 2.5), (2, 2, -1.5), (3, 3, 3.0), (2, 1, -2.0)] {
|
||||
rough[j * cu + i][2] += d;
|
||||
}
|
||||
let faired = fair_net(degree, [&ku, &kv], [cu, cv], &rough, &FairOptions::new(1.0, 8, false, 100.0).unwrap()).unwrap();
|
||||
let near = (0..cu * cv).map(|k| dist(&faired.ctrl[k], &smooth[k])).fold(0.0, f64::max);
|
||||
let faired = fair_net(
|
||||
degree,
|
||||
[&ku, &kv],
|
||||
&Grid::from_fn([cu, cv], |i, j| rough[j * cu + i]).unwrap(),
|
||||
&FairOptions::new(1.0, 8, false, 100.0).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let near = faired.ctrl.cells().iter().zip(&smooth).map(|(a, b)| dist(a, b)).fold(0.0, f64::max);
|
||||
eprintln!("5 × 5 quadratic net: faired to {near:e} mm, energy {:e} → {:e}", faired.report.energy_before, faired.report.energy_after);
|
||||
assert!(near < 1e-6 && faired.report.energy_after < 1e-9 * faired.report.energy_before);
|
||||
for j in 0..cv {
|
||||
for i in 0..cu {
|
||||
if i == 0 || i + 1 == cu || j == 0 || j + 1 == cv {
|
||||
assert_eq!(faired.ctrl[j * cu + i], rough[j * cu + i], "({i}, {j}) is on the boundary and moved");
|
||||
assert_eq!(faired.ctrl.get(i, j), Some(&rough[j * cu + i]), "({i}, {j}) is on the boundary and moved");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
//! Helical sweeps (coils, springs) and lofts to a point (pyramids, cones).
|
||||
|
||||
use mt::builder;
|
||||
use solidcraft_geom::{Loop2, Mesh, Plane, Region2, Seg2, Vec2, Vec3};
|
||||
use solidcraft_geom::{Grid, Loop2, Mesh, Plane, Region2, Seg2, Vec2, Vec3};
|
||||
use truck_modeling as mt;
|
||||
|
||||
use crate::body::{Body, Solid, p3};
|
||||
use crate::build::{cap_and_close, uniform_wire};
|
||||
use crate::build::{NetFit, cap_and_close, interpolate_net, uniform_wire};
|
||||
use crate::numbered::NumberedLoop;
|
||||
use crate::record::{self, Side};
|
||||
use crate::{KernelError, Result, guard};
|
||||
@@ -124,33 +124,13 @@ fn smooth_helix(plane: &Plane, profile: &NumberedLoop, o: Vec3, k: Vec3, pitch:
|
||||
o + rot(w - o, k, a) + k * (pitch * a / std::f64::consts::TAU)
|
||||
};
|
||||
let fail = |w: &str| KernelError::Failed(format!("smooth helix: {w}"));
|
||||
// Per segment: the station curves (control points along v) and the surface net.
|
||||
// Per segment: the wall surface through its samples at every station.
|
||||
let mut faces_data = Vec::with_capacity(nseg);
|
||||
for s in &lp.segs {
|
||||
let mut station_curves = Vec::with_capacity(n + 1);
|
||||
for i in 0..=n {
|
||||
let pts: Vec<Vec3> = (0..SEG_SAMPLES).map(|j| at(i, s.point_at(j as f64 / (SEG_SAMPLES - 1) as f64))).collect();
|
||||
station_curves.push(crate::build::interpolate_cubic(&pts).ok_or_else(|| fail("profile curve"))?);
|
||||
}
|
||||
let kv = station_curves.first().map(|c| c.knot_vec().clone()).ok_or_else(|| fail("no stations"))?;
|
||||
// Along the helix: each control-point column interpolated across the stations.
|
||||
let mut columns = Vec::with_capacity(SEG_SAMPLES);
|
||||
for j in 0..SEG_SAMPLES {
|
||||
let pts: Vec<Vec3> = station_curves
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let p = c.control_point(j);
|
||||
Vec3::new(p.x, p.y, p.z)
|
||||
})
|
||||
.collect();
|
||||
columns.push(crate::build::interpolate_cubic(&pts).ok_or_else(|| fail("helix curve"))?);
|
||||
}
|
||||
let ku = columns.first().map(|c| c.knot_vec().clone()).ok_or_else(|| fail("no columns"))?;
|
||||
let net: Vec<Vec<mt::Point3>> = (0..=n).map(|m| columns.iter().map(|c| *c.control_point(m)).collect()).collect();
|
||||
let surf = mt::BSplineSurface::try_new((ku, kv), net).map_err(|e| fail(&e.to_string()))?;
|
||||
let (Some(first), Some(last)) = (station_curves.first().cloned(), station_curves.last().cloned()) else { return Err(fail("stations")) };
|
||||
let seam = columns.first().cloned().ok_or_else(|| fail("seam"))?;
|
||||
faces_data.push((first, last, seam, surf));
|
||||
// u along the helix (the stations), v along the profile segment.
|
||||
let samples =
|
||||
Grid::from_fn([n + 1, SEG_SAMPLES], |i, j| at(i, s.point_at(j as f64 / (SEG_SAMPLES - 1) as f64))).ok_or_else(|| fail("samples"))?;
|
||||
faces_data.push(interpolate_net(&samples).ok_or_else(|| fail("wall surface"))?);
|
||||
}
|
||||
guard("smooth helix", || {
|
||||
let start: Vec<mt::Vertex> = lp.segs.iter().map(|s| builder::vertex(p3(at(0, s.start())))).collect();
|
||||
@@ -158,7 +138,7 @@ fn smooth_helix(plane: &Plane, profile: &NumberedLoop, o: Vec3, k: Vec3, pitch:
|
||||
let mut e0 = Vec::with_capacity(nseg);
|
||||
let mut e1 = Vec::with_capacity(nseg);
|
||||
let mut seams = Vec::with_capacity(nseg);
|
||||
for (j, (c0, c1, seam, _)) in faces_data.iter().enumerate() {
|
||||
for (j, NetFit { u_ends: [c0, c1], v_ends: [seam, _], .. }) in faces_data.iter().enumerate() {
|
||||
let (Some(a0), Some(b0), Some(a1), Some(b1)) = (start.get(j), start.get((j + 1) % nseg), end.get(j), end.get((j + 1) % nseg)) else {
|
||||
return Err(fail("vertices"));
|
||||
};
|
||||
@@ -167,7 +147,7 @@ fn smooth_helix(plane: &Plane, profile: &NumberedLoop, o: Vec3, k: Vec3, pitch:
|
||||
seams.push(mt::Edge::try_new(a0, a1, mt::Curve::BSplineCurve(seam.clone())).map_err(|e| fail(&e.to_string()))?);
|
||||
}
|
||||
let mut walls = Vec::with_capacity(nseg);
|
||||
for (j, (_, _, _, surf)) in faces_data.iter().enumerate() {
|
||||
for (j, NetFit { surface: surf, .. }) in faces_data.iter().enumerate() {
|
||||
let (Some(a), Some(b), Some(sa), Some(sb)) = (e0.get(j), e1.get(j), seams.get(j), seams.get((j + 1) % nseg)) else {
|
||||
return Err(fail("edges"));
|
||||
};
|
||||
|
||||
@@ -10,10 +10,11 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use mt::{BoundedCurve, InnerSpace, ParametricCurve, ParametricSurface, ParametricSurface3D, SearchNearestParameter};
|
||||
use solidcraft_geom::Vec3;
|
||||
use solidcraft_geom::{Grid, Vec3};
|
||||
use truck_modeling as mt;
|
||||
|
||||
use crate::body::{Body, from_p3, p3};
|
||||
use crate::build::interpolate_net;
|
||||
use crate::history::FaceOrigin;
|
||||
use crate::surfaces::{Offset, map_curve, map_surface, surface_body};
|
||||
use crate::{KernelError, Result, guard};
|
||||
@@ -270,9 +271,10 @@ fn fit(f: &mt::Face, distance: f64, tolerance: f64) -> Result<mt::BSplineSurface
|
||||
}
|
||||
let mut n = START_GRID;
|
||||
loop {
|
||||
let grid: Vec<Vec<Vec3>> =
|
||||
(0..=n).map(|i| (0..=n).map(|j| at(i as f64 / n as f64, j as f64 / n as f64)).collect::<Result<Vec<_>>>()).collect::<Result<_>>()?;
|
||||
let surface = interpolate_surface(&grid).ok_or_else(|| KernelError::Failed("offset: fitting the surface".into()))?;
|
||||
let grid = Grid::from_fn([n + 1, n + 1], |i, j| at(i as f64 / n as f64, j as f64 / n as f64))
|
||||
.ok_or_else(|| KernelError::TooLarge("offset: the sample grid".into()))?
|
||||
.try_map(|p| p)?;
|
||||
let surface = interpolate_net(&grid).map(|fit| fit.surface).ok_or_else(|| KernelError::Failed("offset: fitting the surface".into()))?;
|
||||
// Checked between the samples, where a fit strays most.
|
||||
let mut worst = 0.0f64;
|
||||
for i in 0..n {
|
||||
@@ -315,22 +317,6 @@ fn principal_curvatures(s: &mt::Surface, u: f64, v: f64) -> Option<(f64, f64)> {
|
||||
Some((h + disc, h - disc))
|
||||
}
|
||||
|
||||
/// A cubic B-spline surface through a grid of points at uniform parameters on [0, 1]².
|
||||
fn interpolate_surface(grid: &[Vec<Vec3>]) -> Option<mt::BSplineSurface<mt::Point3>> {
|
||||
let rows: Vec<mt::BSplineCurve<mt::Point3>> = grid.iter().map(|r| crate::build::interpolate_cubic(r)).collect::<Option<_>>()?;
|
||||
let kv = rows.first()?.knot_vec().clone();
|
||||
let m = rows.first()?.control_points().len();
|
||||
let mut cols = Vec::with_capacity(m);
|
||||
for j in 0..m {
|
||||
let pts: Vec<Vec3> = rows.iter().filter_map(|r| r.control_points().get(j).map(|p| from_p3(*p))).collect();
|
||||
cols.push(crate::build::interpolate_cubic(&pts)?);
|
||||
}
|
||||
let ku = cols.first()?.knot_vec().clone();
|
||||
let n = cols.first()?.control_points().len();
|
||||
let net: Vec<Vec<mt::Point3>> = (0..n).map(|i| cols.iter().filter_map(|c| c.control_points().get(i).copied()).collect()).collect();
|
||||
mt::BSplineSurface::try_new((ku, kv), net).ok()
|
||||
}
|
||||
|
||||
/// `s` (on [0, 1]²) with its knots stretched onto `u` × `v`.
|
||||
fn reparameterised(s: mt::BSplineSurface<mt::Point3>, u: (f64, f64), v: (f64, f64)) -> mt::BSplineSurface<mt::Point3> {
|
||||
let stretch = |kv: &mt::KnotVec, (a, b): (f64, f64)| mt::KnotVec::from(kv.iter().map(|k| a + (b - a) * k).collect::<Vec<_>>());
|
||||
|
||||
@@ -6,11 +6,11 @@
|
||||
//! described.
|
||||
|
||||
use mt::builder;
|
||||
use solidcraft_geom::{Plane, Region2, Seg2, Vec2, Vec3};
|
||||
use solidcraft_geom::{Grid, Plane, Region2, Seg2, Vec2, Vec3};
|
||||
use truck_modeling as mt;
|
||||
|
||||
use crate::body::{Body, p3};
|
||||
use crate::build::{cap_and_close, close_sweep, interpolate_cubic, smooth_loft_faces, uniform_wire};
|
||||
use crate::build::{NetFit, cap_and_close, close_sweep, interpolate_net, smooth_loft_faces, uniform_wire};
|
||||
use crate::numbered::{NumberedLoop, NumberedRegion};
|
||||
use crate::record::{self, Side};
|
||||
use crate::{KernelError, Result, guard};
|
||||
@@ -686,32 +686,9 @@ pub(crate) fn smooth_sheet(plane: &Plane, chains: &[Vec<Seg2>], path: &[Vec3], c
|
||||
// and end, and the wall surface.
|
||||
let mut data = Vec::with_capacity(chain.len());
|
||||
for s in chain {
|
||||
let mut station_curves = Vec::with_capacity(n + 1);
|
||||
for i in 0..=n {
|
||||
let q: Vec<Vec3> = (0..SEG_SAMPLES).map(|j| at(i, s.point_at(j as f64 / (SEG_SAMPLES - 1) as f64))).collect();
|
||||
station_curves.push(interpolate_cubic(&q).ok_or_else(|| fail("profile curve"))?);
|
||||
}
|
||||
let kv = station_curves.first().map(|c| c.knot_vec().clone()).ok_or_else(|| fail("no stations"))?;
|
||||
let mut columns = Vec::with_capacity(SEG_SAMPLES);
|
||||
for j in 0..SEG_SAMPLES {
|
||||
let q: Vec<Vec3> = station_curves
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let p = c.control_point(j);
|
||||
Vec3::new(p.x, p.y, p.z)
|
||||
})
|
||||
.collect();
|
||||
columns.push(interpolate_cubic(&q).ok_or_else(|| fail("path curve"))?);
|
||||
}
|
||||
let ku = columns.first().map(|c| c.knot_vec().clone()).ok_or_else(|| fail("no columns"))?;
|
||||
let net: Vec<Vec<mt::Point3>> = (0..=n).map(|m| columns.iter().map(|c| *c.control_point(m)).collect()).collect();
|
||||
let surf = mt::BSplineSurface::try_new((ku, kv), net).map_err(|e| fail(&e.to_string()))?;
|
||||
let (Some(c0), Some(c1), Some(first), Some(last)) =
|
||||
(station_curves.first().cloned(), station_curves.last().cloned(), columns.first().cloned(), columns.last().cloned())
|
||||
else {
|
||||
return Err(fail("stations"));
|
||||
};
|
||||
data.push((c0, c1, first, last, surf));
|
||||
let samples =
|
||||
Grid::from_fn([n + 1, SEG_SAMPLES], |i, j| at(i, s.point_at(j as f64 / (SEG_SAMPLES - 1) as f64))).ok_or_else(|| fail("samples"))?;
|
||||
data.push(interpolate_net(&samples).ok_or_else(|| fail("wall surface"))?);
|
||||
}
|
||||
let walls: Vec<mt::Face> = guard("path sweep", || {
|
||||
let m = chain.len();
|
||||
@@ -725,13 +702,13 @@ pub(crate) fn smooth_sheet(plane: &Plane, chains: &[Vec<Seg2>], path: &[Vec3], c
|
||||
// The column through each corner: the start column of the segment leaving it, or
|
||||
// the end column of the last segment.
|
||||
let col = match data.get(k) {
|
||||
Some((_, _, first, _, _)) => first,
|
||||
None => data.last().map(|d| &d.3).ok_or_else(|| fail("seam"))?,
|
||||
Some(NetFit { v_ends: [first, _], .. }) => first,
|
||||
None => data.last().map(|NetFit { v_ends: [_, last], .. }| last).ok_or_else(|| fail("seam"))?,
|
||||
};
|
||||
seams.push(mt::Edge::try_new(a, b, mt::Curve::BSplineCurve(col.clone())).map_err(|e| fail(&e.to_string()))?);
|
||||
}
|
||||
let mut walls = Vec::with_capacity(m);
|
||||
for (j, (c0, c1, _, _, surf)) in data.iter().enumerate() {
|
||||
for (j, NetFit { surface: surf, u_ends: [c0, c1], .. }) in data.iter().enumerate() {
|
||||
let (Some(a0), Some(b0), Some(a1), Some(b1), Some(sa), Some(sb)) =
|
||||
(start.get(j), start.get(next(j)), end.get(j), end.get(next(j)), seams.get(j), seams.get(next(j)))
|
||||
else {
|
||||
@@ -826,35 +803,15 @@ fn smooth_walls(plane: &Plane, profile: &NumberedLoop, st: &[Station], expected:
|
||||
let n = st.len() - 1;
|
||||
let mut data = Vec::with_capacity(nseg);
|
||||
for s in &lp.segs {
|
||||
let mut station_curves = Vec::with_capacity(n + 1);
|
||||
for i in 0..=n {
|
||||
let pts: Vec<Vec3> = (0..SEG_SAMPLES).map(|j| at(i, s.point_at(j as f64 / (SEG_SAMPLES - 1) as f64))).collect();
|
||||
station_curves.push(interpolate_cubic(&pts).ok_or_else(|| fail("profile curve"))?);
|
||||
}
|
||||
let kv = station_curves.first().map(|c| c.knot_vec().clone()).ok_or_else(|| fail("no stations"))?;
|
||||
let mut columns = Vec::with_capacity(SEG_SAMPLES);
|
||||
for j in 0..SEG_SAMPLES {
|
||||
let pts: Vec<Vec3> = station_curves
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let p = c.control_point(j);
|
||||
Vec3::new(p.x, p.y, p.z)
|
||||
})
|
||||
.collect();
|
||||
columns.push(interpolate_cubic(&pts).ok_or_else(|| fail("path curve"))?);
|
||||
}
|
||||
let ku = columns.first().map(|c| c.knot_vec().clone()).ok_or_else(|| fail("no columns"))?;
|
||||
let net: Vec<Vec<mt::Point3>> = (0..=n).map(|m| columns.iter().map(|c| *c.control_point(m)).collect()).collect();
|
||||
let surf = mt::BSplineSurface::try_new((ku, kv), net).map_err(|e| fail(&e.to_string()))?;
|
||||
let (Some(first), Some(last)) = (station_curves.first().cloned(), station_curves.last().cloned()) else { return Err(fail("stations")) };
|
||||
let seam = columns.first().cloned().ok_or_else(|| fail("seam"))?;
|
||||
data.push((first, last, seam, surf));
|
||||
let samples =
|
||||
Grid::from_fn([n + 1, SEG_SAMPLES], |i, j| at(i, s.point_at(j as f64 / (SEG_SAMPLES - 1) as f64))).ok_or_else(|| fail("samples"))?;
|
||||
data.push(interpolate_net(&samples).ok_or_else(|| fail("wall surface"))?);
|
||||
}
|
||||
guard("path sweep", || {
|
||||
let start: Vec<mt::Vertex> = lp.segs.iter().map(|s| builder::vertex(p3(at(0, s.start())))).collect();
|
||||
let end: Vec<mt::Vertex> = lp.segs.iter().map(|s| builder::vertex(p3(at(n, s.start())))).collect();
|
||||
let (mut e0, mut e1, mut seams) = (Vec::with_capacity(nseg), Vec::with_capacity(nseg), Vec::with_capacity(nseg));
|
||||
for (j, (c0, c1, seam, _)) in data.iter().enumerate() {
|
||||
for (j, NetFit { u_ends: [c0, c1], v_ends: [seam, _], .. }) in data.iter().enumerate() {
|
||||
let (Some(a0), Some(b0), Some(a1), Some(b1)) = (start.get(j), start.get((j + 1) % nseg), end.get(j), end.get((j + 1) % nseg)) else {
|
||||
return Err(fail("vertices"));
|
||||
};
|
||||
@@ -863,7 +820,7 @@ fn smooth_walls(plane: &Plane, profile: &NumberedLoop, st: &[Station], expected:
|
||||
seams.push(mt::Edge::try_new(a0, a1, mt::Curve::BSplineCurve(seam.clone())).map_err(|e| fail(&e.to_string()))?);
|
||||
}
|
||||
let mut walls = Vec::with_capacity(nseg);
|
||||
for (j, (_, _, _, surf)) in data.iter().enumerate() {
|
||||
for (j, NetFit { surface: surf, .. }) in data.iter().enumerate() {
|
||||
let (Some(a), Some(b), Some(sa), Some(sb)) = (e0.get(j), e1.get(j), seams.get(j), seams.get((j + 1) % nseg)) else {
|
||||
return Err(fail("edges"));
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user