SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Joint symbols: a square for rigid joints, sized to the joined parts, faint where they pile up (#6404) (#6742)
sascha21010678ec98c3c6
diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rsindex 97a8495a59..2a2bb88e15 100644--- a/crates/ui-egui/src/dialogs_assembly.rs+++ b/crates/ui-egui/src/dialogs_assembly.rs@@ -2420,31 +2420,175 @@ pub fn drawn_joints(app: &SolveApp) -> Vec<(u64, bool)> {.collect()}-/// Joint glyphs in the viewport: a ring where the joint sits, its motion axis, and its limits-/// (ticks on the ring for a turn, along the axis for a slide). Glyphs are only drawn; they are-/// never picked in the viewport.-pub fn joint_glyphs(app: &SolveApp, painter: &egui::Painter, proj: &Proj) {+thread_local! {+ /// The size (box diagonal) of each occurrence's bodies, for the design revision it was found in.+ static OCCURRENCE_SIZES: std::cell::RefCell<Option<(u64, std::collections::HashMap<u64, f64>)>> = const { std::cell::RefCell::new(None) };+}++/// The size (box diagonal, mm) of each occurrence's bodies, including those of the occurrences+/// inside it; occurrence 0 is the root's own bodies. Found once per design revision, in one+/// pass over the bodies, as [`occurrence_bounds`] would find it for each occurrence.+fn occurrence_sizes(s: &Session) -> std::collections::HashMap<u64, f64> {+ let rev = s.revision;+ if let Some(v) = OCCURRENCE_SIZES.with(|o| o.borrow().as_ref().filter(|(k, _)| *k == rev).map(|(_, v)| v.clone())) {+ return v;+ }+ let model = s.model.state();+ let Ok(world) = s.world_state() else { return std::collections::HashMap::new() };+ let mut boxes: std::collections::HashMap<u64, Aabb3> = std::collections::HashMap::new();+ for (name, _, path, _) in s.doc.body_frames(&model) {+ let Some(b) = world.body(&name) else { continue };+ let bb = b.mesh().bounds();+ let owners: Vec<u64> = if path.is_empty() { vec![0] } else { path.clone() };+ for o in owners {+ let e = boxes.entry(o).or_default();+ *e = e.union(&bb);+ }+ }+ let v: std::collections::HashMap<u64, f64> = boxes.into_iter().filter(|(_, b)| !b.is_empty()).map(|(o, b)| (o, b.diagonal())).collect();+ OCCURRENCE_SIZES.with(|o| *o.borrow_mut() = Some((rev, v.clone())));+ v+}++/// A joint glyph's axis half-length is at most this share of the view height ...+const GLYPH_VIEW_SHARE: f64 = 0.05;+/// ... and at most this share of the smaller joined part's size, so zoomed out the glyphs+/// shrink with the parts they join instead of covering them (#6404).+const GLYPH_PART_SHARE: f64 = 0.25;+/// The half size (screen points) of a rigid joint's square mark.+const RIGID_MARK: f32 = 3.5;++/// How one joint's glyph is drawn.+#[derive(Clone, Debug, PartialEq)]+pub(crate) struct JointGlyph {+ pub id: u64,+ pub picked: bool,+ /// A rigid joint has no motion: a small square, no axis or ring.+ pub rigid: bool,+ /// Half the motion axis (world mm); the ring's radius is half of it.+ pub len: f64,+ /// Lies on a glyph drawn before it (zoomed out, joints piled up): drawn faint.+ pub faded: bool,+ pub centre: Pos2,+}++/// The glyphs to draw, in drawing order: picked joints first, then moving joints, then rigid+/// ones. Each is sized to the view and to the parts it joins; one whose centre falls inside a+/// glyph planned before it is faded, unless it is picked.+pub(crate) fn joint_glyph_plan(app: &SolveApp, proj: &Proj) -> Vec<JointGlyph> {let drawn = drawn_joints(app);if drawn.is_empty() {- return;+ return Vec::new();}- let t = Tokens::get();let frames = joint_frames_world(&app.session);- let len = app.cam.half_height() * 2.0 * 0.05;+ let sizes = occurrence_sizes(&app.session);+ let view_len = app.cam.half_height() * 2.0 * GLYPH_VIEW_SHARE;let at = |m: &solidcraft_engine::doc::Mat, x: f64, y: f64, z: f64| solidcraft_engine::doc::apply_point(m, Vec3::new(x, y, z));+ let mut plan = Vec::new();for (id, picked) in drawn {let Some(j) = app.session.doc.assembly.joints.iter().find(|j| j.id == id) else { continue };let Some((_, m)) = frames.iter().find(|(f, _)| *f == id) else { continue };- let col = if picked {+ let Some(centre) = proj.to_screen(at(m, 0.0, 0.0, 0.0)) else { continue };+ let part = [j.a.occurrence, j.b.occurrence]+ .iter()+ .filter_map(|o| sizes.get(o).copied())+ .filter(|d| d.is_finite() && *d > 0.0)+ .fold(f64::INFINITY, f64::min);+ let len = view_len.min(part * GLYPH_PART_SHARE);+ plan.push((JointGlyph { id, picked, rigid: j.kind == JointKind::Rigid, len, faded: false, centre }, *m));+ }+ plan.sort_by_key(|(g, _)| (!g.picked, g.rigid));+ // Screen reach of each glyph: its ring (or a rigid mark), for the overlap test.+ let reach = |g: &JointGlyph, m: &solidcraft_engine::doc::Mat| -> f32 {+ if g.rigid {+ return RIGID_MARK;+ }+ let r = g.len * 0.5;+ [(r, 0.0, 0.0), (0.0, r, 0.0)]+ .iter()+ .filter_map(|p| proj.to_screen(at(m, p.0, p.1, p.2)))+ .map(|q| q.distance(g.centre))+ .fold(RIGID_MARK, f32::max)+ };+ let mut placed: Vec<(Pos2, f32)> = Vec::new();+ for (g, m) in &mut plan {+ let r = reach(g, m);+ g.faded = !g.picked && placed.iter().any(|(c, rc)| c.distance(g.centre) < rc.max(r));+ if !g.faded {+ placed.push((g.centre, r));+ }+ }+ plan.into_iter().map(|(g, _)| g).collect()+}++/// How near (screen points) the pointer must come to a glyph's centre for its tooltip.+const GLYPH_TIP_REACH: f32 = 8.0;++/// The joint whose glyph the pointer at `pos` is on: the nearest centre within reach, and of+/// glyphs on the same spot the one drawn on top (#6404).+pub(crate) fn joint_glyph_at(plan: &[JointGlyph], pos: Pos2) -> Option<u64> {+ plan.iter().map(|g| (g.id, g.centre.distance(pos))).filter(|(_, d)| *d <= GLYPH_TIP_REACH).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(id, _)| id)+}++/// A glyph's tooltip: the joint's name and type, e.g. "Glue (Rigid)", or the name alone when it says the type ("Rigid 7"), so the square, ring and+/// axis explain themselves (#6404).+pub(crate) fn joint_glyph_tip(app: &SolveApp, id: u64) -> Option<String> {+ let j = app.session.doc.assembly.joints.iter().find(|j| j.id == id)?;+ let kind = app.tr(kind_label(j.kind));+ // A name that already says the type ("Rigid 7") is enough on its own.+ Some(if j.name.to_lowercase().contains(&kind.to_lowercase()) { j.name.clone() } else { format!("{} ({kind})", j.name) })+}++/// Joint glyphs in the viewport: a ring where a moving joint sits, its motion axis and its+/// limits (ticks on the ring for a turn, along the axis for a slide); a small square for a rigid+/// joint. Glyphs are never picked in the viewport; hovering one names the joint and its type.+pub fn joint_glyphs(app: &SolveApp, painter: &egui::Painter, proj: &Proj) {+ let plan = joint_glyph_plan(app, proj);+ if plan.is_empty() {+ return;+ }+ let ctx = painter.ctx();+ let pointer = ctx+ .input(|i| if i.pointer.any_down() { None } else { i.pointer.hover_pos() })+ .filter(|p| painter.clip_rect().contains(*p) && !crate::shell::covered(app, *p));+ if let Some(p) = pointer+ && let Some(id) = joint_glyph_at(&plan, p)+ && let Some(tip) = joint_glyph_tip(app, id)+ {+ egui::containers::Tooltip::always_open(+ ctx.clone(),+ painter.layer_id(),+ egui::Id::unique(("joint_glyph_tip", id)),+ egui::PopupAnchor::Pointer,+ )+ .show(|ui| ui.label(tip));+ }+ let t = Tokens::get();+ let frames = joint_frames_world(&app.session);+ let at = |m: &solidcraft_engine::doc::Mat, x: f64, y: f64, z: f64| solidcraft_engine::doc::apply_point(m, Vec3::new(x, y, z));+ // Back to front, so the glyphs drawn first in the plan end up on top.+ for g in plan.iter().rev() {+ let Some(j) = app.session.doc.assembly.joints.iter().find(|j| j.id == g.id) else { continue };+ let Some((_, m)) = frames.iter().find(|(f, _)| *f == g.id) else { continue };+ crate::scenario::publish_handle(&format!("joint-glyph:{}", j.name), g.centre);+ let col = if g.picked {t.sel_edge} else if j.suppressed {t.text_dim} else {t.accent};- let width = if picked { 2.5 } else { 1.5 };+ let col = if g.faded { col.gamma_multiply(0.3) } else { col };+ let width = if g.picked { 2.5 } else { 1.5 };let stroke = Stroke::new(width, col);- let Some(c) = proj.to_screen(at(m, 0.0, 0.0, 0.0)) else { continue };+ let c = g.centre;+ if g.rigid {+ let half = if g.picked { RIGID_MARK + 1.0 } else { RIGID_MARK };+ let fill = if g.faded { t.panel.gamma_multiply(0.3) } else { t.panel };+ painter.rect(egui::Rect::from_center_size(c, vec2(half * 2.0, half * 2.0)), 0.0, fill, stroke, egui::StrokeKind::Middle);+ continue;+ }+ let len = g.len;// The motion axis (z), both ways.if let (Some(a), Some(b)) = (proj.to_screen(at(m, 0.0, 0.0, -len)), proj.to_screen(at(m, 0.0, 0.0, len))) {painter.line_segment([a, b], stroke);@@ -2461,6 +2605,7 @@ pub fn joint_glyphs(app: &SolveApp, painter: &egui::Painter, proj: &Proj) {painter.add(egui::Shape::line(ring, stroke));}// Limits: ticks across the ring for a turn, across the axis (or slot) for a slide.+ let warning = if g.faded { t.warning.gamma_multiply(0.3) } else { t.warning };for (i, lim) in j.limits.iter().enumerate() {let Some((lo, hi)) = lim else { continue };let name = j.kind.dofs().get(i).copied().unwrap_or("");@@ -2475,14 +2620,19 @@ pub fn joint_glyphs(app: &SolveApp, painter: &egui::Painter, proj: &Proj) {_ => continue,};if let (Some(p), Some(q)) = (proj.to_screen(at(m, p.0, p.1, p.2)), proj.to_screen(at(m, q.0, q.1, q.2))) {- painter.line_segment([p, q], Stroke::new(width, t.warning));+ painter.line_segment([p, q], Stroke::new(width, warning));}}}- painter.circle(c, if picked { 4.5 } else { 3.5 }, t.panel, stroke);+ let fill = if g.faded { t.panel.gamma_multiply(0.3) } else { t.panel };+ painter.circle(c, if g.picked { 4.5 } else { 3.5 }, fill, stroke);}}+#[cfg(test)]+#[path = "joint_glyph_tests.rs"]+mod joint_glyph_tests;+#[cfg(test)]#[path = "joint_browser_tests.rs"]mod joint_browser_tests;diff --git a/crates/ui-egui/src/joint_glyph_tests.rs b/crates/ui-egui/src/joint_glyph_tests.rsnew file mode 100644index 0000000000..abcb2e633e--- /dev/null+++ b/crates/ui-egui/src/joint_glyph_tests.rs@@ -0,0 +1,108 @@+//! Joint glyphs in a crowded assembly (#6404): a rigid joint draws a small square without the+//! motion axis and ring, glyphs shrink with the parts they join when zoomed out, and glyphs+//! piled on one another are drawn faint, except a picked one. Hovering a glyph names the joint+//! and its type.++use serde_json::json;++use crate::dialogs_assembly::{JointGlyph, joint_glyph_at, joint_glyph_plan, joint_glyph_tip};+use crate::scenario::Harness;++/// Components A (grounded), B and C, 20 × 20 × 10 boxes (diagonal 30); B joined to A by a+/// revolute "Hinge", C by a rigid "Glue".+fn harness() -> Harness {+ let mut h = Harness::new();+ h.app.home.open = false;+ crate::test_support::grounded_boxes(&[("A", 0), ("B", 30), ("C", 60)], |id, p| h.app.run(id, p).unwrap());+ h.app+ .run("joint.create", json!({"type": "revolute", "name": "Hinge", "a": {"occurrence": "A:1", "face": [10, 10, 10]}, "b": {"occurrence": "B:1", "face": [40, 10, 0]}}))+ .unwrap();+ h.app+ .run("joint.create", json!({"type": "rigid", "name": "Glue", "a": {"occurrence": "A:1", "face": [20, 10, 5]}, "b": {"occurrence": "C:1", "face": [60, 10, 5]}}))+ .unwrap();+ h.frames(3);+ h+}++fn id(h: &Harness, name: &str) -> u64 {+ h.app.session.doc.assembly.joints.iter().find(|j| j.name == name).unwrap().id+}++/// The glyph plan with the camera `distance` mm from its target.+fn plan_at(h: &mut Harness, distance: f64) -> Vec<JointGlyph> {+ h.app.cam.distance = distance;+ h.frames(2);+ let rect = h.app.viewport.rect.expect("the viewport was laid out");+ joint_glyph_plan(&h.app, &crate::viewport::projection(&h.app, rect))+}++fn glyph(plan: &[JointGlyph], id: u64) -> &JointGlyph {+ plan.iter().find(|g| g.id == id).unwrap_or_else(|| panic!("no glyph for joint {id}: {plan:?}"))+}++#[test]+fn a_rigid_joint_draws_a_square_and_a_moving_joint_its_axis() {+ let mut h = harness();+ let (hinge, glue) = (id(&h, "Hinge"), id(&h, "Glue"));+ let plan = plan_at(&mut h, 120.0);+ assert!(!glyph(&plan, hinge).rigid, "a revolute joint keeps its axis and ring");+ assert!(glyph(&plan, glue).rigid, "a rigid joint has no motion to show");+ let order: Vec<u64> = plan.iter().map(|g| g.id).collect();+ assert_eq!(order, [hinge, glue], "moving joints are planned (and so drawn on top) before rigid ones");+}++#[test]+fn hovering_a_glyph_names_its_joint_and_type() {+ let mut h = harness();+ let (hinge, glue) = (id(&h, "Hinge"), id(&h, "Glue"));+ let plan = plan_at(&mut h, 120.0);+ let (at_hinge, at_glue) = (glyph(&plan, hinge).centre, glyph(&plan, glue).centre);+ assert_eq!(joint_glyph_at(&plan, at_glue + egui::vec2(3.0, -2.0)), Some(glue));+ assert_eq!(joint_glyph_at(&plan, at_hinge), Some(hinge));+ assert_eq!(joint_glyph_at(&plan, at_glue + egui::vec2(20.0, 0.0)), None, "off the glyph: no tooltip");+ assert_eq!(joint_glyph_tip(&h.app, glue).as_deref(), Some("Glue (Rigid)"));+ assert_eq!(joint_glyph_tip(&h.app, hinge).as_deref(), Some("Hinge (Revolute)"));+ // A name that already says the type is not followed by it again.+ if let Some(j) = h.app.session.doc_mut().assembly.joints.iter_mut().find(|j| j.id == glue) {+ j.name = "Rigid 7".into();+ }+ assert_eq!(joint_glyph_tip(&h.app, glue).as_deref(), Some("Rigid 7"));+ // Piled up far out, the pointer names the glyph drawn on top, not the faded one under it.+ let far = plan_at(&mut h, 20_000.0);+ assert_eq!(joint_glyph_at(&far, glyph(&far, hinge).centre), Some(hinge), "{far:?}");+}++#[test]+fn zoomed_out_glyphs_shrink_with_the_parts_they_join() {+ let mut h = harness();+ let hinge = id(&h, "Hinge");+ // Close in, the screen share is the smaller: 5 % of the view height, as before.+ let near = plan_at(&mut h, 40.0);+ let view = h.app.cam.half_height() * 2.0 * 0.05;+ assert!(view < 30.0 * 0.25, "the test's close view is close enough: {view}");+ assert!((glyph(&near, hinge).len - view).abs() < 1e-9, "{near:?}");+ // Far out, a quarter of the joined boxes' diagonal (30 mm) caps it, whatever the zoom.+ for distance in [2_000.0, 20_000.0] {+ let far = plan_at(&mut h, distance);+ assert!(h.app.cam.half_height() * 2.0 * 0.05 > 7.5);+ assert!((glyph(&far, hinge).len - 7.5).abs() < 1e-6, "at {distance} mm: {far:?}");+ }+}++#[test]+fn piled_up_glyphs_fade_but_a_picked_one_does_not() {+ let mut h = harness();+ let (hinge, glue) = (id(&h, "Hinge"), id(&h, "Glue"));+ // Close in, the two glyphs sit apart and both draw in full.+ let near = plan_at(&mut h, 120.0);+ assert!(near.iter().all(|g| !g.faded), "{near:?}");+ // Far out, both land on a few screen points: the first is drawn, the one on it fades.+ let far = plan_at(&mut h, 20_000.0);+ assert!(glyph(&far, hinge).centre.distance(glyph(&far, glue).centre) < 3.5, "{far:?}");+ assert!(!glyph(&far, hinge).faded && glyph(&far, glue).faded, "{far:?}");+ // A picked joint comes first and never fades; the other one on it fades instead.+ h.app.tree.picked_joints.push(glue);+ let picked = plan_at(&mut h, 20_000.0);+ assert_eq!(picked[0].id, glue);+ assert!(!glyph(&picked, glue).faded && glyph(&picked, hinge).faded, "{picked:?}");+}