Skip to content

armgit / forma

Public Imported from GitHub
0

A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server

fix: build tube and sweep corners as true miter joints

Alp Talha Yazarb567ea8cebe8
diff --git a/crates/forma-core/src/curves.rs b/crates/forma-core/src/curves.rs
index 9e31d93..86b53c4 100644
--- a/crates/forma-core/src/curves.rs
+++ b/crates/forma-core/src/curves.rs
@@ -401,59 +401,15 @@ pub fn make_sweep_advanced(
prof.reverse();
}
let n = path.len();
- let mut tangents = Vec::with_capacity(n);
- for i in 0..n {
- let t = if closed {
- path[(i + 1) % n] - path[(i + n - 1) % n]
- } else if i == 0 {
- path[1] - path[0]
- } else if i == n - 1 {
- path[n - 1] - path[n - 2]
- } else {
- path[i + 1] - path[i - 1]
- };
- let tn = t.normalized();
- if tn.len_sq() < 1e-12 {
- return Err("sweep path contains duplicate adjacent points".into());
- }
- tangents.push(tn);
- }
-
- let mut normal = if tangents[0].z.abs() < 0.9 {
- tangents[0].cross(Vec3::Z).normalized()
- } else {
- tangents[0].cross(Vec3::X).normalized()
- };
- let mut binormal = tangents[0].cross(normal).normalized();
-
let mut m = PolyMesh::new();
- let mut rings = Vec::with_capacity(n);
let twist_rad = twist_deg.to_radians();
let sc_end = scale_end.clamp(0.05, 10.0);
-
- for i in 0..n {
- if i > 0 {
- let ax = tangents[i - 1].cross(tangents[i]);
- let sa = ax.len();
- if sa > 1e-9 {
- let k = ax / sa;
- let ang = sa.atan2(tangents[i - 1].dot(tangents[i]).clamp(-1.0, 1.0));
- let (s, cs) = ang.sin_cos();
- normal = (normal * cs + k.cross(normal) * s + k * (k.dot(normal) * (1.0 - cs))).normalized();
- binormal = tangents[i].cross(normal).normalized();
- }
- }
+ let rings = crate::primitives::add_sweep_rings(&mut m, path, closed, Vec3::Z, "sweep", &|i| {
let u = (i as f64) / ((n - 1).max(1) as f64);
let sc = 1.0 + (sc_end - 1.0) * u;
let (st, ct) = (twist_rad * u).sin_cos();
- let mut ring = Vec::with_capacity(prof.len());
- for &(px, py) in &prof {
- let rx = (px * ct - py * st) * sc;
- let ry = (px * st + py * ct) * sc;
- ring.push(m.add_vert(path[i] + normal * rx + binormal * ry));
- }
- rings.push(ring);
- }
+ prof.iter().map(|&(px, py)| ((px * ct - py * st) * sc, (px * st + py * ct) * sc)).collect()
+ })?;
let seg_count = if closed { n } else { n - 1 };
let np = prof.len();
diff --git a/crates/forma-core/src/primitives.rs b/crates/forma-core/src/primitives.rs
index 48224e1..c4a7888 100644
--- a/crates/forma-core/src/primitives.rs
+++ b/crates/forma-core/src/primitives.rs
@@ -286,7 +286,8 @@ pub fn make_revolve(profile: &[(f64, f64)], segs: usize, op_id: u32) -> Result<P
Ok(m)
}
-/// Sweep a circular tube along a 3D polyline using twist-free parallel transport frames.
+/// Sweep a circular tube along a 3D polyline using twist-free parallel transport frames and miter
+/// joints (see `add_sweep_rings`).
pub fn make_tube(points: &[Vec3], radius: f64, ring_segs: usize, closed: bool, op_id: u32) -> Result<PolyMesh, String> {
if !radius.is_finite() || radius <= 1e-9 {
return Err(format!("tube requires radius > 0 (got {radius})"));
@@ -323,58 +324,15 @@ pub fn make_tube(points: &[Vec3], radius: f64, ring_segs: usize, closed: bool, o
let points: &[Vec3] = &cleaned;
let ring_segs = ring_segs.clamp(6, 64);
let n = points.len();
- let mut tangents = Vec::with_capacity(n);
- for i in 0..n {
- let t = if closed {
- points[(i + 1) % n] - points[(i + n - 1) % n]
- } else if i == 0 {
- points[1] - points[0]
- } else if i == n - 1 {
- points[n - 1] - points[n - 2]
- } else {
- points[i + 1] - points[i - 1]
- };
- let tn = t.normalized();
- if tn.len_sq() < 1e-12 {
- return Err("tube contains duplicate adjacent points".into());
- }
- tangents.push(tn);
- }
-
- // Initial frame
- let mut normal = if tangents[0].y.abs() < 0.9 {
- tangents[0].cross(Vec3::Y).normalized()
- } else {
- tangents[0].cross(Vec3::X).normalized()
- };
- let mut binormal = tangents[0].cross(normal).normalized();
-
- let mut m = PolyMesh::new();
- let mut rings = Vec::with_capacity(n);
-
- for i in 0..n {
- if i > 0 {
- let t_prev = tangents[i - 1];
- let t_curr = tangents[i];
- let axis = t_prev.cross(t_curr);
- let sin_a = axis.len();
- if sin_a > 1e-9 {
- let ax = axis / sin_a;
- let cos_a = t_prev.dot(t_curr).clamp(-1.0, 1.0);
- let ang = sin_a.atan2(cos_a);
- normal = rodrigues(normal, ax, ang).normalized();
- binormal = t_curr.cross(normal).normalized();
- }
- }
- let mut ring = Vec::with_capacity(ring_segs);
- for j in 0..ring_segs {
+ let circle: Vec<(f64, f64)> = (0..ring_segs)
+ .map(|j| {
let a = 2.0 * PI * (j as f64) / (ring_segs as f64);
let (s, c) = a.sin_cos();
- let p = points[i] + normal * (radius * c) + binormal * (radius * s);
- ring.push(m.add_vert(p));
- }
- rings.push(ring);
- }
+ (radius * c, radius * s)
+ })
+ .collect();
+ let mut m = PolyMesh::new();
+ let rings = add_sweep_rings(&mut m, points, closed, Vec3::Y, "tube", &|_| circle.clone())?;
let seg_count = if closed { n } else { n - 1 };
for i in 0..seg_count {
@@ -695,7 +653,7 @@ pub fn make_thread(
}
/// Sweep an arbitrary closed 2D cross-section polygon along a 3D polyline using twist-free
-/// parallel transport frames (ideal for I-beams, channels, gaskets, rails, handles).
+/// parallel transport frames and miter joints (ideal for I-beams, channels, gaskets, rails, handles).
pub fn make_sweep(
profile_2d: &[(f64, f64)],
path: &[Vec3],
@@ -723,54 +681,8 @@ pub fn make_sweep(
};
let n = path.len();
- let mut tangents = Vec::with_capacity(n);
- for i in 0..n {
- let t = if closed {
- path[(i + 1) % n] - path[(i + n - 1) % n]
- } else if i == 0 {
- path[1] - path[0]
- } else if i == n - 1 {
- path[n - 1] - path[n - 2]
- } else {
- path[i + 1] - path[i - 1]
- };
- let tn = t.normalized();
- if tn.len_sq() < 1e-12 {
- return Err("sweep path contains duplicate adjacent points".into());
- }
- tangents.push(tn);
- }
-
- let mut normal = if tangents[0].z.abs() < 0.9 {
- tangents[0].cross(Vec3::Z).normalized()
- } else {
- tangents[0].cross(Vec3::X).normalized()
- };
- let mut binormal = tangents[0].cross(normal).normalized();
-
let mut m = PolyMesh::new();
- let mut rings = Vec::with_capacity(n);
- for i in 0..n {
- if i > 0 {
- let t_prev = tangents[i - 1];
- let t_curr = tangents[i];
- let axis = t_prev.cross(t_curr);
- let sin_a = axis.len();
- if sin_a > 1e-9 {
- let ax = axis / sin_a;
- let cos_a = t_prev.dot(t_curr).clamp(-1.0, 1.0);
- let ang = sin_a.atan2(cos_a);
- normal = rodrigues(normal, ax, ang).normalized();
- binormal = t_curr.cross(normal).normalized();
- }
- }
- let mut ring = Vec::with_capacity(np);
- for &(px, py) in &prof {
- let p = path[i] + normal * px + binormal * py;
- ring.push(m.add_vert(p));
- }
- rings.push(ring);
- }
+ let rings = add_sweep_rings(&mut m, path, closed, Vec3::Z, "sweep", &|_| prof.clone())?;
let seg_count = if closed { n } else { n - 1 };
for i in 0..seg_count {
@@ -1069,6 +981,125 @@ pub fn make_gear(
}
}
+/// A turn with cos(turn / 2) below this doubles back on itself: its miter would be over a million
+/// times the cross-section, too long for the self-intersection test (tolerance 1e-7 of the part's
+/// size) to still resolve the cross-section.
+const MIN_MITER_COS: f64 = 1e-6;
+
+/// Adds the cross-section rings of a polyline sweep with miter joints to `m` and returns their
+/// vertex indices, one ring per path point (shared by `make_tube`, `make_sweep` and
+/// `curves::make_sweep_advanced`). `section(i)` is the 2D cross-section at path point `i`; `path`
+/// has at least 2 points.
+///
+/// Each segment carries a frame, turned from the previous segment's by the minimal rotation between
+/// their directions, so a straight run never twists, even on a non-planar path. The first frame is
+/// built for the direction at point 0 (the first segment of an open path, `p[1] - p[n-1]` on a
+/// closed one): its normal is `direction x up`, or `direction x X` within about 26 degrees of the
+/// `up` axis. At a turn the ring lies on the miter plane, through the point and normal to the
+/// bisector of the two segment directions: each cross-section point is placed in its segment's
+/// frame and slid along the segment onto that plane. Both runs then keep their exact cross-section
+/// up to the joint and meet in the same ring, which is stretched by 1 / cos(turn / 2) across the
+/// bend.
+///
+/// Errors name what cannot be built instead of returning a folded solid: a duplicate point, a turn
+/// that doubles back (it has no miter plane), and a segment too short for the miters at its ends.
+pub(crate) fn add_sweep_rings(
+ m: &mut PolyMesh,
+ path: &[Vec3],
+ closed: bool,
+ up: Vec3,
+ what: &str,
+ section: &dyn Fn(usize) -> Vec<(f64, f64)>,
+) -> Result<Vec<Vec<usize>>, String> {
+ let n = path.len();
+ let seg_count = if closed { n } else { n - 1 };
+ let mut dirs = Vec::with_capacity(seg_count);
+ for k in 0..seg_count {
+ let d = (path[(k + 1) % n] - path[k]).normalized();
+ if d.len_sq() < 1e-12 {
+ return Err(format!("{what} path contains duplicate adjacent points"));
+ }
+ dirs.push(d);
+ }
+ // `normal` turned by the minimal rotation from direction `from` to `to` (None if parallel).
+ let turn = |normal: Vec3, from: Vec3, to: Vec3| {
+ let axis = from.cross(to);
+ let sin_a = axis.len();
+ let angle = sin_a.atan2(from.dot(to).clamp(-1.0, 1.0));
+ (sin_a > 1e-9).then(|| rodrigues(normal, axis / sin_a, angle).normalized())
+ };
+ // The first frame is built for the direction at point 0 and turned onto the first segment. On a
+ // closed path that direction is `p[1] - p[n-1]`, which keeps the profile's roll against the loop.
+ let seed = if closed { (path[1] - path[n - 1]).normalized() } else { dirs[0] };
+ let seed = if seed.len_sq() < 1e-12 { dirs[0] } else { seed };
+ let mut normal = if seed.dot(up).abs() < 0.9 {
+ seed.cross(up).normalized()
+ } else {
+ seed.cross(Vec3::X).normalized()
+ };
+ normal = turn(normal, seed, dirs[0]).unwrap_or(normal);
+ let mut binormal = dirs[0].cross(normal).normalized();
+ let mut frames = Vec::with_capacity(seg_count);
+ frames.push((normal, binormal));
+ for k in 1..seg_count {
+ if let Some(turned) = turn(normal, dirs[k - 1], dirs[k]) {
+ normal = turned;
+ binormal = dirs[k].cross(normal).normalized();
+ }
+ frames.push((normal, binormal));
+ }
+
+ let mut rings: Vec<Vec<Vec3>> = Vec::with_capacity(n);
+ for (i, &origin) in path.iter().enumerate() {
+ // The ring comes from the segment leaving the point; an open path's last point has none.
+ let k = if closed || i + 1 < n { i } else { i - 1 };
+ let incoming = if closed {
+ Some(dirs[(i + n - 1) % n])
+ } else if i > 0 && i + 1 < n {
+ Some(dirs[i - 1])
+ } else {
+ None
+ };
+ let mut miter = None;
+ if let Some(d_in) = incoming {
+ let bisector = d_in + dirs[k];
+ if 0.5 * bisector.len() < MIN_MITER_COS {
+ return Err(format!(
+ "{what}: path turns back on itself at ({}, {}, {}): a 180-degree turn has no miter joint (widen the U-turn with an extra point)",
+ origin.x, origin.y, origin.z
+ ));
+ }
+ if d_in.cross(dirs[k]).len() > 1e-9 {
+ miter = Some(bisector.normalized());
+ }
+ }
+ let (normal, binormal, dir) = (frames[k].0, frames[k].1, dirs[k]);
+ let ring = section(i).into_iter().map(|(x, y)| match miter {
+ None => origin + normal * x + binormal * y,
+ Some(plane) => {
+ let o = normal * x + binormal * y;
+ origin + o - dir * (o.dot(plane) / dir.dot(plane))
+ }
+ });
+ rings.push(ring.collect());
+ }
+
+ // A miter that reaches past the far end of its segment makes some cross-section point run
+ // backwards along the segment, folding the solid over itself between two rings. The
+ // triangle-pair self-intersection test can miss such a fold, so it is refused here.
+ for k in 0..seg_count {
+ let (a, b) = (path[k], path[(k + 1) % n]);
+ let min_run = 1e-9 * (b - a).len();
+ if rings[k].iter().zip(&rings[(k + 1) % n]).any(|(p, q)| (*q - *p).dot(dirs[k]) <= min_run) {
+ return Err(format!(
+ "{what}: the segment from ({}, {}, {}) to ({}, {}, {}) is too short for the miter joints at its ends, so the sweep self-intersects (lengthen it, soften the turn or shrink the cross-section)",
+ a.x, a.y, a.z, b.x, b.y, b.z
+ ));
+ }
+ }
+ Ok(rings.into_iter().map(|ring| ring.into_iter().map(|p| m.add_vert(p)).collect()).collect())
+}
+
fn rodrigues(v: Vec3, axis: Vec3, angle: f64) -> Vec3 {
let (s, c) = angle.sin_cos();
v * c + axis.cross(v) * s + axis * (axis.dot(v) * (1.0 - c))
diff --git a/crates/forma-core/tests/issue_regressions.rs b/crates/forma-core/tests/issue_regressions.rs
index b8134b1..3f8986d 100644
--- a/crates/forma-core/tests/issue_regressions.rs
+++ b/crates/forma-core/tests/issue_regressions.rs
@@ -295,6 +295,224 @@ fn tube_repeated_closing_and_foldback_paths() {
}
}
+// Issues #42 and #71: every corner of a tube or sweep is a miter joint. The expected values are
+// worked out by hand: a mitred band of half-width r along a centreline of length L covers 2rL in
+// the path plane, and a profile centred on the path sweeps (profile area) x L. A 12-gon ring of
+// radius r has area 3r^2 and its in-plane extremes are vertices.
+
+const SQUARE_R02: [(f64, f64); 4] = [(-0.2, -0.2), (0.2, -0.2), (0.2, 0.2), (-0.2, 0.2)];
+
+fn xyz(x: f64, y: f64, z: f64) -> Vec3 {
+ Vec3::new(x, y, z)
+}
+
+fn assert_near(got: f64, want: f64, what: &str) {
+ assert!((got - want).abs() < 1e-9, "{what}: got {got}, want {want}");
+}
+
+fn has_vertex(m: &PolyMesh, p: Vec3) -> bool {
+ m.verts.iter().any(|v| (*v - p).len() < 1e-9)
+}
+
+/// `make_sweep` and `make_sweep_advanced` without taper or twist, which must build the same rings.
+fn both_sweeps(profile: &[(f64, f64)], path: &[Vec3], closed: bool) -> [PolyMesh; 2] {
+ let plain = forma_core::primitives::make_sweep(profile, path, closed, 1).unwrap();
+ let adv = forma_core::curves::make_sweep_advanced(profile, path, 1.0, 0.0, closed, 1).unwrap();
+ assert_eq!(plain.verts.len(), adv.verts.len());
+ for (i, (a, b)) in plain.verts.iter().zip(&adv.verts).enumerate() {
+ assert!((*a - *b).len() < 1e-12, "sweep and sweep_advanced differ at vertex {i}: {a:?} vs {b:?}");
+ }
+ [plain, adv]
+}
+
+#[test]
+fn tube_and_sweep_keep_their_full_width_through_a_right_angle() {
+ use forma_core::primitives::make_tube;
+ use forma_core::spatial::section_z;
+ let l_path = [xyz(0.0, 0.0, 0.0), xyz(2.0, 0.0, 0.0), xyz(2.0, 2.0, 0.0)];
+ let tube = make_tube(&l_path, 0.2, 12, false, 1).unwrap();
+ assert_near(section_z(&tube, 0.0).area, 1.6, "tube L section"); // 0.4 wide, 4 long
+ assert_near(tube.signed_volume(), 0.48, "tube L volume"); // 3 * 0.2^2 * 4
+ // Miter corners: outer at (2 + r, -r), inner at (2 - r, r).
+ assert!(has_vertex(&tube, xyz(2.2, -0.2, 0.0)) && has_vertex(&tube, xyz(1.8, 0.2, 0.0)));
+ for sweep in both_sweeps(&SQUARE_R02, &l_path, false) {
+ assert_near(section_z(&sweep, 0.0).area, 1.6, "sweep L section");
+ assert_near(sweep.signed_volume(), 0.64, "sweep L volume"); // 0.4^2 * 4
+ }
+}
+
+#[test]
+fn closed_square_tube_and_sweep_reach_full_radius_at_every_corner() {
+ use forma_core::primitives::make_tube;
+ let square = [xyz(0.0, 0.0, 0.0), xyz(2.0, 0.0, 0.0), xyz(2.0, 2.0, 0.0), xyz(0.0, 2.0, 0.0)];
+ let mut back_to_start = square.to_vec();
+ back_to_start.push(square[0]);
+ let tube = make_tube(&back_to_start, 0.2, 12, false, 1).unwrap();
+ let [plain, adv] = both_sweeps(&SQUARE_R02, &square, true);
+ // Perimeter 8: tube 3 * 0.2^2 * 8, sweep 0.4^2 * 8.
+ for (m, volume) in [(&tube, 0.96), (&plain, 1.28), (&adv, 1.28)] {
+ let bb = m.aabb();
+ assert_near(bb.min.x, -0.2, "min x");
+ assert_near(bb.min.y, -0.2, "min y");
+ assert_near(bb.max.x, 2.2, "max x");
+ assert_near(bb.max.y, 2.2, "max y");
+ assert_near(m.signed_volume(), volume, "closed square volume");
+ }
+}
+
+#[test]
+fn corners_sit_on_the_true_bisector_for_unequal_legs_and_sharp_turns() {
+ use forma_core::primitives::make_tube;
+ use forma_core::spatial::section_z;
+ // Legs of 2 and 0.6: the inner corner is r in from both walls, not tilted toward the long leg.
+ let t = make_tube(&[xyz(0.0, 0.0, 0.0), xyz(2.0, 0.0, 0.0), xyz(2.0, 0.6, 0.0)], 0.1, 12, false, 1).unwrap();
+ assert_near(section_z(&t, 0.0).area, 0.52, "unequal legs section"); // 0.2 * 2.6
+ assert!(has_vertex(&t, xyz(1.9, 0.1, 0.0)) && has_vertex(&t, xyz(2.1, -0.1, 0.0)));
+ // A 120-degree turn stretches the miter 1 / cos(60) = 2 times in the bend plane.
+ let sharp = [xyz(0.0, 0.0, 0.0), xyz(1.0, 0.0, 0.0), xyz(0.5, 0.75f64.sqrt(), 0.0)];
+ let t = make_tube(&sharp, 0.1, 12, false, 1).unwrap();
+ assert_near(section_z(&t, 0.0).area, 0.4, "120-degree turn section"); // 0.2 * 2
+ // Issue #71: a 50 x 200 mm moulding swept inside a 6 x 4 m room.
+ let room = [xyz(0.0, 0.0, 0.0), xyz(0.0, 4.0, 0.0), xyz(6.0, 4.0, 0.0), xyz(6.0, 0.0, 0.0)];
+ let moulding = [(0.0, 0.0), (0.05, 0.0), (0.05, -0.2), (0.0, -0.2)];
+ for sweep in both_sweeps(&moulding, &room, true) {
+ assert_near(sweep.signed_volume(), 0.198, "moulding volume"); // (24 - 5.9 * 3.9) * 0.2
+ for (x, y) in [(0.05, 0.05), (0.05, 3.95), (5.95, 3.95), (5.95, 0.05)] {
+ for z in [0.0, 0.2] {
+ assert!(has_vertex(&sweep, xyz(x, y, z)), "inner corner ({x}, {y}, {z}) is not 0.05 from both walls");
+ }
+ }
+ }
+}
+
+/// Pins the frame convention: on a straight path every ring is the plain cross-section, tube rings
+/// start at +Z and turn toward -Y, and sweep profiles map x to -Y and y to -Z.
+#[test]
+fn straight_paths_keep_their_rings_and_frame_orientation() {
+ use forma_core::primitives::make_tube;
+ use std::f64::consts::PI;
+ let line = [xyz(0.0, 0.0, 0.0), xyz(1.0, 0.0, 0.0), xyz(3.0, 0.0, 0.0)];
+ let tube = make_tube(&line, 0.2, 12, false, 1).unwrap();
+ let bar = [(-0.3, -0.1), (0.3, -0.1), (0.3, 0.1), (-0.3, 0.1)];
+ let sweeps = both_sweeps(&bar, &line, false);
+ for (i, p) in line.iter().enumerate() {
+ for j in 0..12 {
+ let (s, c) = (2.0 * PI * j as f64 / 12.0).sin_cos();
+ let v = tube.verts[i * 12 + j];
+ assert!((v - xyz(p.x, -0.2 * s, 0.2 * c)).len() < 1e-12, "tube ring {i} vertex {j}: {v:?}");
+ }
+ for (j, &(px, py)) in bar.iter().enumerate() {
+ let v = sweeps[0].verts[i * 4 + j];
+ assert!((v - xyz(p.x, -px, -py)).len() < 1e-12, "sweep ring {i} vertex {j}: {v:?}");
+ }
+ }
+}
+
+/// Pins the first frame of a closed path: it is built for the direction at point 0
+/// (`p[1] - p[n-1]`), so on a vertical loop the bar's wide side faces out of the loop's plane.
+#[test]
+fn closed_vertical_loops_keep_their_profile_roll() {
+ let bar = [(-0.3, -0.1), (0.3, -0.1), (0.3, 0.1), (-0.3, 0.1)];
+ let s = std::f64::consts::FRAC_1_SQRT_2;
+ let walls = [
+ ([xyz(0.0, 0.0, 0.0), xyz(0.0, 0.0, 2.0), xyz(0.0, 2.0, 2.0), xyz(0.0, 2.0, 0.0)], xyz(1.0, 0.0, 0.0)),
+ ([xyz(0.0, 0.0, 0.0), xyz(0.0, 0.0, 2.0), xyz(1.0, 1.0, 2.0), xyz(1.0, 1.0, 0.0)], xyz(s, -s, 0.0)),
+ ];
+ for (loop_path, wall_normal) in walls {
+ for sweep in both_sweeps(&bar, &loop_path, true) {
+ let off_wall: Vec<f64> = sweep.verts.iter().map(|v| v.dot(wall_normal)).collect();
+ let (lo, hi) = off_wall.iter().fold((f64::MAX, f64::MIN), |(lo, hi), &d| (lo.min(d), hi.max(d)));
+ assert_near(lo, -0.3, "wide side behind the wall");
+ assert_near(hi, 0.3, "wide side in front of the wall");
+ }
+ }
+}
+
+#[test]
+fn a_finely_segmented_arc_keeps_its_section() {
+ use forma_core::primitives::make_tube;
+ use forma_core::spatial::section_z;
+ use std::f64::consts::PI;
+ // 16 chords of a quarter circle of radius 2; every joint turns 5.625 degrees.
+ let arc: Vec<Vec3> = (0..=16)
+ .map(|i| {
+ let a = PI / 2.0 * i as f64 / 16.0;
+ xyz(2.0 * a.cos(), 2.0 * a.sin(), 0.0)
+ })
+ .collect();
+ let tube = make_tube(&arc, 0.1, 12, false, 1).unwrap();
+ let chords = 16.0 * 4.0 * (PI / 64.0).sin(); // 16 chords of length 2 * 2 * sin(pi / 64)
+ let area = section_z(&tube, 0.0).area;
+ assert_near(area, 0.2 * chords, "arc section"); // 0.628066
+ assert!((area / (0.2 * PI) - 1.0).abs() < 5e-4, "arc section {area} drifts from the true 0.2 * pi");
+}
+
+#[test]
+fn a_non_planar_sweep_keeps_the_exact_profile_along_every_run() {
+ // A 0.6 x 0.2 bar along +X, then +Y, then +Z. Each run must be a plain prism of the profile:
+ // every edge parallel to its run, so the profile neither twists nor shrinks between corners.
+ let bar = [(-0.3, -0.1), (0.3, -0.1), (0.3, 0.1), (-0.3, 0.1)];
+ let path = [xyz(0.0, 0.0, 0.0), xyz(2.0, 0.0, 0.0), xyz(2.0, 2.0, 0.0), xyz(2.0, 2.0, 2.0)];
+ for sweep in both_sweeps(&bar, &path, false) {
+ assert_near(sweep.signed_volume(), 0.72, "bar volume"); // 0.12 * 6
+ for k in 0..3 {
+ let run = (path[k + 1] - path[k]).normalized();
+ for j in 0..4 {
+ let edge = sweep.verts[(k + 1) * 4 + j] - sweep.verts[k * 4 + j];
+ assert!(edge.cross(run).len() < 1e-12, "run {k}, profile point {j} is not parallel to its run: {edge:?}");
+ }
+ }
+ // The frame starts as x -> -Y, y -> -Z; turning +X to +Y rolls it about Z and +Y to +Z
+ // about X, so the last ring carries profile x along +X and y along +Y.
+ for (j, &(px, py)) in bar.iter().enumerate() {
+ let v = sweep.verts[3 * 4 + j];
+ assert!((v - xyz(2.0 + px, 2.0 + py, 2.0)).len() < 1e-12, "end ring vertex {j}: {v:?}");
+ }
+ }
+}
+
+#[test]
+fn a_path_that_turns_straight_back_is_a_named_error() {
+ use forma_core::curves::make_sweep_advanced;
+ use forma_core::primitives::{make_sweep, make_tube};
+ // A 180-degree turn has no miter plane; it must not become a spike or a self-intersection.
+ let back = [xyz(0.0, 0.0, 0.0), xyz(2.0, 0.0, 0.0), xyz(1.0, 0.0, 0.0)];
+ let err = make_tube(&back, 0.1, 12, false, 1).unwrap_err();
+ assert!(err.starts_with("tube:") && err.contains("turns back") && err.contains("(2, 0, 0)"), "{err}");
+ let err = make_sweep(&SQUARE_R02, &back, false, 1).unwrap_err();
+ assert!(err.starts_with("sweep:") && err.contains("turns back") && err.contains("(2, 0, 0)"), "{err}");
+ let err = make_sweep_advanced(&SQUARE_R02, &back, 0.5, 30.0, false, 1).unwrap_err();
+ assert!(err.starts_with("sweep:") && err.contains("turns back") && err.contains("(2, 0, 0)"), "{err}");
+ // The joint where a closed path wraps around counts too.
+ let line = [xyz(0.0, 0.0, 0.0), xyz(1.0, 0.0, 0.0), xyz(2.0, 0.0, 0.0)];
+ let err = make_sweep(&SQUARE_R02, &line, true, 1).unwrap_err();
+ assert!(err.starts_with("sweep:") && err.contains("turns back"), "{err}");
+ let err = make_tube(&line, 0.1, 12, true, 1).unwrap_err();
+ assert!(err.starts_with("tube:") && err.contains("turns back"), "{err}");
+}
+
+#[test]
+fn a_segment_too_short_for_its_miter_is_a_named_error() {
+ use forma_core::curves::make_sweep_advanced;
+ use forma_core::primitives::{make_sweep, make_tube};
+ // After a 120-degree turn the miter's inner corner sits r * tan(60) = 0.346 along the next
+ // segment, which is only 0.3 long: that edge would run backwards and fold the solid over
+ // itself, a fold the triangle-pair self-intersection test can miss.
+ let short_leg = [xyz(0.0, 0.0, 0.0), xyz(1.0, 0.0, 0.0), xyz(0.85, 0.75f64.sqrt() * 0.3, 0.0)];
+ let err = make_tube(&short_leg, 0.2, 12, false, 1).unwrap_err();
+ assert!(err.starts_with("tube:") && err.contains("self-intersects") && err.contains("from (1, 0, 0)"), "{err}");
+ let err = make_sweep(&SQUARE_R02, &short_leg, false, 1).unwrap_err();
+ assert!(err.starts_with("sweep:") && err.contains("self-intersects") && err.contains("from (1, 0, 0)"), "{err}");
+ // A hairpin whose middle segment is shorter than the two 90-degree miters need (2r).
+ let hairpin = [xyz(0.0, 0.0, 0.0), xyz(2.0, 0.0, 0.0), xyz(2.0, 0.15, 0.0), xyz(0.0, 0.15, 0.0)];
+ let err = make_sweep_advanced(&SQUARE_R02.map(|(x, y)| (x / 2.0, y / 2.0)), &hairpin, 1.0, 0.0, false, 1).unwrap_err();
+ assert!(err.starts_with("sweep:") && err.contains("from (2, 0, 0) to (2, 0.15, 0)"), "{err}");
+ // Just long enough: the same turns with room for the miters stay valid.
+ assert!(make_tube(&[xyz(0.0, 0.0, 0.0), xyz(1.0, 0.0, 0.0), xyz(0.8, 0.75f64.sqrt() * 0.4, 0.0)], 0.2, 12, false, 1).is_ok());
+ let roomy = [xyz(0.0, 0.0, 0.0), xyz(2.0, 0.0, 0.0), xyz(2.0, 0.25, 0.0), xyz(0.0, 0.25, 0.0)];
+ assert!(make_sweep(&SQUARE_R02.map(|(x, y)| (x / 2.0, y / 2.0)), &roomy, false, 1).is_ok());
+}
+
/// A cut or intersect whose true result is empty must return an empty mesh rather than a
/// zero-thickness perturbation skin.
#[test]