SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Joints: large assemblies with many closed loops no longer leave a new joint in conflict (#9687) (#11146)
Mateusz Sych7bdaec8f4d79
diff --git a/crates/doc/src/joints.rs b/crates/doc/src/joints.rsindex bc42a1727e..c03a1ee84e 100644--- a/crates/doc/src/joints.rs+++ b/crates/doc/src/joints.rs@@ -1180,7 +1180,8 @@ impl Placements<'_, '_, '_> {}/// Values the loop solver moves at most in one group of loops, and loop-closing joints it takes-/// on at most: larger ones are only checked.+/// on at most: larger ones are only checked (a group with more values moves only those of its+/// loops that need to move, `moving_loops_values`).const MAX_LOOP_VALUES: usize = 64;const MAX_LOOPS: usize = 100;/// Loop-closing joints one solve takes on at most, over all its groups: a part placed by several@@ -1324,19 +1325,7 @@ type Group = (Vec<u64>, BTreeSet<u64>, BTreeSet<(u64, usize)>);fn loop_groups(tree: &Tree, closing: &[u64], asm: &Assembly, linked: &BTreeSet<(u64, usize)>) -> Vec<Group> {let mut groups: Vec<Group> = Vec::new();for id in closing {- let Some(j) = tree.joints.get(id) else { continue };- // A joint between an occurrence and itself (only a hand-edited file has one) is only checked.- if j.a.occurrence == j.b.occurrence {- continue;- }- let side = |occ: u64| -> BTreeSet<u64> { tree.path(occ).1.iter().map(|(k, _)| *k).collect() };- let mut around: BTreeSet<u64> = side(j.a.occurrence).symmetric_difference(&side(j.b.occurrence)).copied().collect();- around.insert(*id);- // The values the loop depends on: its joints' and those its links read. Loops tie together- // through a shared value only (a rigid joint on both paths has none; two values of one- // joint can feed two independent loops).- let mut touches = link_chains(asm, tree, &around, linked).0;- touches.extend(around.iter().filter_map(|id| tree.joints.get(id)).flat_map(|j| (0..j.kind.dofs().len()).map(|i| (j.id, i))));+ let Some((mut around, mut touches)) = one_loop(tree, *id, asm, linked) else { continue };let mut members = vec![*id];groups.retain(|(c, a, t)| {if t.is_disjoint(&touches) {@@ -1352,6 +1341,79 @@ fn loop_groups(tree: &Tree, closing: &[u64], asm: &Assembly, linked: &BTreeSet<(groups}+/// One loop: the closing joint `id` and the joints on the tree paths between its sides, and the+/// values it depends on (its joints' and those its links read). Loops tie together through a+/// shared value only (a rigid joint on both paths has none; two values of one joint can feed two+/// independent loops). None for a joint between an occurrence and itself (only a hand-edited file+/// has one), which is only checked.+fn one_loop(tree: &Tree, id: u64, asm: &Assembly, linked: &BTreeSet<(u64, usize)>) -> Option<(BTreeSet<u64>, BTreeSet<(u64, usize)>)> {+ let j = tree.joints.get(&id)?;+ if j.a.occurrence == j.b.occurrence {+ return None;+ }+ let side = |occ: u64| -> BTreeSet<u64> { tree.path(occ).1.iter().map(|(k, _)| *k).collect() };+ let mut around: BTreeSet<u64> = side(j.a.occurrence).symmetric_difference(&side(j.b.occurrence)).copied().collect();+ around.insert(id);+ let mut touches = link_chains(asm, tree, &around, linked).0;+ touches.extend(around.iter().filter_map(|id| tree.joints.get(id)).flat_map(|j| (0..j.kind.dofs().len()).map(|i| (j.id, i))));+ Some((around, touches))+}++/// The values to move in a group of loops with more than the solver moves at once (a frame of+/// profiles held by many planar joints, #9687): those of the loops that need to move, open at the+/// start (beyond what the conflict check lets pass) or reading a held value that moves, and the+/// closing joints' of the closed loops those values move, when they are few enough. Every loop of+/// the group is still kept closed. None when no loop needs to move, or those that do have too+/// many values themselves. A solve that needs other values of a closed loop (one whose closing+/// joint is rigid) is not found: that group stays a conflict, as a group this size was before.+fn moving_loops_values(+ tree: &Tree,+ closing: &[u64],+ moves: &[(u64, usize, f64, f64)],+ asm: &Assembly,+ held: &Held,+ linked: &BTreeSet<(u64, usize)>,+ vals: &Values,+ scale: f64,+) -> Option<Vec<(u64, usize)>> {+ let moved: BTreeSet<(u64, usize)> = moves.iter().map(|(id, i, ..)| (*id, *i)).collect();+ let mut gaps = Vec::with_capacity(closing.len() * 9);+ closure_gaps(&mut PlacementWorkspace::new(tree), closing, vals, scale, &mut gaps)?;+ let loose = loose_gap(scale);+ let (mut around, mut others) = (BTreeSet::new(), Vec::new());+ for (id, gap) in closing.iter().zip(gaps.chunks(9)) {+ let Some((joints, touches)) = one_loop(tree, *id, asm, linked) else { continue };+ if largest(gap) > loose || !touches.is_disjoint(&moved) {+ around.extend(joints);+ } else {+ others.push((*id, touches));+ }+ }+ let mut vars = unknowns(tree, &around, asm, linked, held);+ if vars.is_empty() {+ return None;+ }+ // A closed loop through a value that moves stays closed by its own closing joint's values+ // (a part slid on one planar joint slides on its second): they are on no tree path, so no other+ // loop runs through them, but a motion link setting one moves the value its chain starts from,+ // and the loops through that follow the same way.+ while vars.len() <= MAX_LOOP_VALUES {+ let moving: BTreeSet<(u64, usize)> = vars.iter().copied().collect();+ let follow: BTreeSet<u64> = others.iter().filter(|(_, touches)| !touches.is_disjoint(&moving)).map(|(id, _)| *id).collect();+ others.retain(|(id, _)| !follow.contains(id));+ let before = vars.len();+ for v in unknowns(tree, &follow, asm, linked, held) {+ if !vars.contains(&v) {+ vars.push(v);+ }+ }+ if vars.len() == before {+ break;+ }+ }+ (vars.len() <= MAX_LOOP_VALUES).then_some(vars)+}+/// The values a solve of the loops `around` moves: every value of their joints but the `held`/// ones and motion-link targets, and the values the targets' link chains start from.fn unknowns(tree: &Tree, around: &BTreeSet<u64>, asm: &Assembly, linked: &BTreeSet<(u64, usize)>, held: &Held) -> Vec<(u64, usize)> {@@ -1651,12 +1713,16 @@ fn close_group(spent: &std::cell::Cell<usize>,vals: &mut Values,) -> Option<BTreeMap<(u64, usize), f64>> {- let vars = unknowns(tree, around, asm, linked, held);+ let scale = loop_scale(tree, around, vals);+ let mut vars = unknowns(tree, around, asm, linked, held);if vars.len() > MAX_LOOP_VALUES {- return Some(BTreeMap::new());+ // Too many to move at once: only the loops that need to move, or none.+ match moving_loops_values(tree, closing, moves, asm, held, linked, vals, scale) {+ Some(few) => vars = few,+ None => return Some(BTreeMap::new()),+ }}let bounds = limit_bounds(tree, &vars);- let scale = loop_scale(tree, around, vals);// Closer than the conflict check needs: 1e-7 mm, and turns of 1e-10 rad across the loop.let tol = (1e-10 * scale).min(1e-7);// The values with the held ones `t` of the way along (and the unknowns at `x`).diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rsindex 3648dadbd9..1ac3b241a0 100644--- a/crates/engine/src/cmd/joints.rs+++ b/crates/engine/src/cmd/joints.rs@@ -89,7 +89,8 @@ pub static COMMANDS: &[CommandSpec] = &[.params("joint; a?, b?: joint origins as joint.create takes them (a side left out keeps its place; the two must stay on different occurrences); \type?, flip?, offset?, angle? (a number, or an expression the joint then follows), suppressed?, name?; the joint re-solves, keeping \- its limits and expressions (a relation's values start again where its parts are)",+ its limits and expressions (a relation's values start again where its parts are); an edit that places it again (not a rename alone) \+ meets a loop it closes as joint.create does, turning an angle a half turn where only that meets it",),CommandSpec::new("joint.delete", "Delete Joint", delete).icon("delete").params("joint: id|name (or origin: name, link: index)"),CommandSpec::new("joint.list", "List Joints", list).icon("list").noundo().params(@@ -792,7 +793,8 @@ const HALF_TURN_TRIALS: usize = 16;/// on the shortest joint path between its two parts, or one of each, a half turn, and keep the/// first that meets it with no new conflict or error elsewhere than `before` had (stored, for/// the caller's resolve). False, and nothing changed, when none does. Values a motion link or an-/// expression sets, and turns their limits stop short, are left alone.+/// expression sets, and turns their limits stop short, are left alone. `joint.edit` does the same+/// for a joint it places again (#9687).fn close_by_half_turn(s: &mut Session, id: u64, before: &joints::Solution) -> bool {let asm = &s.doc.assembly;let Some(new) = asm.joints.iter().find(|j| j.id == id) else { return false };@@ -1644,7 +1646,14 @@ fn edit(s: &mut Session, p: &Value) -> Result<Value> {j.values = q;}}- let sol = resolve(s);+ let mut sol = resolve(s);+ // An edit that places the joint again (Edit Joint's OK, Unsuppress) meets a loop it closes as+ // joint.create does: a joint saved as a conflict before create turned its part (#9687), or+ // unsuppressed after its part was turned away, is met then. A rename alone moves nothing.+ let placed = reseat || bool_(p, "suppressed") == Some(false);+ if placed && sol.conflicts.iter().any(|(c, ..)| *c == id) && close_by_half_turn(s, id, &sol) {+ sol = resolve(s);+ }Ok(sol_json(&sol, p))}diff --git a/crates/engine/src/cmd/joints_tests.rs b/crates/engine/src/cmd/joints_tests.rsindex 44d38676f7..777f3544b2 100644--- a/crates/engine/src/cmd/joints_tests.rs+++ b/crates/engine/src/cmd/joints_tests.rs@@ -778,6 +778,99 @@ fn any_two_sides_of_turned_boards_meet_on_a_second_planar_joint() {}}+/// #9687: a second planar joint left as a conflict, as a design saved before joint.create turned+/// its part a half turn keeps it, meets when Edit Joint's OK places it again, and one unsuppressed+/// after its part was turned away on the first joint meets too. A rename alone moves nothing.+#[test]+fn editing_or_unsuppressing_a_conflicting_second_planar_joint_turns_its_part_to_meet() {+ let conflicts = |r: &Value| r["conflicts"].as_array().map(Vec::len);+ let values = |s: &Session, name: &str| s.doc.assembly.joints.iter().find(|j| j.name == name).map(|j| j.values.clone()).unwrap_or_default();+ let pose = |s: &Session| [Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z].map(|p| place(s, "Red", p));+ let mut s = boards();+ let planar = |s: &mut Session, name: &str, yellow: [f64; 3], red: [f64; 3]| {+ run(+ s,+ "joint.create",+ json!({"type": "planar", "a": {"occurrence": "Yellow", "face": yellow}, "b": {"occurrence": "Red", "face": red}, "name": name}),+ )+ };+ planar(&mut s, "Top", [200.0, 50.0, 20.0], [200.0, 350.0, 0.0]);+ let on_top = values(&s, "Top");+ // The fronts point the same way: Side meets with Red turned a half turn on Top.+ let r = planar(&mut s, "Side", [200.0, 0.0, 10.0], [200.0, 0.0, 30.0]);+ assert_eq!(conflicts(&r), Some(0), "{r}");+ let met = pose(&s);+ // Red as it met, slid along the line the two planes share (X) at most.+ let meets = |s: &Session| {+ let now = pose(s);+ let dx = Vec3::new(now[0].x - met[0].x, 0.0, 0.0);+ now.iter().zip(&met).all(|(p, q)| near(*p, *q + dx))+ };+ // As a design saved before joint.create turned Red: Top's values from before Side.+ if let Some(j) = s.doc_mut().assembly.joints.iter_mut().find(|j| j.name == "Top") {+ j.values = on_top;+ }+ let r = run(&mut s, "joint.solve", json!({}));+ assert_eq!(conflicts(&r), Some(1), "{r}");+ let saved = pose(&s);+ assert!(!meets(&s), "{saved:?}");+ let r = run(&mut s, "joint.edit", json!({"joint": "Side", "name": "Front"}));+ assert_eq!(conflicts(&r), Some(1), "a rename: {r}");+ assert!(pose(&s).iter().zip(&saved).all(|(p, q)| near(*p, *q)), "a rename moved Red: {:?}", pose(&s));+ // Edit Joint's OK sends the type, flip and offset.+ let r = run(&mut s, "joint.edit", json!({"joint": "Front", "type": "planar", "flip": false, "offset": 0}));+ assert_eq!(conflicts(&r), Some(0), "Edit Joint's OK: {r}");+ assert!(meets(&s), "Edit Joint's OK: {:?}", pose(&s));+ assert_eq!(dof_of(&mut s, "Red"), 1);+ // Suppressed, Red turned a half turn away on Top, then unsuppressed.+ run(&mut s, "joint.edit", json!({"joint": "Front", "suppressed": true}));+ let angle = values(&s, "Top").get(2).copied().unwrap_or(f64::NAN).to_degrees();+ run(&mut s, "joint.drive", json!({"joint": "Top", "index": 2, "value": angle + 180.0}));+ assert!(!meets(&s), "turned away: {:?}", pose(&s));+ let r = run(&mut s, "joint.edit", json!({"joint": "Front", "suppressed": false}));+ assert_eq!(conflicts(&r), Some(0), "unsuppressed: {r}");+ assert!(meets(&s), "unsuppressed: {:?}", pose(&s));+}++/// #9687: a frame held by many planar joints ties its loops into one group with more values than+/// the loop solver moves at once, which was then only checked: a new joint closing a loop in it+/// stayed a conflict, and a drive in it moved nothing. A table on the ground, parts each on the+/// table and on the ground (11 parts: 70 values with the peg), and a peg 10 mm from where P0's+/// pin point sits: P0 slides onto it as it does with one part, and turns about it when driven.+#[test]+fn a_loop_in_a_group_over_the_solvers_values_still_closes_and_drives() {+ let conflicts = |r: &Value| r["conflicts"].as_array().map(Vec::len);+ for parts in [1usize, 11] {+ let mut s = Session::default();+ part(&mut s, "Ground", [-1.0, -1.0, -2.0]);+ let g = occ(&s, "Ground");+ run(&mut s, "occurrence.ground", json!({"occurrence": g, "grounded": true}));+ part(&mut s, "Table", [-1.0, -1.0, 0.0]);+ pin(&mut s, "planar", "Base", "Ground", "Table", Vec3::ZERO, Vec3::Z);+ for k in 0..parts {+ let (name, c) = (format!("P{k}"), Vec3::new(10.0 * k as f64, 20.0, 0.0));+ part(&mut s, &name, [c.x - 1.0, c.y - 1.0, 0.0]);+ pin(&mut s, "planar", &format!("{name} on table"), "Table", &name, c, Vec3::Z);+ pin(&mut s, "planar", &format!("{name} on ground"), "Ground", &name, c, Vec3::Z);+ }+ let at = |o: &str, p: [f64; 3]| json!({"occurrence": o, "point": p, "z": [0, 0, 1]});+ let peg = json!({"type": "revolute", "name": "Peg", "a": at("Ground", [10.0, 20.0, 0.0]), "b": at("P0", [0.0, 20.0, 0.0]), "flip": true});+ let r = run(&mut s, "joint.create", peg);+ assert_eq!(conflicts(&r), Some(0), "{parts} parts: {r}");+ let pin_point = Vec3::new(10.0, 20.0, 0.0);+ assert!(near(place(&s, "P0", Vec3::new(0.0, 20.0, 0.0)), pin_point), "{parts} parts: {:?}", place(&s, "P0", Vec3::new(0.0, 20.0, 0.0)));+ // P0's point 1 mm along X from its pin point (closing the loop may have turned P0 a little+ // about the peg), then 30 degrees further round.+ let (p, q0) = (Vec3::new(1.0, 20.0, 0.0), place(&s, "P0", Vec3::new(1.0, 20.0, 0.0)));+ let turn = s.doc.assembly.joints.iter().find(|j| j.name == "Peg").and_then(|j| j.values.first().copied()).unwrap_or(f64::NAN);+ let r = run(&mut s, "joint.drive", json!({"joint": "Peg", "value": turn.to_degrees() + 30.0}));+ assert!(r["stopped_by_loop"].is_null() && conflicts(&r) == Some(0), "{parts} parts: {r}");+ let (a, b) = (q0 - pin_point, place(&s, "P0", p) - pin_point);+ let sin = a.x * b.y - a.y * b.x;+ assert!((b.len() - 1.0).abs() < 1e-6 && (sin.abs() - 0.5).abs() < 1e-6 && b.z.abs() < 1e-6, "{parts} parts: {a:?} to {b:?}");+ }+}+/// A slider-crank: crank 15 about the origin, rod 40, a piston sliding along X. Returns the crank/// pin and the wrist pin.fn slider_crank() -> (Session, Vec3, Vec3) {