Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Display cosmetic internal and external threads (#2367) (#2868)

amolinari-autotex52e5bc114e74
diff --git a/assets/locales/en.json b/assets/locales/en.json
index b90ba46943..b2464455b4 100644
--- a/assets/locales/en.json
+++ b/assets/locales/en.json
@@ -2594,6 +2594,8 @@
"ui.copy": "Copy",
"ui.corner": "Corner",
"ui.corners": "Corners",
+ "ui.cosmetic_thread_markings": "Cosmetic thread markings",
+ "ui.cosmetic_thread_markings_help": "Show schematic markings on threaded cylindrical walls. Changes only the display, never the design or exports.",
"ui.counterbore": "Counterbore",
"ui.countersink": "Countersink",
"ui.create": "Create",
diff --git a/assets/locales/ja.json b/assets/locales/ja.json
index 9fae5f6c25..8aeb24c3c9 100644
--- a/assets/locales/ja.json
+++ b/assets/locales/ja.json
@@ -2594,6 +2594,8 @@
"ui.copy": "コピー",
"ui.corner": "コーナー",
"ui.corners": "コーナー",
+ "ui.cosmetic_thread_markings": "ねじの簡略表示",
+ "ui.cosmetic_thread_markings_help": "ねじ付き円筒面に簡略化したマークを表示します。表示のみを変更し、設計やエクスポートには影響しません。",
"ui.counterbore": "座ぐり",
"ui.countersink": "皿穴",
"ui.create": "作成",
diff --git a/assets/locales/zh.json b/assets/locales/zh.json
index d5c5d40b07..01fb55b377 100644
--- a/assets/locales/zh.json
+++ b/assets/locales/zh.json
@@ -2594,6 +2594,8 @@
"ui.copy": "复制",
"ui.corner": "角",
"ui.corners": "角点",
+ "ui.cosmetic_thread_markings": "装饰螺纹标记",
+ "ui.cosmetic_thread_markings_help": "在带螺纹的圆柱面上显示示意标记。仅改变显示,不影响设计或导出。",
"ui.counterbore": "沉头孔",
"ui.countersink": "锥形沉孔",
"ui.create": "创建",
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs
index 19e09f4957..1731d06071 100644
--- a/crates/doc/src/eval.rs
+++ b/crates/doc/src/eval.rs
@@ -331,6 +331,8 @@ pub struct ThreadInfo {
pub body: String,
pub designation: String,
pub major_diameter: f64,
+ /// Radius of the actual cylindrical face when the cosmetic thread is evaluated.
+ pub radius: f64,
pub pitch: f64,
pub internal: bool,
pub axis_point: Vec3,
@@ -483,6 +485,7 @@ fn thread_on_impl(
body,
designation: name,
major_diameter: major,
+ radius: cyl.radius,
pitch,
internal: cyl.internal,
axis_point: cyl.axis_point,
@@ -8033,17 +8036,19 @@ pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut
let geom = if ident { c.geom.clone() } else { c.geom.placed(&m) };
out.construct.push(crate::construct::Construct { geom, ..c.clone() });
}
- for t in st
- .threads
- .iter()
- .filter(|t| st.body(&t.body).map(|body| doc.model_body_component(body)).unwrap_or_else(|| comp_of_feature(t.feature)) == comp)
- {
- let mut t2 = t.clone();
- let frame = st.body(&t.body).and_then(|body| doc.model_body_offset(body)).map(|offset| crate::mat_mul(&m, offset)).unwrap_or(m);
- t2.axis_point = crate::apply_point(&frame, t.axis_point);
- t2.axis = crate::apply_vector(&frame, *t.axis).unit().unwrap_or(t.axis);
- out.threads.push(t2);
- }
+ }
+ // Unlike editable sketch guides, cosmetic surfaces belong to every occurrence.
+ for t in st
+ .threads
+ .iter()
+ .filter(|t| st.body(&t.body).map(|body| doc.model_body_component(body)).unwrap_or_else(|| comp_of_feature(t.feature)) == comp)
+ {
+ let mut t2 = t.clone();
+ t2.body = doc.world_body_name(st, &t.body, comp, &path);
+ let frame = st.body(&t.body).and_then(|body| doc.model_body_offset(body)).map(|offset| crate::mat_mul(&m, offset)).unwrap_or(m);
+ t2.axis_point = crate::apply_point(&frame, t.axis_point);
+ t2.axis = crate::apply_vector(&frame, *t.axis).unit().unwrap_or(t.axis);
+ out.threads.push(t2);
}
}
*placed_before = placed_now;
diff --git a/crates/engine/src/cosmetic_threads.rs b/crates/engine/src/cosmetic_threads.rs
new file mode 100644
index 0000000000..4f35f6366e
--- /dev/null
+++ b/crates/engine/src/cosmetic_threads.rs
@@ -0,0 +1,369 @@
+//! Original schematic cylindrical hatching for evaluated cosmetic threads. The segments lie
+//! on the displayed triangles, so neither a separate cylinder nor a helical B-rep is needed.
+use std::collections::HashMap;
+
+use solidcraft_doc::{ModelBody, ThreadInfo};
+use solidcraft_geom::{Mesh, Vec3};
+
+/// Shared upper bound for cosmetic strokes in one viewport/snapshot scene.
+pub const MAX_SCENE_SEGMENTS: usize = 65_536;
+
+/// Shared scene limits, including unsuccessful inspections. Camera-only frames reuse the
+/// viewport's existing scene cache; scene rebuilds cannot restart this budget for each body.
+pub struct Budget {
+ work: usize,
+ strokes: usize,
+}
+
+impl Default for Budget {
+ fn default() -> Self {
+ Self { work: 500_000, strokes: MAX_SCENE_SEGMENTS }
+ }
+}
+
+impl Budget {
+ pub fn available(&self) -> bool {
+ self.work > 0 && self.strokes > 0
+ }
+ fn spend(&mut self, n: usize) -> bool {
+ if n > self.work {
+ self.work = 0;
+ return false;
+ }
+ self.work -= n;
+ self.strokes > 0
+ }
+ /// Bounded preflight before requesting a body's potentially refined display mesh.
+ pub fn has_thread(&mut self, name: &str, threads: &[ThreadInfo]) -> bool {
+ for t in threads {
+ if !self.spend(1) {
+ return false;
+ }
+ if t.body == name {
+ return true;
+ }
+ }
+ false
+ }
+}
+
+/// Depth-tested, section-clippable strokes. Use the same mesh as the visible surface to avoid
+/// fighting a different tessellation. There are at most 32 bands and 32,768 segments per call.
+/// This is a schematic marking, not a representation of the manufactured thread profile.
+pub fn segments(body: &ModelBody, mesh: &Mesh, threads: &[ThreadInfo]) -> Vec<(Vec3, Vec3)> {
+ segments_with_budget(body, mesh, threads, &mut Budget::default())
+}
+
+/// Generate one body's strokes, charging all inspections and emitted segments to the scene.
+pub fn segments_with_budget(body: &ModelBody, mesh: &Mesh, threads: &[ThreadInfo], budget: &mut Budget) -> Vec<(Vec3, Vec3)> {
+ let mut out = Vec::new();
+ // Spread a readable schematic density across ordinary assemblies before hitting a hard
+ // scene cap. A large set of fine-pitch threads need not consume the budget on its first
+ // few occurrences. This is deliberately independent of camera motion and scene caching.
+ let bands = (768.0 / threads.len().max(1) as f64).clamp(4.0, 32.0);
+ if body.body.is_mesh() {
+ return out;
+ }
+ for t in threads {
+ if !budget.spend(1) {
+ return out;
+ }
+ if t.body != body.name {
+ continue;
+ }
+ let length = t.end - t.start;
+ if !t.axis_point.is_finite()
+ || !t.axis.is_finite()
+ || !length.is_finite()
+ || length <= 0.0
+ || !t.start.is_finite()
+ || !t.pitch.is_finite()
+ || t.pitch <= 0.0
+ || !t.major_diameter.is_finite()
+ || t.major_diameter <= 0.0
+ || !t.radius.is_finite()
+ || t.radius <= 0.0
+ {
+ continue;
+ }
+ let seed = if t.axis.x.abs() < 0.9 { Vec3::X } else { Vec3::Y };
+ let Some(u) = t.axis.cross(seed).normalized() else { continue };
+ let tilt = 0.18 * t.radius;
+ let spacing = t.pitch.max((length + 2.0 * tilt) / bands);
+ let tolerance = (t.radius * 1e-6).max(1e-7);
+ let mut faces = HashMap::new();
+ for (tri, face) in mesh.triangles.iter().zip(&mesh.tri_face) {
+ if !budget.spend(1) || out.len() >= 32_768 {
+ return out;
+ }
+ let matched = if let Some(found) = faces.get(face) {
+ *found
+ } else {
+ // face_surface traverses to `face`; charge that traversal too. No unbounded
+ // face collection or full-mesh scan occurs before the budget is checked.
+ if !budget.spend((*face as usize).saturating_add(1)) {
+ return out;
+ }
+ let surface = solidcraft_kernel::guard("cosmetic thread surface", || Ok(solidcraft_kernel::face_surface(&body.body, *face as usize)))
+ .ok()
+ .flatten();
+ let found = match surface {
+ Some(solidcraft_kernel::FaceSurface::Cylinder { origin, axis, radius }) => {
+ let offset = origin - t.axis_point;
+ axis.dot(t.axis).abs() > 1.0 - 1e-6
+ && (offset - t.axis * offset.dot(t.axis)).len() < tolerance
+ && (radius - t.radius).abs() < tolerance
+ }
+ _ => false,
+ };
+ faces.insert(*face, found);
+ found
+ };
+ if !matched {
+ continue;
+ }
+ let Some(points) = mesh.tri(tri) else { continue };
+ let [a, b, c] = points;
+ let center = (a + b + c) / 3.0 - t.axis_point;
+ let radial = center - t.axis * center.dot(t.axis);
+ // Mesh winding distinguishes a bore from a shaft without rescanning the entire
+ // mesh for every cylindrical face.
+ let inward = (b - a).cross(c - a).dot(radial) < 0.0;
+ if inward != t.internal {
+ continue;
+ }
+ // Tilt bands across the placed cylindrical wall. The world-axis seed can change
+ // their schematic orientation after rotation; it never changes their surface.
+ let phase = points.map(|p| {
+ let v = p - t.axis_point;
+ (v.dot(t.axis) - t.start + 0.18 * v.dot(u)) / spacing
+ });
+ // A long face can extend far beyond a short threaded interval. Restrict the
+ // candidate bands before the loop so its budget never hides that interval.
+ let lo = phase.into_iter().fold(f64::INFINITY, f64::min).max(-tilt / spacing).ceil();
+ let hi = phase.into_iter().fold(f64::NEG_INFINITY, f64::max).min((length + tilt) / spacing).floor();
+ if !lo.is_finite() || !hi.is_finite() || lo.abs() > 1e9 || hi.abs() > 1e9 {
+ continue;
+ }
+ for band in (lo as i64..=hi as i64).take(64) {
+ if !budget.spend(1) || out.len() >= 32_768 {
+ return out;
+ }
+ let mut hits = Vec::with_capacity(2);
+ for (i, j) in [(0, 1), (1, 2), (2, 0)] {
+ let (Some(&a), Some(&b), Some(&fa), Some(&fb)) = (points.get(i), points.get(j), phase.get(i), phase.get(j)) else { continue };
+ let level = band as f64;
+ if (fa <= level && fb > level) || (fb <= level && fa > level) {
+ hits.push(a + (b - a) * ((level - fa) / (fb - fa)));
+ }
+ }
+ if let [a, b] = hits.as_slice()
+ && let Some(pair) = trim(*a, *b, t)
+ {
+ out.push(pair);
+ budget.strokes -= 1;
+ }
+ }
+ }
+ }
+ out
+}
+
+fn trim(a: Vec3, b: Vec3, t: &ThreadInfo) -> Option<(Vec3, Vec3)> {
+ let z = (a - t.axis_point).dot(t.axis);
+ let dz = (b - a).dot(t.axis);
+ let (mut lo, mut hi) = (0.0f64, 1.0f64);
+ if dz.abs() < 1e-12 {
+ if z < t.start || z > t.end {
+ return None;
+ }
+ } else {
+ let p = (t.start - z) / dz;
+ let q = (t.end - z) / dz;
+ lo = lo.max(p.min(q));
+ hi = hi.min(p.max(q));
+ }
+ (hi > lo).then(|| (a + (b - a) * lo, a + (b - a) * hi))
+}
+
+#[cfg(test)]
+#[allow(clippy::unwrap_used)]
+mod tests {
+ use super::*;
+ use crate::Session;
+ use serde_json::json;
+
+ fn run(s: &mut Session, command: &str, params: serde_json::Value) {
+ s.execute(command, &params).unwrap();
+ }
+
+ #[test]
+ fn modeled_threads_do_not_receive_cosmetic_strokes() {
+ let mut s = Session::default();
+ run(&mut s, "solid.cylinder", json!({"radius":3,"height":4}));
+ let before = s.world_state().bodies[0].mesh().triangles.len();
+ run(&mut s, "solid.thread", json!({"face":[3,0,3],"designation":"M6","length":2,"modeled":true}));
+ let st = s.world_state();
+ assert!(st.threads.is_empty());
+ assert_ne!(st.bodies[0].mesh().triangles.len(), before);
+ assert!(segments(&st.bodies[0], &st.bodies[0].mesh(), &st.threads).is_empty());
+ }
+
+ #[test]
+ fn downstream_enlargement_is_not_mistaken_for_the_threaded_wall() {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length":20,"width":20,"height":10}));
+ run(&mut s, "solid.hole", json!({"position":[10,10,10],"direction":[0,0,-1],"thread":"M6"}));
+ run(&mut s, "solid.hole", json!({"position":[10,10,10],"direction":[0,0,-1],"diameter":8,"depth":3}));
+ let st = s.world_state();
+ let body = &st.bodies[0];
+ let lines = segments(body, &body.mesh(), &st.threads);
+ assert!(!lines.is_empty());
+ for p in lines.iter().flat_map(|(a, b)| [a, b]) {
+ assert!(p.z <= 7.0 + 1e-6, "enlarged smooth wall must be unmarked: {p:?}");
+ }
+ }
+
+ #[test]
+ fn many_occurrences_have_matching_metadata_and_share_work_and_output_limits() {
+ let mut s = Session::default();
+ let c = s.execute("component.create", &json!({"name":"Pegs"})).unwrap();
+ run(&mut s, "solid.cylinder", json!({"radius":3,"height":20}));
+ run(&mut s, "solid.thread", json!({"face":[3,0,10],"designation":"M6"}));
+ for i in 1..96 {
+ run(&mut s, "occurrence.copy", json!({"component":c["component"],"translate":[i*8,0,0]}));
+ }
+ let st = s.world_state();
+ assert_eq!(st.bodies.len(), 96);
+ assert_eq!(st.threads.len(), 96);
+ let started = std::time::Instant::now();
+ let mut budget = Budget::default();
+ let mut count = 0;
+ for b in &st.bodies {
+ assert!(st.threads.iter().any(|t| t.body == b.name));
+ assert!(!segments(b, &b.mesh(), &st.threads).is_empty(), "{}", b.name);
+ if budget.available() {
+ count += segments_with_budget(b, &b.mesh(), &st.threads, &mut budget).len();
+ }
+ }
+ eprintln!("96 occurrences: {count} strokes; {} work units left; {:?} including per-occurrence verification", budget.work, started.elapsed());
+ assert!(count > 1000 && count <= MAX_SCENE_SEGMENTS);
+ let mut stale = st.threads.clone();
+ for t in &mut stale {
+ t.radius *= 2.0;
+ }
+ let mut budget = Budget { work: 10_000, strokes: MAX_SCENE_SEGMENTS };
+ let mut seen = 0;
+ for b in st.bodies.iter().cycle().take(1000) {
+ if !budget.available() {
+ break;
+ }
+ assert!(segments_with_budget(b, &b.mesh(), &stale, &mut budget).is_empty());
+ seen += 1;
+ }
+ assert!(seen > 1);
+ assert_eq!(budget.work, 0);
+ assert_eq!(budget.strokes, MAX_SCENE_SEGMENTS);
+ }
+
+ #[test]
+ fn tapped_hole_marks_survive_reopen_and_rotated_occurrences() {
+ let mut s = Session::default();
+ // This fixture rotates its first component; new assemblies ground that part by default.
+ let c = s.execute("component.create", &json!({"name":"Plate","grounded":false})).unwrap();
+ run(&mut s, "solid.box", json!({"length":20,"width":20,"height":10,"body_name":"PlateBody"}));
+ run(&mut s, "solid.hole", json!({"position":[10,10,10],"direction":[0,0,-1],"thread":"M6","depth":7}));
+ run(&mut s, "occurrence.move", json!({"occurrence":c["occurrence"],"translate":[30,20,10],"axis":[1,0,0],"angle":"90 deg","capture":true}));
+ let saved = s.doc.to_json();
+ let reopened = solidcraft_doc::Document::from_json(&saved).unwrap();
+ let mut s = Session::new(reopened);
+ let st = s.world_state();
+ assert_eq!(st.threads.len(), 1);
+ assert!(st.threads[0].axis.z.abs() < 1e-6);
+ let body = &st.bodies[0];
+ let lines = segments(body, &body.mesh(), &st.threads);
+ assert!(lines.len() > 20);
+ let t = &st.threads[0];
+ for p in lines.iter().flat_map(|(a, b)| [a, b]) {
+ let z = (*p - t.axis_point).dot(t.axis);
+ assert!(z >= t.start - 1e-8 && z <= t.end + 1e-8);
+ }
+ let mut tiny = t.clone();
+ tiny.pitch = 1e-12;
+ assert!(segments(body, &body.mesh(), &[tiny]).len() <= 32_768);
+ s.execute("solid.thread", &json!({"face":[0,0,0],"designation":"bad"})).unwrap_err();
+ assert_eq!(s.doc.to_json(), saved);
+ }
+
+ #[test]
+ fn cosmetic_internal_and_external_marks_preserve_geometry_and_partial_extent() {
+ for internal in [false, true] {
+ let mut s = Session::default();
+ if internal {
+ run(&mut s, "solid.box", json!({"length":20,"width":20,"height":10,"body_name":"Part"}));
+ run(&mut s, "solid.hole", json!({"position":[10,10,10],"diameter":5,"direction":[0,0,-1]}));
+ } else {
+ run(&mut s, "solid.cylinder", json!({"radius":3,"height":10,"body_name":"Part"}));
+ }
+ let before = s.world_state().bodies[0].mesh();
+ let face = if internal { json!([12.5, 10, 9]) } else { json!([3, 0, 9]) };
+ run(&mut s, "solid.thread", json!({"face":face,"designation":"M6","length":4,"modeled":false}));
+ let st = s.world_state();
+ let body = &st.bodies[0];
+ assert_eq!(before.positions, body.mesh().positions);
+ assert_eq!(before.triangles, body.mesh().triangles);
+ let saved = s.doc.to_json();
+ let lines = segments(body, &body.mesh(), &st.threads);
+ assert!(lines.len() > 20, "{internal}: {}", lines.len());
+ let t = &st.threads[0];
+ for p in lines.iter().flat_map(|(a, b)| [a, b]) {
+ let z = (*p - t.axis_point).dot(t.axis);
+ assert!(z >= t.start - 1e-8 && z <= t.end + 1e-8);
+ assert!(p.is_finite());
+ }
+ assert!(segments(body, &body.mesh(), &[]).is_empty());
+ for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
+ for field in 0..5 {
+ let mut hostile = t.clone();
+ match field {
+ 0 => hostile.pitch = value,
+ 1 => hostile.start = value,
+ 2 => hostile.end = value,
+ 3 => hostile.axis_point.x = value,
+ _ => hostile.radius = value,
+ }
+ assert!(segments(body, &body.mesh(), &[hostile]).is_empty());
+ }
+ }
+ assert_eq!(s.doc.to_json(), saved);
+ let scene = crate::view::scene(&s, &crate::render::Camera::default());
+ assert!(!scene.lines.iter().any(|l| l.width == 0.85), "ordinary snapshots preserve the default-off behavior");
+ for distance in [25.0, 60.0] {
+ let cam = crate::render::Camera {
+ target: if internal { Vec3::new(10., 10., 5.) } else { Vec3::new(0., 0., 5.) },
+ distance,
+ ..Default::default()
+ };
+ for section in [None, Some((cam.target, Vec3::X))] {
+ let mut scene = crate::view::scene_with_thread_markings(
+ &s,
+ &cam,
+ section,
+ crate::view::world_curve_parts,
+ &crate::view::Palette::DEFAULT,
+ Default::default(),
+ true,
+ );
+ assert!(scene.lines.iter().any(|l| l.width == 0.85 && !l.on_top));
+ let marked = crate::render::render(&scene, &cam, 320, 240).rgba;
+ scene.lines.retain(|l| l.width != 0.85);
+ let plain = crate::render::render(&scene, &cam, 320, 240).rgba;
+ let changed = marked.as_chunks::<4>().0.iter().zip(plain.as_chunks::<4>().0.iter()).filter(|(a, b)| a != b).count();
+ assert!(changed > 15, "internal={internal}, distance={distance}, section={section:?}: {changed}");
+ }
+ }
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert!(s.world_state().threads.is_empty());
+ }
+ }
+}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 05c91f9ffb..d9a742a140 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -13,6 +13,7 @@ pub mod capture;
pub mod cmd;
pub mod control_auth;
pub mod control_pending;
+pub mod cosmetic_threads;
pub mod crash;
pub mod frames;
pub mod fuzz;
diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs
index 21c024c58d..59fa0408d6 100644
--- a/crates/engine/src/view.rs
+++ b/crates/engine/src/view.rs
@@ -419,7 +419,7 @@ pub fn scene_with_palette(
sampler: impl FnMut(&Sketch, usize, &Plane) -> Vec<Vec<Vec3>>,
p: &Palette,
) -> Scene {
- build_scene(s, cam, section, Guides::default(), sampler, p)
+ build_scene(s, cam, section, Guides::default(), sampler, p, false)
}
/// [`scene_with_palette`] with the ground grid and the origin's axes shown or left out.
@@ -431,7 +431,21 @@ pub fn scene_with_palette_and_guides(
p: &Palette,
guides: Guides,
) -> Scene {
- build_scene(s, cam, section, guides, sampler, p)
+ build_scene(s, cam, section, guides, sampler, p, false)
+}
+
+/// A picture of the view with cosmetic thread markings explicitly enabled or disabled.
+/// The ordinary scene helpers leave these optional markings off.
+pub fn scene_with_thread_markings(
+ s: &Session,
+ cam: &Camera,
+ section: Option<(Vec3, Vec3)>,
+ sampler: impl FnMut(&Sketch, usize, &Plane) -> Vec<Vec<Vec3>>,
+ p: &Palette,
+ guides: Guides,
+ cosmetic_threads: bool,
+) -> Scene {
+ build_scene(s, cam, section, guides, sampler, p, cosmetic_threads)
}
fn build_scene(
@@ -441,6 +455,7 @@ fn build_scene(
guides: Guides,
mut sampler: impl FnMut(&Sketch, usize, &Plane) -> Vec<Vec<Vec3>>,
p: &Palette,
+ cosmetic_threads: bool,
) -> Scene {
let st = s.world_state();
let section = section.filter(|(o, n)| o.is_finite() && n.is_finite() && n.len() > 1e-9);
@@ -496,6 +511,7 @@ fn build_scene(
})
.flatten()
.collect();
+ let mut thread_budget = crate::cosmetic_threads::Budget::default();
for body in st.bodies.iter().filter(|b| s.body_visible(&b.name)) {
let selected = selected_occurrences.contains(&body.name) || s.selection.iter().any(|x| matches!(x, Sel::Body { name } if *name == body.name));
let mesh = body.mesh();
@@ -512,6 +528,15 @@ fn build_scene(
// body is drawn solid, so the selection colour reads.
let opacity = if selected { 1.0 } else { s.doc.model_body_opacity(body) as f32 };
sc.meshes.push(SceneMesh { mesh: Arc::clone(&mesh), color, face_colors, opacity });
+ if cosmetic_threads
+ && thread_budget.available()
+ && s.doc.model_body_opacity(body) >= 0.999
+ && s.doc.face_colors(body).iter().all(|(_, l)| l.opacity >= 0.999)
+ {
+ for (a, b) in crate::cosmetic_threads::segments_with_budget(body, &mesh, &st.threads, &mut thread_budget) {
+ sc.lines.push(SceneLine { points: vec![a, b], color: p.edge, width: 0.85, on_top: false });
+ }
+ }
for (i, e) in mesh.edges.iter().enumerate() {
if !mesh.shaded_edge_visible(i) {
continue;
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 590a8689c7..f08f9bd925 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -287,13 +287,14 @@ pub fn request_scope(app: &SolveApp, params: &Value) -> Result<Option<vfs::PathS
/// mode, the section the viewport shows: an open Section Analysis dialog's preview, a sketch's
/// Slice), with the grid and the origin's axes as `guides` says.
pub(crate) fn view_scene(app: &SolveApp, guides: solidcraft_engine::view::Guides) -> solidcraft_engine::render::Scene {
- let mut scene = solidcraft_engine::view::scene_with_palette_and_guides(
+ let mut scene = solidcraft_engine::view::scene_with_thread_markings(
&app.session,
&app.cam,
crate::viewport::section_plane(app),
solidcraft_engine::view::world_curve_parts,
&crate::viewport::scene_palette(app.ui.dark, app.preferences.color_vision),
guides,
+ app.preferences.cosmetic_threads,
);
scene.plain_cap = !crate::viewport::section_hatch(app);
scene
@@ -1222,6 +1223,30 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
+ #[test]
+ fn model_render_cosmetic_threads_preserve_section_hatch_preview() {
+ let mut app = SolveApp::new(Session::default(), Services::default());
+ for cosmetic_threads in [false, true] {
+ app.preferences.cosmetic_threads = cosmetic_threads;
+ for hatch in [false, true] {
+ app.session.section_hatch = hatch;
+ assert_eq!(view_scene(&app, Default::default()).plain_cap, !hatch);
+ app.session.selection = vec![Sel::Plane { name: "XZ".into() }];
+ app.start("inspect.section");
+ let Some(crate::dialogs::Kind::Section { hatch: preview_hatch, .. }) = app.dialog.as_mut().map(|d| &mut d.kind) else {
+ panic!("no section dialog")
+ };
+ *preview_hatch = !hatch;
+ assert_eq!(
+ view_scene(&app, Default::default()).plain_cap,
+ hatch,
+ "the preview's hatch overrides the session with cosmetic_threads={cosmetic_threads}"
+ );
+ app.dialog = None;
+ }
+ }
+ }
+
/// `ui.render` with extra request parameters.
fn render_with(app: &mut SolveApp, path: &std::path::Path, extra: serde_json::Value) -> Vec<u8> {
let mut params = json!({"path": path.to_string_lossy(), "width": 200, "height": 140});
diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs
index 02cb2ba5d8..dee99d8d92 100644
--- a/crates/ui-egui/src/prefs.rs
+++ b/crates/ui-egui/src/prefs.rs
@@ -515,6 +515,8 @@ preference_settings! {
window_system: String = "auto".into(), PAGE_GRAPHICS;
/// Soft contact shading in the GPU viewport; optional and applied immediately.
ambient_occlusion: bool = false, PAGE_GRAPHICS;
+ /// Optional schematic markings on threaded cylindrical walls; off for new and older preferences.
+ cosmetic_threads: bool = false, PAGE_GRAPHICS;
/// The grid turns to the upright origin plane facing a side view (#1470). Off by default: the
/// grid stays on the ground plane (XY) whatever the view.
grid_follows_view: bool = false => check("Grid follows the view", "Side views show the grid on the upright plane facing them instead of the ground");
@@ -3737,6 +3739,37 @@ mod tests {
assert!(h.app.preferences.radial_context_menu, "Cancel restores the last Apply");
}
+ #[test]
+ fn cosmetic_threads_default_off_and_follow_preferences_transactions() {
+ assert!(!Prefs::default().cosmetic_threads);
+ let old: Prefs = serde_json::from_value(json!({"theme":"light","msaa":4})).unwrap();
+ assert!(!old.cosmetic_threads && old.theme == "light" && old.msaa == 4);
+ let malformed = lenient(&json!({"cosmetic_threads":"yes","theme":"light"}));
+ assert!(!malformed.cosmetic_threads && malformed.theme == "light");
+ let mut h = crate::scenario::Harness::new();
+ let design = h.app.session.doc.to_json();
+ h.call("ui.prefs", json!({"open":"Graphics"}));
+ super::reveal_preference(&mut h, "prefs:cosmetic_threads");
+ let checkbox = crate::scenario::handle_at("prefs:cosmetic_threads").unwrap();
+ h.call("ui.click", json!({"x":checkbox.x,"y":checkbox.y}));
+ assert!(h.app.preferences.cosmetic_threads, "the actual checkbox enables the optional markings");
+ let mut restored = SolveApp::new(solidcraft_engine::Session::default(), Default::default());
+ restored.load_prefs(&h.app.prefs());
+ assert!(restored.preferences.cosmetic_threads, "the preference survives saved application settings");
+ h.call("ui.prefs", json!({"button":"cancel"}));
+ assert!(!h.app.preferences.cosmetic_threads);
+ h.call("ui.prefs", json!({"open":"Graphics","cosmetic_threads":true,"button":"apply"}));
+ h.call("ui.prefs", json!({"button":"defaults"}));
+ assert!(!h.app.preferences.cosmetic_threads, "Graphics defaults restore the default-off policy");
+ h.call("ui.prefs", json!({"button":"cancel"}));
+ assert!(h.app.preferences.cosmetic_threads, "Cancel restores the last Apply");
+ h.call("ui.prefs", json!({"cosmetic_threads":false}));
+ restored.load_prefs(&h.app.prefs());
+ assert!(!restored.preferences.cosmetic_threads, "an explicitly disabled value also survives reload");
+ assert_eq!(h.app.session.doc.to_json(), design);
+ assert!(h.app.session.undo.is_empty());
+ }
+
#[test]
fn tool_modifier_prefs_default_classic_and_persist() {
let d = Prefs::default();
diff --git a/crates/ui-egui/src/prefs/graphics.rs b/crates/ui-egui/src/prefs/graphics.rs
index 9534485dc5..efef8ae1d8 100644
--- a/crates/ui-egui/src/prefs/graphics.rs
+++ b/crates/ui-egui/src/prefs/graphics.rs
@@ -118,6 +118,9 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
ui_kit::text(ui, app.tr("prefs.contact_shading_note"), ui_kit::Text::Hint("ao"));
});
ui_kit::settings_section(ui, "viewport", app.tr("prefs.viewport"), |ui| {
+ let response = ui_kit::checkbox(ui, app.tr("ui.cosmetic_thread_markings"), &mut app.preferences.cosmetic_threads)
+ .on_hover_text(app.tr("ui.cosmetic_thread_markings_help"));
+ crate::scenario::publish_handle("prefs:cosmetic_threads", response.rect.center());
ui.columns(2, |columns| {
if let Some(left) = columns.get_mut(0) {
ui_kit::checkbox(left, crate::i18n::tr_label("Grid"), &mut app.ui.show_grid);
diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs
index 1c016ea52b..4d5d19a223 100644
--- a/crates/ui-egui/src/viewport.rs
+++ b/crates/ui-egui/src/viewport.rs
@@ -402,6 +402,7 @@ fn scene_key(app: &SolveApp) -> u64 {
app.session.active_occurrence_path.hash(&mut h);
app.preview.effective_replaced().hash(&mut h);
app.preview.rolled_back.hash(&mut h);
+ app.preferences.cosmetic_threads.hash(&mut h);
app.tree.redefine.hash(&mut h);
crate::theme::is_dark().hash(&mut h);
crate::theme::vision().hash(&mut h);
@@ -946,8 +947,22 @@ pub(crate) fn build_scene(app: &SolveApp) -> GpuScene {
// are drawn as instances of them: one copy of the triangles on the GPU, and none moved on
// the CPU.
let mut instances = Instances::new(app, &shown, shaded);
+ let mut thread_budget = solidcraft_engine::cosmetic_threads::Budget::default();
for b in shown {
let faded = body_faded(app, b, &active_bodies);
+ if app.preferences.cosmetic_threads
+ && thread_budget.available()
+ && shaded
+ && !faded
+ && thread_budget.has_thread(&b.name, &st.threads)
+ && s.doc.model_body_opacity(b) >= 0.999
+ && s.doc.face_colors(b).iter().all(|(_, l)| l.opacity >= 0.999)
+ {
+ let mesh = shown_mesh(app, b, &active_bodies);
+ for (a, c) in solidcraft_engine::cosmetic_threads::segments_with_budget(b, &mesh, &st.threads, &mut thread_budget) {
+ sc.line(a.to_f32(), c.to_f32(), c4(tk.body_edge), 0.85, false);
+ }
+ }
let base = body_color(&s.doc, b).unwrap_or(tk.body);
let col = if faded { c4(base.gamma_multiply(0.35)) } else { c4(base) };
// Appearances: the body's opacity, and faces with looks of their own.
@@ -8148,6 +8163,128 @@ mod tests {
}
}
+ #[test]
+ fn cosmetic_threads_use_depth_tested_lines_and_keep_selection_and_wireframe() {
+ let mut s = solidcraft_engine::Session::default();
+ s.execute("solid.cylinder", &json!({"radius":3,"height":10})).unwrap();
+ s.execute("solid.thread", &json!({"face":[3,0,5],"designation":"M6","length":5})).unwrap();
+ let mut app = SolveApp::new(s, crate::Services::default());
+ let count = |sc: GpuScene| {
+ sc.merged()
+ .lines
+ .as_chunks::<{ crate::gpu::LINE_SIZE }>()
+ .0
+ .iter()
+ .filter(|line| line.get(28..32) == Some(0.85f32.to_le_bytes().as_slice()))
+ .count()
+ };
+ assert_eq!(count(build_scene(&app)), 0, "markings are off by default");
+ let off_key = scene_key(&app);
+ app.preferences.cosmetic_threads = true;
+ assert_ne!(scene_key(&app), off_key, "toggling invalidates the scene without a camera move");
+ assert!(count(build_scene(&app)) > 20);
+ assert!(crate::control::view_scene(&app, Default::default()).lines.iter().any(|l| l.width == 0.85));
+ app.preferences.cosmetic_threads = false;
+ assert_eq!(count(build_scene(&app)), 0);
+ assert!(!crate::control::view_scene(&app, Default::default()).lines.iter().any(|l| l.width == 0.85));
+ app.preferences.cosmetic_threads = true;
+ app.session.selection = vec![Sel::Face { body: "Body1".into(), index: 0, point: Vec3::new(3., 0., 5.) }];
+ let selection = app.session.selection.clone();
+ assert!(count(build_scene(&app)) > 20);
+ assert!(!build_highlight(&app).merged().tris.is_empty());
+ assert_eq!(app.session.selection, selection);
+ app.ui.visual_style = 2;
+ assert_eq!(count(build_scene(&app)), 0);
+ app.ui.visual_style = 0;
+ app.session.visibility.hidden_bodies.push("Body1".into());
+ assert_eq!(count(build_scene(&app)), 0);
+ app.session.visibility.hidden_bodies.clear();
+ app.session.doc_mut().appearances.bodies.insert("Body1".into(), solidcraft_engine::doc::appearance::Look::custom([150, 150, 150], 0.5));
+ assert_eq!(count(build_scene(&app)), 0, "transparent bodies omit cosmetic strokes");
+ app.session.doc_mut().appearances.bodies.clear();
+ app.session.execute("component.create", &json!({"name":"Other active component"})).unwrap();
+ assert_eq!(count(build_scene(&app)), 0, "inactive bodies are faded and unmarked");
+ }
+
+ #[test]
+ fn cosmetic_threads_preference_controls_internal_and_external_markings_without_editing_the_design() {
+ for internal in [false, true] {
+ let mut s = solidcraft_engine::Session::default();
+ let face = if internal {
+ s.execute("solid.box", &json!({"length":20,"width":20,"height":10})).unwrap();
+ s.execute("solid.hole", &json!({"position":[10,10,10],"direction":[0,0,-1],"diameter":5})).unwrap();
+ json!([12.5, 10, 9])
+ } else {
+ s.execute("solid.cylinder", &json!({"radius":3,"height":10})).unwrap();
+ json!([3, 0, 9])
+ };
+ s.execute("solid.thread", &json!({"face":face,"designation":"M6","length":4})).unwrap();
+ let mut app = SolveApp::new(s, crate::Services::default());
+ let design = app.session.doc.to_json();
+ let camera = app.cam;
+ let count = |app: &SolveApp| {
+ build_scene(app)
+ .merged()
+ .lines
+ .as_chunks::<{ crate::gpu::LINE_SIZE }>()
+ .0
+ .iter()
+ .filter(|line| line.get(28..32) == Some(0.85f32.to_le_bytes().as_slice()))
+ .count()
+ };
+ let key = scene_key(&app);
+ assert_eq!(count(&app), 0);
+ crate::prefs::set(&mut app, &json!({"cosmetic_threads":true})).unwrap();
+ assert_ne!(scene_key(&app), key);
+ assert!(count(&app) > 20, "internal={internal}");
+ assert!(crate::control::view_scene(&app, Default::default()).lines.iter().any(|l| l.width == 0.85));
+ crate::prefs::set(&mut app, &json!({"cosmetic_threads":false})).unwrap();
+ assert_eq!(scene_key(&app), key);
+ assert_eq!(count(&app), 0);
+ assert_eq!(app.session.doc.to_json(), design);
+ assert_eq!(app.cam, camera);
+ }
+ }
+
+ #[test]
+ fn cosmetic_thread_scene_is_bounded_for_many_occurrences_and_cached_across_camera_moves() {
+ let mut s = solidcraft_engine::Session::default();
+ let c = s.execute("component.create", &json!({"name":"Threaded pegs"})).unwrap();
+ s.execute("solid.cylinder", &json!({"radius":3,"height":20})).unwrap();
+ s.execute("solid.thread", &json!({"face":[3,0,10],"designation":"M6"})).unwrap();
+ for i in 1..96 {
+ s.execute("occurrence.copy", &json!({"component":c["component"],"translate":[i*8,0,0]})).unwrap();
+ }
+ s.execute("component.activate", &json!({"component":0})).unwrap();
+ let mut app = SolveApp::new(s, crate::Services::default());
+ let started = std::time::Instant::now();
+ app.preferences.cosmetic_threads = true;
+ let scene = build_scene(&app).merged();
+ let strokes = scene
+ .lines
+ .as_chunks::<{ crate::gpu::LINE_SIZE }>()
+ .0
+ .iter()
+ .filter(|line| line.get(28..32) == Some(0.85f32.to_le_bytes().as_slice()))
+ .count();
+ eprintln!("96 occurrence viewport scene: {strokes} cosmetic strokes, {:?}", started.elapsed());
+ assert!(strokes > 1000 && strokes <= solidcraft_engine::cosmetic_threads::MAX_SCENE_SEGMENTS);
+ let marked_occurrences: std::collections::HashSet<i32> = scene
+ .lines
+ .as_chunks::<{ crate::gpu::LINE_SIZE }>()
+ .0
+ .iter()
+ .filter(|line| line.get(28..32) == Some(0.85f32.to_le_bytes().as_slice()))
+ .filter_map(|line| line.get(0..4).and_then(|bytes| bytes.try_into().ok()).map(f32::from_le_bytes))
+ .map(|x| (x / 8.0).round() as i32)
+ .collect();
+ assert_eq!(marked_occurrences.len(), 96, "schematic density shares strokes across all 96 pegs");
+ let key = scene_key(&app);
+ app.cam.distance *= 1.5;
+ app.cam.yaw += 0.2;
+ assert_eq!(scene_key(&app), key, "ordinary camera changes reuse the scene; LOD changes have their own generation");
+ }
+
#[test]
fn section_outlines_follow_the_cut() {
let mut s = solidcraft_engine::Session::default();
diff --git a/docs/cosmetic-threads.md b/docs/cosmetic-threads.md
new file mode 100644
index 0000000000..a18dd6123d
--- /dev/null
+++ b/docs/cosmetic-threads.md
@@ -0,0 +1,46 @@
+# Cosmetic thread display
+
+Cosmetic markings are **off by default**, including when preferences saved by an older
+version have no setting for them. Turn on **Preferences > Graphics > Cosmetic thread markings**
+to display them. The switch applies immediately, without moving the camera or rebuilding
+the design, and is saved in application preferences. Cancel, Apply and Restore Defaults
+follow the other Graphics settings. It is not a document property or a geometry feature.
+
+Tapped Hole and non-modeled Thread features now mark the threaded cylindrical wall with
+original, slightly tilted bands. Plain holes remain smooth. Both internal and external
+threads use the evaluated thread metadata, including partial length and occurrence placement.
+This is schematic hatching, not a manufactured thread profile or helical solid.
+
+The strokes lie on the same triangles as the displayed surface, follow display refinement,
+use the existing edge color and depth-tested line renderer, and are clipped by section planes.
+Selection and hover still use the original faces and their normal highlight passes. No
+geometry, volume, physical material, design format, or mesh-export data changes.
+
+The shaded desktop/web viewport and its GPU/CPU model snapshots share the setting and the
+same marking generator. Ordinary headless scene helpers leave markings off; callers can
+explicitly request them through `scene_with_thread_markings`. The marking needs no texture
+file, compute shader or new graphics capability.
+The wireframe viewport omits the marking. Transparent or faded bodies omit it because the
+ordinary depth-tested line pass cannot represent their visibility correctly.
+
+Pitch determines spacing until a bounded schematic density is reached (up to 32 bands).
+Large threaded assemblies reduce the density target, down to four bands, before the hard
+scene limits apply so repeated parts share the marking budget. Short regions may show fewer
+bands. The count includes hidden thread metadata, so hiding parts does not increase density.
+Strokes have a fixed subpixel output width, like the existing edge renderer; very small holes
+may still require zooming in. A face must remain an analytic cylinder, coaxial with the stored
+thread and within its diameter range. Removed/replaced or unsupported surfaces are not marked.
+One shared scene budget bounds successful and unsuccessful work (500,000 inspection units,
+65,536 strokes; 32,768 per body). Lazy face classification also charges face traversal. The
+viewport caches the scene across ordinary camera moves; LOD refinement rebuilds it with a fresh
+bounded budget. Very large models can therefore omit later markings. This is not a thread inspection or dimension
+tool. There is no separate major-diameter entry circle. Physically modeled threads continue
+to display their actual geometry and do not receive this cosmetic hatch.
+
+The evaluated metadata records the target cylinder's actual radius and placed body name.
+This prevents marking a later enlarged bore and keeps copied/rotated occurrences associated
+with their own walls. It adds no saved feature field. The schematic band's orientation can
+change after arbitrary rotations because its tilt seed uses world axes.
+
+The marking is an original Rust construction using SolidCraft's existing line and material
+conventions. It introduces no artwork, texture assets or dependencies.