refactor: geom::UnitVec3 for unit axes and normals (#2603)

* geom: UnitVec3; a face's analytic axes and normals are unit by type

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

* geom: UnitVec3 adds to and subtracts from a Vec3

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

* kernel, doc, engine: cylinder axes and measured normals held as UnitVec3

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

* kernel, engine: functions that take a unit axis or direction say so by type

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

* doc: a face's normal goes to Plane::from_normal as is

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

* kernel, doc: main's new cylinder helpers take the face's axis as a UnitVec3

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
JIJINBEI
2026-10-19 10:16:31 +09:00
committed by GitHub
parent a3080d02d6
commit 7ad5130cd2
27 changed files with 279 additions and 145 deletions
+1 -1
View File
@@ -350,7 +350,7 @@ fn actions(s: &Session) -> Vec<Action> {
// The surface's normal at `p` (either way round): exact on analytic faces.
let normal_at = |f: u32, p: Vec3| -> Option<Vec3> {
match face_surface(&b.body, f as usize) {
Some(FaceSurface::Plane { normal, .. }) => Some(normal),
Some(FaceSurface::Plane { normal, .. }) => Some(*normal),
Some(FaceSurface::Cylinder { origin, axis, .. }) => {
let v = p - origin;
(v - axis * v.dot(axis)).normalized()
+1 -1
View File
@@ -32,7 +32,7 @@ pub(crate) fn remap_sheet_metadata(st: &mut ModelState, names: &[String], transf
.filter(|(_, t)| names.contains(t.body.as_str()))
.map(|(i, t)| {
let point = apply_point(transform, t.axis_point);
let axis = apply_vector(transform, t.axis).normalized().ok_or_else(|| DocError::Invalid("invalid transferred thread axis".into()))?;
let axis = apply_vector(transform, *t.axis).unit().ok_or_else(|| DocError::Invalid("invalid transferred thread axis".into()))?;
if !point.is_finite() {
return Err(DocError::Invalid("invalid transferred thread placement".into()));
}
+5 -5
View File
@@ -285,9 +285,9 @@ pub(crate) fn line(ctx: &Ctx, g: &GeoRef) -> Result<(Vec3, Vec3)> {
GeoRef::Face { at, name } => {
let (b, fi, _) = face_of(ctx.st, *at, name)?;
match kernel::face_surface(&b.body, fi) {
Some(FaceSurface::Cylinder { origin, axis, .. }) => Ok((origin, axis)),
Some(FaceSurface::Cone { apex, axis, .. }) => Ok((apex, axis)),
Some(FaceSurface::Torus { center, axis, .. }) => Ok((center, axis)),
Some(FaceSurface::Cylinder { origin, axis, .. }) => Ok((origin, *axis)),
Some(FaceSurface::Cone { apex, axis, .. }) => Ok((apex, *axis)),
Some(FaceSurface::Torus { center, axis, .. }) => Ok((center, *axis)),
_ => Err(bad("the face is not a cylinder, cone or torus")),
}
}
@@ -367,7 +367,7 @@ fn path_points(ctx: &Ctx, g: &GeoRef) -> Result<Vec<Vec3>> {
/// The surface's unit normal at (the point of the surface nearest) `p`, and that point.
fn surface_normal(s: FaceSurface, p: Vec3) -> Option<(Vec3, Vec3)> {
match s {
FaceSurface::Plane { normal, point } => Some((p - normal * (p - point).dot(normal), normal)),
FaceSurface::Plane { normal, point } => Some((p - normal * (p - point).dot(normal), *normal)),
FaceSurface::Cylinder { origin, axis, radius } => {
let w = p - origin;
let r = (w - axis * w.dot(axis)).normalized()?;
@@ -403,7 +403,7 @@ fn face_surface_at(ctx: &Ctx, g: &GeoRef) -> Result<(FaceSurface, Vec3)> {
}
GeoRef::Plane { .. } => {
let pl = plane(ctx, g)?;
Ok((FaceSurface::Plane { normal: pl.normal(), point: pl.origin }, pl.origin))
Ok((FaceSurface::Plane { normal: pl.normal().unit().ok_or_else(|| bad("degenerate plane"))?, point: pl.origin }, pl.origin))
}
_ => Err(bad("pick a face")),
}
+6 -6
View File
@@ -6,7 +6,7 @@ use std::sync::{Arc, OnceLock};
use serde::Serialize;
use solidcraft_geom::tess::TessPlan;
use solidcraft_geom::{Mesh, Plane, Region2, Vec2, Vec3, regions_apart};
use solidcraft_geom::{Mesh, Plane, Region2, UnitVec3, Vec2, Vec3, regions_apart};
use solidcraft_kernel::{self as kernel, Body, BoolOp};
use solidcraft_sketch::{CurveKind, Profile, SolveReport, find_profiles};
@@ -179,7 +179,7 @@ pub struct ThreadInfo {
pub pitch: f64,
pub internal: bool,
pub axis_point: Vec3,
pub axis: Vec3,
pub axis: UnitVec3,
/// Threaded part along the axis from `axis_point`.
pub start: f64,
pub end: f64,
@@ -365,10 +365,10 @@ fn thread_groove(t: &ThreadInfo, radius: f64, open: (bool, bool)) -> Result<soli
// at the threaded length's end.
let (s0, s1) = (if open.0 { t.start - p } else { t.start }, if open.1 { t.end + p } else { t.end });
let base = t.axis_point + k * s0;
let plane = Plane { origin: base, x: u, y: k };
let plane = Plane { origin: base, x: u, y: *k };
let section = [Vec2::new(r0, -w0), Vec2::new(r1, -w1), Vec2::new(r1, w1), Vec2::new(r0, w0)];
// Sections 7.5° apart: the chords sag 0.2% of the radius.
Ok(kernel::sweep_helix_mesh(&plane, &section, base, k, p, (s1 - s0) / p, 48)?)
Ok(kernel::sweep_helix_mesh(&plane, &section, base, *k, p, (s1 - s0) / p, 48)?)
}
/// A constant fillet of `edges`; with [`FilletFit::Reduce`](crate::FilletFit::Reduce), a radius too
@@ -2390,7 +2390,7 @@ fn faces_through(st: &ModelState, p: Vec3, reach: f64) -> Vec<(f64, Vec3, Option
}
for (f, (d, facet)) in near {
let (exact, off) = match kernel::face_surface(&b.body, f as usize) {
Some(kernel::FaceSurface::Plane { normal, point }) => (Some(normal), Some((p - point).dot(normal).abs())),
Some(kernel::FaceSurface::Plane { normal, point }) => (Some(*normal), Some((p - point).dot(normal).abs())),
Some(kernel::FaceSurface::Cylinder { origin, axis, .. }) => {
let v = p - origin;
((v - axis * v.dot(axis)).normalized(), None)
@@ -5805,7 +5805,7 @@ pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut
let mut t2 = t.clone();
let frame = st.body(&t.body).and_then(|body| doc.model_body_offset(body)).map(|offset| crate::mat_mul(&m, offset)).unwrap_or(m);
t2.axis_point = crate::apply_point(&frame, t.axis_point);
t2.axis = crate::apply_vector(&frame, t.axis);
t2.axis = crate::apply_vector(&frame, *t.axis).unit().unwrap_or(t.axis);
out.threads.push(t2);
}
}
+1 -1
View File
@@ -72,7 +72,7 @@ impl NamedFace<'_> {
/// A cylinder of a body's own coordinates placed by the body's (rigid) offset.
pub(super) fn placed(m: &Mat, c: CylinderFace) -> CylinderFace {
CylinderFace { axis_point: apply_point(m, c.axis_point), axis: apply_vector(m, c.axis), ..c }
CylinderFace { axis_point: apply_point(m, c.axis_point), axis: apply_vector(m, *c.axis).unit().unwrap_or(c.axis), ..c }
}
/// The face across the rim at the `at` end (along the axis) of cylinder `c`, face `face` of `b`
+5 -5
View File
@@ -50,7 +50,7 @@
use std::collections::BTreeMap;
use std::f64::consts::{FRAC_PI_2, PI, TAU};
use solidcraft_geom::{Loop2, Mesh, Plane, Region2, Seg2, Vec2, Vec3};
use solidcraft_geom::{Loop2, Mesh, Plane, Region2, Seg2, UnitVec3, Vec2, Vec3};
use solidcraft_kernel::{Body, FaceSurface, face_surface};
use super::{FlatWork, ReliefOverride, RuleValues, SheetBody, SheetFlange, base_flange, point_in, polys_cross, signed_area, snap};
@@ -71,7 +71,7 @@ fn at(p: Vec3) -> String {
/// arc where that face is a round wall (`round[i]`: the circle's centre and the arc's middle).
/// `holes`: its inner loops, in `plane`, each with the faces of its walls.
struct Face {
n: Vec3,
n: UnitVec3,
pts: Vec<Vec3>,
across: Vec<Option<usize>>,
round: Vec<Option<(Vec3, Vec3)>>,
@@ -89,7 +89,7 @@ struct Panel {
}
/// Area of a loop in space, positive when it runs counter-clockwise about `n`.
fn area_about(pts: &[Vec3], n: Vec3) -> f64 {
fn area_about(pts: &[Vec3], n: UnitVec3) -> f64 {
let Some(&o) = pts.first() else { return 0.0 };
pts.windows(2).map(|w| (w[0] - o).cross(w[1] - o).dot(n)).sum::<f64>() / 2.0
}
@@ -227,7 +227,7 @@ fn outline(b: &Body, mesh: &Mesh, f: usize, tol: f64) -> Result<Face> {
loops.push(lp);
}
let mut walls = std::collections::HashMap::new();
let mut wall = |g: u32| *walls.entry(g).or_insert_with(|| round_wall(b, &plane, n, g));
let mut wall = |g: u32| *walls.entry(g).or_insert_with(|| round_wall(b, &plane, *n, g));
// Each loop with the faces of its walls.
let mut shaped: Vec<(Vec<(Seg2, Option<u32>)>, Vec<usize>)> = loops
.iter()
@@ -388,7 +388,7 @@ fn bend_cylinder(b: &Body, mesh: &Mesh, f: usize, tol: f64) -> Option<Chamfer> {
let Some(FaceSurface::Plane { normal: n, .. }) = face_surface(b, g) else { continue };
let radial = (p - origin) - axis * (p - origin).dot(axis);
if radial.normalized().is_some_and(|out| n.dot(out).abs() >= 1.0 - 1e-6) {
sides.push((g, n));
sides.push((g, *n));
}
}
let &[(a, na), (bb, nb)] = sides.as_slice() else { return None };
@@ -148,10 +148,10 @@ fn transferred_thread_follows_body_frame_without_changing_world_axis() {
run(&mut s, "component.move_bodies", json!({"component":to,"bodies":["Shaft"]}));
let after = s.world_state().threads[0].clone();
assert!(after.axis_point.dist(before.axis_point) < 1e-6);
assert!(after.axis.dist(before.axis) < 1e-6);
assert!(after.axis.dist(*before.axis) < 1e-6);
let mut reopened = Session { doc: solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap().into(), ..Session::default() };
reopened.refresh();
assert!(reopened.world_state().threads[0].axis.dist(before.axis) < 1e-6);
assert!(reopened.world_state().threads[0].axis.dist(*before.axis) < 1e-6);
}
#[test]
+9 -9
View File
@@ -5,7 +5,7 @@
//! have a direction (planar faces, straight edges), the angle.
use serde_json::{Value, json};
use solidcraft_geom::{Mesh, Vec3};
use solidcraft_geom::{Mesh, UnitVec3, Vec3};
use super::measure_shape::{Shape, Slot, add_round, centre};
use crate::params::bad;
@@ -84,7 +84,7 @@ struct Item {
/// The circle through a polyline's points (all on one within `tol`): a fallback for edges the
/// kernel can't name (mesh bodies).
fn fit_circle(pts: &[Vec3], tol: f64) -> Option<(Vec3, Vec3, f64)> {
fn fit_circle(pts: &[Vec3], tol: f64) -> Option<(Vec3, UnitVec3, f64)> {
let n = pts.len().checked_sub(1)?;
let (a, b, c) = (*pts.first()?, *pts.get(n / 3)?, *pts.get(2 * n / 3)?);
let (u, v) = (b - a, c - a);
@@ -93,7 +93,7 @@ fn fit_circle(pts: &[Vec3], tol: f64) -> Option<(Vec3, Vec3, f64)> {
return None;
}
let center = a + (v * u.len2() - u * v.len2()).cross(w) * (1.0 / (2.0 * w.len2()));
let axis = w.normalized()?;
let axis = w.unit()?;
let radius = center.dist(a);
let on = pts.iter().all(|p| (p.dist(center) - radius).abs() <= tol && (*p - center).dot(axis).abs() <= tol);
(on && radius.is_finite()).then_some((center, axis, radius))
@@ -123,7 +123,7 @@ fn edge_round(b: &solidcraft_doc::ModelBody, m: &Mesh, index: usize, whole: bool
}
/// Points along a circle or arc (`angle` from `start` about `axis`).
fn arc_points(center: Vec3, axis: Vec3, start: Vec3, angle: f64) -> Vec<Vec3> {
fn arc_points(center: Vec3, axis: UnitVec3, start: Vec3, angle: f64) -> Vec<Vec3> {
let x = start - center;
let y = axis.cross(x);
let n = 128;
@@ -157,7 +157,7 @@ fn sketch_curve(ss: &solidcraft_doc::SolvedSketch, id: &str) -> Option<Item> {
let sk = &ss.sketch;
let c = sk.curves.get(sk.curve_index(id)?)?;
let at = |i: usize| sk.points.get(i).map(|p| ss.plane.to_world(p.pos));
let normal = ss.plane.normal();
let normal = ss.plane.normal().unit()?;
let (shape, pts) = match c.kind {
CurveKind::Circle { c, r } => {
let center = at(c)?;
@@ -203,7 +203,7 @@ fn profile(ss: &solidcraft_doc::SolvedSketch, index: usize) -> Option<Item> {
let pr = ss.profiles.get(index)?;
let outline: Vec<Vec3> = pr.region.outer.polyline(1e-3).iter().map(|p| ss.plane.to_world(*p)).collect();
let mut json = json!({"type": "profile", "area_mm2": pr.region.area()});
let normal = ss.plane.normal();
let normal = ss.plane.normal().unit()?;
// Arcs about one centre merge (a circle is two halves); straight pieces stay as they are.
let mut arcs: Vec<(Vec2, f64, f64)> = Vec::new();
let mut lines: Vec<(Vec2, Vec2)> = Vec::new();
@@ -242,7 +242,7 @@ fn profile(ss: &solidcraft_doc::SolvedSketch, index: usize) -> Option<Item> {
slot = Some(s);
}
}
let planar = Some(normal);
let planar = Some(*normal);
let geo = Geo::Points(densify(&outline));
let shape = if matches!(shape, Shape::Other) { Shape::Plane { point: ss.plane.origin, normal } } else { shape };
Some(Item { geo, dir: planar, json, shape, slot })
@@ -308,7 +308,7 @@ fn describe(s: &Session, sel: &Sel) -> Option<Item> {
let patch = m.surface_patch(*index);
let tris = patch.iter().flat_map(|f| face_tris(&m, *f)).collect::<Vec<_>>();
let area: f64 = tris.iter().map(|[a, b, c]| (*b - *a).cross(*c - *a).len() * 0.5).sum();
let normals: Vec<Vec3> = tris.iter().filter_map(|[a, b, c]| (*b - *a).cross(*c - *a).normalized()).collect();
let normals: Vec<UnitVec3> = tris.iter().filter_map(|[a, b, c]| (*b - *a).cross(*c - *a).unit()).collect();
let planar = normals.first().copied().filter(|n0| normals.iter().all(|n| n.dot(*n0) > 1.0 - 1e-6));
let mut json = json!({"type": "face", "area_mm2": area, "planar": planar.is_some()});
let verts: Vec<Vec3> = tris.iter().flat_map(|t| t.iter().copied()).collect();
@@ -328,7 +328,7 @@ fn describe(s: &Session, sel: &Sel) -> Option<Item> {
if let Some(sl) = &slot {
json["slot"] = sl.json();
}
Some(Item { geo: Geo::Tris(tris), dir: planar, json, shape, slot })
Some(Item { geo: Geo::Tris(tris), dir: planar.map(Vec3::from), json, shape, slot })
}
Sel::Body { name } => {
let m = st.body(name)?.mesh();
+25 -26
View File
@@ -4,7 +4,7 @@
//! round item measures from its centre or axis, with the closest and farthest distances too.
use serde_json::{Value, json};
use solidcraft_geom::Vec3;
use solidcraft_geom::{UnitVec3, Vec3};
use std::f64::consts::{PI, TAU};
@@ -17,7 +17,7 @@ pub(crate) enum Shape {
/// around the axis (2π all the way round).
Round {
center: Vec3,
axis: Vec3,
axis: UnitVec3,
radius: f64,
angle: f64,
planar: bool,
@@ -26,7 +26,7 @@ pub(crate) enum Shape {
},
Plane {
point: Vec3,
normal: Vec3,
normal: UnitVec3,
},
Line {
a: Vec3,
@@ -70,8 +70,7 @@ pub(crate) fn add_round(v: &mut Value, shape: &Shape) {
/// Cylinder `axis` through `origin` of radius `radius` over the points of its face: the
/// round shape, centred level with the middle of the face, with its extent and coverage.
pub(crate) fn cylinder(origin: Vec3, axis: Vec3, radius: f64, pts: &[Vec3]) -> Option<Shape> {
let axis = axis.normalized()?;
pub(crate) fn cylinder(origin: Vec3, axis: UnitVec3, radius: f64, pts: &[Vec3]) -> Option<Shape> {
if pts.is_empty() || !(radius.is_finite() && radius > 0.0) {
return None;
}
@@ -83,7 +82,7 @@ pub(crate) fn cylinder(origin: Vec3, axis: Vec3, radius: f64, pts: &[Vec3]) -> O
}
/// The angle around the axis the points cover: a whole turn less the widest gap between them.
pub(crate) fn coverage(center: Vec3, axis: Vec3, pts: &[Vec3]) -> f64 {
pub(crate) fn coverage(center: Vec3, axis: UnitVec3, pts: &[Vec3]) -> f64 {
let x = axis.any_perp();
let y = axis.cross(x);
let mut angles: Vec<f64> = pts
@@ -105,7 +104,7 @@ pub(crate) fn coverage(center: Vec3, axis: Vec3, pts: &[Vec3]) -> f64 {
}
/// The unit direction a point leaves the axis at, towards the middle of the face's points.
fn bulge(center: Vec3, axis: Vec3, pts: &[Vec3]) -> Option<Vec3> {
fn bulge(center: Vec3, axis: UnitVec3, pts: &[Vec3]) -> Option<Vec3> {
let sum = pts.iter().fold(Vec3::ZERO, |acc, p| {
let d = *p - center;
acc + (d - axis * d.dot(axis)).normalized().unwrap_or(Vec3::ZERO)
@@ -114,7 +113,7 @@ fn bulge(center: Vec3, axis: Vec3, pts: &[Vec3]) -> Option<Vec3> {
}
/// Closest points of two infinite lines (a point and a unit direction each).
fn line_line(p1: Vec3, d1: Vec3, p2: Vec3, d2: Vec3) -> (Vec3, Vec3) {
fn line_line(p1: Vec3, d1: UnitVec3, p2: Vec3, d2: UnitVec3) -> (Vec3, Vec3) {
let w = p1 - p2;
let b = d1.dot(d2);
let denom = 1.0 - b * b;
@@ -127,8 +126,8 @@ fn line_line(p1: Vec3, d1: Vec3, p2: Vec3, d2: Vec3) -> (Vec3, Vec3) {
(p1 + d1 * s, p2 + d2 * t)
}
fn parallel(a: Vec3, b: Vec3) -> bool {
a.cross(b).len() < 1e-6
fn parallel(a: impl Into<Vec3>, b: impl Into<Vec3>) -> bool {
a.into().cross(b).len() < 1e-6
}
/// A measurement from a round item's centre or axis.
@@ -214,7 +213,7 @@ fn from_round(a: &Shape, b: &Shape) -> Option<Centre> {
}
}
Shape::Line { a: la, b: lb } => {
let dir = (lb - la).normalized()?;
let dir = (lb - la).unit()?;
let across = dir.dot(na).abs() < 1e-6;
if pa {
// A circle/arc has a fixed centre. Project that point onto the picked
@@ -342,7 +341,7 @@ mod tests {
use solidcraft_geom::Vec2;
fn circle(c: Vec3, r: f64) -> Shape {
Shape::Round { center: c, axis: Vec3::Z, radius: r, angle: TAU, planar: true, lo: 0.0, hi: 0.0 }
Shape::Round { center: c, axis: UnitVec3::Z, radius: r, angle: TAU, planar: true, lo: 0.0, hi: 0.0 }
}
#[test]
@@ -367,8 +366,8 @@ mod tests {
#[test]
fn arcs_on_different_planes_measure_between_their_centres() {
let a = Shape::Round { center: Vec3::ZERO, axis: Vec3::Z, radius: 2.0, angle: PI, planar: true, lo: 0.0, hi: 0.0 };
let b = Shape::Round { center: Vec3::new(3.0, 4.0, 12.0), axis: Vec3::X, radius: 4.0, angle: PI / 2.0, planar: true, lo: 0.0, hi: 0.0 };
let a = Shape::Round { center: Vec3::ZERO, axis: UnitVec3::Z, radius: 2.0, angle: PI, planar: true, lo: 0.0, hi: 0.0 };
let b = Shape::Round { center: Vec3::new(3.0, 4.0, 12.0), axis: UnitVec3::X, radius: 4.0, angle: PI / 2.0, planar: true, lo: 0.0, hi: 0.0 };
let c = centre(&a, &b).unwrap();
assert_eq!((c.from, c.to, c.distance), (Vec3::ZERO, Vec3::new(3.0, 4.0, 12.0), 13.0));
assert!(c.min.is_none() && c.max.is_none());
@@ -377,10 +376,10 @@ mod tests {
#[test]
fn a_circle_to_a_cylinder_uses_its_fixed_centre_and_the_cylinders_axis() {
let a = circle(Vec3::new(0.0, 0.0, 10.0), 4.0);
for axis in [Vec3::Z, Vec3::X] {
for axis in [UnitVec3::Z, UnitVec3::X] {
let b = Shape::Round { center: Vec3::new(34.0, 19.0, 27.0), axis, radius: 4.0, angle: TAU, planar: false, lo: -5.0, hi: 5.0 };
let c = centre(&a, &b).unwrap();
let expected = if axis == Vec3::Z { Vec3::new(34.0, 19.0, 10.0) } else { Vec3::new(0.0, 19.0, 27.0) };
let expected = if axis == UnitVec3::Z { Vec3::new(34.0, 19.0, 10.0) } else { Vec3::new(0.0, 19.0, 27.0) };
assert_eq!((c.from, c.to), (Vec3::new(0.0, 0.0, 10.0), expected));
assert!((c.distance - c.from.dist(expected)).abs() < 1e-12);
let swapped = centre(&b, &a).unwrap();
@@ -390,8 +389,8 @@ mod tests {
#[test]
fn two_cylindrical_faces_still_measure_axis_pitch() {
let a = Shape::Round { center: Vec3::new(0.0, 0.0, 5.0), axis: Vec3::Z, radius: 4.0, angle: TAU, planar: false, lo: -5.0, hi: 5.0 };
let b = Shape::Round { center: Vec3::new(34.0, 19.0, 27.0), axis: Vec3::Z, radius: 4.0, angle: TAU, planar: false, lo: -5.0, hi: 5.0 };
let a = Shape::Round { center: Vec3::new(0.0, 0.0, 5.0), axis: UnitVec3::Z, radius: 4.0, angle: TAU, planar: false, lo: -5.0, hi: 5.0 };
let b = Shape::Round { center: Vec3::new(34.0, 19.0, 27.0), axis: UnitVec3::Z, radius: 4.0, angle: TAU, planar: false, lo: -5.0, hi: 5.0 };
let c = centre(&a, &b).unwrap();
assert_eq!((c.from, c.to), (Vec3::new(0.0, 0.0, 5.0), Vec3::new(34.0, 19.0, 5.0)));
assert!((c.distance - 1517_f64.sqrt()).abs() < 1e-12);
@@ -399,8 +398,8 @@ mod tests {
#[test]
fn a_cylinder_to_a_side_plane_measures_from_its_axis() {
let cyl = Shape::Round { center: Vec3::new(10.0, 15.0, 5.0), axis: Vec3::Z, radius: 2.5, angle: TAU, planar: false, lo: -5.0, hi: 5.0 };
let plane = Shape::Plane { point: Vec3::ZERO, normal: Vec3::new(-1.0, 0.0, 0.0) };
let cyl = Shape::Round { center: Vec3::new(10.0, 15.0, 5.0), axis: UnitVec3::Z, radius: 2.5, angle: TAU, planar: false, lo: -5.0, hi: 5.0 };
let plane = Shape::Plane { point: Vec3::ZERO, normal: -UnitVec3::X };
let c = centre(&cyl, &plane).unwrap();
assert!((c.distance - 10.0).abs() < 1e-12);
assert!((c.min.unwrap() - 7.5).abs() < 1e-12 && (c.max.unwrap() - 12.5).abs() < 1e-12);
@@ -408,12 +407,12 @@ mod tests {
let d = centre(&plane, &cyl).unwrap();
assert_eq!((d.from, d.to), (c.to, c.from));
// A cylinder crossing a plane has no single axis distance.
assert!(centre(&cyl, &Shape::Plane { point: Vec3::ZERO, normal: Vec3::Z }).is_none());
assert!(centre(&cyl, &Shape::Plane { point: Vec3::ZERO, normal: UnitVec3::Z }).is_none());
}
#[test]
fn an_axis_to_a_crossing_edge_is_the_distance_between_the_lines() {
let cyl = Shape::Round { center: Vec3::new(10.0, 15.0, 5.0), axis: Vec3::Z, radius: 2.5, angle: TAU, planar: false, lo: -5.0, hi: 5.0 };
let cyl = Shape::Round { center: Vec3::new(10.0, 15.0, 5.0), axis: UnitVec3::Z, radius: 2.5, angle: TAU, planar: false, lo: -5.0, hi: 5.0 };
let edge = Shape::Line { a: Vec3::new(0.0, 0.0, 10.0), b: Vec3::new(40.0, 0.0, 10.0) };
let c = centre(&cyl, &edge).unwrap();
assert!((c.distance - 15.0).abs() < 1e-12);
@@ -425,7 +424,7 @@ mod tests {
fn a_circle_or_arc_to_a_line_keeps_its_real_center() {
let edge = Shape::Line { a: Vec3::new(0.0, 0.0, 6.0), b: Vec3::new(68.0, 0.0, 6.0) };
for angle in [TAU, PI / 2.0] {
let round = Shape::Round { center: Vec3::new(34.0, 25.0, 20.0), axis: Vec3::Z, radius: 12.0, angle, planar: true, lo: 0.0, hi: 0.0 };
let round = Shape::Round { center: Vec3::new(34.0, 25.0, 20.0), axis: UnitVec3::Z, radius: 12.0, angle, planar: true, lo: 0.0, hi: 0.0 };
let c = centre(&round, &edge).unwrap();
assert_eq!((c.from, c.to), (Vec3::new(34.0, 25.0, 20.0), Vec3::new(34.0, 0.0, 6.0)));
assert!((c.distance - 25_f64.hypot(14.0)).abs() < 1e-12);
@@ -442,7 +441,7 @@ mod tests {
#[test]
fn a_tilted_arc_to_a_sloped_line_keeps_all_components() {
let edge = Shape::Line { a: Vec3::ZERO, b: Vec3::new(6.0, 0.0, 6.0) };
for axis in [Vec3::X, Vec3::Y, Vec3::Z] {
for axis in [UnitVec3::X, UnitVec3::Y, UnitVec3::Z] {
let arc = Shape::Round { center: Vec3::new(3.0, 4.0, 6.0), axis, radius: 2.0, angle: PI, planar: true, lo: 0.0, hi: 0.0 };
let c = centre(&arc, &edge).unwrap();
assert!(c.from.dist(Vec3::new(3.0, 4.0, 6.0)) < 1e-12);
@@ -468,8 +467,8 @@ mod tests {
let ring = |n: usize, span: f64| -> Vec<Vec3> {
(0..=n).map(|i| Vec3::new((span * i as f64 / n as f64).cos(), (span * i as f64 / n as f64).sin(), 0.0)).collect()
};
assert!((coverage(Vec3::ZERO, Vec3::Z, &ring(32, PI)) - PI).abs() < 1e-9);
assert_eq!(coverage(Vec3::ZERO, Vec3::Z, &ring(32, TAU)), TAU);
assert!((coverage(Vec3::ZERO, UnitVec3::Z, &ring(32, PI)) - PI).abs() < 1e-9);
assert_eq!(coverage(Vec3::ZERO, UnitVec3::Z, &ring(32, TAU)), TAU);
}
#[test]
+1 -1
View File
@@ -71,7 +71,7 @@ fn a_large_sheet_shows_its_small_bends_and_holes_round() {
let (mut bends, mut walls) = (0, 0);
for face in 0..b.body.face_count() {
let Some(FaceSurface::Cylinder { origin, axis, radius }) = face_surface(&b.body, face) else { continue };
let (steps, widest) = steps_around(&m, face, origin, axis);
let (steps, widest) = steps_around(&m, face, origin, *axis);
assert!(widest <= DISPLAY_ANGLE * 1.001, "radius {radius}: a facet spans {} degrees", widest.to_degrees());
if (radius - 2.0).abs() < 1e-6 {
// Half of a hole's wall.
+2
View File
@@ -27,6 +27,7 @@ pub mod section;
pub mod spline_space;
pub mod tess;
pub mod tspline;
mod unit_vec3;
mod vec;
pub use arcfit::MAX_FIT_PIECES;
@@ -35,6 +36,7 @@ pub use bvh::{Bvh, MeshIndex};
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};
pub use unit_vec3::UnitVec3;
pub use vec::{Vec2, Vec3};
/// Geometric tolerance for coincidence tests (mm).
+2 -2
View File
@@ -31,8 +31,8 @@ impl Plane {
}
/// Plane through `origin` with normal `n` (in-plane axes chosen deterministically).
pub fn from_normal(origin: Vec3, n: Vec3) -> Option<Plane> {
let n = n.normalized()?;
pub fn from_normal(origin: Vec3, n: impl Into<Vec3>) -> Option<Plane> {
let n = n.into().normalized()?;
// Horizontal planes keep world X as sketch x; others use the horizontal direction Z × n.
let cand = if n.dot(Vec3::Z).abs() > 0.9 { Vec3::X } else { Vec3::Z.cross(n) };
let x = (cand - n * cand.dot(n)).normalized()?;
+120
View File
@@ -0,0 +1,120 @@
//! A unit vector: a 3D vector of length 1.
use std::ops::{Add, Deref, Mul, Neg, Sub};
use serde::{Deserialize, Serialize};
use crate::Vec3;
/// A unit vector: length 1 up to rounding. Made only from a vector with a length
/// ([`UnitVec3::new`], [`Vec3::unit`]), so a function taking one need not normalise it or
/// handle a zero vector again. It reads as the [`Vec3`] it holds (`d.dot(v)`, `*d`), and
/// [`Vec3::dot`] and [`Vec3::cross`] take one.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(into = "Vec3", try_from = "Vec3")]
pub struct UnitVec3(Vec3);
impl UnitVec3 {
pub const X: UnitVec3 = UnitVec3(Vec3::X);
pub const Y: UnitVec3 = UnitVec3(Vec3::Y);
pub const Z: UnitVec3 = UnitVec3(Vec3::Z);
/// `v` scaled to length 1; `None` when it has no length (or is not finite).
pub fn new(v: Vec3) -> Option<UnitVec3> {
v.normalized().map(UnitVec3)
}
pub fn vec(self) -> Vec3 {
self.0
}
}
impl Vec3 {
/// This vector scaled to length 1 ([`UnitVec3::new`]).
pub fn unit(self) -> Option<UnitVec3> {
UnitVec3::new(self)
}
}
impl Deref for UnitVec3 {
type Target = Vec3;
fn deref(&self) -> &Vec3 {
&self.0
}
}
impl From<UnitVec3> for Vec3 {
fn from(d: UnitVec3) -> Vec3 {
d.0
}
}
impl TryFrom<Vec3> for UnitVec3 {
type Error = &'static str;
fn try_from(v: Vec3) -> Result<UnitVec3, Self::Error> {
UnitVec3::new(v).ok_or("a unit vector needs a finite vector with a length")
}
}
impl From<&UnitVec3> for Vec3 {
fn from(d: &UnitVec3) -> Vec3 {
d.0
}
}
impl Neg for UnitVec3 {
type Output = UnitVec3;
fn neg(self) -> UnitVec3 {
UnitVec3(-self.0)
}
}
/// `+` and `-` with a [`Vec3`] or another unit vector, giving a [`Vec3`].
macro_rules! sum_ops {
($($l:ty, $r:ty);*) => {$(
impl Add<$r> for $l {
type Output = Vec3;
fn add(self, o: $r) -> Vec3 {
Vec3::from(self) + Vec3::from(o)
}
}
impl Sub<$r> for $l {
type Output = Vec3;
fn sub(self, o: $r) -> Vec3 {
Vec3::from(self) - Vec3::from(o)
}
}
)*};
}
sum_ops!(UnitVec3, Vec3; Vec3, UnitVec3; UnitVec3, UnitVec3);
impl Mul<f64> for UnitVec3 {
type Output = Vec3;
fn mul(self, s: f64) -> Vec3 {
self.0 * s
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_unit_vector_has_length_one() {
let d = Vec3::new(0.0, 3.0, 4.0).unit().unwrap();
assert_eq!(*d, Vec3::new(0.0, 0.6, 0.8));
assert_eq!(d * 5.0, Vec3::new(0.0, 3.0, 4.0));
assert_eq!(*-d, Vec3::new(0.0, -0.6, -0.8));
assert_eq!(d.dot(Vec3::Z), 0.8);
assert_eq!(UnitVec3::Z.cross(UnitVec3::X), Vec3::Y);
assert_eq!(Vec3::X.dot(d), 0.0);
assert_eq!(Vec3::X + d, Vec3::new(1.0, 0.6, 0.8));
assert!((d - UnitVec3::Z).dist(Vec3::new(0.0, 0.6, -0.2)) < 1e-15);
}
#[test]
fn no_length_no_unit_vector() {
assert_eq!(Vec3::ZERO.unit(), None);
assert_eq!(Vec3::new(f64::NAN, 0.0, 1.0).unit(), None);
assert_eq!(Vec3::new(f64::INFINITY, 0.0, 0.0).unit(), None);
}
}
+6 -2
View File
@@ -96,10 +96,14 @@ impl Vec3 {
pub const fn new(x: f64, y: f64, z: f64) -> Self {
Vec3 { x, y, z }
}
pub fn dot(self, o: Vec3) -> f64 {
/// Takes a [`Vec3`] or a [`UnitVec3`](crate::UnitVec3).
pub fn dot(self, o: impl Into<Vec3>) -> f64 {
let o = o.into();
self.x * o.x + self.y * o.y + self.z * o.z
}
pub fn cross(self, o: Vec3) -> Vec3 {
/// Takes a [`Vec3`] or a [`UnitVec3`](crate::UnitVec3).
pub fn cross(self, o: impl Into<Vec3>) -> Vec3 {
let o = o.into();
Vec3::new(self.y * o.z - self.z * o.y, self.z * o.x - self.x * o.z, self.x * o.y - self.y * o.x)
}
pub fn len(self) -> f64 {
+11 -3
View File
@@ -3,14 +3,22 @@
//! cylinder recut from silently removing an additional material boundary that
//! the fallback's coarse material samples do not see.
use crate::body::{Body, from_p3};
use solidcraft_geom::{Plane, Seg2, Vec3};
use solidcraft_geom::{Plane, Seg2, UnitVec3, Vec3};
use std::collections::HashSet;
use truck_modeling as mt;
pub(super) fn boundaries_clear(body: &Body, bore_faces: &[usize], origin: Vec3, axis: Vec3, radius: f64, lo: f64, hi: f64, tol: f64) -> Option<()> {
pub(super) fn boundaries_clear(
body: &Body,
bore_faces: &[usize],
origin: Vec3,
axis: UnitVec3,
radius: f64,
lo: f64,
hi: f64,
tol: f64,
) -> Option<()> {
let plane = Plane::from_normal(origin, axis)?;
if !origin.is_finite()
|| !axis.is_finite()
|| ![radius, lo, hi, tol].iter().all(|v| v.is_finite())
|| radius <= tol
|| hi <= lo
+2 -2
View File
@@ -1,6 +1,6 @@
#![allow(clippy::unwrap_used, clippy::panic)]
use crate::*;
use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3};
use solidcraft_geom::{Loop2, Plane, Region2, Seg2, UnitVec3, Vec2, Vec3};
fn fixture() -> (Body, Body, Vec3, f64) {
let slope = 1f64.to_radians().tan();
@@ -113,7 +113,7 @@ fn unproved_curved_boundary_between_clear_endpoints_refuses_recut() {
assert!(a.len() > 5. && b.len() > 5., "endpoint samples miss the interior excursion");
assert!(body.tessellate_with(1e-4, true).unwrap().contains(Vec3::new(4.5, 0., 16.06)));
let before = step_export(&[&body], "curved source").unwrap();
assert!(crate::bore_guard::boundaries_clear(&body, &[], Vec3::ZERO, Vec3::Z, 5., 14., 24., 1e-6).is_none());
assert!(crate::bore_guard::boundaries_clear(&body, &[], Vec3::ZERO, UnitVec3::Z, 5., 14., 24., 1e-6).is_none());
assert_eq!(step_export(&[&body], "curved source").unwrap(), before);
}
+3 -3
View File
@@ -14,7 +14,7 @@
//! band, a hole that is not round all the way, a pin end inside the hole), the overlap is not
//! answered here and the caller takes the general boolean.
use solidcraft_geom::{Aabb3, Vec3};
use solidcraft_geom::{Aabb3, UnitVec3, Vec3};
use crate::body::Body;
use crate::{BoolOp, FaceSurface};
@@ -43,7 +43,7 @@ const STEP: f64 = 0.1;
struct Wall {
faces: Vec<usize>,
origin: Vec3,
axis: Vec3,
axis: UnitVec3,
radius: f64,
/// Material inside the cylinder (a pin), not outside it (a hole).
boss: bool,
@@ -209,7 +209,7 @@ fn cylinders(b: &Body) -> Vec<Wall> {
(0..b.face_count())
.filter_map(|i| match crate::face_surface(b, i)? {
FaceSurface::Cylinder { origin, axis, radius } if origin.is_finite() && radius.is_finite() && radius > 0.0 => {
Some(Wall { faces: vec![i], origin, axis: axis.normalized()?, radius, boss: false, spans: Vec::new() })
Some(Wall { faces: vec![i], origin, axis, radius, boss: false, spans: Vec::new() })
}
_ => None,
})
+3 -3
View File
@@ -24,7 +24,7 @@
use std::collections::HashMap;
use solidcraft_geom::{Aabb3, Vec3};
use solidcraft_geom::{Aabb3, UnitVec3, Vec3};
use truck_modeling::{self as mt, builder};
use crate::body::shell_groups::boxes_separate;
@@ -1475,7 +1475,7 @@ fn inset_into(outer: &Body, inner: &Body, outer_operand: usize) -> Option<Result
struct CylFace {
index: usize,
origin: Vec3,
axis: Vec3,
axis: UnitVec3,
radius: f64,
}
@@ -1637,7 +1637,7 @@ pub(crate) fn bore_union(a: &Body, b: &Body, accept: &dyn Fn(&Body) -> bool) ->
return Err(KernelError::Failed("narrowing a bore: an unsound result".into()));
}
let Some(joined) = crate::ops::boolean(target, &narrowed, BoolOp::Union)? else { return Ok(None) };
let cut = crate::build::cylinder(at(lo, 0.0, 0.0), c.axis, c.radius, hi - lo)?;
let cut = crate::build::cylinder(at(lo, 0.0, 0.0), *c.axis, c.radius, hi - lo)?;
let Some(r) = crate::ops::boolean(&joined, &cut, BoolOp::Cut)? else { return Ok(None) };
let h = recut(&r, &joined, &narrowed, &cut, &bore, tool_operand);
Ok(Some(r.with_checked_history(h, &record::counts(&[a, b]))))
+8 -8
View File
@@ -4,7 +4,7 @@
use std::collections::HashMap;
use std::f64::consts::{FRAC_PI_2, PI, TAU};
use solidcraft_geom::{Loop2, Mesh, Plane, Region2, Seg2, Vec2, Vec3};
use solidcraft_geom::{Loop2, Mesh, Plane, Region2, Seg2, UnitVec3, Vec2, Vec3};
use super::{Body, DISPLAY_ANGLE};
use crate::{FaceSurface, extrude, face_surface};
@@ -46,7 +46,7 @@ fn plate_with_holes(centres: &[Vec2], radius: f64) -> Body {
}
/// The faces of a body on cylinders of this radius.
fn cylinder_faces(b: &Body, radius: f64) -> Vec<(usize, Vec3, Vec3)> {
fn cylinder_faces(b: &Body, radius: f64) -> Vec<(usize, Vec3, UnitVec3)> {
(0..b.face_count())
.filter_map(|i| match face_surface(b, i)? {
FaceSurface::Cylinder { origin, axis, radius: r } if (r - radius).abs() < 1e-6 => Some((i, origin, axis)),
@@ -166,16 +166,16 @@ fn a_small_bend_on_a_large_sheet_is_meshed_round() {
assert_eq!(faces.len(), 1, "one bend face of radius {radius}");
let (face, origin, axis) = faces[0];
// The chord tolerance alone: one flat strip from tangent line to tangent line.
assert_eq!(angles_around(&coarse, face, origin, axis).len(), 2, "radius {radius}");
assert!(sag(&coarse, face, origin, axis, radius) > 0.29 * radius);
let a = angles_around(&round, face, origin, axis);
assert_eq!(angles_around(&coarse, face, origin, *axis).len(), 2, "radius {radius}");
assert!(sag(&coarse, face, origin, *axis, radius) > 0.29 * radius);
let a = angles_around(&round, face, origin, *axis);
assert!(a.len() > facets, "radius {radius}: {} facets across the bend", a.len() - 1);
assert!((a[a.len() - 1] - FRAC_PI_2).abs() < 1e-6, "the bend is a quarter turn: {a:?}");
let widest = a.windows(2).map(|w| w[1] - w[0]).fold(0.0, f64::max);
assert!(widest <= DISPLAY_ANGLE * 1.001, "radius {radius}: a facet spans {} degrees", widest.to_degrees());
// Within the chord tolerance of the cylinder, and by much: a facet that turns no more
// than the angle sags no more than 1 - cos(angle / 2) of the radius.
let s = sag(&round, face, origin, axis, radius);
let s = sag(&round, face, origin, *axis, radius);
assert!(s <= radius * (1.0 - (DISPLAY_ANGLE / 2.0).cos()) * 1.001 && s < tol, "radius {radius}: sag {s}");
}
// The flat faces along the sheet meet the bends in straight lines and need nothing more:
@@ -236,9 +236,9 @@ fn a_small_hole_on_a_large_plate_has_a_round_rim() {
}
// The hole's wall follows its rims.
for (face, origin, axis) in cylinder_faces(&b, 2.0) {
let a = angles_around(&round, face, origin, axis);
let a = angles_around(&round, face, origin, *axis);
assert!(a.windows(2).map(|w| w[1] - w[0]).fold(0.0, f64::max) <= DISPLAY_ANGLE * 1.001);
assert!(sag(&round, face, origin, axis, 2.0) <= 2.0 * (1.0 - (DISPLAY_ANGLE / 2.0).cos()) * 1.001);
assert!(sag(&round, face, origin, *axis, 2.0) <= 2.0 * (1.0 - (DISPLAY_ANGLE / 2.0).cos()) * 1.001);
}
assert_eq!(open_sides(&round, 1e-6), 0);
}
+8 -7
View File
@@ -120,7 +120,7 @@ fn crossings_that_are_not_touching_are_left_alone() {
let r = 10.0;
let size = 100.0;
let tol = size * 1e-6;
let cyl = |face, origin: Vec3, axis: Vec3, radius| tangent_cylinders::Cylinder::new(face, origin, axis, radius);
let cyl = |face, origin: Vec3, axis: Vec3, radius| tangent_cylinders::Cylinder::new(face, origin, axis, radius).unwrap();
let z = cyl(0, Vec3::ZERO, Vec3::Z, r);
// Different radius, parallel axes, skew axes: no touching points to split at.
assert!(tangent_cylinders::crossing(&z, &cyl(1, Vec3::ZERO, Vec3::Y, r * 0.9), tol).is_none());
@@ -137,13 +137,14 @@ fn crossings_that_are_not_touching_are_left_alone() {
fn hostile_cylinders_are_refused() {
let tol = 1e-4;
let cyl = |axis: Vec3, radius, origin: Vec3| tangent_cylinders::Cylinder::new(0, origin, axis, radius);
let good = cyl(Vec3::Z, 10.0, Vec3::ZERO);
// An axis with no direction cannot make a cylinder at all.
assert!(cyl(Vec3::new(f64::NAN, 0.0, 1.0), 10.0, Vec3::ZERO).is_none());
assert!(cyl(Vec3::ZERO, 10.0, Vec3::ZERO).is_none());
let good = cyl(Vec3::Z, 10.0, Vec3::ZERO).unwrap();
for bad in [
cyl(Vec3::new(f64::NAN, 0.0, 1.0), 10.0, Vec3::ZERO),
cyl(Vec3::Y, f64::NAN, Vec3::ZERO),
cyl(Vec3::Y, f64::INFINITY, Vec3::ZERO),
cyl(Vec3::Y, 10.0, Vec3::new(f64::INFINITY, 0.0, 0.0)),
cyl(Vec3::ZERO, 10.0, Vec3::ZERO),
cyl(Vec3::Y, f64::NAN, Vec3::ZERO).unwrap(),
cyl(Vec3::Y, f64::INFINITY, Vec3::ZERO).unwrap(),
cyl(Vec3::Y, 10.0, Vec3::new(f64::INFINITY, 0.0, 0.0)).unwrap(),
] {
assert!(tangent_cylinders::crossing(&good, &bad, tol).is_none(), "{bad:?}");
}
-1
View File
@@ -36,7 +36,6 @@ fn next_split(body: &Body) -> Option<(usize, Plane)> {
FaceSurface::Cone { apex, axis, .. } => (apex, axis),
_ => return None,
};
let axis = axis.normalized()?;
let p = from_p3(seam.front().point());
let off = p - origin;
let radial: Vec3 = (off - axis * off.dot(axis)).normalized()?;
+12 -9
View File
@@ -9,7 +9,7 @@
use std::collections::HashMap;
use mt::{BoundedCurve, InnerSpace, MetricSpace, ParametricCurve, ParametricSurface, ParametricSurface3D, SearchNearestParameter};
use solidcraft_geom::{Plane, Seg2, Vec2, Vec3};
use solidcraft_geom::{Plane, Seg2, UnitVec3, Vec2, Vec3};
use truck_meshalgo::tessellation::RobustMeshableShape;
use truck_modeling as mt;
@@ -41,7 +41,7 @@ enum Field {
/// +1 when the tool's normal points away from the axis.
Cylinder {
o: Vec3,
axis: Vec3,
axis: UnitVec3,
r: f64,
out: f64,
},
@@ -464,7 +464,7 @@ fn fit_on(g: &Field, face: &mt::Face, pts: &[mt::Point3], scale: f64) -> Result<
&& a.distance(*b) > scale * 1e-9
{
let n = pl.normal();
if n.cross(crate::body::v3(*axis)).magnitude() < 1e-9 {
if n.cross(crate::body::v3(axis.vec())).magnitude() < 1e-9 {
let (va, vb) = (mt::Vertex::new(*a), mt::Vertex::new(*b));
let e = guard("split arc", || Ok(mt::builder::circle_arc(&va, &vb, *m)))?;
return Ok(e.curve());
@@ -908,7 +908,7 @@ fn surface_field(s: &mt::Surface) -> Field {
for along_v in [true, false] {
let pt = |t: f64, w: f64| if along_v { at(t, w) } else { at(w, t) };
let d = pt(0.0, 1.0) - pt(0.0, 0.0);
let Some(axis) = d.normalized() else { continue };
let Some(axis) = d.unit() else { continue };
let straight = (0..=6).all(|k| {
let t = k as f64 / 6.0;
(0..=4).all(|m| (pt(t, m as f64 / 4.0) - pt(t, 0.0) - d * (m as f64 / 4.0)).len() <= tol)
@@ -940,7 +940,7 @@ fn surface_field(s: &mt::Surface) -> Field {
/// A plane or circular cylinder behind a surface (for offsetting).
pub(crate) enum Analytic {
Plane { n: Vec3 },
Cylinder { o: Vec3, axis: Vec3, r: f64, out: f64 },
Cylinder { o: Vec3, axis: UnitVec3, r: f64, out: f64 },
}
pub(crate) fn analytic_field(s: &mt::Surface) -> Option<Analytic> {
@@ -998,9 +998,12 @@ fn fields(tool: &SplitTool) -> Result<Vec<Field>> {
let n = plane.normal().cross(wb - wa).normalized().ok_or_else(|| KernelError::Invalid("a zero-length split line".into()))?;
Field::Plane { o: wa, n }
}
[Seg2::Arc { center, radius, .. }] if radius.is_finite() && *radius > 0.0 => {
Field::Cylinder { o: plane.to_world(*center), axis: plane.normal(), r: *radius, out: 1.0 }
}
[Seg2::Arc { center, radius, .. }] if radius.is_finite() && *radius > 0.0 => Field::Cylinder {
o: plane.to_world(*center),
axis: plane.normal().unit().ok_or_else(|| KernelError::Invalid("a sketch plane with no normal".into()))?,
r: *radius,
out: 1.0,
},
segs => {
let mut pts: Vec<Vec2> = Vec::new();
for sg in segs {
@@ -1265,7 +1268,7 @@ pub fn split_body(body: &Body, tool: &SplitTool) -> Result<Vec<Body>> {
let x = (if axis.x.abs() < 0.9 { Vec3::X } else { Vec3::Y }).cross(*axis).normalized().unwrap_or(Vec3::X);
let (a, b) = (*o + *axis * lo + x * *r, *o + *axis * hi + x * *r);
let line = mt::Curve::Line(mt::Line(p3(a), p3(b)));
crate::step_in::geom::revolved_oriented(line, p3(*o), crate::body::v3(*axis), 0.5, crate::body::v3(x * *out))
crate::step_in::geom::revolved_oriented(line, p3(*o), crate::body::v3(axis.vec()), 0.5, crate::body::v3(x * *out))
}
Field::Surface(s) => s.clone(),
Field::Curve { .. } => return Err(KernelError::Invalid("a body is split by a plane or a face".into())),
+9 -9
View File
@@ -26,8 +26,8 @@
use std::collections::HashMap;
use mt::{BoundedCurve, ParametricCurve, ParametricSurface};
use solidcraft_geom::Vec3;
use solidcraft_geom::tess::EvalSurface;
use solidcraft_geom::{UnitVec3, Vec3};
use truck_modeling as mt;
use crate::body::{Body, from_p3, p3};
@@ -145,9 +145,9 @@ struct Local {
/// Its parameters on the surface (unwrapped along the loop).
q: [f64; 2],
/// The surface's unit normal (`S_u × S_v`, as the parameters run).
n: Vec3,
n: UnitVec3,
/// The edge's unit direction as the loop runs, in the tangent plane.
d: Vec3,
d: UnitVec3,
/// Unit, in the tangent plane, square to the edge, away from the face.
out: Vec3,
su: Vec3,
@@ -247,7 +247,7 @@ impl Frame {
let n = normal(su, sv)?;
let dc = curve.der(t);
let dc = Vec3::new(dc.x, dc.y, dc.z);
let d = (dc - n * dc.dot(n)).normalized().ok_or_else(|| KernelError::Invalid("an edge to extend has no direction".into()))?;
let d = (dc - n * dc.dot(n)).unit().ok_or_else(|| KernelError::Invalid("an edge to extend has no direction".into()))?;
Ok(Local { p, q, n, d, out: d.cross(n) * self.ccw, su, sv })
}
@@ -262,12 +262,12 @@ impl Frame {
}
/// The unit normal from the parameter derivatives; refused at a pole (where it has none).
fn normal(su: Vec3, sv: Vec3) -> Result<Vec3> {
fn normal(su: Vec3, sv: Vec3) -> Result<UnitVec3> {
let c = su.cross(sv);
if !(c.len() > 1e-12 * (su.len2() + sv.len2())) {
return Err(KernelError::Invalid("the extension runs into a pole of the surface (a point with no normal)".into()));
}
c.normalized().ok_or_else(|| KernelError::Invalid("the extension runs into a pole of the surface".into()))
c.unit().ok_or_else(|| KernelError::Invalid("the extension runs into a pole of the surface".into()))
}
/// The parameter step `(a, b)` with `a·S_u + b·S_v = w` for `w` in the tangent plane, its
@@ -392,11 +392,11 @@ impl<'a> Extension<'a> {
.ok_or_else(|| KernelError::Invalid("two extended edges turn back on each other at a corner".into()))?;
(r, None)
} else if pc {
if !self.opts.neighbours || smooth { (prev.out, None) } else { (-next.d, Some(i)) }
if !self.opts.neighbours || smooth { (prev.out, None) } else { ((-next.d).vec(), Some(i)) }
} else if !self.opts.neighbours || smooth {
(next.out, None)
} else {
(prev.d, Some(pi))
(prev.d.vec(), Some(pi))
};
for (chosen, l) in [(pc, &prev), (nc, &next)] {
if chosen && r.dot(l.out) < MIN_COS {
@@ -996,7 +996,7 @@ fn arc_param(fr: &Frame, q: [f64; 2], ab: [f64; 2], length: f64) -> Result<f64>
/// The surface's normal curvature along the tangent `a·S_u + b·S_v` (unit) at `q`, signed
/// toward `n`.
fn normal_curvature(s: &mt::Surface, q: [f64; 2], ab: [f64; 2], n: Vec3) -> f64 {
fn normal_curvature(s: &mt::Surface, q: [f64; 2], ab: [f64; 2], n: UnitVec3) -> f64 {
let (uu, uv, vv) = (s.uuder(q[0], q[1]), s.uvder(q[0], q[1]), s.vvder(q[0], q[1]));
let second = uu * (ab[0] * ab[0]) + uv * (2.0 * ab[0] * ab[1]) + vv * (ab[1] * ab[1]);
let k = Vec3::new(second.x, second.y, second.z).dot(n);
+18 -18
View File
@@ -1,7 +1,7 @@
//! What surface a face lies on (plane, cylinder, cone, sphere, torus), for construction
//! geometry: axes through round faces, centres of spheres and tori.
use solidcraft_geom::Vec3;
use solidcraft_geom::{UnitVec3, Vec3};
use truck_modeling as mt;
@@ -9,23 +9,23 @@ use crate::Body;
use crate::body::from_p3;
use crate::offset::{Surf, surf_of};
/// A face's analytic surface. Axes are unit vectors.
/// A face's analytic surface.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FaceSurface {
/// Outward unit normal and a point on the plane.
Plane {
normal: Vec3,
normal: UnitVec3,
point: Vec3,
},
Cylinder {
origin: Vec3,
axis: Vec3,
axis: UnitVec3,
radius: f64,
},
/// Apex, axis pointing into the cone, half-angle (radians).
Cone {
apex: Vec3,
axis: Vec3,
axis: UnitVec3,
half_angle: f64,
},
Sphere {
@@ -35,7 +35,7 @@ pub enum FaceSurface {
/// Centre of the ring, its axis, the ring (major) and tube (minor) radii.
Torus {
center: Vec3,
axis: Vec3,
axis: UnitVec3,
major: f64,
minor: f64,
},
@@ -50,11 +50,11 @@ pub fn face_surface(b: &Body, face: usize) -> Option<FaceSurface> {
pub(crate) fn surface_of(f: &mt::Face, size: f64) -> Option<FaceSurface> {
let tol = (size * 1e-7).max(1e-9) * 100.0;
Some(match surf_of(f, tol)? {
Surf::Plane { n, d } => FaceSurface::Plane { normal: n, point: n * d },
Surf::Cylinder { o, a, r, .. } => FaceSurface::Cylinder { origin: o, axis: a, radius: r },
Surf::Cone { v, a, half, .. } => FaceSurface::Cone { apex: v, axis: a, half_angle: half },
Surf::Plane { n, d } => FaceSurface::Plane { normal: n.unit()?, point: n * d },
Surf::Cylinder { o, a, r, .. } => FaceSurface::Cylinder { origin: o, axis: a.unit()?, radius: r },
Surf::Cone { v, a, half, .. } => FaceSurface::Cone { apex: v, axis: a.unit()?, half_angle: half },
Surf::Sphere { c, r, .. } => FaceSurface::Sphere { center: c, radius: r },
Surf::Torus { o, a, big, h, r, .. } => FaceSurface::Torus { center: o + a * h, axis: a, major: big, minor: r },
Surf::Torus { o, a, big, h, r, .. } => FaceSurface::Torus { center: o + a * h, axis: a.unit()?, major: big, minor: r },
})
}
@@ -62,8 +62,8 @@ pub(crate) fn surface_of(f: &mt::Face, size: f64) -> Option<FaceSurface> {
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct EdgeCircle {
pub center: Vec3,
/// Unit normal of the circle's plane, oriented so the edge runs counter-clockwise about it.
pub axis: Vec3,
/// Normal of the circle's plane, oriented so the edge runs counter-clockwise about it.
pub axis: UnitVec3,
pub radius: f64,
/// The edge's ends (the same point for a closed circle).
pub start: Vec3,
@@ -106,7 +106,7 @@ fn circle_through(s: &[Vec3], tol: f64) -> Option<EdgeCircle> {
return None;
}
let center = a + (v * u.len2() - u * v.len2()).cross(w) * (1.0 / (2.0 * w.len2()));
let axis = w.normalized()?;
let axis = w.unit()?;
let radius = center.dist(a);
if !(radius.is_finite() && radius > tol) || s.iter().any(|p| (p.dist(center) - radius).abs() > tol || (*p - center).dot(axis).abs() > tol) {
return None;
@@ -132,7 +132,7 @@ fn circle_through(s: &[Vec3], tol: f64) -> Option<EdgeCircle> {
angle += d;
last = t;
}
let (axis, angle) = if angle < 0.0 { (axis * -1.0, -angle) } else { (axis, angle) };
let (axis, angle) = if angle < 0.0 { (-axis, -angle) } else { (axis, angle) };
let angle = if closed { std::f64::consts::TAU } else { angle.min(std::f64::consts::TAU) };
Some(EdgeCircle { center, axis, radius, start, end, angle })
}
@@ -180,19 +180,19 @@ mod tests {
/// Each surface's nearest point, worked out by hand.
#[test]
fn the_nearest_point_of_each_surface() {
let plane = FaceSurface::Plane { normal: Vec3::Z, point: Vec3::new(0.0, 0.0, 4.0) };
let plane = FaceSurface::Plane { normal: UnitVec3::Z, point: Vec3::new(0.0, 0.0, 4.0) };
assert!(near(plane.nearest(Vec3::new(3.0, 5.0, 9.0)), Vec3::new(3.0, 5.0, 4.0)));
// A cylinder of radius 5 about the line x = 1, y = 2: (7, 10, 3) is 10 from it along (3, 4)/5.
let cylinder = FaceSurface::Cylinder { origin: Vec3::new(1.0, 2.0, 0.0), axis: Vec3::Z, radius: 5.0 };
let cylinder = FaceSurface::Cylinder { origin: Vec3::new(1.0, 2.0, 0.0), axis: UnitVec3::Z, radius: 5.0 };
assert!(near(cylinder.nearest(Vec3::new(7.0, 10.0, 3.0)), Vec3::new(4.0, 6.0, 3.0)));
assert!(cylinder.nearest(Vec3::new(1.0, 2.0, 3.0)).is_none(), "on the axis every direction is as near");
let sphere = FaceSurface::Sphere { center: Vec3::new(1.0, 2.0, 3.0), radius: 5.0 };
assert!(near(sphere.nearest(Vec3::new(1.0, 2.0, 13.0)), Vec3::new(1.0, 2.0, 8.0)));
// A torus of ring radius 10 and tube radius 2 about Z: (14, 0, 0) is 2 beyond the tube's outside.
let torus = FaceSurface::Torus { center: Vec3::ZERO, axis: Vec3::Z, major: 10.0, minor: 2.0 };
let torus = FaceSurface::Torus { center: Vec3::ZERO, axis: UnitVec3::Z, major: 10.0, minor: 2.0 };
assert!(near(torus.nearest(Vec3::new(14.0, 0.0, 0.0)), Vec3::new(12.0, 0.0, 0.0)));
// A cone of half-angle 45 degrees: (2, 0, 0) is √2 along its line (1, 0, 1)/√2.
let cone = FaceSurface::Cone { apex: Vec3::ZERO, axis: Vec3::Z, half_angle: std::f64::consts::FRAC_PI_4 };
let cone = FaceSurface::Cone { apex: Vec3::ZERO, axis: UnitVec3::Z, half_angle: std::f64::consts::FRAC_PI_4 };
assert!(cone.nearest(Vec3::new(2.0, 0.0, 0.0)).is_some_and(|q| q.dist(Vec3::new(1.0, 0.0, 1.0)) < 1e-12));
assert!(plane.nearest(Vec3::new(f64::NAN, 0.0, 0.0)).is_none());
}
+2 -2
View File
@@ -8,7 +8,7 @@
use std::collections::HashMap;
use mt::{BoundedCurve, InnerSpace, MetricSpace, ParametricCurve, ParametricSurface3D, SearchNearestParameter};
use solidcraft_geom::{Plane, Region2, Seg2, Vec2, Vec3};
use solidcraft_geom::{Plane, Region2, Seg2, UnitVec3, Vec2, Vec3};
use truck_modeling as mt;
use crate::body::{Body, from_p3, p3};
@@ -706,7 +706,7 @@ pub fn stitch(bodies: &[&Body], tol: f64) -> Result<Body> {
#[derive(Clone, Copy)]
pub(crate) enum Offset {
Plane { n: Vec3 },
Cylinder { o: Vec3, axis: Vec3, r: f64, out: f64 },
Cylinder { o: Vec3, axis: UnitVec3, r: f64, out: f64 },
}
impl Offset {
+8 -9
View File
@@ -10,7 +10,7 @@
//! through the touching points (the solids are unchanged), and the result's history is composed
//! back over the operands as they were given.
use solidcraft_geom::{Plane, Vec3};
use solidcraft_geom::{Plane, UnitVec3, Vec3};
use truck_modeling::{ParametricCurve, SearchNearestParameter};
use crate::body::{Body, from_p3, p3};
@@ -27,22 +27,23 @@ const MAX_SPLITS: usize = 16;
pub(crate) struct Cylinder {
face: usize,
origin: Vec3,
axis: Vec3,
axis: UnitVec3,
radius: f64,
}
impl Cylinder {
#[cfg(test)]
pub(crate) fn new(face: usize, origin: Vec3, axis: Vec3, radius: f64) -> Self {
Self { face, origin, axis, radius }
/// `None` for an axis with no direction.
pub(crate) fn new(face: usize, origin: Vec3, axis: Vec3, radius: f64) -> Option<Self> {
Some(Self { face, origin, axis: axis.unit()?, radius })
}
}
fn cylinders(body: &Body) -> Vec<Cylinder> {
(0..body.face_count())
.filter_map(|face| match face_surface(body, face)? {
FaceSurface::Cylinder { origin, axis, radius } if origin.is_finite() && axis.is_finite() && radius.is_finite() => {
Some(Cylinder { face, origin, axis: axis.normalized()?, radius })
FaceSurface::Cylinder { origin, axis, radius } if origin.is_finite() && radius.is_finite() => {
Some(Cylinder { face, origin, axis, radius })
}
_ => None,
})
@@ -58,12 +59,10 @@ pub(crate) struct Crossing {
}
pub(crate) fn crossing(x: &Cylinder, y: &Cylinder, tol: f64) -> Option<Crossing> {
let finite = [x, y].iter().all(|c| c.origin.is_finite() && c.axis.is_finite() && c.radius.is_finite() && c.radius > 0.0);
let finite = [x, y].iter().all(|c| c.origin.is_finite() && c.radius.is_finite() && c.radius > 0.0);
if !finite || !tol.is_finite() || (x.radius - y.radius).abs() > tol {
return None;
}
// Unit axes, as the cross product below and the planes take them.
let (x, y) = (&Cylinder { axis: x.axis.normalized()?, ..*x }, &Cylinder { axis: y.axis.normalized()?, ..*y });
let across = x.axis.cross(y.axis);
// Axes within a hair of parallel touch along a line, which is another matter.
let sine = across.len();
+9 -10
View File
@@ -8,7 +8,7 @@
use std::collections::{BTreeMap, HashMap};
use serde::Serialize;
use solidcraft_geom::{Mesh, Vec3};
use solidcraft_geom::{Mesh, UnitVec3, Vec3};
use crate::Result;
use crate::body::{Body, from_p3};
@@ -24,7 +24,7 @@ pub struct TopoCounts {
#[derive(Clone, Copy, Debug, PartialEq)]
enum Surf {
Plane { n: Vec3, d: f64 },
Cylinder { axis: Vec3, p: Vec3, r: f64 },
Cylinder { axis: UnitVec3, p: Vec3, r: f64 },
Sphere { c: Vec3, r: f64 },
Cone { axis: Vec3, apex: Vec3, cos: f64 },
Other(usize),
@@ -97,7 +97,7 @@ fn classify(pts: &[Vec3], nrm: &[Vec3], tol: f64, id: usize) -> Surf {
}
// Cylinder: all normals perpendicular to one axis.
let far = nrm.iter().copied().min_by(|a, b| a.dot(n0).abs().total_cmp(&b.dot(n0).abs())).unwrap_or(n0);
if let Some(axis) = n0.cross(far).normalized()
if let Some(axis) = n0.cross(far).unit()
&& nrm.iter().all(|n| n.dot(axis).abs() < 2e-3)
{
let u = axis.any_perp();
@@ -381,10 +381,10 @@ fn classify_faces(b: &Body, mesh: &Mesh, nf: usize, tol: f64) -> Vec<Surf> {
.map(|(i, fit)| match (fit, faces.get(i)) {
(Surf::Sphere { .. } | Surf::Other(_), Some(face)) => match crate::offset::surf_of(face, exact_tol) {
Some(crate::offset::Surf::Plane { n, d }) => Surf::Plane { n, d },
Some(crate::offset::Surf::Cylinder { o, a, r, .. }) => {
let axis = if a.x + a.y * 1e-3 + a.z * 1e-6 < 0.0 { -a } else { a };
Surf::Cylinder { axis, p: o, r }
}
Some(crate::offset::Surf::Cylinder { o, a, r, .. }) => match a.unit() {
Some(a) => Surf::Cylinder { axis: if a.x + a.y * 1e-3 + a.z * 1e-6 < 0.0 { -a } else { a }, p: o, r },
None => fit,
},
Some(crate::offset::Surf::Sphere { c, r, .. }) => Surf::Sphere { c, r },
_ => fit,
},
@@ -636,7 +636,7 @@ pub fn merged_topology(b: &Body, mesh: &Mesh) -> Result<TopoCounts> {
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize)]
pub struct CylinderFace {
pub axis_point: Vec3,
pub axis: Vec3,
pub axis: UnitVec3,
pub radius: f64,
pub start: f64,
pub end: f64,
@@ -688,7 +688,6 @@ pub fn cylinder_face_at(b: &Body, p: Vec3) -> Option<CylinderFace> {
/// body's). `None` when the face is not part of a cylinder, or has no triangles.
pub fn cylinder_face(b: &Body, mesh: &Mesh, face: usize) -> Option<CylinderFace> {
let crate::FaceSurface::Cylinder { origin, axis, radius } = crate::face_surface(b, face)? else { return None };
let axis = axis.normalized()?;
let c = cylinder_extent(mesh, u32::try_from(face).ok()?, axis, origin, radius);
(c.start.is_finite() && c.end.is_finite()).then_some(c)
}
@@ -724,7 +723,7 @@ pub fn cylinder_end_at(b: &Body, p: Vec3) -> Option<CylinderFace> {
}
/// The extent along its axis, and the side, of a cylindrical face of a tessellated body.
fn cylinder_extent(mesh: &Mesh, face: u32, axis: Vec3, ap: Vec3, r: f64) -> CylinderFace {
fn cylinder_extent(mesh: &Mesh, face: u32, axis: UnitVec3, ap: Vec3, r: f64) -> CylinderFace {
let mut lo = f64::INFINITY;
let mut hi = f64::NEG_INFINITY;
let mut inward = 0.0;