* claim: #5968 * Joint dialog: Find Limits fills the limits from where parts collide (#5968) joint.find_limits sweeps each value of a joint both ways from where it is, on a copy and with its own limits left out, and answers where the parts it moves first touch another part, where a closed loop stops closing, or that nothing is met within a turn (angles) or the parts' reach (distances). Edit Joint's Limits section gets a Find Limits button that runs it on the joint as the dialog has it, off the window thread, and fills the rows. joint.sweep now tells touching bodies apart from the other bodies of the same two parts: on the Hinge Assembly sample the pins touch where it starts, and the plates used to pass through each other unnoticed. * find_limits: read the session only * find_limits: a joint with nothing to meet, edits during a search, tiny ranges * find_limits: keep touching at the start per pair of parts Per body, the Hinge Assembly sample's plates, which only come flush in the end plane the two leaves share, stopped the search. The leaves never pass into each other: the sample's answer is a whole turn. * find_limits: touching boxes cost no collision work; stale results and rounding * find_limits: each pair of bodies of resting parts held to its own depth; loops without bodies * find_limits: a 32-bit budget it can pass, a repaint with the result, a bad form says so first * find_limits: each pair of resting bodies gets its own margin * find_limits: Arabic, Hebrew and Vietnamese strings (complete catalogs on main) * find_limits: search the joint with Edit Joint's side picks Edit Joint now keeps the joint's sides as picks in its inputs, and its OK commands compare them with what it opened on. Built without them, the commands Find Limits applies first asked for the sides again, so every search failed. --------- Co-authored-by: MateuszSychXpl <151755914+MateuszSychXpl@users.noreply.github.com>
This commit is contained in:
@@ -94,6 +94,7 @@ fn contact_mesh(body: &solidcraft_doc::ModelBody) -> Result<ContactMesh> {
|
||||
/// A member of a contact set: (occurrence id, name).
|
||||
pub(super) type Member = (u64, String);
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct ContactGeometry {
|
||||
bodies: Vec<CachedBody>,
|
||||
/// Body indices, and the set members (occurrence id, name) they are under.
|
||||
@@ -211,6 +212,12 @@ impl ContactGeometry {
|
||||
ContactGeometry { bodies: self.bodies.clone(), pairs: taken, step: self.step }
|
||||
}
|
||||
|
||||
/// The diagonal of the box the bodies fill in `s`: past it, a part moving in a straight
|
||||
/// line meets nothing it has not met.
|
||||
pub(super) fn reach(&self, s: &Session) -> Result<f64> {
|
||||
Ok(self.bounds(s)?.size().len())
|
||||
}
|
||||
|
||||
/// How many mesh points are placed for each check.
|
||||
pub(super) fn vertex_count(&self) -> usize {
|
||||
self.bodies.iter().map(|b| b.mesh.positions.len()).fold(0, usize::saturating_add)
|
||||
@@ -315,38 +322,12 @@ impl ContactGeometry {
|
||||
let meshes = self.placed(s)?;
|
||||
// Each mesh's box once, not once per pair it is in.
|
||||
let boxes: Vec<Aabb3> = meshes.iter().map(Mesh::bounds).collect();
|
||||
for (a, b, oa, ob) in &self.pairs {
|
||||
for (i, (_, _, oa, ob)) in self.pairs.iter().enumerate() {
|
||||
// Members already found colliding need no more of their bodies tested.
|
||||
if found.contains(&(oa.0.min(ob.0), oa.0.max(ob.0))) {
|
||||
continue;
|
||||
}
|
||||
let (Some(ma), Some(mb), Some(ba), Some(bb)) = (meshes.get(*a), meshes.get(*b), self.bodies.get(*a), self.bodies.get(*b)) else {
|
||||
return Err(limit("invalid contact geometry pair"));
|
||||
};
|
||||
let (Some(aabb), Some(bbb)) = (boxes.get(*a), boxes.get(*b)) else {
|
||||
return Err(limit("invalid contact geometry pair"));
|
||||
};
|
||||
if aabb.max.x < bbb.min.x
|
||||
|| bbb.max.x < aabb.min.x
|
||||
|| aabb.max.y < bbb.min.y
|
||||
|| bbb.max.y < aabb.min.y
|
||||
|| aabb.max.z < bbb.min.z
|
||||
|| bbb.max.z < aabb.min.z
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let cost = ma
|
||||
.positions
|
||||
.len()
|
||||
// 4 sample points and 3 edges to probe per triangle of `a` against each triangle of `b` (#3323), and the other way round.
|
||||
.saturating_add(ma.triangles.len().saturating_mul(7))
|
||||
.saturating_mul(mb.triangles.len())
|
||||
.saturating_add(mb.positions.len().saturating_add(mb.triangles.len().saturating_mul(7)).saturating_mul(ma.triangles.len()));
|
||||
*work = work.saturating_add(cost);
|
||||
if *work > budget {
|
||||
return Err(limit("motion exceeds contact sweep collision budget; simplify the contact set or use smaller increments"));
|
||||
}
|
||||
if let Some(depth) = super::mesh_overlap(ma, mb, 1e-4 * ba.size.max(bb.size).max(1.0)) {
|
||||
if let Some(depth) = self.depth(i, &meshes, &boxes, work, budget)? {
|
||||
found.insert((oa.0.min(ob.0), oa.0.max(ob.0)));
|
||||
out.push((oa.clone(), ob.clone(), depth));
|
||||
if !all {
|
||||
@@ -356,6 +337,66 @@ impl ContactGeometry {
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// How deep the bodies of each pair pass into each other in `s` (0 where they don't), in
|
||||
/// the order of the pairs. `work` adds up the cost, refused past `budget`.
|
||||
pub(super) fn depths(&self, s: &Session, work: &mut usize, budget: usize) -> Result<Vec<f64>> {
|
||||
let meshes = self.placed(s)?;
|
||||
let boxes: Vec<Aabb3> = meshes.iter().map(Mesh::bounds).collect();
|
||||
(0..self.pairs.len()).map(|i| Ok(self.depth(i, &meshes, &boxes, work, budget)?.unwrap_or(0.0))).collect()
|
||||
}
|
||||
|
||||
/// The set members pair `i` is between.
|
||||
pub(super) fn members(&self, i: usize) -> Option<(Member, Member)> {
|
||||
self.pairs.get(i).map(|(_, _, a, b)| (a.clone(), b.clone()))
|
||||
}
|
||||
|
||||
/// How far the meshes of pair `i` may stray from their faces (see [`ContactGeometry::chord`]).
|
||||
pub(super) fn pair_chord(&self, i: usize) -> f64 {
|
||||
let chord = |b: usize| self.bodies.get(b).map_or(0.0, |b| b.chord);
|
||||
self.pairs.get(i).map_or(0.0, |(a, b, _, _)| chord(*a).max(chord(*b)))
|
||||
}
|
||||
|
||||
/// Pair `i` alone (with the same bodies).
|
||||
pub(super) fn only(&self, i: usize) -> ContactGeometry {
|
||||
ContactGeometry { bodies: self.bodies.clone(), pairs: self.pairs.get(i).cloned().into_iter().collect(), step: self.step }
|
||||
}
|
||||
|
||||
/// How deep the bodies of pair `i` (placed as `meshes`, in `boxes`) pass into each other,
|
||||
/// when more than a touch.
|
||||
fn depth(&self, i: usize, meshes: &[Mesh], boxes: &[Aabb3], work: &mut usize, budget: usize) -> Result<Option<f64>> {
|
||||
let Some((a, b, _, _)) = self.pairs.get(i) else { return Err(limit("invalid contact geometry pair")) };
|
||||
let (Some(ma), Some(mb), Some(ba), Some(bb)) = (meshes.get(*a), meshes.get(*b), self.bodies.get(*a), self.bodies.get(*b)) else {
|
||||
return Err(limit("invalid contact geometry pair"));
|
||||
};
|
||||
let (Some(aabb), Some(bbb)) = (boxes.get(*a), boxes.get(*b)) else {
|
||||
return Err(limit("invalid contact geometry pair"));
|
||||
};
|
||||
// Boxes apart, or only touching (parts end to end): `mesh_overlap` finds nothing there,
|
||||
// so it costs nothing (#5968).
|
||||
let tol = 1e-4 * ba.size.max(bb.size).max(1.0);
|
||||
if aabb.max.x < bbb.min.x + tol
|
||||
|| bbb.max.x < aabb.min.x + tol
|
||||
|| aabb.max.y < bbb.min.y + tol
|
||||
|| bbb.max.y < aabb.min.y + tol
|
||||
|| aabb.max.z < bbb.min.z + tol
|
||||
|| bbb.max.z < aabb.min.z + tol
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let cost = ma
|
||||
.positions
|
||||
.len()
|
||||
// 4 sample points and 3 edges to probe per triangle of `a` against each triangle of `b` (#3323), and the other way round.
|
||||
.saturating_add(ma.triangles.len().saturating_mul(7))
|
||||
.saturating_mul(mb.triangles.len())
|
||||
.saturating_add(mb.positions.len().saturating_add(mb.triangles.len().saturating_mul(7)).saturating_mul(ma.triangles.len()));
|
||||
*work = work.saturating_add(cost);
|
||||
if *work > budget {
|
||||
return Err(limit("motion exceeds contact sweep collision budget; simplify the contact set or use smaller increments"));
|
||||
}
|
||||
Ok(super::mesh_overlap(ma, mb, tol))
|
||||
}
|
||||
}
|
||||
|
||||
/// How near two set members come: the bodies under them nearest each other.
|
||||
|
||||
@@ -12,8 +12,12 @@ use solidcraft_kernel::Body;
|
||||
use super::CommandSpec;
|
||||
use super::joints::{cannot_move, effective_values, joint_id, occurrence_id, place_holding, value};
|
||||
use crate::params::{bad, bool_, str_, vec3};
|
||||
use crate::schema::motion::{FindLimitsParams, FindLimitsResult};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
const FIND_LIMITS_CONTRACT: TypedContract<FindLimitsParams> = TypedContract::new();
|
||||
|
||||
#[path = "motion_analysis.rs"]
|
||||
mod analysis;
|
||||
#[path = "motion_animation.rs"]
|
||||
@@ -101,6 +105,12 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.noundo()
|
||||
.params(analysis::INTERFERENCE_DOC),
|
||||
CommandSpec::new("joint.sweep", "Sweep Joint", sweep::sweep).icon("interference").params(sweep::SWEEP_DOC),
|
||||
CommandSpec::new("joint.find_limits", "Find Joint Limits", crate::checked!("joint.find_limits", sweep::find_limits))
|
||||
.icon("interference")
|
||||
.noundo()
|
||||
.contract(&FIND_LIMITS_CONTRACT)
|
||||
.output(output_schema_for::<FindLimitsResult>)
|
||||
.params(sweep::FIND_LIMITS_DOC),
|
||||
CommandSpec::new("motion.list", "List Motion Studies", list_studies).icon("list").noundo(),
|
||||
CommandSpec::new("motion.delete", "Delete Motion Study", delete_study).icon("delete").params("study"),
|
||||
CommandSpec::new("explode.create", "Exploded View", explode_create).at("SOLID", "ASSEMBLE").icon("explode").enabled(has_parts_to_explode).params(
|
||||
|
||||
@@ -2,19 +2,23 @@
|
||||
//! toward `to` on a copy of the design (closed loops following on their branch), measures the
|
||||
//! gaps between parts at each sample and bisects the first contact down to `refine`, so a hinge,
|
||||
//! door or linkage answers how far it opens, what stops it and how much room each part has.
|
||||
//! `joint.find_limits` sweeps each value both ways from where it is, for the joint dialog's Find
|
||||
//! Limits.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_doc::Document;
|
||||
use solidcraft_doc::joints::JointKind;
|
||||
use solidcraft_geom::Vec3;
|
||||
|
||||
use super::analysis::checked_pairs;
|
||||
use super::contact_sweep::{ContactGeometry, Gap};
|
||||
use super::{drive_with_contact, joint_id, value};
|
||||
use crate::params::{bad, bool_};
|
||||
use crate::{Result, Session};
|
||||
use crate::schema::motion::{FindLimitsResult, FoundLimits, Overlap, Stop, Why};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
pub const SWEEP_DOC: &str = "joint: id|name; from, to: its value the sweep runs between (degrees for angles, mm for distances, \
|
||||
or expressions); index? (which value, default 0); step? (between samples, in the joint's unit; default: fine enough that \
|
||||
@@ -31,12 +35,29 @@ pub const SWEEP_DOC: &str = "joint: id|name; from, to: its value the sweep runs
|
||||
on its frame: these stop it only once they pass into each other deeper than they start), applied. The parts are tested at the samples and through the bisection; the motion is on a copy (closed loops \
|
||||
follow, contact sets do not stop it)";
|
||||
|
||||
pub const FIND_LIMITS_DOC: &str = "joint: id|name; index? (one value; default every value); refine?, step?, occurrences?, \
|
||||
against?, contact_sets? (as joint.sweep) → values: [{index, dof, unit, value (now), min, max, min_by, max_by, range}], \
|
||||
each value swept both ways from where it is, its own limits ignored, closed loops following; each side stops at the \
|
||||
first contact (bisected to `refine`), where a loop cannot close, or at another limit (another value's, or another joint's through a motion link): min_by/max_by {a, b, at} | \
|
||||
\"loop\" | \"limit\" | \"turn\" (an angle with no contact within a turn: a turn from the other side, or ±180° from \
|
||||
now when nothing is met at all) | \"range\" (a distance with no contact within the parts' reach: min/max null); \
|
||||
touching_at_start, overlapping_at_start: [{a, b, depth_mm}] (already passing into each other: they stop it only going \
|
||||
deeper), refine_mm, gap_method, gap_tolerance_mm, pairs (0: no two parts to check, so nothing is swept). The design is \
|
||||
not changed";
|
||||
|
||||
/// Most samples a sweep takes before its bisection: each is a solve.
|
||||
const MAX_SAMPLES: usize = 4096;
|
||||
/// Most bisection steps: each halves the bracket around the first contact.
|
||||
const MAX_BISECTIONS: usize = 64;
|
||||
/// Most gap work over a whole sweep (see `ContactGeometry::gaps`).
|
||||
const MAX_WORK: usize = 500_000_000;
|
||||
/// Most gap work each side of a limit search takes: a whole turn of curved pins passing into each
|
||||
/// other costs about 20 M a sample, some 500 samples a turn (a few seconds). A 32-bit build, the
|
||||
/// web, takes half what its `usize` holds, so the work it adds up can still pass it.
|
||||
const FIND_WORK: usize = {
|
||||
let most = MAX_WORK.saturating_mul(40);
|
||||
if most > usize::MAX / 2 { usize::MAX / 2 } else { most }
|
||||
};
|
||||
|
||||
/// The nearest a part came to another along the sweep.
|
||||
struct Nearest {
|
||||
@@ -45,23 +66,86 @@ struct Nearest {
|
||||
to: String,
|
||||
}
|
||||
|
||||
pub(super) fn sweep(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "joint.sweep";
|
||||
/// One sweep of a joint value.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Sweep {
|
||||
id: u64,
|
||||
index: usize,
|
||||
from: f64,
|
||||
to: f64,
|
||||
step: Option<f64>,
|
||||
refine: f64,
|
||||
report_gaps: bool,
|
||||
/// The gap work it may take.
|
||||
budget: usize,
|
||||
/// The value's own limit left out (the copy only).
|
||||
free: bool,
|
||||
}
|
||||
|
||||
/// What a sweep found.
|
||||
struct Swept {
|
||||
/// The last value clear of contact (or where a loop or limit stopped it), and what stopped
|
||||
/// it; `None`: it reached `to`.
|
||||
stop: Option<(f64, Stop)>,
|
||||
samples: Vec<Value>,
|
||||
nearest: BTreeMap<String, Nearest>,
|
||||
touching: Vec<[String; 2]>,
|
||||
/// Pairs of parts passing into each other at the start deeper than a touch: (a, b, mm).
|
||||
overlapping: Vec<(String, String, f64)>,
|
||||
pairs: usize,
|
||||
chord: f64,
|
||||
/// The design where it stopped.
|
||||
doc: Arc<Document>,
|
||||
}
|
||||
|
||||
/// The joint a command sweeps: its id, name and kind (a rigid joint is refused).
|
||||
fn swept_joint(s: &Session, p: &Value, cmd: &str) -> Result<(u64, String, JointKind)> {
|
||||
let id = joint_id(s, p.get("joint"), cmd)?;
|
||||
let joint = s.doc.assembly.joints.iter().find(|j| j.id == id).ok_or_else(|| bad(cmd, "joint"))?;
|
||||
let (kind, name) = (joint.kind, joint.name.clone());
|
||||
let dofs = kind.dofs().len();
|
||||
if dofs == 0 {
|
||||
if joint.kind.dofs().is_empty() {
|
||||
return Err(bad(cmd, "a rigid joint does not move"));
|
||||
}
|
||||
let index = match p.get("index") {
|
||||
None | Some(Value::Null) => 0,
|
||||
Ok((id, joint.name.clone(), joint.kind))
|
||||
}
|
||||
|
||||
/// `index`, below `dofs` (`None`: not given).
|
||||
fn value_index(p: &Value, dofs: usize, cmd: &str) -> Result<Option<usize>> {
|
||||
match p.get("index") {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v
|
||||
.as_u64()
|
||||
.and_then(|i| usize::try_from(i).ok())
|
||||
.filter(|i| *i < dofs)
|
||||
.ok_or_else(|| bad(cmd, format!("`index` must be below {dofs}, the joint's value count")))?,
|
||||
};
|
||||
.map(Some)
|
||||
.ok_or_else(|| bad(cmd, format!("`index` must be below {dofs}, the joint's value count"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// A number above 0, at most `max` (`None`: not given).
|
||||
fn positive(p: &Value, key: &str, max: f64, cmd: &str) -> Result<Option<f64>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v
|
||||
.as_f64()
|
||||
.filter(|x| x.is_finite() && *x > 0.0 && *x <= max)
|
||||
.map(Some)
|
||||
.ok_or_else(|| bad(cmd, format!("`{key}` must be a number above 0, at most {max}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The parts the command checks, refused when there are no two to check against each other.
|
||||
fn pairs_to_check(s: &Session, p: &Value, cmd: &str) -> Result<ContactGeometry> {
|
||||
let geometry = checked_pairs(s, p, cmd)?;
|
||||
if !geometry.has_pairs() {
|
||||
return Err(bad(cmd, "no pairs of parts to check: list two or more `occurrences` with bodies, or give `against`"));
|
||||
}
|
||||
Ok(geometry)
|
||||
}
|
||||
|
||||
pub(super) fn sweep(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "joint.sweep";
|
||||
let (id, name, kind) = swept_joint(s, p, cmd)?;
|
||||
let index = value_index(p, kind.dofs().len(), cmd)?.unwrap_or(0);
|
||||
let angle = kind.is_angle(index);
|
||||
// Shown in degrees for angles, mm for distances.
|
||||
let shown = |v: f64| if angle { v.to_degrees() } else { v };
|
||||
@@ -70,29 +154,152 @@ pub(super) fn sweep(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => Err(bad(cmd, format!("give `from` and `to`: the joint's values the sweep runs between (no `{key}`)"))),
|
||||
};
|
||||
let (from, to) = (end("from")?, end("to")?);
|
||||
let positive = |key: &str, max: f64| -> Result<Option<f64>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v
|
||||
.as_f64()
|
||||
.filter(|x| x.is_finite() && *x > 0.0 && *x <= max)
|
||||
.map(Some)
|
||||
.ok_or_else(|| bad(cmd, format!("`{key}` must be a number above 0, at most {max}"))),
|
||||
}
|
||||
};
|
||||
let refine = positive("refine", 1e3)?.unwrap_or(0.01);
|
||||
let step = positive("step", 1e9)?.map(|x| if angle { x.to_radians() } else { x });
|
||||
let refine = positive(p, "refine", 1e3, cmd)?.unwrap_or(0.01);
|
||||
let step = positive(p, "step", 1e9, cmd)?.map(|x| if angle { x.to_radians() } else { x });
|
||||
let report_gaps = bool_(p, "report_gaps").unwrap_or(false);
|
||||
let apply = bool_(p, "apply").unwrap_or(false);
|
||||
let geometry = pairs_to_check(s, p, cmd)?;
|
||||
let sweep = Sweep { id, index, from, to, step, refine, report_gaps, budget: MAX_WORK, free: false };
|
||||
let r = run(s, geometry, sweep, cmd)?;
|
||||
|
||||
let mut geometry = checked_pairs(s, p, cmd)?;
|
||||
if !geometry.has_pairs() {
|
||||
return Err(bad(cmd, "no pairs of parts to check: list two or more `occurrences` with bodies, or give `against`"));
|
||||
let applied = apply && !Arc::ptr_eq(&r.doc, &s.doc);
|
||||
if applied {
|
||||
let mut doc = (*r.doc).clone();
|
||||
doc.assembly.contact_enabled = s.doc.assembly.contact_enabled;
|
||||
*s.doc_mut() = doc;
|
||||
}
|
||||
let by = |stop: &Stop| serde_json::to_value(stop).map_err(|e| EngineError::Other(e.to_string()));
|
||||
let mut out = json!({
|
||||
"joint": id, "name": name, "index": index, "unit": if angle { "deg" } else { "mm" },
|
||||
"from": shown(from), "to": shown(to),
|
||||
"stopped_at": r.stop.as_ref().map(|(v, _)| shown(*v)),
|
||||
"stopped_by": r.stop.as_ref().map(|(_, stop)| by(stop)).transpose()?,
|
||||
"samples": r.samples,
|
||||
"refine_mm": refine,
|
||||
"gap_method": "mesh", "gap_tolerance_mm": r.chord,
|
||||
"pairs": r.pairs,
|
||||
"touching_at_start": r.touching,
|
||||
"applied": applied,
|
||||
});
|
||||
if report_gaps {
|
||||
out["min_gap"] =
|
||||
r.nearest.into_iter().map(|(k, g)| (k, json!({"mm": g.mm, "at_value": g.at, "to": g.to}))).collect::<serde_json::Map<_, _>>().into();
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub(super) fn find_limits(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "joint.find_limits";
|
||||
// Every search is on a copy: the design is only read.
|
||||
let s: &Session = s;
|
||||
let (id, name, kind) = swept_joint(s, p, cmd)?;
|
||||
let indices: Vec<usize> = match value_index(p, kind.dofs().len(), cmd)? {
|
||||
Some(i) => vec![i],
|
||||
None => (0..kind.dofs().len()).collect(),
|
||||
};
|
||||
let refine = positive(p, "refine", 1e3, cmd)?.unwrap_or(0.01);
|
||||
let step = positive(p, "step", 1e9, cmd)?;
|
||||
// No two parts to check (the joint turns the only part with bodies): nothing can be met, but
|
||||
// a closed loop or a limit can still stop an angle, swept a degree at a time; a distance has
|
||||
// nothing to search over. Parts the call names that make no pair are refused, as
|
||||
// `joint.sweep` refuses them.
|
||||
let named = p.get("occurrences").is_some_and(|v| !v.is_null()) || bool_(p, "contact_sets").unwrap_or(false);
|
||||
let geometry = if named { pairs_to_check(s, p, cmd)? } else { checked_pairs(s, p, cmd)? };
|
||||
let paired = geometry.has_pairs();
|
||||
let now = s.doc.assembly.joints.iter().find(|j| j.id == id).map(|j| j.values.clone()).unwrap_or_default();
|
||||
// A distance is searched as far as the parts reach: past it, a straight move meets nothing new.
|
||||
let reach = if paired { geometry.reach(s)? } else { 0.0 };
|
||||
if paired && (!reach.is_finite() || reach <= 0.0) {
|
||||
return Err(bad(cmd, "the parts have no size to search over"));
|
||||
}
|
||||
let turn = std::f64::consts::TAU;
|
||||
let mut values = Vec::with_capacity(indices.len());
|
||||
let mut first: Option<Swept> = None;
|
||||
for index in indices {
|
||||
let angle = kind.is_angle(index);
|
||||
let shown = |v: f64| if angle { v.to_degrees() } else { v };
|
||||
let c = now.get(index).copied().unwrap_or(0.0);
|
||||
if !c.is_finite() {
|
||||
return Err(bad(cmd, "the joint's value is not a number"));
|
||||
}
|
||||
let range = if angle { turn } else { reach };
|
||||
let step = match step {
|
||||
Some(x) => Some(if angle { x.to_radians() } else { x }),
|
||||
None if !paired => Some(1f64.to_radians()),
|
||||
None => None,
|
||||
};
|
||||
let side = |to: f64| {
|
||||
if !angle && !paired {
|
||||
return Ok(None);
|
||||
}
|
||||
let sweep = Sweep { id, index, from: c, to, step, refine, report_gaps: false, budget: FIND_WORK, free: true };
|
||||
Ok::<_, EngineError>(Some(run(s, geometry.clone(), sweep, cmd)?))
|
||||
};
|
||||
// (value, what stopped it) for each side; `None` value: no limit that side. An angle is
|
||||
// searched a turn up, then down to a turn below where that stopped: a span of at most a
|
||||
// turn, each side checked (a motion link can make the way down differ from the way up).
|
||||
let up = side(c + range)?;
|
||||
let up_stop = up.as_ref().and_then(|u| u.stop.clone());
|
||||
let down = side(if angle { up_stop.as_ref().map_or(c, |(u, _)| *u) - turn } else { c - range })?.and_then(|d| d.stop);
|
||||
let turned = |v: f64| (Some(v), Stop::Other(Why::Turn));
|
||||
let (min, max) = match (angle, up_stop, down) {
|
||||
(true, None, None) => (turned(c - turn / 2.0), turned(c + turn / 2.0)),
|
||||
(true, None, Some((d, by))) => ((Some(d), by), turned(d + turn)),
|
||||
(true, Some((u, by)), None) => (turned(u - turn), (Some(u), by)),
|
||||
(_, up, down) => {
|
||||
let found = |stop: Option<(f64, Stop)>| stop.map_or((None, Stop::Other(Why::Range)), |(v, by)| (Some(v), by));
|
||||
(found(down), found(up))
|
||||
}
|
||||
};
|
||||
values.push(FoundLimits {
|
||||
index,
|
||||
dof: kind.dofs().get(index).copied().unwrap_or("value").to_string(),
|
||||
unit: if angle { "deg" } else { "mm" }.to_string(),
|
||||
value: shown(c),
|
||||
min: min.0.map(shown),
|
||||
max: max.0.map(shown),
|
||||
min_by: min.1,
|
||||
max_by: max.1,
|
||||
range: shown(range),
|
||||
});
|
||||
if first.is_none() {
|
||||
first = up;
|
||||
}
|
||||
}
|
||||
let reply = FindLimitsResult {
|
||||
joint: id,
|
||||
name,
|
||||
values,
|
||||
refine_mm: refine,
|
||||
gap_method: "mesh".into(),
|
||||
gap_tolerance_mm: first.as_ref().map_or(0.0, |f| f.chord),
|
||||
pairs: first.as_ref().map_or(0, |f| f.pairs),
|
||||
touching_at_start: first.as_ref().map(|f| f.touching.clone()).unwrap_or_default(),
|
||||
overlapping_at_start: first
|
||||
.map(|f| f.overlapping)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|(a, b, depth_mm)| Overlap { a, b, depth_mm })
|
||||
.collect(),
|
||||
param_warnings: Vec::new(),
|
||||
};
|
||||
serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string()))
|
||||
}
|
||||
|
||||
/// Drive the value `sw` names from `sw.from` toward `sw.to` on a copy of `s`, checking the pairs
|
||||
/// of `geometry` at each sample, and bisect the first contact.
|
||||
fn run(s: &Session, mut geometry: ContactGeometry, sw: Sweep, cmd: &str) -> Result<Swept> {
|
||||
let Sweep { id, index, from, to, step, refine, report_gaps, budget, free } = sw;
|
||||
let (dofs, angle) =
|
||||
s.doc.assembly.joints.iter().find(|j| j.id == id).map(|j| (j.kind.dofs().len(), j.kind.is_angle(index))).ok_or_else(|| bad(cmd, "joint"))?;
|
||||
let shown = |v: f64| if angle { v.to_degrees() } else { v };
|
||||
// On a copy, played from where the parts are placed; contact sets do not stop it.
|
||||
let mut t = s.scratch();
|
||||
t.pending_moves.clear();
|
||||
t.doc_mut().assembly.contact_enabled = false;
|
||||
if free && let Some(limit) = t.doc_mut().assembly.joints.iter_mut().find(|j| j.id == id).and_then(|j| j.limits.get_mut(index)) {
|
||||
*limit = None;
|
||||
}
|
||||
let given = BTreeSet::from([(id, index)]);
|
||||
let drive_to = |t: &mut Session, v: f64| -> Result<Value> {
|
||||
let mut q = t.doc.assembly.joints.iter().find(|j| j.id == id).map(|j| j.values.clone()).unwrap_or_default();
|
||||
@@ -118,17 +325,26 @@ pub(super) fn sweep(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let key = |x: u64, y: u64| (x.min(y), x.max(y));
|
||||
// Pairs touching where the sweep starts (parts joined face to face, a door on its frame)
|
||||
// stop it only when they pass into each other, deeper than they start (by more than their
|
||||
// meshes can be off): a door resting on its frame cannot sweep through it.
|
||||
let start: Vec<Gap> = geometry.gaps(&t, touch, &mut work, MAX_WORK)?;
|
||||
// meshes can be off): a door resting on its frame cannot sweep through it. Each pair of their
|
||||
// bodies is held to its own depth: pins already in each other don't hide arms of the same
|
||||
// parts meeting later, and plates that only come flush (parts end to end) never stop it.
|
||||
let start: Vec<Gap> = geometry.gaps(&t, touch, &mut work, budget)?;
|
||||
let touching: BTreeSet<(u64, u64)> = start.iter().map(|g| key(g.a.0, g.b.0)).collect();
|
||||
let touching_names: Vec<Value> = start.iter().map(|g| json!([g.a.1, g.b.1])).collect();
|
||||
let touching_names: Vec<[String; 2]> = start.iter().map(|g| [g.a.1.clone(), g.b.1.clone()]).collect();
|
||||
let resting = geometry.take_pairs(|x, y| touching.contains(&key(x, y)));
|
||||
let rest_depth: BTreeMap<(u64, u64), f64> = if resting.has_pairs() {
|
||||
resting.hits(&t, &mut work, MAX_WORK, true)?.into_iter().map(|(a, b, d)| (key(a.0, b.0), d)).collect()
|
||||
} else {
|
||||
BTreeMap::new()
|
||||
};
|
||||
let margin = touch.max(2.0 * resting.chord());
|
||||
let rest_depth: Vec<f64> = if resting.has_pairs() { resting.depths(&t, &mut work, budget)? } else { Vec::new() };
|
||||
// A pair of bodies' own margin: flat faces against flat faces are exact.
|
||||
let margin = |i: usize| touch.max(2.0 * resting.pair_chord(i));
|
||||
// Parts already passing into each other, deeper than a touch: the deepest of their bodies.
|
||||
let mut overlapping: BTreeMap<(u64, u64), (String, String, f64)> = BTreeMap::new();
|
||||
for (i, depth) in rest_depth.iter().enumerate() {
|
||||
if *depth > margin(i)
|
||||
&& let Some((a, b)) = resting.members(i)
|
||||
{
|
||||
let entry = overlapping.entry(key(a.0, b.0)).or_insert((a.1, b.1, 0.0));
|
||||
entry.2 = entry.2.max(*depth);
|
||||
}
|
||||
}
|
||||
|
||||
// The samples run to where the joint gets: a limit or a loop can stop it short of `to`, and
|
||||
// the default count is for the motion up to there. One more drive toward `to` then finds
|
||||
@@ -145,7 +361,7 @@ pub(super) fn sweep(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut end = t.scratch();
|
||||
drive_to(&mut end, to)?;
|
||||
let n = geometry.samples(&t, &end).map_err(|e| match e {
|
||||
crate::EngineError::BadParams { msg, .. } => bad(cmd, format!("{msg} (or give a `step`)")),
|
||||
EngineError::BadParams { msg, .. } => bad(cmd, format!("{msg} (or give a `step`)")),
|
||||
e => e,
|
||||
})?;
|
||||
let got = reached(&end);
|
||||
@@ -163,7 +379,7 @@ pub(super) fn sweep(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
samples.push(json!({"value": shown(v)}));
|
||||
return Ok(());
|
||||
}
|
||||
let gaps = geometry.gaps(t, f64::INFINITY, work, MAX_WORK)?;
|
||||
let gaps = geometry.gaps(t, f64::INFINITY, work, budget)?;
|
||||
match gaps.first() {
|
||||
Some(g) => samples.push(json!({"value": shown(v), "min_gap_mm": g.mm, "pair": [g.a.1, g.b.1]})),
|
||||
None => samples.push(json!({"value": shown(v), "min_gap_mm": null, "pair": null})),
|
||||
@@ -178,24 +394,23 @@ pub(super) fn sweep(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(())
|
||||
};
|
||||
let contact = |t: &Session, work: &mut usize, geometry: &ContactGeometry| -> Result<Option<Gap>> {
|
||||
if let Some(g) = geometry.gaps(t, touch, work, MAX_WORK)?.into_iter().next() {
|
||||
if let Some(g) = geometry.gaps(t, touch, work, budget)?.into_iter().next() {
|
||||
return Ok(Some(g));
|
||||
}
|
||||
if !resting.has_pairs() {
|
||||
return Ok(None);
|
||||
}
|
||||
let deeper =
|
||||
resting.hits(t, work, MAX_WORK, true)?.into_iter().find(|(a, b, d)| *d > rest_depth.get(&key(a.0, b.0)).copied().unwrap_or(0.0) + margin);
|
||||
let Some((a, b, _)) = deeper else { return Ok(None) };
|
||||
// Where: the nearest points of that pair (passing into each other, at no gap).
|
||||
let k = key(a.0, b.0);
|
||||
let at = resting.gaps(t, touch, work, MAX_WORK)?.into_iter().find(|g| key(g.a.0, g.b.0) == k).map_or((Vec3::ZERO, Vec3::ZERO), |g| g.at);
|
||||
let depths = resting.depths(t, work, budget)?;
|
||||
let deeper = depths.iter().enumerate().find(|(i, d)| **d > rest_depth.get(*i).copied().unwrap_or(0.0) + margin(*i)).map(|(i, _)| i);
|
||||
let Some((i, (a, b))) = deeper.and_then(|i| resting.members(i).map(|m| (i, m))) else { return Ok(None) };
|
||||
// Where: the nearest points of those bodies (passing into each other, at no gap).
|
||||
let at = resting.only(i).gaps(t, touch, work, budget)?.into_iter().next().map_or((Vec3::ZERO, Vec3::ZERO), |g| g.at);
|
||||
Ok(Some(Gap { a, b, mm: 0.0, at }))
|
||||
};
|
||||
|
||||
record(&t, from, &mut work, &geometry)?;
|
||||
let (mut lo_doc, mut lo_v): (Arc<Document>, f64) = (t.doc.clone(), from);
|
||||
let mut stop: Option<(f64, Value)> = None;
|
||||
let mut stop: Option<(f64, Stop)> = None;
|
||||
for target in targets {
|
||||
let r = drive_to(&mut t, target)?;
|
||||
let v = reached(&t);
|
||||
@@ -217,7 +432,7 @@ pub(super) fn sweep(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
t.doc = lo_doc.clone();
|
||||
let at = (hit.at.0 + hit.at.1) * 0.5;
|
||||
stop = Some((lo_v, json!({"a": hit.a.1, "b": hit.b.1, "at": [at.x, at.y, at.z]})));
|
||||
stop = Some((lo_v, Stop::Contact { a: hit.a.1, b: hit.b.1, at: [at.x, at.y, at.z] }));
|
||||
break;
|
||||
}
|
||||
// (The drive on toward `to` past a limit stays where the last sample was.)
|
||||
@@ -225,37 +440,24 @@ pub(super) fn sweep(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
record(&t, v, &mut work, &geometry)?;
|
||||
}
|
||||
if r["stopped_by_loop"].is_object() {
|
||||
stop = Some((v, json!("loop")));
|
||||
stop = Some((v, Stop::Other(Why::Loop)));
|
||||
break;
|
||||
}
|
||||
if (v - target).abs() > 1e-9 {
|
||||
stop = Some((v, json!("limit")));
|
||||
stop = Some((v, Stop::Other(Why::Limit)));
|
||||
break;
|
||||
}
|
||||
(lo_doc, lo_v) = (t.doc.clone(), v);
|
||||
}
|
||||
|
||||
let applied = apply && !Arc::ptr_eq(&t.doc, &s.doc);
|
||||
if applied {
|
||||
let mut doc = (*t.doc).clone();
|
||||
doc.assembly.contact_enabled = s.doc.assembly.contact_enabled;
|
||||
*s.doc_mut() = doc;
|
||||
}
|
||||
let mut out = json!({
|
||||
"joint": id, "name": name, "index": index, "unit": if angle { "deg" } else { "mm" },
|
||||
"from": shown(from), "to": shown(to),
|
||||
"stopped_at": stop.as_ref().map(|(v, _)| shown(*v)),
|
||||
"stopped_by": stop.map(|(_, by)| by),
|
||||
"samples": samples,
|
||||
"refine_mm": refine,
|
||||
"gap_method": "mesh", "gap_tolerance_mm": geometry.chord(),
|
||||
"pairs": geometry.pair_count() + resting.pair_count(),
|
||||
"touching_at_start": touching_names,
|
||||
"applied": applied,
|
||||
});
|
||||
if report_gaps {
|
||||
out["min_gap"] =
|
||||
nearest.into_iter().map(|(k, g)| (k, json!({"mm": g.mm, "at_value": g.at, "to": g.to}))).collect::<serde_json::Map<_, _>>().into();
|
||||
}
|
||||
Ok(out)
|
||||
let pairs = geometry.pair_count() + resting.pair_count();
|
||||
Ok(Swept {
|
||||
stop,
|
||||
samples,
|
||||
nearest,
|
||||
touching: touching_names,
|
||||
overlapping: overlapping.into_values().collect(),
|
||||
pairs,
|
||||
chord: geometry.chord(),
|
||||
doc: t.doc,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! `joint.sweep` against stops worked out by hand: a door swinging into a block, the four-bar's
|
||||
//! rocker meeting a stop and a Watt six-bar's output link meeting one, each checked against the
|
||||
//! linkage solved with circle intersections and a separating-axis test of the parts' outlines.
|
||||
//! `joint.find_limits` against the same stops met both ways, a slider, the four-bar's toggles
|
||||
//! and the Hinge Assembly sample.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_geom::Vec3;
|
||||
@@ -305,3 +307,174 @@ fn a_watt_six_bar_output_meets_a_stop() {
|
||||
let names = [r["stopped_by"]["a"].as_str(), r["stopped_by"]["b"].as_str()];
|
||||
assert!(names.contains(&Some("Output:1")) && names.contains(&Some("Stop:1")), "{r}");
|
||||
}
|
||||
|
||||
/// The limits `joint.find_limits` found for the joint's first value: (min, max, min_by, max_by).
|
||||
fn limits(r: &Value) -> (f64, f64, Value, Value) {
|
||||
let v = &r["values"][0];
|
||||
(num(&v["min"]), num(&v["max"]), v["min_by"].clone(), v["max_by"].clone())
|
||||
}
|
||||
|
||||
/// A stop (or overlap) between parts `a` and `b`.
|
||||
fn by_parts(by: &Value, a: &str, b: &str) -> bool {
|
||||
let names = [by["a"].as_str(), by["b"].as_str()];
|
||||
names.contains(&Some(a)) && names.contains(&Some(b))
|
||||
}
|
||||
|
||||
/// Opened, the door meets the block as in `a_door_swings_until_it_meets_the_block`; closed the
|
||||
/// other way round, the face through its hinge line reaches the block's corner (60, 50) first,
|
||||
/// a turn back. Its own limits are left out of the search, and the design is not changed.
|
||||
#[test]
|
||||
fn find_limits_meets_the_block_both_ways_round() {
|
||||
let mut s = door();
|
||||
run(&mut s, "joint.limits", json!({"joint": "Hinge", "min": -30, "max": 10}));
|
||||
let corner = |x: f64, y: f64| y.atan2(x) - (4.0 / x.hypot(y)).asin();
|
||||
let max = [(60.0, 30.0), (80.0, 30.0), (60.0, 50.0), (80.0, 50.0)].iter().map(|(x, y)| corner(*x, *y)).fold(f64::INFINITY, f64::min).to_degrees();
|
||||
let min = 50f64.atan2(60.0).to_degrees() - 360.0;
|
||||
let before = s.doc.clone();
|
||||
let r = run(&mut s, "joint.find_limits", json!({"joint": "Hinge", "refine": 0.001}));
|
||||
assert_eq!(*s.doc, *before, "the search leaves the design as it was");
|
||||
let (lo, hi, lo_by, hi_by) = limits(&r);
|
||||
assert!((hi - max).abs() < 0.01 && hi <= max + 1e-9, "max {hi}°, the block is met at {max}°: {r}");
|
||||
assert!((lo - min).abs() < 0.01 && lo >= min - 1e-9, "min {lo}°, the block is met at {min}°: {r}");
|
||||
assert!(by_parts(&lo_by, "Door:1", "Block:1") && by_parts(&hi_by, "Door:1", "Block:1"), "{r}");
|
||||
assert_eq!((r["values"][0]["unit"].as_str(), num(&r["values"][0]["value"]), num(&r["values"][0]["range"])), (Some("deg"), 0.0, 360.0));
|
||||
assert!(r["touching_at_start"].as_array().is_some_and(Vec::is_empty) && r["overlapping_at_start"].as_array().is_some_and(Vec::is_empty), "{r}");
|
||||
}
|
||||
|
||||
/// A door that meets nothing on a whole turn either way gets a turn, half each way from where
|
||||
/// it is: alone (nothing to meet, nothing swept) and with a lamp above it.
|
||||
#[test]
|
||||
fn find_limits_of_a_door_that_meets_nothing_spans_a_turn() {
|
||||
let mut s = Session::default();
|
||||
block(&mut s, "Door", [0.0, 0.0, 0.0], [100.0, 4.0, 50.0]);
|
||||
run(
|
||||
&mut s,
|
||||
"joint.create",
|
||||
json!({"type": "revolute", "a": {"occurrence": 0, "point": [0, 0, 0]}, "b": {"occurrence": "Door", "point": [0, 0, 0]}, "flip": true, "name": "Hinge"}),
|
||||
);
|
||||
run(&mut s, "joint.drive", json!({"joint": "Hinge", "value": 30}));
|
||||
for lamp in [false, true] {
|
||||
if lamp {
|
||||
block(&mut s, "Lamp", [0.0, 0.0, 80.0], [20.0, 20.0, 20.0]);
|
||||
}
|
||||
let r = run(&mut s, "joint.find_limits", json!({"joint": "Hinge"}));
|
||||
let (lo, hi, lo_by, hi_by) = limits(&r);
|
||||
assert!((lo + 150.0).abs() < 1e-6 && (hi - 210.0).abs() < 1e-6, "{lo}° … {hi}°");
|
||||
assert_eq!((lo_by, hi_by, num(&r["pairs"])), (json!("turn"), json!("turn"), if lamp { 1.0 } else { 0.0 }), "{r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A slider pushed into a wall stops where they meet; the other way it meets nothing within the
|
||||
/// parts' reach, and that side has no limit.
|
||||
#[test]
|
||||
fn find_limits_of_a_slider_leaves_a_free_side_open() {
|
||||
let mut s = Session::default();
|
||||
block(&mut s, "Slide", [0.0, 0.0, 0.0], [10.0, 10.0, 10.0]);
|
||||
block(&mut s, "Wall", [50.0, -20.0, -20.0], [10.0, 50.0, 50.0]);
|
||||
let at = |o: &str| json!({"occurrence": o, "point": [0, 0, 0], "z": [1, 0, 0]});
|
||||
run(&mut s, "joint.create", json!({"type": "slider", "a": at("Wall"), "b": at("Slide"), "flip": true, "name": "Rail"}));
|
||||
let id = occ(&s, "Wall");
|
||||
run(&mut s, "occurrence.ground", json!({"occurrence": id, "grounded": true}));
|
||||
let r = run(&mut s, "joint.find_limits", json!({"joint": "Rail", "refine": 0.001}));
|
||||
let v = &r["values"][0];
|
||||
// The joint's value grows one way or the other along X: the wall is met 40 mm away.
|
||||
let (closed, open) = if v["max"].is_null() { ("min", "max") } else { ("max", "min") };
|
||||
assert!((num(&v[closed]).abs() - 40.0).abs() < 0.002 && num(&v[closed]).abs() <= 40.0 + 1e-9, "{r}");
|
||||
assert!(by_parts(&v[format!("{closed}_by")], "Slide:1", "Wall:1"), "{r}");
|
||||
assert!(v[open].is_null() && v[format!("{open}_by")] == "range", "{r}");
|
||||
assert_eq!(v["unit"], "mm");
|
||||
assert!(num(&v["range"]) > 60.0, "the parts reach past the wall: {r}");
|
||||
}
|
||||
|
||||
/// The four-bar's rocker swings between its toggles, where the loop can no longer close (|Q| =
|
||||
/// 70 and |Q| = 30, about 69.3° and 139.2° from the ground line): both sides stop there.
|
||||
#[test]
|
||||
fn find_limits_of_a_four_bar_rocker_stops_at_its_toggles() {
|
||||
let (mut s, _, q0) = four_bar();
|
||||
let start = q0.y.atan2(q0.x - 45.0).to_degrees();
|
||||
// |Q|² = 45² + 40² + 2·45·40·cos φ.
|
||||
let toggle = |q: f64| ((q * q - 3625.0) / 3600.0).acos().to_degrees() - start;
|
||||
let r = run(&mut s, "joint.find_limits", json!({"joint": "Rocker", "occurrences": ["Rocker"], "against": ["Ground"]}));
|
||||
let (lo, hi, lo_by, hi_by) = limits(&r);
|
||||
assert_eq!((lo_by, hi_by), (json!("loop"), json!("loop")), "{r}");
|
||||
assert!(hi > toggle(30.0) - 1.0 && hi <= toggle(30.0) + 1e-6, "max {hi}°, the loop closes up to {}°", toggle(30.0));
|
||||
assert!(lo < toggle(70.0) + 1.0 && lo >= toggle(70.0) - 1e-6, "min {lo}°, the loop closes down to {}°", toggle(70.0));
|
||||
}
|
||||
|
||||
/// The Hinge Assembly sample (#5968): its leaves sit end to end along the pin, mated face to face
|
||||
/// at the pin's end, so they touch across that end and meet nothing else on a whole turn either
|
||||
/// way. A whole turn each way is what `joint.sweep` ran out of work on (from 60° to 360°); the
|
||||
/// search has the room for it.
|
||||
#[test]
|
||||
fn find_limits_of_the_hinge_sample_spans_a_turn() {
|
||||
let sample = crate::sample::samples().into_iter().find(|x| x.name == "Hinge Assembly").expect("the hinge sample");
|
||||
let mut s = Session::default();
|
||||
s.run_script(&(sample.script)()).unwrap_or_else(|e| panic!("{e}"));
|
||||
let r = run(&mut s, "joint.find_limits", json!({"joint": "Hinge"}));
|
||||
let (lo, hi, lo_by, hi_by) = limits(&r);
|
||||
assert!((lo + 120.0).abs() < 1e-6 && (hi - 240.0).abs() < 1e-6, "{lo}° … {hi}°: {r}");
|
||||
assert_eq!((lo_by, hi_by), (json!("turn"), json!("turn")), "{r}");
|
||||
let touching = r["touching_at_start"].as_array().cloned().unwrap_or_default();
|
||||
assert!(touching.len() == 1 && touching[0].as_array().is_some_and(|p| p.contains(&json!("Leaf A:1")) && p.contains(&json!("Leaf B:1"))), "{r}");
|
||||
assert!(r["overlapping_at_start"].as_array().is_some_and(Vec::is_empty), "{r}");
|
||||
// The same whole turn fits `joint.sweep`'s own work now (pairs whose boxes only touch cost
|
||||
// nothing), where it ran out going from 60° to 0° two degrees at a time.
|
||||
let r = run(&mut s, "joint.sweep", json!({"joint": "Hinge", "from": 60, "to": 0, "step": 2}));
|
||||
assert!(r["stopped_by"].is_null(), "{r}");
|
||||
}
|
||||
|
||||
/// Two parts of two bodies each: a post with a pin of radius 5 on Z and a stop block at
|
||||
/// (40…50, 10…20), and an arm turning about Z with a pin of radius 3 inside the post's (the pins
|
||||
/// are in each other where it starts, as deep wherever the arm turns) and a 4 mm plate from x 10
|
||||
/// to 60. The plate's faces, 2 mm off the axis, meet the block's corners as the door's do: the
|
||||
/// pins in each other must not hide that.
|
||||
#[test]
|
||||
fn find_limits_sees_arms_meet_behind_pins_already_in_each_other() {
|
||||
let mut s = Session::default();
|
||||
for (name, corner, size, radius) in [("Post", [40.0, 10.0, 0.0], [10.0, 10.0, 20.0], 5), ("Arm", [10.0, -2.0, 0.0], [50.0, 4.0, 20.0], 3)] {
|
||||
block(&mut s, name, corner, size);
|
||||
run(&mut s, "solid.cylinder", json!({"base": [0, 0, 0], "axis": [0, 0, 1], "radius": radius, "height": 20, "operation": "new"}));
|
||||
}
|
||||
run(&mut s, "component.activate", json!({"component": "root"}));
|
||||
let post = occ(&s, "Post");
|
||||
run(&mut s, "occurrence.ground", json!({"occurrence": post, "grounded": true}));
|
||||
let at = |o: &str| json!({"occurrence": o, "point": [0, 0, 0], "z": [0, 0, 1]});
|
||||
run(&mut s, "joint.create", json!({"type": "revolute", "a": at("Post"), "b": at("Arm"), "flip": true, "name": "Swing"}));
|
||||
let corners = [(40.0f64, 10.0f64), (50.0, 10.0), (40.0, 20.0), (50.0, 20.0)];
|
||||
let max = corners.iter().map(|(x, y)| y.atan2(*x) - (2.0 / x.hypot(*y)).asin()).fold(f64::INFINITY, f64::min).to_degrees();
|
||||
let min = corners.iter().map(|(x, y)| y.atan2(*x) + (2.0 / x.hypot(*y)).asin()).fold(f64::NEG_INFINITY, f64::max).to_degrees() - 360.0;
|
||||
let r = run(&mut s, "joint.find_limits", json!({"joint": "Swing", "refine": 0.001}));
|
||||
let (lo, hi, lo_by, hi_by) = limits(&r);
|
||||
// The joint's value may grow either way round Z.
|
||||
let near = |a: f64, b: f64| (a - b).abs() < 0.05;
|
||||
assert!((near(hi, max) && near(lo, min)) || (near(hi, -min) && near(lo, -max)), "{lo}° … {hi}°, the block is met at {max}° and {min}°: {r}");
|
||||
assert!(by_parts(&lo_by, "Arm:1", "Post:1") && by_parts(&hi_by, "Arm:1", "Post:1"), "{r}");
|
||||
let overlapping = r["overlapping_at_start"].as_array().cloned().unwrap_or_default();
|
||||
assert!(overlapping.len() == 1 && by_parts(&overlapping[0], "Arm:1", "Post:1") && num(&overlapping[0]["depth_mm"]) > 1.0, "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_limits_refuses_what_it_cannot_do() {
|
||||
let mut s = door();
|
||||
for p in [
|
||||
json!({}),
|
||||
json!({"joint": "Nope"}),
|
||||
json!({"joint": 5.5}),
|
||||
json!({"joint": "Hinge", "index": 1}),
|
||||
json!({"joint": "Hinge", "index": -1}),
|
||||
json!({"joint": "Hinge", "refine": 0}),
|
||||
json!({"joint": "Hinge", "refine": 1e9}),
|
||||
json!({"joint": "Hinge", "refine": "nan"}),
|
||||
json!({"joint": "Hinge", "step": 0}),
|
||||
json!({"joint": "Hinge", "step": -1}),
|
||||
json!({"joint": "Hinge", "step": 1e-9}),
|
||||
json!({"joint": "Hinge", "occurrences": ["Door"]}),
|
||||
json!({"joint": "Hinge", "against": ["Block"]}),
|
||||
json!({"joint": "Hinge", "occurrences": ["Door"], "against": ["Door"]}),
|
||||
json!({"joint": "Hinge", "occurrences": ["Door", "Block"], "contact_sets": true}),
|
||||
] {
|
||||
assert!(s.execute("joint.find_limits", &p).is_err(), "{p}");
|
||||
}
|
||||
run(&mut s, "joint.as_built", json!({"type": "rigid", "a": "Block", "b": "Door", "name": "Lock"}));
|
||||
assert!(s.execute("joint.find_limits", &json!({"joint": "Lock"})).is_err(), "a rigid joint does not move");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user