From b0f814527460f274ceb6d9071ed5f71aed7b1a42 Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Sun, 8 Nov 2026 14:33:18 +0000 Subject: [PATCH 1/2] Drawings: where a thread's lines lie in a view (#13050) Drawings draw threads by ISO 6410's convention, not turn by turn. This adds the geometry in the drawing code: for a thread's axis, span and crest and root radii, its lines on a view's plane. Seen end on, the crest's circle and the root's three-quarter arc with its gap in the upper right; seen from the side, the crest and root lines and the limit lines asked for; seen at a slant, none. A thread that can't be drawn gives none, never a panic. The next commit draws them in views. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/drawing.rs | 1 + crates/doc/src/drawing/thread_lines.rs | 106 +++++++++ crates/doc/src/drawing/thread_lines_tests.rs | 220 +++++++++++++++++++ 3 files changed, 327 insertions(+) create mode 100644 crates/doc/src/drawing/thread_lines.rs create mode 100644 crates/doc/src/drawing/thread_lines_tests.rs diff --git a/crates/doc/src/drawing.rs b/crates/doc/src/drawing.rs index dc79bdb917a..6dc66788a81 100644 --- a/crates/doc/src/drawing.rs +++ b/crates/doc/src/drawing.rs @@ -77,6 +77,7 @@ pub mod note; pub mod symbol; pub mod table; pub mod template; +pub mod thread_lines; pub mod view; use balloon::Balloon; diff --git a/crates/doc/src/drawing/thread_lines.rs b/crates/doc/src/drawing/thread_lines.rs new file mode 100644 index 00000000000..770ebea1dc6 --- /dev/null +++ b/crates/doc/src/drawing/thread_lines.rs @@ -0,0 +1,106 @@ +//! A cosmetic thread's lines in a drawing view, as ISO 6410 draws them (#13050): where they lie on +//! the view's plane. Nothing here finds a body's threads or decides how a line is drawn; the view does. +//! +//! - The **crest** is the thread's outside for a screw (the major diameter) and its inside for a +//! tapped hole (the minor); it is drawn as the part's edges are. The **root** is the other one, +//! drawn thin: seen from the side, two lines along the thread; seen end on, three quarters of a +//! circle, its gap in the upper right quadrant. So for an M8 tapped hole the crest is the Ø6.8 +//! drilled hole and the root a thin arc of Ø8; for an M8 screw the crest is Ø8 and the root a thin +//! arc at the minor diameter. +//! - A **limit line** goes across the thread where its full form ends, as long as the major diameter. +//! - A thread seen at a slant draws no thread lines. +//! +//! Lines are in the view's plane coordinates ([`Plane::to_local`]), as a view's other lines, for +//! [`ViewFrame::seg_to_paper`](solidcraft_geom::drawing_view::ViewFrame::seg_to_paper). A view's +//! paper map turns nothing, so an angle in the plane is the same angle on paper. + +use solidcore_record::{Plane, Seg2, Vec3}; +use solidcraft_geom::UnitVec3; +use solidcraft_geom::prelude::*; +use solidcraft_geom::section::validate_plane; + +/// How near square or parallel to the view's normal a thread's axis must be, by the sine or cosine +/// of their angle, to be seen end on or from the side: the view's own test for a parallel line. +const PARALLEL: f64 = 1e-9; +/// The largest size of any number a thread is drawn from, in millimetres: the section's cap. +const MAX_NUMBER: f64 = 1e12; + +/// A thread as a view needs it: its axis, the threaded span along it, and its two radii. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Thread { + pub axis_point: Vec3, + pub axis: UnitVec3, + /// The threaded span, along the axis from `axis_point`. + pub start: f64, + pub end: f64, + /// The crest's and the root's radii: an internal thread's root is outside its crest, an + /// external one's inside. + pub crest_radius: f64, + pub root_radius: f64, + pub internal: bool, + /// Whether a limit line goes across at `start` and at `end`. + pub limits: [bool; 2], +} + +/// A thread's lines on a view's plane. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ThreadLines { + pub crest: Vec, + pub root: Vec, + pub limits: Vec, +} + +impl Thread { + /// Every number finite and within 1e12 mm, a span that runs forward, radii above zero, and the + /// root on its kind's side of the crest. + fn is_drawable(&self) -> bool { + let within = |v: f64| v.is_finite() && v.abs() <= MAX_NUMBER; + let p = self.axis_point; + let numbers = [p.x, p.y, p.z, self.start, self.end, self.crest_radius, self.root_radius].into_iter().all(within); + let root_side = if self.internal { self.root_radius > self.crest_radius } else { self.root_radius < self.crest_radius }; + numbers && self.start < self.end && self.crest_radius > 0.0 && self.root_radius > 0.0 && root_side + } +} + +/// `thread`'s lines in the view through `basis`: end on (its axis within [`PARALLEL`] of the view's +/// normal, by the sine of their angle), the crest's circle and the root's three-quarter arc; side +/// on (within [`PARALLEL`] of square to it, by the cosine), the crest's and the root's lines along +/// the span and the limit lines asked for. Seen at a slant, a thread that can't be drawn (any number +/// not finite, a span that doesn't run forward, a radius not above zero, the root on the wrong side +/// of the crest) or a basis that isn't one: none. +pub fn thread_lines(basis: &Plane, thread: &Thread) -> Option { + validate_plane(basis).ok()?; + if !thread.is_drawable() { + return None; + } + let axis = thread.axis.vec().normalized()?; + let normal = basis.x.cross(basis.y); + let on_plane = |along: f64| basis.to_local(thread.axis_point + axis * along); + if axis.cross(normal).len() <= PARALLEL { + let centre = on_plane(thread.start); + let circle = |radius: f64, start: f64, sweep: f64| Seg2::Arc { center: centre, radius, start, sweep }; + let quarter = std::f64::consts::FRAC_PI_2; + return Some(ThreadLines { + crest: vec![circle(thread.crest_radius, 0.0, 4.0 * quarter)], + root: vec![circle(thread.root_radius, quarter, 3.0 * quarter)], + limits: Vec::new(), + }); + } + if axis.dot(normal).abs() > PARALLEL { + return None; + } + let (from, to) = (on_plane(thread.start), on_plane(thread.end)); + let across = (to - from).normalized()?.perp(); + let pair = |radius: f64| [-1.0, 1.0].map(|side| Seg2::Line { a: from + across * (side * radius), b: to + across * (side * radius) }).to_vec(); + let major = thread.crest_radius.max(thread.root_radius); + let limits = [(thread.limits[0], from), (thread.limits[1], to)]; + Some(ThreadLines { + crest: pair(thread.crest_radius), + root: pair(thread.root_radius), + limits: limits.into_iter().filter(|(asked, _)| *asked).map(|(_, at)| Seg2::Line { a: at - across * major, b: at + across * major }).collect(), + }) +} + +#[cfg(test)] +#[path = "thread_lines_tests.rs"] +mod tests; diff --git a/crates/doc/src/drawing/thread_lines_tests.rs b/crates/doc/src/drawing/thread_lines_tests.rs new file mode 100644 index 00000000000..1409f9e068d --- /dev/null +++ b/crates/doc/src/drawing/thread_lines_tests.rs @@ -0,0 +1,220 @@ +use super::*; +use solidcore_record::Vec2; +use solidcraft_geom::drawing_view::{NamedView, Scale, ViewFrame, basis_looking}; +use std::f64::consts::{FRAC_PI_2, PI, TAU}; + +/// A small deterministic generator for seeded test data. +struct Lcg(u64); +impl Lcg { + fn unit(&mut self) -> f64 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (self.0 >> 11) as f64 / (1u64 << 53) as f64 + } +} + +const EPS: f64 = 1e-9; + +/// An M8 tapped hole 12 mm deep from `at`, down: the drilled Ø6.8 its crest, Ø8 its root. +fn tapped(at: Vec3, limits: [bool; 2]) -> Thread { + let down = UnitVec3::new(Vec3::new(0.0, 0.0, -1.0)).unwrap(); + Thread { axis_point: at, axis: down, start: 0.0, end: 12.0, crest_radius: 3.4, root_radius: 4.0, internal: true, limits } +} + +fn close(a: Vec2, b: Vec2) -> bool { + (a - b).len() < EPS +} + +fn ends(seg: &Seg2) -> (Vec2, Vec2) { + (seg.start(), seg.end()) +} + +/// Seen end on, an M8 tapped hole draws the Ø6.8 circle and a Ø8 arc of three quarters, its gap in +/// the upper right quadrant, centred on the axis: from above and from below alike. +#[test] +fn an_m8_tapped_hole_seen_end_on_is_a_circle_and_a_three_quarter_arc() { + for (view, centre) in [(NamedView::Top, Vec2::new(20.0, 5.0)), (NamedView::Bottom, Vec2::new(20.0, -5.0))] { + let lines = thread_lines(&view.basis(), &tapped(Vec3::new(20.0, 5.0, 0.0), [false, true])).unwrap(); + assert_eq!(lines.crest, vec![Seg2::Arc { center: centre, radius: 3.4, start: 0.0, sweep: TAU }], "{view:?}"); + assert_eq!(lines.root, vec![Seg2::Arc { center: centre, radius: 4.0, start: FRAC_PI_2, sweep: 3.0 * FRAC_PI_2 }], "{view:?}"); + // From 90° round to 360°: the gap is the upper right quadrant. + assert!(close(lines.root[0].start(), centre + Vec2::new(0.0, 4.0)) && close(lines.root[0].end(), centre + Vec2::new(4.0, 0.0))); + assert!(close(lines.root[0].point_at(0.5), centre + Vec2::from_angle(5.0 * PI / 4.0) * 4.0), "through the lower left"); + assert!(lines.limits.is_empty(), "end on, a limit line is a point"); + } +} + +/// Seen from the side, an M8 tapped hole 12 mm deep draws its root lines 8 apart and its crest lines +/// 6.8 apart, each as long as the thread, and one limit line 8 long at its inner end: to 1e-6 mm. +#[test] +fn an_m8_tapped_hole_seen_from_the_side_is_drawn_to_its_sizes() { + let lines = thread_lines(&NamedView::Front.basis(), &tapped(Vec3::new(20.0, 5.0, 0.0), [false, true])).unwrap(); + let apart = |pair: &[Seg2]| (pair[0].start() - pair[1].start()).len(); + assert!((apart(&lines.root) - 8.0).abs() < 1e-6 && (apart(&lines.crest) - 6.8).abs() < 1e-6); + for seg in lines.root.iter().chain(&lines.crest) { + assert!((seg.length() - 12.0).abs() < 1e-6); + let (a, b) = ends(seg); + assert!((a.y - 0.0).abs() < 1e-6 && (b.y + 12.0).abs() < 1e-6, "from the face down: {seg:?}"); + } + assert_eq!(lines.limits.len(), 1); + let (a, b) = ends(&lines.limits[0]); + assert!((a.dist(b) - 8.0).abs() < 1e-6 && (a.y + 12.0).abs() < 1e-6 && (b.y + 12.0).abs() < 1e-6 && close((a + b) * 0.5, Vec2::new(20.0, -12.0))); + let none = thread_lines(&NamedView::Front.basis(), &tapped(Vec3::new(20.0, 5.0, 0.0), [false, false])).unwrap(); + assert!(none.limits.is_empty()); + let start = thread_lines(&NamedView::Front.basis(), &tapped(Vec3::new(20.0, 5.0, 0.0), [true, false])).unwrap(); + assert!(close((start.limits[0].start() + start.limits[0].end()) * 0.5, Vec2::new(20.0, 0.0)), "the limit at the start"); +} + +/// An external M8 (a screw): its crest is the major diameter, the root inside it, the limit line +/// across the crest. +#[test] +fn an_external_thread_has_its_crest_outside() { + let screw = Thread { crest_radius: 4.0, root_radius: 3.3, internal: false, ..tapped(Vec3::ZERO, [false, true]) }; + let lines = thread_lines(&NamedView::Front.basis(), &screw).unwrap(); + let apart = |pair: &[Seg2]| (pair[0].start() - pair[1].start()).len(); + assert!((apart(&lines.crest) - 8.0).abs() < 1e-12 && (apart(&lines.root) - 6.6).abs() < 1e-12); + assert!((lines.limits[0].length() - 8.0).abs() < 1e-12); + let end_on = thread_lines(&NamedView::Top.basis(), &screw).unwrap(); + assert!(matches!(&end_on.root[..], [Seg2::Arc { radius, .. }] if *radius == 3.3)); +} + +/// A thread off the origin, in a slanted view, lies where its axis is seen: each line's ends on +/// paper are the model points it stands for, seen through the view. +#[test] +fn a_thread_in_a_slanted_view_lies_where_its_axis_is_seen() { + let basis = basis_looking(Vec3::new(1.0, -2.0, -0.5), Vec3::Z, Vec3::new(4.0, -3.0, 2.0)).unwrap(); + let frame = ViewFrame::new(basis, Scale::new(1.0, 2.0).unwrap(), Vec2::new(3.0, 1.0), Vec2::new(150.0, 100.0)).unwrap(); + let axis = UnitVec3::new(basis.x * 0.6 + basis.y * 0.8).unwrap(); + let thread = Thread { + axis_point: Vec3::new(30.0, 12.0, -7.0), + axis, + start: 2.0, + end: 17.0, + crest_radius: 5.0, + root_radius: 4.2, + internal: false, + limits: [true, true], + }; + let lines = thread_lines(&basis, &thread).unwrap(); + let across = axis.vec().cross(basis.x.cross(basis.y)); + let paper = |p: Vec3| frame.to_paper(p); + for (pair, radius) in [(&lines.crest, 5.0), (&lines.root, 4.2)] { + let wanted: Vec<(Vec2, Vec2)> = [-1.0, 1.0] + .iter() + .map(|side| { + let off = across * (side * radius); + (paper(thread.axis_point + axis.vec() * 2.0 + off), paper(thread.axis_point + axis.vec() * 17.0 + off)) + }) + .collect(); + for seg in pair { + let (a, b) = ends(&frame.seg_to_paper(seg)); + assert!(wanted.iter().any(|(wa, wb)| close(a, *wa) && close(b, *wb)), "{a:?} {b:?} in {wanted:?}"); + } + } + let limit = frame.seg_to_paper(&lines.limits[1]); + assert!(close((limit.start() + limit.end()) * 0.5, paper(thread.axis_point + axis.vec() * 17.0)), "the limit at the end"); +} + +/// End on and side on are each within `PARALLEL` (1e-9): 1e-10 off still counts, 1e-8 off is a +/// slant and draws nothing, as is 1° off. +#[test] +fn a_thread_at_a_slant_draws_nothing() { + let off = |tilt: f64| tapped(Vec3::ZERO, [false, true]).with_axis(Vec3::new(tilt, 0.0, -1.0)); + let top = NamedView::Top.basis(); + assert!(matches!(thread_lines(&top, &off(1e-10)), Some(l) if l.limits.is_empty())); + assert_eq!(thread_lines(&top, &off(1e-8)), None); + assert_eq!(thread_lines(&top, &off(1f64.to_radians().tan())), None); + let side = |tilt: f64| tapped(Vec3::ZERO, [false, true]).with_axis(Vec3::new(0.0, tilt, -1.0)); + let front = NamedView::Front.basis(); + assert!(matches!(thread_lines(&front, &side(1e-10)), Some(l) if l.limits.len() == 1)); + assert_eq!(thread_lines(&front, &side(1e-8)), None); + assert_eq!(thread_lines(&front, &side(1f64.to_radians().tan())), None); +} + +impl Thread { + fn with_axis(self, axis: Vec3) -> Thread { + Thread { axis: UnitVec3::new(axis).unwrap(), ..self } + } +} + +/// A thread that can't be drawn draws nothing, whatever is wrong with it, and nothing panics. +#[test] +fn hostile_threads_draw_nothing() { + let good = tapped(Vec3::new(1.0, 2.0, 3.0), [true, true]); + let front = NamedView::Front.basis(); + assert!(thread_lines(&front, &good).is_some()); + let mut bad = Vec::new(); + for v in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e300, -1.0000001e12] { + bad.push(Thread { axis_point: Vec3::new(v, 0.0, 0.0), ..good }); + bad.push(Thread { start: v, ..good }); + bad.push(Thread { end: v, ..good }); + bad.push(Thread { crest_radius: v, ..good }); + bad.push(Thread { root_radius: v, ..good }); + } + bad.extend([ + Thread { start: 12.0, ..good }, + Thread { start: 13.0, ..good }, + Thread { crest_radius: 0.0, ..good }, + Thread { root_radius: -4.0, ..good }, + // The root on the wrong side of the crest, for each kind, and equal to it. + Thread { crest_radius: 4.0, root_radius: 3.4, ..good }, + Thread { crest_radius: 4.0, root_radius: 4.0, ..good }, + Thread { internal: false, ..good }, + ]); + for thread in &bad { + assert_eq!(thread_lines(&front, thread), None, "{thread:?}"); + } + let skewed = Plane { origin: Vec3::ZERO, x: Vec3::X, y: Vec3::X }; + assert_eq!(thread_lines(&skewed, &good), None); + let huge = Plane { origin: Vec3::new(f64::NAN, 0.0, 0.0), ..front }; + assert_eq!(thread_lines(&huge, &good), None); +} + +/// Seeded threads in seeded views: nothing panics; every line is finite; side on, every line runs +/// along the seen axis and the limit lines across it. +#[test] +fn seeded_threads_draw_finite_lines_along_their_axis() { + let mut rng = Lcg(0x7d3); + let mut drawn = [0usize; 2]; + for _ in 0..5000 { + let unit = |rng: &mut Lcg| Vec3::new(rng.unit() - 0.5, rng.unit() - 0.5, rng.unit() - 0.5); + let Ok(basis) = basis_looking(unit(&mut rng), unit(&mut rng), unit(&mut rng) * 100.0) else { continue }; + let normal = basis.x.cross(basis.y); + let pick = rng.unit(); + let axis = if pick < 0.4 { + basis.x * (rng.unit() - 0.5) + basis.y * (rng.unit() - 0.5) + } else if pick < 0.8 { + normal * (rng.unit() - 0.5) + } else { + unit(&mut rng) + }; + let Some(axis) = UnitVec3::new(axis) else { continue }; + let scale = 10f64.powf(rng.unit() * 6.0 - 2.0); + let (crest, root) = (scale * (0.1 + rng.unit()), scale * (0.1 + rng.unit())); + let thread = Thread { + axis_point: unit(&mut rng) * scale * 10.0, + axis, + start: (rng.unit() - 0.5) * scale, + end: rng.unit() * scale, + crest_radius: crest, + root_radius: root, + internal: root > crest, + limits: [rng.unit() < 0.5, rng.unit() < 0.5], + }; + let Some(lines) = thread_lines(&basis, &thread) else { continue }; + let all: Vec<&Seg2> = lines.crest.iter().chain(&lines.root).chain(&lines.limits).collect(); + assert!(all.iter().all(|s| s.start().is_finite() && s.end().is_finite()), "{thread:?}"); + if lines.crest.len() == 2 { + drawn[1] += 1; + let seen = basis.to_local(thread.axis_point + axis.vec()) - basis.to_local(thread.axis_point); + for seg in lines.crest.iter().chain(&lines.root) { + assert!((seg.end() - seg.start()).cross(seen).abs() < 1e-9 * seg.length().max(1.0), "{thread:?}"); + } + for seg in &lines.limits { + assert!((seg.end() - seg.start()).dot(seen).abs() < 1e-9 * seg.length().max(1.0), "{thread:?}"); + } + } else { + drawn[0] += 1; + } + } + assert!(drawn.iter().all(|n| *n > 500), "{drawn:?}"); +} From 968746900a02bab3ee87d6f96697e2edac3ee18b Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Sun, 15 Nov 2026 16:50:01 +0000 Subject: [PATCH 2/2] Drawings: cosmetic threads drawn in views, seen where their crest is (#13050) A drawing view now draws each cosmetic thread its bodies carry by the ISO 6410 convention. End on, a thin three-quarter arc at the root, its gap in the upper right; from the side, two thin root lines along the thread and a limit line where it stops inside its face. The crest is the face's own edge or silhouette, which the view already draws. A root line lies inside its own body's material, so no hidden-line test can see it. Each thread line takes, stretch by stretch, the visibility of the crest line the view drew beside it (end on, the crest circle's at that angle). Hidden ones are dashed and appear only when the style draws hidden lines; a reference part's are thin; a shaded part's are left to its picture. Thread strokes can't be picked. The pairing is paper geometry in the drawing code (`thread_lines::on_paper`), with the chord-sag tolerance the view's exact arcs already use, now one function. The engine finds each shown body's threads and calls it at the end of a view's lines, so the sheet and the snapshot draw the same; the snapshot reports them as `threads`. A view's cache key holds each body's threads, since a cosmetic thread changes no geometry. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/drawing/thread_lines.rs | 227 +++++++++++++++- crates/doc/src/drawing/thread_lines_tests.rs | 272 +++++++++++++++++++ crates/engine/src/cmd/drawing_view.rs | 23 +- crates/engine/src/cmd/drawing_view_tests.rs | 115 ++++++++ crates/engine/src/drawing_scene.rs | 15 +- crates/engine/src/drawing_scene_tests.rs | 73 +++++ crates/engine/src/drawing_view.rs | 7 +- crates/engine/src/drawing_view_exact.rs | 2 +- crates/engine/src/drawing_view_lines.rs | 103 +++++-- crates/engine/src/drawing_view_threads.rs | 45 +++ crates/engine/src/schema/drawing_view.rs | 26 ++ 11 files changed, 879 insertions(+), 29 deletions(-) create mode 100644 crates/engine/src/drawing_view_threads.rs diff --git a/crates/doc/src/drawing/thread_lines.rs b/crates/doc/src/drawing/thread_lines.rs index 770ebea1dc6..0a06df8616c 100644 --- a/crates/doc/src/drawing/thread_lines.rs +++ b/crates/doc/src/drawing/thread_lines.rs @@ -10,15 +10,26 @@ //! - A **limit line** goes across the thread where its full form ends, as long as the major diameter. //! - A thread seen at a slant draws no thread lines. //! +//! - **Each thread line is seen where its crest is seen** ([`on_paper`]): a root line lies inside +//! its own body's material, so no hidden-line test can see it. It takes, stretch by stretch, the +//! visibility of the crest line the view drew beside it (end on, the crest circle at that angle); +//! where the view drew no crest, it draws nothing. +//! //! Lines are in the view's plane coordinates ([`Plane::to_local`]), as a view's other lines, for //! [`ViewFrame::seg_to_paper`](solidcraft_geom::drawing_view::ViewFrame::seg_to_paper). A view's //! paper map turns nothing, so an angle in the plane is the same angle on paper. -use solidcore_record::{Plane, Seg2, Vec3}; +use std::f64::consts::{PI, TAU}; + +use solidcore_record::{Plane, Seg2, Vec2, Vec3}; use solidcraft_geom::UnitVec3; +use solidcraft_geom::drawing_view::ViewFrame; +use solidcraft_geom::hlr::Visibility; use solidcraft_geom::prelude::*; use solidcraft_geom::section::validate_plane; +use crate::ThreadInfo; + /// How near square or parallel to the view's normal a thread's axis must be, by the sine or cosine /// of their angle, to be seen end on or from the side: the view's own test for a parallel line. const PARALLEL: f64 = 1e-9; @@ -51,6 +62,27 @@ pub struct ThreadLines { } impl Thread { + /// A cosmetic thread as a view draws it: its crest is the threaded face's own radius; its root + /// is the major radius for a tapped hole, and for a screw the minor radius a modelled thread is + /// cut to ([`crate::thread_forms::ThreadForm::groove`]), so the two draw alike. A taper thread + /// draws none: its lines are not parallel to its axis. No limit lines: [`on_paper`] finds them. + pub fn of(info: &ThreadInfo) -> Option { + if info.form.is_taper() { + return None; + } + let root_radius = if info.internal { info.major_diameter / 2.0 } else { info.form.groove(info.major_diameter, info.pitch, false).root_r }; + Some(Thread { + axis_point: info.axis_point, + axis: info.axis, + start: info.start, + end: info.end, + crest_radius: info.radius, + root_radius, + internal: info.internal, + limits: [false, false], + }) + } + /// Every number finite and within 1e12 mm, a span that runs forward, radii above zero, and the /// root on its kind's side of the crest. fn is_drawable(&self) -> bool { @@ -101,6 +133,199 @@ pub fn thread_lines(basis: &Plane, thread: &Thread) -> Option { }) } +/// One run of a line the view drew, at one visibility, on paper: where a crest may lie. +#[derive(Clone, Copy, Debug)] +pub struct Drawn<'a> { + pub visibility: Visibility, + pub path: &'a [Seg2], +} + +/// Which of a thread's lines a piece is: a root line (drawn thin) or a limit line (drawn as the +/// part's edges are). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ThreadStroke { + Root, + Limit, +} + +/// A run of a thread line at one visibility, on paper. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ThreadPiece { + pub stroke: ThreadStroke, + pub visibility: Visibility, + pub seg: Seg2, +} + +/// `thread`'s root and limit lines in the view `frame` places on paper, each seen where the crest +/// beside it is among `drawn` (the lines the view drew of the thread's body), to within `near_mm` on +/// paper. Side on, a root line takes the visibility of the crest line on its own side; a limit line +/// goes where the thread ends while a crest runs on (the thread stops inside its face) and takes the +/// crests' visibility there. End on, the root arc takes the crest circle's by angle. Where crests of +/// several visibilities overlap, the one most seen wins ([`rank`]). Nothing for a thread +/// [`thread_lines`] draws nothing for, or a `near_mm` that isn't a finite size. +pub fn on_paper(frame: &ViewFrame, thread: &Thread, drawn: &[Drawn<'_>], near_mm: f64) -> Vec { + let basis = frame.basis(); + let Some(lines) = thread_lines(&basis, thread) else { return Vec::new() }; + if !(near_mm.is_finite() && near_mm >= 0.0) { + return Vec::new(); + } + let segs = || drawn.iter().flat_map(|d| d.path.iter().map(move |seg| (d.visibility, seg))); + let paper = |segs: &[Seg2]| segs.iter().map(|s| frame.seg_to_paper(s)).collect::>(); + match (paper(&lines.crest).as_slice(), paper(&lines.root).as_slice()) { + ([crest], [root]) => end_on(crest, root, segs(), near_mm), + ([crest_a, crest_b], [root_a, root_b]) => { + // Along each side's crest, from the thread's start: the stretches the view drew of it. + let mut sides = Vec::with_capacity(2); + for (crest, root) in [(crest_a, root_a), (crest_b, root_b)] { + let Some(dir) = (crest.end() - crest.start()).normalized() else { return Vec::new() }; + let spans: Vec = segs().filter_map(|(visibility, seg)| along_line(seg, crest.start(), dir, near_mm, visibility)).collect(); + sides.push((*root, dir, spans)); + } + let length = crest_a.length(); + let mut out = Vec::new(); + for (root, dir, spans) in &sides { + let stretch = |(lo, hi, visibility)| ThreadPiece { + stroke: ThreadStroke::Root, + visibility, + seg: Seg2::Line { a: root.start() + *dir * lo, b: root.start() + *dir * hi }, + }; + out.extend(runs(0.0, length, spans, near_mm).into_iter().map(stretch)); + } + let all: Vec = sides.into_iter().flat_map(|(.., spans)| spans).collect(); + let first = all.iter().map(|s| s.lo).fold(f64::INFINITY, f64::min); + let last = all.iter().map(|s| s.hi).fold(f64::NEG_INFINITY, f64::max); + let ends = [(first < -near_mm, 0.0), (last > length + near_mm, length)]; + // thread_lines gives the limit lines asked for, in the order of the ends. + let Some(limits) = thread_lines(&basis, &Thread { limits: ends.map(|(inside, _)| inside), ..*thread }) else { return out }; + let at = ends.into_iter().filter(|(inside, _)| *inside).map(|(_, t)| t); + for (t, limit) in at.zip(&limits.limits) { + if let Some(visibility) = seen_at(&all, t, near_mm) { + out.push(ThreadPiece { stroke: ThreadStroke::Limit, visibility, seg: frame.seg_to_paper(limit) }); + } + } + out + } + _ => Vec::new(), + } +} + +/// A stretch of a crest the view drew: from `lo` to `hi` along it (millimetres on paper, or radians +/// round a circle), at one visibility. +#[derive(Clone, Copy, Debug)] +struct Span { + lo: f64, + hi: f64, + visibility: Visibility, +} + +/// Which visibility wins where crests overlap: the most seen. +fn rank(visibility: Visibility) -> u8 { + match visibility { + Visibility::Visible => 2, + Visibility::Uncertain => 1, + Visibility::Hidden => 0, + } +} + +/// End on: the root arc, cut where the crest circle's visibility changes. +fn end_on<'a>(crest: &Seg2, root: &Seg2, segs: impl Iterator, near_mm: f64) -> Vec { + let (&Seg2::Arc { center, radius, .. }, &Seg2::Arc { radius: root_radius, start, sweep, .. }) = (crest, root) else { return Vec::new() }; + let mut spans = Vec::new(); + for (visibility, seg) in segs { + if let Some((lo, turn)) = round_circle(seg, center, radius, near_mm) { + // A full turn either way too, so the stretch meets the root arc however it is numbered. + spans.extend([-TAU, 0.0, TAU].map(|shift| Span { lo: lo + shift, hi: lo + turn + shift, visibility })); + } + } + let arc = |(lo, hi, visibility)| ThreadPiece { + stroke: ThreadStroke::Root, + visibility, + seg: Seg2::Arc { center, radius: root_radius, start: lo, sweep: hi - lo }, + }; + runs(start, start + sweep, &spans, near_mm / radius).into_iter().map(arc).collect() +} + +/// Where `seg` runs round the circle about `center` of `radius`, both its ends within `near_mm` of +/// it: its start angle (from 0 to a full turn) and how far it turns (above 0, at most a full turn). +/// An arc must be of that circle; a line goes the short way round between its ends. +fn round_circle(seg: &Seg2, center: Vec2, radius: f64, near_mm: f64) -> Option<(f64, f64)> { + let on = |p: Vec2| (p.dist(center) - radius).abs() <= near_mm; + let (lo, turn) = match *seg { + Seg2::Arc { center: c, radius: r, start, sweep } => { + if !(c.dist(center) <= near_mm && (r - radius).abs() <= near_mm) { + return None; + } + if sweep < 0.0 { (start + sweep, -sweep) } else { (start, sweep) } + } + Seg2::Line { a, b } => { + if !(on(a) && on(b)) { + return None; + } + let (from, to) = ((a - center).angle(), (b - center).angle()); + let turn = (to - from + PI).rem_euclid(TAU) - PI; + if turn < 0.0 { (to, -turn) } else { (from, turn) } + } + // A view draws no free-form curve where a crest is a circle. + _ => return None, + }; + (lo.is_finite() && turn.is_finite() && turn > 0.0).then(|| (lo.rem_euclid(TAU), turn.min(TAU))) +} + +/// Side on: where `seg`, a line with both ends within `near_mm` of the line through `from` along +/// `dir`, runs along it. +fn along_line(seg: &Seg2, from: Vec2, dir: Vec2, near_mm: f64, visibility: Visibility) -> Option { + let Seg2::Line { a, b } = *seg else { return None }; + let off = |p: Vec2| (p - from).cross(dir).abs(); + if !(off(a) <= near_mm && off(b) <= near_mm) { + return None; + } + let (ta, tb) = ((a - from).dot(dir), (b - from).dot(dir)); + (ta.is_finite() && tb.is_finite()).then(|| Span { lo: ta.min(tb), hi: ta.max(tb), visibility }) +} + +/// The stretches from `lo` to `hi` that `spans` cover, each at the winning visibility of the spans +/// over it ([`rank`]). Runs no longer than `join` are left out, and runs of one visibility that close +/// to each other are one: a crest drawn in chords meets itself only to within that. +fn runs(lo: f64, hi: f64, spans: &[Span], join: f64) -> Vec<(f64, f64, Visibility)> { + // Each visibility's spans merged first, so the walk below meets a handful of stretches however + // finely the crest was drawn: O(n log n) in the drawn chords. + let mut merged: Vec = Vec::new(); + for visibility in [Visibility::Visible, Visibility::Uncertain, Visibility::Hidden] { + let mut own: Vec = spans.iter().filter(|s| s.visibility == visibility && s.hi > lo && s.lo < hi).copied().collect(); + own.sort_by(|a, b| a.lo.total_cmp(&b.lo)); + let first = merged.len(); + for span in own { + let joins = merged.len() > first && merged.last().is_some_and(|last| span.lo <= last.hi + join); + match merged.last_mut() { + Some(last) if joins => last.hi = last.hi.max(span.hi), + _ => merged.push(span), + } + } + } + let mut cuts: Vec = merged.iter().flat_map(|s| [s.lo, s.hi]).filter(|t| *t > lo && *t < hi).chain([lo, hi]).collect(); + cuts.sort_by(f64::total_cmp); + cuts.dedup(); + let mut out: Vec<(f64, f64, Visibility)> = Vec::new(); + for (&a, &b) in cuts.iter().zip(cuts.iter().skip(1)) { + let mid = 0.5 * (a + b); + let over = merged.iter().filter(|s| s.lo <= mid && mid <= s.hi).map(|s| s.visibility).max_by_key(|v| rank(*v)); + let Some(visibility) = over else { continue }; + if b - a <= join { + continue; + } + match out.last_mut() { + Some(last) if last.2 == visibility && a - last.1 <= join => last.1 = b, + _ => out.push((a, b, visibility)), + } + } + out +} + +/// The winning visibility of the crest stretches within `near_mm` of `t`, if any. +fn seen_at(spans: &[Span], t: f64, near_mm: f64) -> Option { + spans.iter().filter(|s| s.lo - near_mm <= t && t <= s.hi + near_mm).map(|s| s.visibility).max_by_key(|v| rank(*v)) +} + #[cfg(test)] #[path = "thread_lines_tests.rs"] mod tests; diff --git a/crates/doc/src/drawing/thread_lines_tests.rs b/crates/doc/src/drawing/thread_lines_tests.rs index 1409f9e068d..ede6bc5946f 100644 --- a/crates/doc/src/drawing/thread_lines_tests.rs +++ b/crates/doc/src/drawing/thread_lines_tests.rs @@ -1,4 +1,5 @@ use super::*; +use crate::thread_forms::{ThreadForm, ThreadHand}; use solidcore_record::Vec2; use solidcraft_geom::drawing_view::{NamedView, Scale, ViewFrame, basis_looking}; use std::f64::consts::{FRAC_PI_2, PI, TAU}; @@ -218,3 +219,274 @@ fn seeded_threads_draw_finite_lines_along_their_axis() { } assert!(drawn.iter().all(|n| *n > 500), "{drawn:?}"); } + +// ---- Each thread line seen where its crest is seen (`on_paper`). + +/// How near a drawn line must lie to a crest to be it, on paper: these tests' chords are exact. +const NEAR: f64 = 0.02; + +/// A view at 1:1 whose paper coordinates are its plane's. +fn view(named: NamedView) -> ViewFrame { + ViewFrame::new(named.basis(), Scale::new(1.0, 1.0).unwrap(), Vec2::ZERO, Vec2::ZERO).unwrap() +} + +fn line(a: (f64, f64), b: (f64, f64)) -> Seg2 { + Seg2::Line { a: Vec2::new(a.0, a.1), b: Vec2::new(b.0, b.1) } +} + +/// A vertical line at `x` from `y0` down to `y1` in steps of `step`, as a mesh draws one in chords. +fn chords(x: f64, y0: f64, y1: f64, step: f64) -> Vec { + let n = ((y0 - y1) / step).round() as usize; + (0..n).map(|k| line((x, y0 - k as f64 * step), (x, y0 - (k + 1) as f64 * step))).collect() +} + +/// The M8 tapped hole at (20, 5, 0), seen from the front: its crest lines are x = 16.6 and 23.4 on +/// paper, from y = 0 (the face) down; its root lines x = 16 and 24, 12 long. +fn hole() -> Thread { + tapped(Vec3::new(20.0, 5.0, 0.0), [false, false]) +} + +/// Each piece of `stroke` lying along x = `x`, as (top, bottom, visibility), top first. +fn along(pieces: &[ThreadPiece], stroke: ThreadStroke, x: f64) -> Vec<(f64, f64, Visibility)> { + let mut out: Vec<(f64, f64, Visibility)> = pieces + .iter() + .filter(|p| p.stroke == stroke) + .filter_map(|p| { + let (a, b) = ends(&p.seg); + ((a.x - x).abs() < 1e-9 && (b.x - x).abs() < 1e-9).then(|| (a.y.max(b.y), a.y.min(b.y), p.visibility)) + }) + .collect(); + out.sort_by(|p, q| q.0.total_cmp(&p.0)); + out +} + +fn same(got: &[(f64, f64, Visibility)], wanted: &[(f64, f64, Visibility)]) -> bool { + got.len() == wanted.len() && got.iter().zip(wanted).all(|(g, w)| (g.0 - w.0).abs() < 1e-9 && (g.1 - w.1).abs() < 1e-9 && g.2 == w.2) +} + +use Visibility::{Hidden, Visible}; + +/// From the side, each root line takes its own side's crest's visibility stretch by stretch, the +/// crest drawn in chords or in one line alike; the limit line at 12 deep takes the crest's there. +#[test] +fn a_root_line_is_seen_where_its_crest_line_is_seen() { + let left_seen = chords(16.6, 0.0, -6.0, 1.0); + let left_hidden = [line((16.6, -6.0), (16.6, -16.0))]; + let right = [line((23.4, 0.0), (23.4, -16.0))]; + let drawn = [ + Drawn { visibility: Visible, path: &left_seen }, + Drawn { visibility: Hidden, path: &left_hidden }, + Drawn { visibility: Hidden, path: &right }, + ]; + let pieces = on_paper(&view(NamedView::Front), &hole(), &drawn, NEAR); + assert!(same(&along(&pieces, ThreadStroke::Root, 16.0), &[(0.0, -6.0, Visible), (-6.0, -12.0, Hidden)]), "{pieces:?}"); + assert!(same(&along(&pieces, ThreadStroke::Root, 24.0), &[(0.0, -12.0, Hidden)]), "{pieces:?}"); + let limits: Vec<&ThreadPiece> = pieces.iter().filter(|p| p.stroke == ThreadStroke::Limit).collect(); + assert_eq!(limits.len(), 1, "{pieces:?}"); + let (a, b) = ends(&limits[0].seg); + assert!((a.dist(b) - 8.0).abs() < 1e-9 && (a.y + 12.0).abs() < 1e-9 && close((a + b) * 0.5, Vec2::new(20.0, -12.0)), "{limits:?}"); + assert_eq!(limits[0].visibility, Hidden, "both crests are hidden at 12 deep"); +} + +/// A crest drawn on one side never draws the other side's root line, and a line that isn't a crest +/// draws nothing. +#[test] +fn a_crest_on_one_side_draws_only_that_sides_root_line() { + let right = [line((23.4, 0.0), (23.4, -16.0))]; + let other = [line((10.0, 0.0), (10.0, -16.0)), line((16.6, -20.0), (19.0, -20.0))]; + let drawn = [Drawn { visibility: Visible, path: &right }, Drawn { visibility: Visible, path: &other }]; + let pieces = on_paper(&view(NamedView::Front), &hole(), &drawn, NEAR); + assert!(same(&along(&pieces, ThreadStroke::Root, 24.0), &[(0.0, -12.0, Visible)]), "{pieces:?}"); + assert!(along(&pieces, ThreadStroke::Root, 16.0).is_empty(), "{pieces:?}"); + assert_eq!(pieces.iter().filter(|p| p.stroke == ThreadStroke::Root).count(), 1, "{pieces:?}"); +} + +/// Where the view drew no crest (another body hides it, the boundary clips it), the root line has +/// a gap too. +#[test] +fn a_gap_in_the_crest_is_a_gap_in_the_root_line() { + let left = [line((16.6, 0.0), (16.6, -4.0)), line((16.6, -8.0), (16.6, -16.0))]; + let pieces = on_paper(&view(NamedView::Front), &hole(), &[Drawn { visibility: Visible, path: &left }], NEAR); + assert!(same(&along(&pieces, ThreadStroke::Root, 16.0), &[(0.0, -4.0, Visible), (-8.0, -12.0, Visible)]), "{pieces:?}"); +} + +/// End on, the root arc takes the crest circle's visibility by angle: drawn as two half circles (one +/// turning back) or in chords. +#[test] +fn end_on_the_root_arc_takes_its_circles_visibility_by_angle() { + let centre = Vec2::new(20.0, 5.0); + let seen = [Seg2::Arc { center: centre, radius: 3.4, start: 0.0, sweep: PI }]; + let hidden = [Seg2::Arc { center: centre, radius: 3.4, start: TAU, sweep: -PI }]; + let drawn = [Drawn { visibility: Visible, path: &seen }, Drawn { visibility: Hidden, path: &hidden }]; + let pieces = on_paper(&view(NamedView::Top), &hole(), &drawn, NEAR); + let arc = |start: f64, sweep: f64, visibility| ThreadPiece { + stroke: ThreadStroke::Root, + visibility, + seg: Seg2::Arc { center: centre, radius: 4.0, start, sweep }, + }; + let near_arc = |got: &ThreadPiece, wanted: &ThreadPiece| match (got.seg, wanted.seg) { + (Seg2::Arc { center: c, radius: r, start: s, sweep: w }, Seg2::Arc { center, radius, start, sweep }) => { + got.stroke == wanted.stroke + && got.visibility == wanted.visibility + && close(c, center) + && (r - radius).abs() < 1e-9 + && (s - start).abs() < 1e-9 + && (w - sweep).abs() < 1e-9 + } + _ => false, + }; + let wanted = [arc(FRAC_PI_2, FRAC_PI_2, Visible), arc(PI, PI, Hidden)]; + assert!(pieces.len() == 2 && pieces.iter().zip(&wanted).all(|(g, w)| near_arc(g, w)), "{pieces:?}"); + let ring: Vec = (0..64).map(|k| line_on(centre, 3.4, k, 64)).collect(); + let pieces = on_paper(&view(NamedView::Top), &hole(), &[Drawn { visibility: Visible, path: &ring }], NEAR); + assert!(pieces.len() == 1 && near_arc(&pieces[0], &arc(FRAC_PI_2, 3.0 * FRAC_PI_2, Visible)), "{pieces:?}"); +} + +/// The `k`th of `n` chords round the circle about `centre` of `radius`. +fn line_on(centre: Vec2, radius: f64, k: usize, n: usize) -> Seg2 { + let at = |k: usize| centre + Vec2::from_angle(TAU * k as f64 / n as f64) * radius; + Seg2::Line { a: at(k), b: at(k + 1) } +} + +/// A limit line goes only where the thread stops while its face runs on: none where the thread +/// fills its face, one at its inner end in a deeper hole, both where the face runs on either way. +#[test] +fn limit_lines_go_only_where_the_thread_stops_inside_its_face() { + let limits = |top: f64, bottom: f64| { + let crests = [line((16.6, top), (16.6, bottom)), line((23.4, top), (23.4, bottom))]; + let pieces = on_paper(&view(NamedView::Front), &hole(), &[Drawn { visibility: Visible, path: &crests }], NEAR); + let mut at: Vec = pieces.iter().filter(|p| p.stroke == ThreadStroke::Limit).map(|p| 0.5 * (p.seg.start().y + p.seg.end().y)).collect(); + at.sort_by(|a, b| b.total_cmp(a)); + at + }; + assert!(limits(0.0, -12.0).is_empty()); + assert!(limits(0.005, -12.005).is_empty(), "within the tolerance it is the thread's own end"); + let deep = limits(0.0, -16.0); + assert!(deep.len() == 1 && (deep[0] + 12.0).abs() < 1e-9, "{deep:?}"); + let both = limits(2.0, -16.0); + assert!(both.len() == 2 && both[0].abs() < 1e-9 && (both[1] + 12.0).abs() < 1e-9, "{both:?}"); +} + +/// A tolerance that isn't a finite size, a drawn line that isn't finite, or a thread that can't be +/// drawn: nothing wrong is drawn, and nothing panics. +#[test] +fn hostile_lines_and_tolerances_draw_nothing_wrong() { + let crests = [line((16.6, 0.0), (16.6, -16.0)), line((23.4, 0.0), (23.4, -16.0))]; + let good = [Drawn { visibility: Visible, path: &crests }]; + let front = view(NamedView::Front); + assert!(!on_paper(&front, &hole(), &good, NEAR).is_empty()); + for near in [f64::NAN, f64::INFINITY, -1.0] { + assert!(on_paper(&front, &hole(), &good, near).is_empty(), "{near}"); + } + let mut bad = Vec::new(); + for v in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e300] { + bad.extend([line((v, 0.0), (16.6, -16.0)), line((16.6, v), (16.6, -16.0))]); + bad.extend([Seg2::Arc { center: Vec2::new(v, 5.0), radius: 3.4, start: 0.0, sweep: v }]); + bad.push(Seg2::Arc { center: Vec2::new(20.0, 5.0), radius: 3.4, start: v, sweep: v }); + } + for named in [NamedView::Front, NamedView::Top] { + let pieces = on_paper(&view(named), &hole(), &[Drawn { visibility: Visible, path: &bad }], NEAR); + assert!(pieces.iter().all(|p| p.seg.start().is_finite() && p.seg.end().is_finite()), "{pieces:?}"); + } + assert!(on_paper(&front, &Thread { root_radius: 3.0, ..hole() }, &good, NEAR).is_empty()); +} + +/// Seeded views, threads and drawn lines, some along the crests: nothing panics, every piece is +/// finite and takes the drawn visibility, and every root piece lies on a root line within the +/// thread's span. +#[test] +fn seeded_lines_pair_onto_root_lines_only() { + let mut rng = Lcg(0x13050); + let mut paired = 0usize; + for _ in 0..3000 { + let named = if rng.unit() < 0.5 { NamedView::Front } else { NamedView::Top }; + let thread = Thread { end: 1.0 + rng.unit() * 20.0, ..hole() }; + let Some(lines) = thread_lines(&named.basis(), &thread) else { continue }; + let mut path = Vec::new(); + for _ in 0..(rng.unit() * 12.0) as usize { + let pick = rng.unit(); + let crest = lines.crest.get((rng.unit() * lines.crest.len() as f64) as usize).copied(); + let seg = match crest { + Some(Seg2::Line { a, b }) if pick < 0.6 => { + let (s, t) = (rng.unit() * 1.4 - 0.2, rng.unit() * 1.4 - 0.2); + Seg2::Line { a: a.lerp(b, s), b: a.lerp(b, t) } + } + Some(Seg2::Arc { center, radius, .. }) if pick < 0.6 => { + Seg2::Arc { center, radius, start: rng.unit() * 7.0 - 0.5, sweep: rng.unit() * 8.0 - 4.0 } + } + _ => { + let mut at = || (rng.unit() - 0.5) * 60.0; + line((at(), at()), (at(), at())) + } + }; + path.push(seg); + } + let visibility = if rng.unit() < 0.5 { Visible } else { Hidden }; + let pieces = on_paper(&view(named), &thread, &[Drawn { visibility, path: &path }], NEAR); + for p in &pieces { + assert!(p.seg.start().is_finite() && p.seg.end().is_finite() && p.visibility == visibility, "{p:?}"); + if p.stroke != ThreadStroke::Root { + continue; + } + paired += 1; + let on_root = lines.root.iter().any(|root| match (*root, p.seg) { + (Seg2::Line { a, b }, Seg2::Line { a: pa, b: pb }) => { + let dir = (b - a).normalized().unwrap(); + let fits = |q: Vec2| (q - a).cross(dir).abs() < 1e-9 && (q - a).dot(dir) > -1e-9 && (q - a).dot(dir) < (b - a).len() + 1e-9; + fits(pa) && fits(pb) + } + (Seg2::Arc { center, radius, start, sweep }, Seg2::Arc { center: c, radius: r, start: s, sweep: w }) => { + close(center, c) && radius == r && s >= start - 1e-9 && s + w <= start + sweep + 1e-9 && w > 0.0 + } + _ => false, + }); + assert!(on_root, "{p:?} on {lines:?}"); + } + } + assert!(paired > 1000, "{paired}"); +} + +/// A cosmetic thread's record as a view draws it: an M8 screw's root at the minor radius its +/// modelled thread is cut to (4 - 5H/8, H = 1.25 √3 / 2), an M8 tapped hole's at the major radius, +/// both crests at the face's own radius; a taper thread draws none. +#[test] +fn a_cosmetic_thread_is_drawn_from_its_record() { + let info = |internal: bool, radius: f64, form: ThreadForm| ThreadInfo { + feature: 1, + body: "Body".into(), + designation: "M8".into(), + major_diameter: 8.0, + radius, + pitch: 1.25, + internal, + axis_point: Vec3::new(1.0, 2.0, 3.0), + axis: UnitVec3::new(Vec3::Z).unwrap(), + start: 0.0, + end: 10.0, + form, + hand: ThreadHand::default(), + starts: 1, + }; + let screw = Thread::of(&info(false, 4.0, ThreadForm::Metric)).unwrap(); + let minor = 4.0 - 5.0 * (1.25 * 3f64.sqrt() / 2.0) / 8.0; + assert!((screw.root_radius - minor).abs() < 1e-12 && screw.crest_radius == 4.0 && !screw.internal, "{screw:?}"); + assert_eq!((screw.axis_point, screw.start, screw.end, screw.limits), (Vec3::new(1.0, 2.0, 3.0), 0.0, 10.0, [false, false])); + let tapped = Thread::of(&info(true, 3.4, ThreadForm::Metric)).unwrap(); + assert_eq!((tapped.root_radius, tapped.crest_radius, tapped.internal), (4.0, 3.4, true)); + for form in [ThreadForm::Bspt, ThreadForm::Npt] { + assert_eq!(Thread::of(&info(false, 4.0, form)), None, "{form:?}"); + } + // A record saved without its face's radius (0) can't be drawn. + assert_eq!(thread_lines(&NamedView::Front.basis(), &Thread::of(&info(true, 0.0, ThreadForm::Metric)).unwrap()), None); +} + +/// Where crests of two visibilities overlap (two faces' lines on one silhouette), the most seen +/// wins: the root line is seen where any of its crest is. +#[test] +fn where_crests_overlap_the_most_seen_wins() { + let seen = [line((16.6, 0.0), (16.6, -8.0))]; + let hidden = [line((16.6, -4.0), (16.6, -16.0))]; + let drawn = [Drawn { visibility: Hidden, path: &hidden }, Drawn { visibility: Visible, path: &seen }]; + let pieces = on_paper(&view(NamedView::Front), &hole(), &drawn, NEAR); + assert!(same(&along(&pieces, ThreadStroke::Root, 16.0), &[(0.0, -8.0, Visible), (-8.0, -12.0, Hidden)]), "{pieces:?}"); +} diff --git a/crates/engine/src/cmd/drawing_view.rs b/crates/engine/src/cmd/drawing_view.rs index 654039f6cbe..a4d5fa427c0 100644 --- a/crates/engine/src/cmd/drawing_view.rs +++ b/crates/engine/src/cmd/drawing_view.rs @@ -53,6 +53,7 @@ use solidcraft_doc::drawing::cutting_line::CuttingLine; use solidcraft_doc::drawing::dimension::{Dimension, LabelKind, MAX_DECIMALS, reading_label}; use solidcraft_doc::drawing::fold::{FoldFor, FoldRefusal, FoldSide, auxiliary_side}; use solidcraft_doc::drawing::note::Note; +use solidcraft_doc::drawing::thread_lines::{ThreadPiece, ThreadStroke}; use solidcraft_doc::drawing::view::{Beside, ResolvedView, SetBy, Setting, View, ViewKind, ViewLabel, ViewPlace, check_occurrence_paths, check_pose}; use solidcraft_doc::drawing_view::{ Exploded, JointPose, Looking, MAX_POSE_JOINTS, OccurrencePaths, Pose, StudyStep, TangentEdges, ViewConfiguration, ViewDirection, ViewOverrides, @@ -80,7 +81,8 @@ use crate::schema::drawing_view::{ FromResult, InspectParams, InspectResult, LabelResult, LabelSet, LineResult, LinesStatusResult, MeasureParam, MeasurementResult, MoveParams, OutsideResult, PathSegResult, PictureResult, PieceResult, PlaceParam, PoseParam, PoseResult, ProjectedParams, ProjectionForParams, ProjectionForResult, ScaleResult, SceneResult, SectionParams, SettingResult, SettingsResult, SnapshotParams, SnapshotResult, SourceResult, - StudyPoseParam, StudyStepResult, ToSheetResult, ViewLineParam, ViewMoveParams, ViewMoveResult, ViewResult, ViewSet, + StudyPoseParam, StudyStepResult, ThreadPieceResult, ThreadResult, ToSheetResult, ViewLineParam, ViewMoveParams, ViewMoveResult, ViewResult, + ViewSet, }; use crate::schema::{TypedContract, output_schema_for}; use crate::{Result, Session}; @@ -294,6 +296,7 @@ fn snapshot(s: &mut Session, p: &Value) -> Result { extents: extents_result(&extents, None, false), boundary_mm: BoxResult { min: boundary.min.into(), max: boundary.max.into() }, lines: line_results(&set, &drawn), + threads: thread_results(&set, &drawn), status: LinesStatusResult { lines: if drawn.lines.iter().flat_map(|l| &l.pieces).any(|p| matches!(p.accuracy, CurveAccuracy::Sampled { .. })) { "approximate" @@ -508,6 +511,24 @@ fn line_results(shown: &ShownSet, drawn: &Lines) -> Vec { drawn.lines.iter().map(line).collect() } +fn thread_results(shown: &ShownSet, drawn: &Lines) -> Vec { + let thread = |t: &crate::drawing_view::ThreadLine| { + let body = shown.bodies.get(t.shown); + let piece = |p: &ThreadPiece| ThreadPieceResult { + stroke: if p.stroke == ThreadStroke::Limit { "limit" } else { "root" }, + visibility: if p.visibility == Visibility::Hidden { "hidden" } else { "visible" }, + path: vec![PathSegResult(p.seg)], + }; + ThreadResult { + occurrence: body.map(|b| b.path.clone()).unwrap_or_default(), + body: body.map(|b| b.body.clone()).unwrap_or_default(), + reference: t.reference, + pieces: t.pieces.iter().map(piece).collect(), + } + }; + drawn.threads.iter().map(thread).collect() +} + fn inspect(s: &mut Session, p: &Value) -> Result { let request: InspectParams = crate::schema::read(INSPECT, p)?; let d = s.drawing(INSPECT)?; diff --git a/crates/engine/src/cmd/drawing_view_tests.rs b/crates/engine/src/cmd/drawing_view_tests.rs index be89e8b7bfc..140420dad63 100644 --- a/crates/engine/src/cmd/drawing_view_tests.rs +++ b/crates/engine/src/cmd/drawing_view_tests.rs @@ -4661,3 +4661,118 @@ fn a_section_views_letter_is_given() { } assert_eq!(letters, ["A", "B"]); } + +/// A 40 x 40 x 20 mm block from the origin with an M8 tapped hole down from the middle of its top: +/// drilled Ø6.8 16 deep, threaded 12 deep. At 1:1 the block's centre is the A3 sheet's (210, 148.5), +/// so from above the hole is round it, and from the front its top is at y = 158.5 on the sheet. +fn tapped_block() -> Session { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 20, "body_name": "Block"})); + run(&mut s, "solid.hole", json!({"position": [20, 20, 20], "direction": [0, 0, -1], "thread": "M8", "depth": 16, "thread_depth": 12})); + s +} + +/// Every segment of `v`'s thread pieces of `stroke` at `visibility`, on the sheet. +fn thread_segs(v: &Value, stroke: &str, visibility: &str) -> Vec { + let pieces = v["threads"].as_array().into_iter().flatten().flat_map(|t| t["pieces"].as_array().into_iter().flatten()); + let wanted = pieces.filter(|p| p["stroke"] == stroke && p["visibility"] == visibility); + wanted.flat_map(|p| p["path"].as_array().into_iter().flatten().cloned()).collect() +} + +/// A line segment's ends, top first. +fn top_first(seg: &Value) -> (Vec2, Vec2) { + let (a, b) = (point(&seg["a"]), point(&seg["b"])); + if a.y >= b.y { (a, b) } else { (b, a) } +} + +/// From above, the M8 tapped hole draws its root as a thin three-quarter arc of radius 4.0 round +/// the hole's centre, from 90° round to 360°, so its gap is the upper right quadrant: the Ø6.8 drill +/// is the circle the view draws already. +#[test] +fn a_tapped_holes_root_is_a_three_quarter_arc_seen_from_above() { + let mut s = tapped_block(); + let v = snap(&mut s, json!({"view": "top", "scale": "1:1"})); + let schema = output_schema_for::(); + assert!(conforms(schema.as_value(), schema.as_value(), &v), "{v}"); + let roots = thread_segs(&v, "root", "visible"); + assert_eq!(roots.len(), 1, "{v}"); + let arc = &roots[0]; + assert_eq!(arc["type"], "arc", "{arc}"); + assert!(point(&arc["center"]).dist(Vec2::new(210.0, 148.5)) < 1e-6, "{arc}"); + let (radius, start, sweep) = (arc["radius"].as_f64().unwrap(), arc["start"].as_f64().unwrap(), arc["sweep"].as_f64().unwrap()); + assert!( + (radius - 4.0).abs() < 1e-6 && (start - std::f64::consts::FRAC_PI_2).abs() < 1e-6 && (sweep - 3.0 * std::f64::consts::FRAC_PI_2).abs() < 1e-6, + "{arc}" + ); + assert!(thread_segs(&v, "limit", "visible").is_empty() && thread_segs(&v, "limit", "hidden").is_empty(), "end on, no limit line: {v}"); + assert!(arcs(&v, "visible").iter().any(|(c, r, ..)| c.dist(Vec2::new(210.0, 148.5)) < 1e-6 && (r - 3.4).abs() < 1e-6), "the drill: {v}"); +} + +/// From the front, with hidden lines drawn, the hole's thread is hidden: two dashed root lines 8.0 +/// apart, each 12.0 long down from the top, and a limit line 8.0 long across at 12 deep, where the +/// thread stops in its 16 mm hole. With hidden lines left out, the thread draws nothing. +#[test] +fn a_tapped_holes_thread_is_hidden_from_the_side() { + let mut s = tapped_block(); + let v = snap(&mut s, json!({"scale": "1:1", "visual_style": "visible_hidden"})); + let mut roots: Vec<(Vec2, Vec2)> = thread_segs(&v, "root", "hidden").iter().map(top_first).collect(); + roots.sort_by(|p, q| p.0.x.total_cmp(&q.0.x)); + assert_eq!(roots.len(), 2, "{v}"); + for ((top, bottom), x) in roots.iter().zip([206.0, 214.0]) { + assert!(top.dist(Vec2::new(x, 158.5)) < 1e-6 && bottom.dist(Vec2::new(x, 146.5)) < 1e-6, "{top:?} {bottom:?} {v}"); + } + let limits: Vec<(Vec2, Vec2)> = thread_segs(&v, "limit", "hidden").iter().map(top_first).collect(); + assert_eq!(limits.len(), 1, "{v}"); + let (a, b) = limits[0]; + assert!( + (a.dist(b) - 8.0).abs() < 1e-6 && (a.y - 146.5).abs() < 1e-6 && (b.y - 146.5).abs() < 1e-6 && ((a.x + b.x) / 2.0 - 210.0).abs() < 1e-6, + "{v}" + ); + assert!(thread_segs(&v, "root", "visible").is_empty() && thread_segs(&v, "limit", "visible").is_empty(), "{v}"); + let v = snap(&mut s, json!({"scale": "1:1"})); + assert_eq!(v["threads"], json!([]), "{v}"); +} + +/// A tapped block drawn from the mesh (a mesh cube stands in front of its lower right corner, clear +/// of the hole) still draws its thread: two hidden root lines 8.0 apart, each 12.0 long, and a limit +/// line 8.0 long across their lower ends. The thread lines pair with the mesh's crest lines as with +/// exact ones. +#[test] +fn a_tapped_block_drawn_from_the_mesh_draws_its_thread() { + let mut s = tapped_block(); + with_mesh_cube(&mut s, [30.0, -30.0, -10.0], "tapped"); + let v = snap(&mut s, json!({"scale": "1:1", "visual_style": "visible_hidden"})); + assert_eq!(v["status"]["provenance"], "mesh_projection", "{v}"); + let mut roots: Vec<(Vec2, Vec2)> = thread_segs(&v, "root", "hidden").iter().map(top_first).collect(); + roots.sort_by(|p, q| p.0.x.total_cmp(&q.0.x)); + assert_eq!(roots.len(), 2, "{v}"); + let (left, right) = (roots[0], roots[1]); + assert!((right.0.x - left.0.x - 8.0).abs() < 1e-6 && (left.0.y - right.0.y).abs() < 1e-6, "{roots:?}"); + assert!(roots.iter().all(|(top, bottom)| (top.x - bottom.x).abs() < 1e-6 && (top.y - bottom.y - 12.0).abs() < 1e-6), "{roots:?}"); + let limits: Vec<(Vec2, Vec2)> = thread_segs(&v, "limit", "hidden").iter().map(top_first).collect(); + assert_eq!(limits.len(), 1, "{v}"); + let (a, b) = limits[0]; + assert!((a.dist(b) - 8.0).abs() < 1e-6 && (a.y - left.1.y).abs() < 1e-6 && (b.y - left.1.y).abs() < 1e-6, "{limits:?} {roots:?}"); +} + +/// An M8 shaft threaded 10 mm down from its top, seen from the side: its root lines are thin and +/// seen, at the minor radius a modelled M8 is cut to (4 - 5H/8 for H = 1.25 √3 / 2), 10 long; a +/// limit line goes across where the thread stops, and none at the free end, where the shaft's own +/// edge is drawn. +#[test] +fn a_shafts_thread_is_seen_from_the_side() { + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 4, "height": 20, "body_name": "Shaft"})); + run(&mut s, "solid.thread", json!({"face": [4, 0, 10], "designation": "M8", "length": 10, "from": [4, 0, 20]})); + let v = snap(&mut s, json!({"scale": "1:1"})); + let minor = 4.0 - 5.0 * (1.25 * 3f64.sqrt() / 2.0) / 8.0; + let mut roots: Vec<(Vec2, Vec2)> = thread_segs(&v, "root", "visible").iter().map(top_first).collect(); + roots.sort_by(|p, q| p.0.x.total_cmp(&q.0.x)); + assert_eq!(roots.len(), 2, "{v}"); + for ((top, bottom), x) in roots.iter().zip([210.0 - minor, 210.0 + minor]) { + assert!(top.dist(Vec2::new(x, 158.5)) < 1e-6 && bottom.dist(Vec2::new(x, 148.5)) < 1e-6, "{top:?} {bottom:?} {v}"); + } + let limits: Vec<(Vec2, Vec2)> = thread_segs(&v, "limit", "visible").iter().map(top_first).collect(); + assert_eq!(limits.len(), 1, "{v}"); + assert!((limits[0].0.y - 148.5).abs() < 1e-6 && (limits[0].0.dist(limits[0].1) - 8.0).abs() < 1e-6, "{v}"); +} diff --git a/crates/engine/src/drawing_scene.rs b/crates/engine/src/drawing_scene.rs index 426ab20bcf2..33a6ea91d47 100644 --- a/crates/engine/src/drawing_scene.rs +++ b/crates/engine/src/drawing_scene.rs @@ -74,7 +74,7 @@ use solidcraft_doc::drawing::note::{Anchor, Note}; use solidcraft_doc::drawing::view::{FlatOf, ResolvedView, View}; use solidcraft_doc::drawing::{Drawing, Sheet, Updates}; use solidcraft_doc::drawing_view::TangentEdges; -use solidcraft_doc::{DocError, Document, ModelState, ids}; +use solidcraft_doc::{DocError, Document, ModelState, ThreadInfo, ids}; use solidcraft_geom::cell::{Part, Projection}; use solidcraft_geom::drawing_view::ViewFrame; use solidcraft_geom::hlr::Source; @@ -695,7 +695,7 @@ fn draw( let pictures = picture_items(id, &view_parts(&set, styles), rect); // The pictures go under the strokes, so the owners start with one empty entry for each. let owner = |at: usize| lines.lines.get(at).map(|line| (line.shown, line.source)); - let items = std::iter::repeat_n(None, pictures.len()).chain(drew.into_iter().map(owner)).collect(); + let items = std::iter::repeat_n(None, pictures.len()).chain(drew.into_iter().map(|at| at.and_then(owner))).collect(); group.items.splice(0..0, pictures); if group.records() > MAX_RECORDS { return none(Status::Failed(format!("its lines are more than a paper scene's {MAX_RECORDS} records: choose a smaller scale"))); @@ -1411,19 +1411,24 @@ pub struct Cache { } /// What a view's lines show: each body of the world state by the occurrences that place it, its -/// definition's body name, whether it is a reference, and its geometry where it stands. A world state +/// definition's body name, whether it is a reference, its geometry where it stands, and its cosmetic +/// threads (which change no geometry, yet draw lines of their own). A world state /// with the same draws the same lines, so an appearance, or an edit taken back, draws nothing. It /// keys the whole set, not a view's own bodies: which bodies share a mesh, so the lines' last bits, /// hangs on all of them ([`crate::mesh_lines`]). #[derive(Debug, PartialEq)] -pub(crate) struct SourceKey(Vec<(Vec, String, bool, u64)>); +pub(crate) struct SourceKey(Vec<(Vec, String, bool, u64, Vec)>); impl SourceKey { /// None when there is nothing to show, or a body's geometry has no key: a view drawn from it /// always draws again. fn of(shown: &std::result::Result) -> Option> { let set = shown.as_ref().ok()?; - let body = |one: &Shown| Some((one.path.clone(), one.body.clone(), one.reference, set.body(one)?.geometry_key()?)); + let body = |one: &Shown| { + let body = set.body(one)?; + let threads = set.state.threads.iter().filter(|t| t.body == body.name).cloned().collect(); + Some((one.path.clone(), one.body.clone(), one.reference, body.geometry_key()?, threads)) + }; set.bodies.iter().map(body).collect::>>().map(|bodies| Arc::new(SourceKey(bodies))) } } diff --git a/crates/engine/src/drawing_scene_tests.rs b/crates/engine/src/drawing_scene_tests.rs index 34733a161db..1e67042bb18 100644 --- a/crates/engine/src/drawing_scene_tests.rs +++ b/crates/engine/src/drawing_scene_tests.rs @@ -3677,3 +3677,76 @@ fn a_rule_change_draws_the_flat_view_again() { settled(&mut s, sheet); assert!(extract(&mut s, sheet).unwrap().stale.is_empty()); } + +/// [`front_and_top`]'s block with a hole drilled Ø6.8 16 deep down from the middle of its top, and an +/// M8 cosmetic thread 12 deep in it (the feature `Tap`): a thread of its own, so editing it changes +/// no geometry. +fn tapped_front_and_top() -> (Session, u64, [u64; 2]) { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 100, "width": 50, "height": 20, "body_name": "Block"})); + run(&mut s, "solid.hole", json!({"position": [50, 25, 20], "direction": [0, 0, -1], "diameter": 6.8, "depth": 16})); + run(&mut s, "solid.thread", json!({"face": [53.4, 25, 15], "designation": "M8", "length": 12, "from": [53.4, 25, 20], "name": "Tap"})); + front_and_top_of(s) +} + +/// The arcs of `group`'s strokes of `radius` (paper millimetres). +fn arcs_of(group: &Group, radius: f64) -> usize { + let segs = group.items.iter().filter_map(|item| match item { + Item::Stroke { path, .. } => Some(path), + _ => None, + }); + segs.flatten().filter(|seg| matches!(seg, Seg2::Arc { radius: r, .. } if (r - radius).abs() < 1e-9)).count() +} + +/// A sheet's view draws a cosmetic thread's lines as its snapshot does: from the front, hidden +/// (two root lines and the limit line, dashed); from above, the root's three-quarter arc, radius 2 +/// on paper at 1:2. Changing only the thread's depth draws the front view again, with its limit line +/// moved, though the block's geometry is the same. +#[test] +fn a_views_threads_draw_as_its_snapshot_does_and_follow_the_thread() { + let (mut s, sheet, [front, top]) = tapped_front_and_top(); + run(&mut s, "drawing.view.edit", json!({"view": ids::encode(front), "set": {"visual_style": "visible_hidden"}})); + let scene = settled(&mut s, sheet).scene; + let group = |scene: &Scene, id: u64| scene.groups.iter().find(|g| g.object == id).unwrap().clone(); + let ours = group(&scene, front); + assert_eq!(arcs_of(&group(&scene, top), 2.0), 1, "{:?}", group(&scene, top)); + let dashed = ours.items.iter().filter(|item| matches!(item, Item::Stroke { pattern: Some(_), .. })).count(); + // The drill's two sides and its floor, its cone's two sides, and the thread's three lines. + assert!(dashed >= 6, "{ours:?}"); + let drawing = ids::encode(s.open_drawing.unwrap()); + run(&mut s, "drawing.close", json!({})); + let p = json!({"view": "front", "scale": "1:2", "position_mm": [150, 150], "scene": true, "visual_style": "visible_hidden"}); + let v = run(&mut s, "drawing.view.snapshot", p); + let snapped: Scene = serde_json::from_value(v["scene"].clone()).unwrap(); + assert!(same_within(&ours, &snapped.groups[0], 1e-9), "{ours:?} {:?}", snapped.groups[0]); + assert_eq!(v["threads"].as_array().map(Vec::len), Some(1), "{v}"); + let geometry = s.world_state().unwrap().bodies[0].geometry_key(); + run(&mut s, "timeline.edit", json!({"feature": "Tap", "set": {"length": "8"}})); + assert_eq!(s.world_state().unwrap().bodies[0].geometry_key(), geometry, "a cosmetic thread changes no geometry"); + run(&mut s, "drawing.open", json!({"drawing": drawing})); + let moved = group(&settled(&mut s, sheet).scene, front); + assert_ne!(bytes_of(&moved), bytes_of(&ours), "the limit line moves with the thread"); + run(&mut s, "drawing.close", json!({})); + let v = run( + &mut s, + "drawing.view.snapshot", + json!({"view": "front", "scale": "1:2", "position_mm": [150, 150], "scene": true, "visual_style": "visible_hidden"}), + ); + let snapped: Scene = serde_json::from_value(v["scene"].clone()).unwrap(); + assert!(same_within(&moved, &snapped.groups[0], 1e-9), "{moved:?} {:?}", snapped.groups[0]); +} + +/// Two placements of a tapped plate each draw their own thread: two root arcs from above. +#[test] +fn each_placement_of_a_tapped_part_draws_its_thread() { + let mut s = Session::default(); + let plate = run(&mut s, "component.create", json!({"name": "Plate"})); + run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 10, "body_name": "PlateBody"})); + run(&mut s, "solid.hole", json!({"position": [20, 20, 10], "direction": [0, 0, -1], "thread": "M8", "depth": 8})); + run(&mut s, "component.activate", json!({"component": 0})); + run(&mut s, "occurrence.copy", json!({"component": plate["component"], "translate": [60, 0, 0]})); + let (mut s, sheet, [_, top]) = front_and_top_of(s); + let scene = settled(&mut s, sheet).scene; + let top = scene.groups.iter().find(|g| g.object == top).unwrap(); + assert_eq!(arcs_of(top, 2.0), 2, "{top:?}"); +} diff --git a/crates/engine/src/drawing_view.rs b/crates/engine/src/drawing_view.rs index c600a35e39c..e6c8f76216a 100644 --- a/crates/engine/src/drawing_view.rs +++ b/crates/engine/src/drawing_view.rs @@ -31,9 +31,12 @@ use crate::{Result, Session}; mod exact; #[path = "drawing_view_lines.rs"] mod lines; +#[path = "drawing_view_threads.rs"] +mod threads; pub use exact::{Fallback, PreparedBodies}; pub use lines::{CHORD_MM, CHORD_RANGE, LineRequest, Lines, MIN_MODEL_CHORD_MM, Made, Piece, Stats, ViewLine, lines, paper_group, paper_lines}; +pub use threads::ThreadLine; #[path = "drawing_view_flat.rs"] mod flat; @@ -151,7 +154,9 @@ impl Styles { /// Leaves out a shaded part's own lines: its picture draws it, and it still hides what lies /// behind it. pub fn leave_shaded_to_pictures(&self, lines: &mut Lines) { - lines.lines.retain(|l| !(if l.reference { self.reference } else { self.display }).is_shaded()); + let shaded = |reference: bool| (if reference { self.reference } else { self.display }).is_shaded(); + lines.lines.retain(|l| !shaded(l.reference)); + lines.threads.retain(|t| !shaded(t.reference)); } } diff --git a/crates/engine/src/drawing_view_exact.rs b/crates/engine/src/drawing_view_exact.rs index b49e24b98d8..34356a0f932 100644 --- a/crates/engine/src/drawing_view_exact.rs +++ b/crates/engine/src/drawing_view_exact.rs @@ -325,7 +325,7 @@ fn clipped(path: &[Seg2], area: &Aabb2, chord: f64) -> Vec<(Vec, bool)> { } ends = q.dist(b) <= EPS; } - let near = |radius: f64| 2.0 * chord + radius * 1e-9; + let near = |radius: f64| super::lines::near(chord, radius); for (points, starts) in kept { let part = match seg { Seg2::Arc { .. } => on_arc(seg, &points, false, near, 0.0).map(|(arc, _)| vec![arc]), diff --git a/crates/engine/src/drawing_view_lines.rs b/crates/engine/src/drawing_view_lines.rs index 85c67b73818..2743bd60374 100644 --- a/crates/engine/src/drawing_view_lines.rs +++ b/crates/engine/src/drawing_view_lines.rs @@ -9,6 +9,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap}; use solidcore_record::{Plane, Seg2, Vec2, Vec3}; use solidcraft_doc::Mat; +use solidcraft_doc::drawing::thread_lines::ThreadStroke; use solidcraft_geom::drawing_view::ViewFrame; use solidcraft_geom::hlr::{self, Source, Visibility}; use solidcraft_geom::paper::line::{LineGroup, LineKind}; @@ -20,6 +21,7 @@ use solidcraft_kernel::PlanarPiece; use super::ShownSet; use super::exact::{self, Fallback, PreparedBodies}; +use super::threads::{ThreadLine, threads}; use crate::mesh_lines::{self, Ask, Origin, Owner, Refused, Scene, View}; use crate::params::bad; use crate::{Result, Session}; @@ -57,6 +59,8 @@ pub struct Piece { #[derive(Clone, Debug)] pub struct Lines { pub lines: Vec, + /// The shown bodies' cosmetic threads, drawn where their crests are ([`threads`]). + pub threads: Vec, /// Pieces drawn where another source lay too. pub covered: usize, /// The chord the mesh was asked for, in model millimetres. @@ -208,10 +212,12 @@ fn lines_with( } // Each body's lines together, in the shown set's order. out.sort_by_key(|line| line.shown); - if out.iter().map(|line| line.pieces.len()).fold(0usize, usize::saturating_add) > MAX_RECORDS { + let threads = threads(shown, frame, &out, model_chord_mm); + let pieces = out.iter().map(|line| line.pieces.len()).chain(threads.iter().map(|thread| thread.pieces.len())); + if pieces.fold(0usize, usize::saturating_add) > MAX_RECORDS { return Err(bad(cmd, format!("the view has more than {MAX_RECORDS} line pieces: raise chord_mm, or choose a smaller view"))); } - Ok(Lines { lines: out, covered, model_chord_mm, stats, made }) + Ok(Lines { lines: out, threads, covered, model_chord_mm, stats, made }) } /// The lines the mesh projection draws whose owners `keep` takes, each tested against every shown @@ -261,8 +267,7 @@ fn meshed( let runs: Vec<(Owner, Vec<(bool, Vec)>)> = by_owner.into_iter().map(|(owner, stretches)| (owner, chain(&stretches, join))).collect(); let arcs = exact_arcs(shown, &scene, &frame.basis(), &runs); let sampled = frame.accuracy_on_paper(CurveAccuracy::Sampled { max_sample_deviation_mm: 0.0 }); - // A cut point lies on a chord, so off the true curve by up to the chord's sag. - let near = |radius: f64| 2.0 * model_chord_mm + radius * 1e-9; + let near = |radius: f64| near(model_chord_mm, radius); let mut out = Vec::with_capacity(runs.len()); for (owner, runs) in runs { let placement = scene.placements.get(owner.placement as usize).ok_or_else(|| bad(cmd, "a line names no placement"))?; @@ -298,7 +303,13 @@ fn meshed( occlusion_ms: drawing.occlusion_ms, ..Stats::default() }; - Ok(Lines { lines: out, covered, model_chord_mm, stats, made: Made::default() }) + Ok(Lines { lines: out, threads: Vec::new(), covered, model_chord_mm, stats, made: Made::default() }) +} + +/// How far a line the mesh drew may lie off the true curve of `radius` (model millimetres), for +/// chords of `model_chord_mm`: a cut point lies on a chord, so off the curve by up to its sag. +pub(super) fn near(model_chord_mm: f64, radius: f64) -> f64 { + 2.0 * model_chord_mm + radius * 1e-9 } /// The part of the line from `a` to `b` inside `area`, if any. @@ -317,10 +328,11 @@ pub fn paper_group(lines: &Lines, object: u64, group: LineGroup) -> Group { } /// `lines` as the paper scene group of the view `object`, in line `group`, and the index in `lines` -/// of the line each stroke draws: each piece one stroke, closed when it ends where it starts. Painted -/// from the bottom: hidden pieces, dashed hidden lines, then reference parts' visible ones as thin -/// lines, then the model's as visible lines. -pub fn paper_lines(lines: &Lines, object: u64, group: LineGroup) -> (Group, Vec) { +/// of the line each stroke draws (none for a thread's): each piece one stroke, closed when it ends +/// where it starts. Painted from the bottom: hidden pieces, dashed hidden lines, then reference +/// parts' visible ones as thin lines, then the model's as visible lines; each with its threads after +/// it: root lines thin, limit lines as the part's edges. +pub fn paper_lines(lines: &Lines, object: u64, group: LineGroup) -> (Group, Vec>) { let stroke = |piece: &Piece, width_mm: f64| { let path: Vec = piece.path.iter().copied().filter_map(drawable).collect(); let ends_meet = path.first().zip(path.last()).is_some_and(|(first, last)| last.end().dist(first.start()) <= EPS); @@ -333,15 +345,23 @@ pub fn paper_lines(lines: &Lines, object: u64, group: LineGroup) -> (Group, Vec< let strokes = |reference: bool, visibility: Visibility, width_mm: f64| { let pieces = lines.lines.iter().enumerate().filter(move |(_, l)| l.reference == reference); let pieces = pieces.flat_map(|(at, l)| l.pieces.iter().map(move |p| (at, p))); - pieces.filter(move |(_, p)| p.visibility == visibility).filter_map(move |(at, p)| Some((stroke(p, width_mm)?, at))) + pieces.filter(move |(_, p)| p.visibility == visibility).filter_map(move |(at, p)| Some((stroke(p, width_mm)?, Some(at)))) + }; + // A thread's piece is one segment: a limit line at the width given, a root line thin. + let thin_mm = LineKind::Thin.width_mm(group); + let threads = |reference: bool, visibility: Visibility, width_mm: f64| { + let pieces = lines.threads.iter().filter(move |t| t.reference == reference).flat_map(|t| &t.pieces); + pieces.filter(move |p| p.visibility == visibility).filter_map(move |p| { + let width_mm = if p.stroke == ThreadStroke::Limit { width_mm } else { thin_mm.min(width_mm) }; + Some((stroke(&Piece { visibility, path: vec![p.seg], accuracy: CurveAccuracy::Analytic }, width_mm)?, None)) + }) + }; + let painted = |reference: bool, visibility: Visibility, width_mm: f64| { + strokes(reference, visibility, width_mm).chain(threads(reference, visibility, width_mm)) }; let hidden_mm = LineKind::Hidden.width_mm(group); - let hidden = strokes(true, Visibility::Hidden, hidden_mm).chain(strokes(false, Visibility::Hidden, hidden_mm)); - let visible = strokes(true, Visibility::Visible, LineKind::Thin.width_mm(group)).chain(strokes( - false, - Visibility::Visible, - LineKind::Visible.width_mm(group), - )); + let hidden = painted(true, Visibility::Hidden, hidden_mm).chain(painted(false, Visibility::Hidden, hidden_mm)); + let visible = painted(true, Visibility::Visible, thin_mm).chain(painted(false, Visibility::Visible, LineKind::Visible.width_mm(group))); let (items, drew) = hidden.chain(visible).unzip(); (Group { object, kind: ObjectKind::View, items }, drew) } @@ -547,7 +567,7 @@ mod tests { fn lines_of(pieces: Vec) -> Lines { let line = ViewLine { shown: 0, reference: false, source: Source::Edge { edge: 0, tangent: false }, pieces }; - Lines { lines: vec![line], covered: 0, model_chord_mm: 0.01, stats: Stats::default(), made: Made::default() } + Lines { lines: vec![line], threads: Vec::new(), covered: 0, model_chord_mm: 0.01, stats: Stats::default(), made: Made::default() } } fn piece(visibility: Visibility, path: Vec) -> Piece { @@ -601,6 +621,7 @@ mod tests { }; let lines = Lines { lines: vec![line(false), line(true), line(false)], + threads: Vec::new(), covered: 0, model_chord_mm: 0.01, stats: Stats::default(), @@ -622,7 +643,7 @@ mod tests { LineKind::Visible.width_mm(LineGroup::DEFAULT) ] ); - assert_eq!(paper_lines(&lines, 7, LineGroup::DEFAULT).1, [1, 0, 2], "each stroke says which line it draws"); + assert_eq!(paper_lines(&lines, 7, LineGroup::DEFAULT).1, [Some(1), Some(0), Some(2)], "each stroke says which line it draws"); } /// Hidden pieces come first, the reference parts' and then the model's, whatever order they were @@ -643,7 +664,14 @@ mod tests { ); let reference = line(true, vec![piece(Visibility::Visible, vec![Seg2::Line { a: b, b: c }]), piece(Visibility::Hidden, vec![Seg2::Line { a, b: c }])]); - let lines = Lines { lines: vec![model, reference], covered: 0, model_chord_mm: 0.01, stats: Stats::default(), made: Made::default() }; + let lines = Lines { + lines: vec![model, reference], + threads: Vec::new(), + covered: 0, + model_chord_mm: 0.01, + stats: Stats::default(), + made: Made::default(), + }; let group = paper_group(&lines, 7, LineGroup::DEFAULT); let dashes = Dashes { lengths_mm: vec![3.0, 0.75], phase_mm: 0.0 }; let strokes: Vec<(usize, bool, f64, Option<&Dashes>)> = group @@ -663,7 +691,7 @@ mod tests { (1, false, LineKind::Visible.width_mm(LineGroup::DEFAULT), None), ]; assert_eq!(strokes, want); - assert_eq!(paper_lines(&lines, 7, LineGroup::DEFAULT).1, [1, 0, 0, 1, 0], "each stroke's line, in paint order"); + assert_eq!(paper_lines(&lines, 7, LineGroup::DEFAULT).1, [Some(1), Some(0), Some(0), Some(1), Some(0)], "each stroke's line, in paint order"); let scene = solidcraft_geom::paper::Scene::new(Vec2::new(420.0, 297.0), vec![group]); assert!(scene.validate().is_ok()); } @@ -681,6 +709,7 @@ mod tests { }; let lines = Lines { lines: vec![line(false, Visibility::Visible), line(false, Visibility::Hidden), line(true, Visibility::Visible)], + threads: Vec::new(), covered: 0, model_chord_mm: 0.01, stats: Stats::default(), @@ -699,6 +728,40 @@ mod tests { assert_eq!(drawn, [(0.35, Some(vec![12.0 * narrow, 3.0 * narrow])), (0.35, None), (0.7, None)]); } + /// A thread's root lines are thin and its limit lines drawn as the part's edges, a reference + /// part's all thin; hidden ones dashed. Each is painted after the lines of its kind, and no stroke + /// of a thread names a line, so a thread can't be picked. + #[test] + fn a_threads_lines_are_painted_thin_with_limit_lines_as_edges() { + use solidcraft_doc::drawing::thread_lines::ThreadPiece; + let seg = Seg2::Line { a: Vec2::new(0.0, 0.0), b: Vec2::new(0.0, 12.0) }; + let one = |stroke, visibility| ThreadPiece { stroke, visibility, seg }; + let thread = |reference| ThreadLine { + shown: 0, + reference, + pieces: vec![ + one(ThreadStroke::Root, Visibility::Visible), + one(ThreadStroke::Limit, Visibility::Visible), + one(ThreadStroke::Root, Visibility::Hidden), + ], + }; + let mut lines = lines_of(vec![piece(Visibility::Visible, vec![seg])]); + lines.threads = vec![thread(false), thread(true)]; + let (group, drew) = paper_lines(&lines, 7, LineGroup::Mm0_7); + let drawn: Vec<(f64, bool)> = group + .items + .iter() + .filter_map(|i| match i { + Item::Stroke { width_mm, pattern, .. } => Some((*width_mm, pattern.is_some())), + _ => None, + }) + .collect(); + // Hidden: the reference's thread, the model's thread; visible: the reference's thread (all + // thin), the model's line, the model's thread (root thin, limit as edges). + assert_eq!(drawn, [(0.35, true), (0.35, true), (0.35, false), (0.35, false), (0.7, false), (0.35, false), (0.7, false)]); + assert_eq!(drew, [None, None, None, None, Some(0), None, None]); + } + /// A view's group past the paper scene's 100,000 records is caught by the scene's own check. #[test] fn a_group_past_the_scenes_records_is_refused_by_its_check() { diff --git a/crates/engine/src/drawing_view_threads.rs b/crates/engine/src/drawing_view_threads.rs new file mode 100644 index 00000000000..e0982efe724 --- /dev/null +++ b/crates/engine/src/drawing_view_threads.rs @@ -0,0 +1,45 @@ +//! A drawing view's cosmetic threads (#13050): each shown body's threads, drawn by ISO 6410's +//! convention where the view drew their crests ([`thread_lines::on_paper`] pairs them). A modelled +//! thread leaves no cosmetic record, so it draws only its own edges. + +use solidcraft_doc::drawing::thread_lines::{self, Drawn, Thread, ThreadPiece}; +use solidcraft_geom::drawing_view::ViewFrame; + +use super::ShownSet; +use super::lines::{ViewLine, near}; + +/// One cosmetic thread's lines in a view, on paper. +#[derive(Clone, Debug, PartialEq)] +pub struct ThreadLine { + /// The index of the body among the shown set's. + pub shown: usize, + /// The body is a reference part. + pub reference: bool, + pub pieces: Vec, +} + +/// The threads of the bodies `shown` holds, in the view `frame` places on paper, paired with the +/// `lines` the view drew of each body, sampled from meshes asked for chords of `model_chord_mm`. A +/// thread whose crest the view drew nowhere draws nothing; so does a mesh body's. +pub fn threads(shown: &ShownSet, frame: &ViewFrame, lines: &[ViewLine], model_chord_mm: f64) -> Vec { + let factor = frame.scale().factor(); + let mut out = Vec::new(); + for (at, one) in shown.bodies.iter().enumerate() { + let Some(body) = shown.body(one).filter(|b| !b.body.is_mesh()) else { continue }; + let mut own = shown.state.threads.iter().filter(|t| t.body == body.name).peekable(); + if own.peek().is_none() { + continue; + } + let drawn: Vec> = + lines.iter().filter(|l| l.shown == at).flat_map(|l| l.pieces.iter().map(|p| Drawn { visibility: p.visibility, path: &p.path })).collect(); + for thread in own.filter_map(Thread::of) { + // The crest's lines lie off it by up to the chord's sag, as their arcs' cut points do. + let near_mm = near(model_chord_mm, thread.crest_radius.max(thread.root_radius)) * factor; + let pieces = thread_lines::on_paper(frame, &thread, &drawn, near_mm); + if !pieces.is_empty() { + out.push(ThreadLine { shown: at, reference: one.reference, pieces }); + } + } + } + out +} diff --git a/crates/engine/src/schema/drawing_view.rs b/crates/engine/src/schema/drawing_view.rs index 4d8afce8f16..233937fdc97 100644 --- a/crates/engine/src/schema/drawing_view.rs +++ b/crates/engine/src/schema/drawing_view.rs @@ -1288,6 +1288,29 @@ pub struct LineResult { pub pieces: Vec, } +/// One cosmetic thread's lines in a view. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ThreadResult { + /// The occurrences that place its body, from the design's root. + pub occurrence: Vec, + /// Its body's name in its definition. + pub body: String, + /// Whether the body is a reference part. + pub reference: bool, + pub pieces: Vec, +} + +/// A run of a thread line at one visibility, in paper millimetres. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ThreadPieceResult { + /// `root`: the root diameter's line, drawn thin (a three-quarter arc seen end on); `limit`: the + /// line across where the thread stops inside its face. + pub stroke: &'static str, + /// `visible` or `hidden`. + pub visibility: &'static str, + pub path: Vec, +} + /// What drew a line: an edge of the body (as `model.edges` numbers them), or a silhouette across /// one of its faces. #[derive(Debug, Serialize, JsonSchema)] @@ -1581,6 +1604,9 @@ pub struct SnapshotResult { pub boundary_mm: BoxResult, /// Each placed source's lines, in placement order, then edges before silhouettes. pub lines: Vec, + /// Each cosmetic thread's lines, in placement order: drawn by ISO 6410's convention where the + /// view drew the thread's crest, and seen where that crest is seen. + pub threads: Vec, pub status: LinesStatusResult, pub stats: LinesStatsResult, /// With `scene: true`: the lines as a paper scene of the sheet.