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:
@@ -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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
|
||||
@@ -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]))))
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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:?}");
|
||||
}
|
||||
|
||||
@@ -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()?;
|
||||
|
||||
@@ -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())),
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user