Skip to content

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

Agents and scripts: Joint Origin, Rigid Group, Reach Point, Motion Link, Gear, Rack and Pinion, Screw and Cam describe their exact parameters and reply (#13185) (#13242)

PeppaWutz2c82e702f54b
diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs
index 7968f18bc6..04587e4c93 100644
--- a/crates/engine/src/cmd/joints.rs
+++ b/crates/engine/src/cmd/joints.rs
@@ -16,10 +16,12 @@ use solidcraft_geom::Aabb3;
use super::CommandSpec;
use crate::params::{bad, bool_, num, str_, vec3};
use crate::schema::joints::{
- AsBuiltJointParams, CamLift, ContactStop, CreateJointParams, DeleteJointParams, DeleteJointResult, DriveJointParams, DriveJointResult,
- EditJointResult, FloatingChain, HeldValue, InspectJointParams, InspectJointResult, JointAddedResult, JointDeleted, JointFrame, JointLimitsParams,
- JointProblem, LinkInfo, ListJointsParams, ListJointsResult, ListedJoint, ListedOrigin, LoopStop, NamedValue, OccurrenceDof, SolveJointsParams,
- SolveReport, SolveResult, ValueUnit,
+ AsBuiltJointParams, CamLift, CamParams, CamResult, ContactStop, CouplingResult, CreateJointParams, DeleteJointParams, DeleteJointResult,
+ DriveJointParams, DriveJointResult, EditJointResult, FloatingChain, GearParams, HeldValue, InspectJointParams, InspectJointResult,
+ JointAddedResult, JointDeleted, JointFrame, JointLimitsParams, JointProblem, LimitSide, LimitStop, LinkInfo, ListJointsParams, ListJointsResult,
+ ListedJoint, ListedOrigin, LoopStop, MakeJointOriginParams, MakeJointOriginResult, MotionLinkParams, NamedValue, OccurrenceDof, RackPinionParams,
+ ReachLoopStop, ReachParams, ReachResult, ReachedJoint, RigidGroupParams, RigidGroupResult, ScrewParams, SolveJointsParams, SolveReport,
+ SolveResult, ValueUnit,
};
use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};
@@ -33,12 +35,25 @@ const DELETE_CONTRACT: TypedContract<DeleteJointParams> = TypedContract::new();
const LIST_CONTRACT: TypedContract<ListJointsParams> = TypedContract::new();
const INSPECT_CONTRACT: TypedContract<InspectJointParams> = TypedContract::new();
const SOLVE_CONTRACT: TypedContract<SolveJointsParams> = TypedContract::new();
+const ORIGIN_CONTRACT: TypedContract<MakeJointOriginParams> = TypedContract::new();
+const RIGID_GROUP_CONTRACT: TypedContract<RigidGroupParams> = TypedContract::new();
+const REACH_CONTRACT: TypedContract<ReachParams> = TypedContract::new();
+const MOTION_LINK_CONTRACT: TypedContract<MotionLinkParams> = TypedContract::new();
+const GEAR_CONTRACT: TypedContract<GearParams> = TypedContract::new();
+const RACK_PINION_CONTRACT: TypedContract<RackPinionParams> = TypedContract::new();
+const SCREW_CONTRACT: TypedContract<ScrewParams> = TypedContract::new();
+const CAM_CONTRACT: TypedContract<CamParams> = TypedContract::new();
#[path = "joints_inspect.rs"]
mod inspect;
pub static COMMANDS: &[CommandSpec] = &[
- CommandSpec::new("joint.origin", "Joint Origin", joint_origin).at("SOLID", "CREATE").icon("joint_origin").params(
+ CommandSpec::new("joint.origin", "Joint Origin", crate::checked!("joint.origin", joint_origin))
+ .at("SOLID", "CREATE")
+ .icon("joint_origin")
+ .contract(&ORIGIN_CONTRACT)
+ .output(output_schema_for::<MakeJointOriginResult>)
+ .params(
"name?, occurrence?: id|name (default: from the pick, or the named face's component), face: [x,y,z] | \"<name>\" (centre of a planar face) | circle: [x,y,z] | \"<name>\" (centre of a round end: a point on its wall or rim, the end's centre, or the round face's name as model.faces lists it) | edge: [x,y,z] (a point on an edge of a planar face: the edge's middle, z out of the face, y into it; on?: [x,y,z] a point on the face (default: the larger planar face beside the edge); corner?: [x,y,z] near one end: the corner there, x and y along its two edges into the face; found again by name, so it follows the face as it changes size; z?: [x,y,z] the frame's z instead of the face's normal, along the edge when it runs that way, x chosen from z: an edge or corner picked as it is, kept as a point where it can't be found by name) | point: [x,y,z], z?: [x,y,z]; a circle's z?: [x,y,z] (a round edge's centre with the way out of it: its end by name when that is the frame it shows, else a point there); body?: the named face's body; end?: \"<name>\" (a circle's end: the face across its rim there; default the end nearer the pick); x?: [x,y,z] (a direction, world) | \"<face name>\" | {face: [x,y,z]} (the frame's x: a direction, a plane's normal, or the way to another hole's axis; keeps a round origin's turn; a point's x is a direction, laid square to its z, default: chosen from z alone). Faces are kept by name: the origin follows its face, and a circle its end, when the design changes",
),
CommandSpec::new("joint.create", "Joint", crate::checked!("joint.create", joint))
@@ -68,7 +83,12 @@ pub static COMMANDS: &[CommandSpec] = &[
"type, a: occurrence, b: occurrence (stay where they are); at?: joint origin (default: b's origin) — the joint's frame; one on a or b is kept on its face or hole there, so the joint follows it as the design changes; \
name?; limits?: [[min, max] | null…]; quiet?: bool",
),
- CommandSpec::new("joint.rigid_group", "Rigid Group", rigid_group).at("SOLID", "ASSEMBLE").icon("rigid_group").params("occurrences: [ids or names] (move together, as they are)"),
+ CommandSpec::new("joint.rigid_group", "Rigid Group", crate::checked!("joint.rigid_group", rigid_group))
+ .at("SOLID", "ASSEMBLE")
+ .icon("rigid_group")
+ .contract(&RIGID_GROUP_CONTRACT)
+ .output(output_schema_for::<RigidGroupResult>)
+ .params("occurrences: [ids or names] (move together, as they are)"),
CommandSpec::new("joint.drive", "Drive Joints", crate::checked!("joint.drive", drive))
.at("SOLID", "ASSEMBLE")
.icon("drive")
@@ -83,33 +103,59 @@ pub static COMMANDS: &[CommandSpec] = &[
reason: why the joint can move nothing (suppressed: nothing is stored; its origins lost; its chain joined to nothing grounded → unconnected: \
the occurrence named; or, when nothing moved, the first held value's why); index?: zero-based coordinate to drive with value (the other coordinates follow); continuous?: bool (drag frame, suppress UI echo)",
),
- CommandSpec::new("joint.reach", "Reach Point", reach).icon("reach").params(
+ CommandSpec::new("joint.reach", "Reach Point", crate::checked!("joint.reach", reach))
+ .icon("reach")
+ .contract(&REACH_CONTRACT)
+ .output(output_schema_for::<ReachResult>)
+ .params(
"occurrence: id|name; point: [x,y,z] (where its point goes, world); at?: [x,y,z] (its point, in the world where it is now; default: the centre of its bodies' box); z?: [x,y,z] (the way its axis then points); axis?: [x,y,z] (that axis, in the world now; default: its own z); joints?: [ids or names] (only these move toward the point; the other joints of a closed loop they are in follow); quiet?: bool; continuous?: bool (a frame of a drag: the answer says continuous, and the app's command line doesn't echo it). Moves the values of the joints on its chain from where they are to the nearest pose, within their limits, through motion links, keeping closed loops closed as joint.drive does (contact sets are not checked) → reached; error_mm (and error_deg with z): how close it got; point: where its point is; values: [{joint, name, values}] of the joints that moved, as joint.list gives them; moved; stopped_by_limit: [{joint, value, limit: min|max}]: the limits it rests on short of the point; stopped_by_loop: {joint}: the closed loop that stopped it (its chain alone gets closer); reason: why nothing can move",
),
- CommandSpec::new("joint.motion_link", "Motion Link", motion_link)
+ CommandSpec::new("joint.motion_link", "Motion Link", crate::checked!("joint.motion_link", motion_link))
.at("SOLID", "ASSEMBLE")
.icon("motion_link")
+ .contract(&MOTION_LINK_CONTRACT)
+ .output(output_schema_for::<SolveResult>)
.params("a, b: joints; ratio (b = ratio · a + offset): b's units per a's (mm per deg for an angle driving a distance); offset?: in b's units (deg for an angle, mm for a distance, or an expression); ia?, ib?: value indices (default 0)"),
- CommandSpec::new("joint.gear", "Gear", gear).at("SOLID", "ASSEMBLE").icon("gear").params(
+ CommandSpec::new("joint.gear", "Gear", crate::checked!("joint.gear", gear))
+ .at("SOLID", "ASSEMBLE")
+ .icon("gear")
+ .contract(&GEAR_CONTRACT)
+ .output(output_schema_for::<CouplingResult>)
+ .params(
"a, b: joints that turn (revolute), b driven by a; ra, rb: the gears' pitch radii (or tooth counts): mm, an expression, or \
{circle: [x,y,z], occurrence?}: the round face there, its radius (read again whenever the design changes, so the ratio follows \
edits); internal?: bool (one is a ring gear: both turn the same way; by default b turns the other way); reverse?: bool; \
link?: index (replace that motion link) → link, ratio (b's degrees per a's); b keeps where it is, also when the link replaces \
another (at the current pose)",
),
- CommandSpec::new("joint.rack_pinion", "Rack and Pinion", rack_pinion).at("SOLID", "ASSEMBLE").icon("rack_pinion").params(
+ CommandSpec::new("joint.rack_pinion", "Rack and Pinion", crate::checked!("joint.rack_pinion", rack_pinion))
+ .at("SOLID", "ASSEMBLE")
+ .icon("rack_pinion")
+ .contract(&RACK_PINION_CONTRACT)
+ .output(output_schema_for::<CouplingResult>)
+ .params(
"a, b: a joint that turns (revolute: the pinion) and one that slides (slider: the rack), in either order, b driven by a; \
radius: the pinion's pitch radius (mm, an expression, or {circle: [x,y,z], occurrence?}): the rack travels radius × the turn in \
radians; reverse?: bool; link?: index (replace that motion link) → link, ratio (mm per degree, or degrees per mm); b keeps \
where it is, also when the link replaces another (at the current pose)",
),
- CommandSpec::new("joint.screw", "Screw", screw).at("SOLID", "ASSEMBLE").icon("screw").params(
+ CommandSpec::new("joint.screw", "Screw", crate::checked!("joint.screw", screw))
+ .at("SOLID", "ASSEMBLE")
+ .icon("screw")
+ .contract(&SCREW_CONTRACT)
+ .output(output_schema_for::<CouplingResult>)
+ .params(
"joint: a cylindrical joint (its turn drives its travel) | a, b: a joint that turns and one that slides, b driven by a; pitch: \
travel per turn (mm or an expression); reverse?: bool (a left-hand thread); link?: index (replace that motion link) → link, \
ratio (mm per degree, or degrees per mm); b keeps where it is, also when the link replaces another (at the current \
pose)",
),
- CommandSpec::new("joint.cam", "Cam", cam_cmd).at("SOLID", "ASSEMBLE").icon("cam").params(
+ CommandSpec::new("joint.cam", "Cam", crate::checked!("joint.cam", cam_cmd))
+ .at("SOLID", "ASSEMBLE")
+ .icon("cam")
+ .contract(&CAM_CONTRACT)
+ .output(output_schema_for::<CamResult>)
+ .params(
"a: the cam's joint (revolute); b: the follower's joint, a slider (a translating follower) or a revolute (an oscillating one), b driven by a; profile: {sketch: id|name, index?: the profile (default: the largest)} | {edges: [[x,y,z]…] (points on edges of the cam's bodies forming one closed loop, world), occurrence?}: the cam's outline, in a plane square to its axis, read again whenever the design changes; follower?: knife|roller|flat (default knife; flat: a face square to a slider's line); radius?: the roller's radius (mm, an expression or {circle: [x,y,z], occurrence?}: the roller's round face, which is its tip too); tip?: a joint origin where the follower touches: its knife's point or its roller's centre, such as {circle: [x,y,z]} on the roller (needed for an oscillating follower; a translating one's line runs through it, by default along its slider's axis); flip?: bool (ride the cam from the other side than the one the follower is on now); link?: index (replace that motion link) → link, lift: {min, max, rise, unit} (b's travel over a turn of the cam), reverse (the side it rides from), follower_offset (mm: how far a translating follower's line passes from the cam's axis); b keeps where it is, also when the link replaces another (at the current pose)",
),
CommandSpec::new("joint.limits", "Joint Limits", crate::checked!("joint.limits", limits))
@@ -306,11 +352,6 @@ fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
/// A joint's values as `joint.list` gives them: degrees for angles, mm for distances, each with
/// its name and limits. The numbers are rounded for reading (#10747); the joint keeps full
/// precision.
-pub(crate) fn named_values(j: &Joint, q: &[f64]) -> Vec<Value> {
- named_value_list(j, q).into_iter().map(|v| serde_json::to_value(v).unwrap_or_default()).collect()
-}
-
-/// [`named_values`], typed.
pub(crate) fn named_value_list(j: &Joint, q: &[f64]) -> Vec<NamedValue> {
j.kind
.dofs()
@@ -586,7 +627,7 @@ fn same_frame(s: &Session, o: &JointOrigin, at: Vec3, z: Vec3) -> bool {
/// The longest face name a joint origin takes. A face that cuts split and merged keeps the names
/// of the faces around it (`<name>#[<name>,…]`): several hundred characters on a part a text or
/// a pattern of holes was cut through.
-const MAX_FACE_NAME: usize = 16_384;
+pub(crate) const MAX_FACE_NAME: usize = 16_384;
/// The component an occurrence places (0 for the root, or an unknown occurrence).
pub(crate) fn component_of(s: &Session, occurrence: u64) -> u64 {
@@ -977,7 +1018,7 @@ fn joint_origin(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, format!("there is already a joint origin `{name}`")));
}
s.doc_mut().assembly.origins.push(NamedOrigin { name: name.clone(), origin });
- Ok(json!({"origin": name}))
+ reply(cmd, MakeJointOriginResult { origin: name, param_warnings: Vec::new() })
}
fn kind_param(p: &Value, cmd: &str) -> Result<JointKind> {
@@ -1098,9 +1139,9 @@ fn rigid_group(s: &mut Session, p: &Value) -> Result<Value> {
let mut made = Vec::new();
for other in ids.iter().skip(1) {
let r = as_built(s, &json!({"type": "rigid", "a": first, "b": other, "name": format!("Rigid Group {first}:{other}")}))?;
- made.push(r["joint"].clone());
+ made.push(r["joint"].as_u64().ok_or_else(|| bad(cmd, "the joint made has no id"))?);
}
- Ok(json!({"joints": made}))
+ reply(cmd, RigidGroupResult { joints: made, param_warnings: Vec::new() })
}
fn drive(s: &mut Session, p: &Value) -> Result<Value> {
@@ -1263,7 +1304,7 @@ fn held_values(s: &Session, j: &Joint, requested: &[f64], driven: &[usize], r: &
}
/// Joints `joint.reach` takes at most in `joints`.
-const MAX_REACH_JOINTS: usize = 1000;
+pub(crate) const MAX_REACH_JOINTS: usize = 1000;
fn reach(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "joint.reach";
@@ -1314,49 +1355,54 @@ fn reach(s: &mut Session, p: &Value) -> Result<Value> {
let sol = if response_analysis(p) == joints::Analysis::Placement { place(s) } else { resolve(s) };
let t = joints::occurrence_world(&s.doc, occ);
let got = solidcraft_doc::apply_point(&t, at);
- let mut out = sol_json(&sol, p);
- out["occurrence"] = json!(occurrence_name(s, occ));
- out["point"] = json!([got.x, got.y, got.z]);
- out["error_mm"] = json!(got.dist(to));
let mut there = got.dist(to) <= joints::REACH_TOL;
+ let mut error_deg = None;
if let Some((a, z)) = axis {
// From the sine too: the cosine alone loses small angles to rounding.
let v = solidcraft_doc::apply_vector(&t, a);
let deg = v.cross(z).len().atan2(v.dot(z)).to_degrees();
- out["error_deg"] = json!(deg);
+ error_deg = Some(deg);
there &= deg <= joints::REACH_TOL;
}
- out["reached"] = json!(there);
let name = |id: u64| s.doc.assembly.joints.iter().find(|j| j.id == id);
// As joint.list gives them: with what motion links set.
let effective = joints::joint_values(&s.doc.assembly);
- out["values"] = reached
+ let values = reached
.values
.keys()
.filter_map(|id| name(*id))
- .map(|j| json!({"joint": j.id, "name": j.name, "values": named_values(j, effective.get(&j.id).unwrap_or(&j.values))}))
+ .map(|j| ReachedJoint { joint: j.id, name: j.name.clone(), values: named_value_list(j, effective.get(&j.id).unwrap_or(&j.values)) })
.collect();
- out["moved"] = json!(super::motion::moved(&before, &super::motion::positions(s)).next().is_some());
- out["stopped_by_limit"] = if reached.limits.is_empty() {
- Value::Null
- } else {
+ let stopped_by_limit = (!reached.limits.is_empty()).then(|| {
reached
.limits
.iter()
.filter_map(|(id, i, upper)| {
let j = name(*id)?;
- Some(json!({"joint": j.name, "value": j.kind.dofs().get(*i), "limit": if *upper { "max" } else { "min" }}))
+ Some(LimitStop {
+ joint: j.name.clone(),
+ value: j.kind.dofs().get(*i).map(|d| (*d).to_string()),
+ limit: if *upper { LimitSide::Max } else { LimitSide::Min },
+ })
})
.collect()
+ });
+ let result = ReachResult {
+ solved: solve_report(&sol, p),
+ occurrence: occurrence_name(s, occ),
+ point: [got.x, got.y, got.z],
+ error_mm: got.dist(to),
+ error_deg,
+ reached: there,
+ values,
+ moved: super::motion::moved(&before, &super::motion::positions(s)).next().is_some(),
+ stopped_by_limit,
+ stopped_by_loop: reached.stopped_by_loop.and_then(name).map(|j| ReachLoopStop { joint: j.name.clone() }),
+ reason: r.err(),
+ continuous: (bool_(p, "continuous") == Some(true)).then_some(true),
+ param_warnings: Vec::new(),
};
- out["stopped_by_loop"] = json!(reached.stopped_by_loop.and_then(name).map(|j| json!({"joint": j.name})));
- if let Err(why) = r {
- out["reason"] = json!(why);
- }
- if bool_(p, "continuous") == Some(true) {
- out["continuous"] = json!(true);
- }
- Ok(out)
+ reply(cmd, result)
}
/// The centre of the box around an occurrence's bodies, in its own coordinates (its origin when
@@ -1387,7 +1433,7 @@ fn motion_link(s: &mut Session, p: &Value) -> Result<Value> {
let ratio = ratio * ratio_scale(s, a, ia, b, ib);
s.doc_mut().assembly.links.push(MotionLink { a, ia, b, ib, ratio, offset, coupling: None, lift: Vec::new() });
let sol = resolve(s);
- Ok(sol_json(&sol, p))
+ reply(cmd, SolveResult { solved: solve_report(&sol, p), param_warnings: Vec::new() })
}
/// A coupling length: a number (mm), an expression (kept as typed, so it follows the
@@ -1442,7 +1488,7 @@ fn gear(s: &mut Session, p: &Value) -> Result<Value> {
internal: bool_(p, "internal").unwrap_or(false),
reverse: reverse(p),
};
- couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c), lift: Vec::new() })
+ reply(cmd, couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c), lift: Vec::new() })?)
}
fn rack_pinion(s: &mut Session, p: &Value) -> Result<Value> {
@@ -1450,7 +1496,7 @@ fn rack_pinion(s: &mut Session, p: &Value) -> Result<Value> {
let (a, b) = joint_pair(s, p, cmd)?;
let (ia, ib) = turn_and_travel(s, a, b, cmd)?;
let c = Coupling::RackPinion { radius: size_param(s, p, "radius", cmd)?, reverse: reverse(p) };
- couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c), lift: Vec::new() })
+ reply(cmd, couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c), lift: Vec::new() })?)
}
fn screw(s: &mut Session, p: &Value) -> Result<Value> {
@@ -1470,7 +1516,7 @@ fn screw(s: &mut Session, p: &Value) -> Result<Value> {
}
};
let c = Coupling::Screw { pitch: size_param(s, p, "pitch", cmd)?, reverse: reverse(p) };
- couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c), lift: Vec::new() })
+ reply(cmd, couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c), lift: Vec::new() })?)
}
fn cam_cmd(s: &mut Session, p: &Value) -> Result<Value> {
@@ -1504,26 +1550,23 @@ fn cam_cmd(s: &mut Session, p: &Value) -> Result<Value> {
c.reverse = cam::default_reverse(&s.doc, &st, &probe, &c).map_err(|e| bad(cmd, e.to_string()))? != bool_(p, "flip").unwrap_or(false);
let offset = cam::follower_offset(&s.doc, &st, &probe, &c).map_err(|e| bad(cmd, e.to_string()))?;
let reverse = c.reverse;
- let mut out = couple(s, p, cmd, MotionLink { coupling: Some(Coupling::Cam(c)), ..probe })?;
- let index = out["link"].as_u64().and_then(|i| usize::try_from(i).ok()).unwrap_or(usize::MAX);
- if let (Some(o), Some(l)) = (out.as_object_mut(), s.doc.assembly.links.get(index)) {
- o.remove("ratio");
- o.insert("lift".into(), lift_json(l, oscillating));
- o.insert("reverse".into(), json!(reverse));
- if !oscillating {
- o.insert("follower_offset".into(), json!(offset));
- }
- }
- Ok(out)
+ let coupled = couple(s, p, cmd, MotionLink { coupling: Some(Coupling::Cam(c)), ..probe })?;
+ let lift = s.doc.assembly.links.get(coupled.link).and_then(|l| lift_info(l, oscillating));
+ reply(
+ cmd,
+ CamResult {
+ solved: coupled.solved,
+ link: coupled.link,
+ lift,
+ reverse,
+ follower_offset: (!oscillating).then_some(offset),
+ param_warnings: Vec::new(),
+ },
+ )
}
/// A cam's follower travel over a turn of the cam: b's lowest and highest values and their
-/// difference, in degrees (`angle`) or mm.
-fn lift_json(l: &MotionLink, angle: bool) -> Value {
- serde_json::to_value(lift_info(l, angle)).unwrap_or_default()
-}
-
-/// [`lift_json`], typed: `None` for a table that is not whole.
+/// difference, in degrees (`angle`) or mm; `None` for a table that is not whole.
fn lift_info(l: &MotionLink, angle: bool) -> Option<CamLift> {
// A table that is not whole (a hand-edited file) moves nothing, and says so.
if l.lift.len() != cam::CAM_SAMPLES {
@@ -1594,7 +1637,7 @@ fn cam_profile(s: &Session, p: &Value, cmd: &str) -> Result<CamProfile> {
/// Add a coupling's motion link, or put it in place of link `link`: its ratio worked out from its
/// sizes, its offset leaving b where it is (the teeth mesh as they are now), for a new link and
/// one put in place of another alike.
-fn couple(s: &mut Session, p: &Value, cmd: &str, mut l: MotionLink) -> Result<Value> {
+fn couple(s: &mut Session, p: &Value, cmd: &str, mut l: MotionLink) -> Result<CouplingResult> {
let links = &s.doc.assembly.links;
let replace = match p.get("link") {
None => None,
@@ -1647,10 +1690,7 @@ fn couple(s: &mut Session, p: &Value, cmd: &str, mut l: MotionLink) -> Result<Va
}
};
let sol = resolve(s);
- let mut out = sol_json(&sol, p);
- out["link"] = json!(index);
- out["ratio"] = json!(shown);
- Ok(out)
+ Ok(CouplingResult { solved: solve_report(&sol, p), link: index, ratio: shown, param_warnings: Vec::new() })
}
fn is_angle(s: &Session, joint: u64, i: usize) -> bool {
diff --git a/crates/engine/src/schema/joints.rs b/crates/engine/src/schema/joints.rs
index 1041b1a83e..9449b9c60f 100644
--- a/crates/engine/src/schema/joints.rs
+++ b/crates/engine/src/schema/joints.rs
@@ -6,11 +6,15 @@ use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::{Map, Value, json};
+use solidcore_record::Vec3;
+use solidcraft_doc::joints::cam::MAX_PROFILE_EDGES;
use solidcraft_doc::joints::{Coupling, JointExprs, JointKind, Snap};
+use solidcraft_geom::Vec3Geom;
use super::check::whole;
use super::motion::require;
use super::types::{AngleExpr, IdOrName, LengthExpr, present};
+use crate::cmd::joints::{MAX_FACE_NAME, MAX_REACH_JOINTS};
use crate::params;
/// A joint origin as joint.create takes it: a joint origin's name, or an object with the snap
@@ -1407,6 +1411,1101 @@ pub enum JointDeleted {
},
}
+// ---------------------------------------------------------------------------------------------
+// joint.origin, joint.rigid_group, joint.reach, joint.motion_link, joint.gear, joint.rack_pinion,
+// joint.screw and joint.cam (#13185).
+//
+// As above: each key reads as its handler reads it and fails with the handler's message, and a key
+// the handler refuses when it is left out is optional in the type and required in the schema. A
+// key the handler reads only in some cases (a joint origin's `end`, `on` or `z`, a screw's `a` and
+// `b`, a roller's `radius`) is read here in the same cases. Where the handler reads a key
+// leniently (a value of the wrong type taken as if the key were left out) the type is stricter,
+// which is what warn and strict report.
+// ---------------------------------------------------------------------------------------------
+
+/// A point [x, y, z] in mm, or {x, y, z}, as `params::vec3` reads it. Only its schema: the
+/// parameter types read their points themselves, with each handler's message.
+pub struct WorldPoint;
+
+impl JsonSchema for WorldPoint {
+ fn schema_name() -> Cow<'static, str> {
+ "WorldPoint".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "A point [x, y, z] in mm, or {x, y, z}, each number below 1e9 in size.",
+ "anyOf": [
+ {"type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3},
+ {"type": "object", "properties": {"x": {"type": "number"}, "y": {"type": "number"}, "z": {"type": "number"}}, "required": ["x", "y", "z"]}
+ ]
+ })
+ }
+}
+
+/// A direction [x, y, z] or {x, y, z}, which may not be zero. Only its schema.
+pub struct WorldDirection;
+
+impl JsonSchema for WorldDirection {
+ fn schema_name() -> Cow<'static, str> {
+ "WorldDirection".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "A direction [x, y, z] or {x, y, z} of numbers below 1e9 in size, not the zero vector.",
+ "anyOf": [
+ {"type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3},
+ {"type": "object", "properties": {"x": {"type": "number"}, "y": {"type": "number"}, "z": {"type": "number"}}, "required": ["x", "y", "z"]}
+ ]
+ })
+ }
+}
+
+fn vector(v: &Value) -> Option<[f64; 3]> {
+ params::vec3(v).map(|p| [p.x, p.y, p.z])
+}
+
+/// `key` as `joint.reach` reads a point (`direction` false) or a direction: finite and under 1e9
+/// in length; a direction not zero. `null` is refused, not read as absent.
+fn reach_vector<E: serde::de::Error>(m: &Map<String, Value>, key: &str, direction: bool) -> Result<Option<[f64; 3]>, E> {
+ let Some(v) = m.get(key) else { return Ok(None) };
+ let found = params::vec3(v).filter(|v| v.is_finite() && v.len() < 1e9);
+ let found = if direction { found.and_then(Vec3::normalized) } else { found };
+ match found {
+ Some(_) => Ok(vector(v)),
+ None if direction => Err(E::custom(whole(format!("`{key}` must be a direction [x, y, z]")))),
+ None => Err(E::custom(whole(format!("`{key}` must be [x, y, z]")))),
+ }
+}
+
+/// `key` as the handlers' `link` read: the index of a motion link, a whole number; whether the
+/// link exists is the handler's to check.
+fn link_index<E: serde::de::Error>(m: &Map<String, Value>, key: &str) -> Result<Option<u64>, E> {
+ match m.get(key) {
+ None => Ok(None),
+ Some(v) => v.as_u64().map(Some).ok_or_else(|| E::custom(whole("no such motion link"))),
+ }
+}
+
+/// A joint origin as an object or a name, as `origin_param` reads one before it looks at the
+/// design (a coupling's round face, a cam's `tip`): the forms of [`JointOriginArg`], and a face
+/// given by its name is 1…16384 characters.
+fn origin_arg(v: &Value) -> Result<JointOriginArg, String> {
+ let named = ["face", "circle"].iter().find_map(|k| v.get(*k).and_then(Value::as_str));
+ if let Some(name) = named
+ && (name.is_empty() || name.len() > MAX_FACE_NAME)
+ {
+ return Err(format!("a face name is 1…{MAX_FACE_NAME} characters"));
+ }
+ JointOriginArg::read(v)
+}
+
+/// A coupling's length: a number (mm), an expression (kept as typed, so it follows the
+/// parameters), or `{circle: [x, y, z], occurrence?}`, the round face there, by its radius. Kept
+/// as given, for the handler.
+#[derive(Clone, Debug, PartialEq)]
+pub struct CouplingSize(pub Value);
+
+impl CouplingSize {
+ /// `v` as `size_param` reads `key`.
+ fn read(v: &Value, key: &str) -> Result<Self, String> {
+ match v {
+ Value::Number(_) => Ok(CouplingSize(v.clone())),
+ Value::String(t) if t.len() <= 1000 => Ok(CouplingSize(v.clone())),
+ Value::Object(o) if o.contains_key("circle") => origin_arg(v).map(|_| CouplingSize(v.clone())),
+ _ => Err(format!("`{key}` must be a length (mm or an expression) or a round face ({{circle: [x, y, z]}})")),
+ }
+ }
+}
+
+impl JsonSchema for CouplingSize {
+ fn schema_name() -> Cow<'static, str> {
+ "CouplingSize".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let point = generator.subschema_for::<WorldPoint>();
+ json_schema!({
+ "description": "A length: a number (mm), an expression (text of at most 1000 bytes, kept as typed so it follows the design's parameters), or {circle: [x, y, z], occurrence?}, the round face there, by its radius, read again whenever the design changes. The circle is a point on the round face (not its centre), or the face's name as model.faces lists it.",
+ "anyOf": [
+ {"type": "number"},
+ {"type": "string"},
+ {
+ "type": "object",
+ "properties": {
+ "circle": {"description": "A point on the round face, in world coordinates, or its name.", "anyOf": [point, {"type": "string", "minLength": 1}]},
+ "occurrence": {"description": "The occurrence the face is on, by id or name. Default: found from the point, or the named face's component.", "type": ["number", "string"]}
+ },
+ "required": ["circle"]
+ }
+ ]
+ })
+ }
+}
+
+/// `key`, read by `CouplingSize::read` with the key named in its message.
+fn size<E: serde::de::Error>(m: &Map<String, Value>, key: &str) -> Result<Option<CouplingSize>, E> {
+ m.get(key).map(|v| CouplingSize::read(v, key).map_err(|e| E::custom(whole(e)))).transpose()
+}
+
+/// Two joints `a` and `b`, read in that order.
+fn joint_pair<E: serde::de::Error>(m: &Map<String, Value>) -> Result<(Option<JointKey>, Option<JointKey>), E> {
+ Ok((given(m, "a", JointKey::read)?, given(m, "b", JointKey::read)?))
+}
+
+/// A list of joints by id or name, as `joint.reach` reads `joints`.
+#[derive(Clone, Debug, PartialEq)]
+pub struct JointKeyList(pub Vec<JointKey>);
+
+impl JointKeyList {
+ fn read(v: &Value) -> Result<Self, String> {
+ match v {
+ Value::Array(items) if items.len() <= MAX_REACH_JOINTS => items.iter().map(JointKey::read).collect::<Result<_, _>>().map(JointKeyList),
+ _ => Err(format!("`joints` must be a list of joints (ids or names), at most {MAX_REACH_JOINTS}")),
+ }
+ }
+}
+
+impl JsonSchema for JointKeyList {
+ fn schema_name() -> Cow<'static, str> {
+ "JointKeyList".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let joint = generator.subschema_for::<JointKey>();
+ json_schema!({
+ "description": "A list of joints, each by id or name.",
+ "type": "array",
+ "items": joint,
+ "maxItems": MAX_REACH_JOINTS
+ })
+ }
+}
+
+/// Two or more occurrences, by id or name, as `joint.rigid_group` reads them.
+#[derive(Clone, Debug, PartialEq)]
+pub struct OccurrenceList(pub Vec<OccurrenceKey>);
+
+impl OccurrenceList {
+ fn read(v: &Value) -> Result<Self, String> {
+ match v {
+ Value::Array(items) if (2..=1000).contains(&items.len()) => {
+ items.iter().map(OccurrenceKey::read).collect::<Result<_, _>>().map(OccurrenceList)
+ }
+ _ => Err("`occurrences` must list 2…1000 occurrences".into()),
+ }
+ }
+}
+
+impl JsonSchema for OccurrenceList {
+ fn schema_name() -> Cow<'static, str> {
+ "OccurrenceList".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let occurrence = generator.subschema_for::<OccurrenceKey>();
+ json_schema!({
+ "description": "2 to 1000 occurrences, each by id or name.",
+ "type": "array",
+ "items": occurrence,
+ "minItems": 2,
+ "maxItems": 1000
+ })
+ }
+}
+
+read_with!(JointKeyList, OccurrenceList);
+
+/// Which follower a cam drives.
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
+#[serde(rename_all = "lowercase")]
+pub enum CamFollower {
+ /// A point on the cam's outline.
+ Knife,
+ /// A roller of the given `radius`.
+ Roller,
+ /// A flat face, square to a slider's line.
+ Flat,
+}
+
+/// A cam's outline, as `cam_profile` reads it: a sketch's closed profile, or picked edges of the
+/// cam's bodies. Whether the sketch, the profile or an occurrence exists, and whether the edges
+/// close, is the handler's to check.
+#[derive(Clone, Debug, PartialEq)]
+pub enum CamProfileParam {
+ /// A closed profile of a sketch (its largest by default).
+ Sketch { sketch: String, index: Option<u64> },
+ /// Points on the edges of the cam's bodies, in world coordinates.
+ Edges { edges: Vec<[f64; 3]>, occurrence: Option<OccurrenceKey> },
+}
+
+impl CamProfileParam {
+ fn read(v: &Value) -> Result<Self, String> {
+ // `sketch`, once given (`null` included), makes it a sketch's profile, whatever else it has.
+ if let Some(sketch) = v.get("sketch") {
+ let sketch = crate::cmd::sketch_key(Some(sketch)).ok_or("`profile.sketch` must be a sketch id or name")?;
+ let index = match v.get("index") {
+ None => None,
+ Some(i) => Some(i.as_u64().ok_or("the sketch has no such closed profile (an open curve makes none)")?),
+ };
+ return Ok(CamProfileParam::Sketch { sketch, index });
+ }
+ let Some(Value::Array(points)) = v.get("edges") else {
+ return Err("`profile` is {sketch: id|name} or {edges: [[x, y, z], …]}".into());
+ };
+ if points.is_empty() || points.len() > MAX_PROFILE_EDGES {
+ return Err(format!("pick 1 to {MAX_PROFILE_EDGES} edges"));
+ }
+ let edges = points.iter().map(vector).collect::<Option<Vec<_>>>().ok_or("`edges` are finite [x, y, z] points")?;
+ let occurrence = v.get("occurrence").map(OccurrenceKey::read).transpose()?;
+ Ok(CamProfileParam::Edges { edges, occurrence })
+ }
+}
+
+impl JsonSchema for CamProfileParam {
+ fn schema_name() -> Cow<'static, str> {
+ "CamProfile".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let point = generator.subschema_for::<WorldPoint>();
+ let occurrence = generator.subschema_for::<OccurrenceKey>();
+ json_schema!({
+ "description": "The cam's outline, in a plane square to its axis, read again whenever the design changes: {sketch, index?}, a closed profile of a sketch; or {edges, occurrence?}, points on edges of the cam's bodies that form one closed loop. A call with `sketch` is the first form, whatever else it has.",
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "sketch": {"description": "The sketch, by id or name.", "type": ["number", "string"]},
+ "index": {"description": "Which closed profile of the sketch, counted from zero. Default: the largest.", "type": "integer", "minimum": 0}
+ },
+ "required": ["sketch"]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "edges": {"description": "Points on edges of the cam's bodies (world coordinates), 1 to 64, which form one closed loop.", "type": "array", "items": point, "minItems": 1, "maxItems": MAX_PROFILE_EDGES},
+ "occurrence": occurrence
+ },
+ "required": ["edges"],
+ "not": {"required": ["sketch"]}
+ }
+ ]
+ })
+ }
+}
+
+read_with!(CamProfileParam);
+
+/// A joint origin's turn about z: `x` of `joint.origin`.
+pub struct OriginX;
+
+impl JsonSchema for OriginX {
+ fn schema_name() -> Cow<'static, str> {
+ "OriginX".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let direction = generator.subschema_for::<WorldDirection>();
+ let point = generator.subschema_for::<WorldPoint>();
+ json_schema!({
+ "description": "A direction [x, y, z] in world coordinates (for a point origin also {x, y, z}), a face's name, or {face: a point on a face of the origin's component, or its name}: a direction, the way to another hole's axis or a plane's normal.",
+ "anyOf": [
+ direction,
+ {"type": "string", "minLength": 1},
+ {"type": "object", "properties": {"face": {"anyOf": [point, {"type": "string", "minLength": 1}]}}, "required": ["face"]}
+ ]
+ })
+ }
+}
+
+/// A joint origin's face or circle: a point on it, or its name. Only its schema.
+pub struct OriginFace;
+
+impl JsonSchema for OriginFace {
+ fn schema_name() -> Cow<'static, str> {
+ "OriginFace".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let point = generator.subschema_for::<WorldPoint>();
+ json_schema!({
+ "description": "A point in world coordinates, or a face's name as model.faces lists it (1 to 16384 characters).",
+ "anyOf": [point, {"type": "string", "minLength": 1}]
+ })
+ }
+}
+
+/// An explicit frame: its origin and z, and optionally its x. Only its schema.
+pub struct OriginFrame;
+
+impl JsonSchema for OriginFrame {
+ fn schema_name() -> Cow<'static, str> {
+ "OriginFrame".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let point = generator.subschema_for::<WorldPoint>();
+ let direction = generator.subschema_for::<WorldDirection>();
+ json_schema!({
+ "description": "An explicit frame in world coordinates.",
+ "type": "object",
+ "properties": {
+ "origin": {"description": "The frame's origin.", "anyOf": [point]},
+ "z": {"description": "The frame's z axis.", "anyOf": [direction]},
+ "x": {"description": "The frame's x axis. Default: chosen from z.", "anyOf": [direction]}
+ },
+ "required": ["origin", "z"]
+ })
+ }
+}
+
+/// Make a named joint origin: a frame on a face, a round edge, an edge, a point, or given
+/// outright, that joints can then take for a side by its name. Give one of `face`, `circle`,
+/// `edge`, `point` or `frame`; a face or circle given by its name is found again by name, so the
+/// origin follows its face as the design changes. Keys that apply only to some of these (`on` and
+/// `corner` to an edge; `end` to a circle; `body` to a name) are read only then.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = origin_required)]
+pub struct MakeJointOriginParams {
+ /// The origin's name. Default: `Joint Origin` and the first number no origin's name has.
+ /// Blank text gives the default. A name already taken is refused.
+ #[serde(default)]
+ pub name: Option<String>,
+ /// The occurrence the origin is on, by id or name. Default: found from the point, or the
+ /// named face's component.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "OccurrenceKey")]
+ pub occurrence: Option<OccurrenceKey>,
+ /// The centre of a planar face: a point on it, or its name. The first of `face` and `circle`
+ /// given by name wins; then the first given as a point of `face`, `circle`, `edge` and `point`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "OriginFace")]
+ pub face: Option<Value>,
+ /// The centre of a round end: a point on its wall or rim, the end's centre, or the round
+ /// face's name.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "OriginFace")]
+ pub circle: Option<Value>,
+ /// A point on an edge of a planar face: the edge's middle, z out of the face, y into it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "WorldPoint")]
+ pub edge: Option<Value>,
+ /// A point: the frame's origin there, z along `z` (default: the world's z), x along `x`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "WorldPoint")]
+ pub point: Option<Value>,
+ /// An explicit frame, read only when no point is given in `face`, `circle`, `edge` or `point`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "OriginFrame")]
+ pub frame: Option<Value>,
+ /// With `edge`: a point on the face to use. Default: the larger planar face beside the edge.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<WorldPoint>")]
+ pub on: Option<Value>,
+ /// With `edge`: a point near one end of the edge, for the corner there (x and y along its two
+ /// edges into the face), found again by name.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<WorldPoint>")]
+ pub corner: Option<Value>,
+ /// The frame's z, a direction in world coordinates, instead of the face's normal. Read for an
+ /// `edge` (then along the edge when it runs that way), a `circle` given as a point (the way
+ /// out of its end) and a `point`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<WorldDirection>")]
+ pub z: Option<Value>,
+ /// The frame's x, its turn about z: a direction, a face's name or {face}. Read for a `face`,
+ /// a `circle` and a `point` (a direction there). Default: chosen from z alone, or the x the
+ /// face's frame has now.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<OriginX>")]
+ pub x: Option<Value>,
+ /// With `circle`: the end, by the name of the face across its rim there. Default: the end
+ /// nearer the pick. Refused for any other origin; for a circle given as a point with `z` it
+ /// is not checked.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "String")]
+ pub end: Option<Value>,
+ /// With a face or circle given by its name: the body the face is on.
+ #[serde(default)]
+ pub body: Option<String>,
+}
+
+fn origin_required(schema: &mut Schema) {
+ // The handler refuses a call with none of them.
+ schema.insert(
+ "anyOf".into(),
+ json!([{"required": ["face"]}, {"required": ["circle"]}, {"required": ["edge"]}, {"required": ["point"]}, {"required": ["frame"]}]),
+ );
+}
+
+/// The wording of the handler's refusals of a joint origin's keys.
+const ORIGIN_X: &str = "`x` is a direction [x, y, z], a face's name, or {face: [x, y, z]}";
+const END_NAME: &str = "`end` is the name of a face a round end lies on";
+const END_ROUND: &str = "`end` is for a round origin (`circle`)";
+
+/// A face or end name the handlers take: 1…16384 characters.
+fn face_name(v: &Value) -> bool {
+ v.as_str().is_some_and(|n| !n.is_empty() && n.len() <= MAX_FACE_NAME)
+}
+
+/// `x`, as `x_param` reads it: `null` is left out; a direction, a face's name or `{face}`.
+fn origin_x(m: &Map<String, Value>) -> Result<(), String> {
+ let direction = |v: &Value| params::vec3(v).filter(|d| d.is_finite() && d.len() > 1e-9).map(|_| ()).ok_or_else(|| ORIGIN_X.to_string());
+ match m.get("x") {
+ None | Some(Value::Null) => Ok(()),
+ Some(v) if face_name(v) => Ok(()),
+ Some(Value::Object(o)) => match o.get("face") {
+ Some(f) if face_name(f) => Ok(()),
+ Some(p) => params::vec3(p).map(|_| ()).ok_or_else(|| ORIGIN_X.to_string()),
+ None => Err(ORIGIN_X.to_string()),
+ },
+ Some(d) => direction(d),
+ }
+}
+
+/// `z`, as `given_z` reads it: `null` is left out; else a direction that is not zero. Whether it
+/// is given tells which of the handler's paths a call takes.
+fn origin_z(m: &Map<String, Value>) -> Result<bool, String> {
+ match m.get("z") {
+ None | Some(Value::Null) => Ok(false),
+ Some(z) => {
+ params::vec3(z).filter(|z| z.is_finite() && z.len() > 1e-9).map(|_| true).ok_or_else(|| "`z` is a direction [x, y, z]".to_string())
+ }
+ }
+}
+
+/// `end`, as `settle` reads it: the name of a face, and only for a round origin. (`null` is not
+/// left out: it is not a name.)
+fn origin_end(m: &Map<String, Value>, round: bool) -> Result<(), String> {
+ match m.get("end") {
+ None => Ok(()),
+ Some(v) if !face_name(v) => Err(END_NAME.into()),
+ Some(_) if !round => Err(END_ROUND.into()),
+ Some(_) => Ok(()),
+ }
+}
+
+/// A point key the handler reads as a point or leaves out when it is not one (`on`, `corner`, a
+/// point origin's `z`, a frame's `x`): a value that is not a point is refused here, `null`
+/// is left out.
+fn origin_point(v: Option<&Value>, message: &str) -> Result<(), String> {
+ match v {
+ None | Some(Value::Null) => Ok(()),
+ Some(v) => vector(v).map(|_| ()).ok_or_else(|| message.to_string()),
+ }
+}
+
+impl MakeJointOriginParams {
+ /// The keys `origin_param` reads, in the cases it reads them, in the order it reads them.
+ fn check(m: &Map<String, Value>) -> Result<(), String> {
+ // A face or circle given by its name: the first of the two that is text.
+ let named = ["face", "circle"].into_iter().find_map(|k| m.get(k).and_then(Value::as_str).map(|n| (k, n)));
+ if let Some((what, name)) = named {
+ if name.is_empty() || name.len() > MAX_FACE_NAME {
+ return Err(format!("a face name is 1…{MAX_FACE_NAME} characters"));
+ }
+ if !matches!(m.get("body"), None | Some(Value::Null | Value::String(_))) {
+ return Err("`body` must be text".into());
+ }
+ m.get("occurrence").map(OccurrenceKey::read).transpose()?;
+ origin_x(m)?;
+ return origin_end(m, what == "circle");
+ }
+ // Else a point on a face, circle, edge or point, else a frame.
+ let picked = ["face", "circle", "edge", "point"].into_iter().find(|k| m.get(*k).and_then(params::vec3).is_some());
+ let what = match (picked, m.get("frame")) {
+ (Some(k), _) => k,
+ (None, Some(f)) => {
+ f.get("origin").and_then(params::vec3).ok_or("`frame` needs origin and z")?;
+ "frame"
+ }
+ _ => return Err("a joint origin needs face, circle, edge, point or frame [x, y, z], or a face's name".into()),
+ };
+ m.get("occurrence").map(OccurrenceKey::read).transpose()?;
+ match what {
+ "face" => {
+ origin_x(m)?;
+ origin_end(m, false)
+ }
+ // With a `z`, the handler tries the end and then the point, so a bad `end` is not refused.
+ "circle" => {
+ origin_x(m)?;
+ if origin_z(m)? { Ok(()) } else { origin_end(m, true) }
+ }
+ "edge" => {
+ origin_point(m.get("on"), "`on` must be a point [x, y, z]")?;
+ origin_point(m.get("corner"), "`corner` must be a point [x, y, z]")?;
+ // With a `z` the origin is made at once, and `end` is not read.
+ if origin_z(m)? { Ok(()) } else { origin_end(m, false) }
+ }
+ "point" => {
+ origin_point(m.get("z"), "`z` is a direction [x, y, z]")?;
+ match m.get("x") {
+ None | Some(Value::Null) => {}
+ Some(x) => {
+ vector(x).ok_or("a point origin's `x` is a direction [x, y, z]")?;
+ }
+ }
+ origin_end(m, false)
+ }
+ _ => {
+ let frame = m.get("frame");
+ frame.and_then(|f| f.get("z")).and_then(params::vec3).ok_or("`frame` needs a z axis")?;
+ origin_point(frame.and_then(|f| f.get("x")), "`frame`'s x must be a direction [x, y, z]")?;
+ origin_end(m, false)
+ }
+ }
+ }
+}
+
+impl<'de> Deserialize<'de> for MakeJointOriginParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let m = keys(d)?;
+ Self::check(&m).map_err(|e| D::Error::custom(whole(e)))?;
+ let raw = |k: &str| m.get(k).cloned();
+ // The name is read last, once the origin is made.
+ Ok(MakeJointOriginParams {
+ name: text(&m, "name")?,
+ occurrence: m.get("occurrence").and_then(|v| OccurrenceKey::read(v).ok()),
+ face: raw("face"),
+ circle: raw("circle"),
+ edge: raw("edge"),
+ point: raw("point"),
+ frame: raw("frame"),
+ on: raw("on"),
+ corner: raw("corner"),
+ z: raw("z"),
+ x: raw("x"),
+ end: raw("end"),
+ body: m.get("body").and_then(Value::as_str).map(str::to_string),
+ })
+ }
+}
+
+/// What `joint.origin` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct MakeJointOriginResult {
+ /// The new joint origin's name, as joints take it for a side.
+ pub origin: String,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// Join occurrences so that they move together, as they are: a rigid joint, made as built, from
+/// the first occurrence to each of the others. One undo step for each joint.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = rigid_group_required)]
+pub struct RigidGroupParams {
+ // `occurrences` is optional in the type and required in the schema: left out, the handler
+ // refuses it with its own message.
+ /// The occurrences, each by id or name: 2 to 1000. The first is the one the others are joined
+ /// to.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "OccurrenceList")]
+ pub occurrences: Option<OccurrenceList>,
+}
+
+fn rigid_group_required(schema: &mut Schema) {
+ require(schema, "occurrences");
+}
+
+impl<'de> Deserialize<'de> for RigidGroupParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let m = keys(d)?;
+ Ok(RigidGroupParams { occurrences: given(&m, "occurrences", OccurrenceList::read)? })
+ }
+}
+
+/// What `joint.rigid_group` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct RigidGroupResult {
+ /// The rigid joints made, by id: one for each occurrence after the first.
+ pub joints: Vec<u64>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// Move an occurrence's point to a place in the world by changing the values of the joints on its
+/// chain, from where they are to the nearest pose within their limits, through motion links and
+/// keeping closed loops closed as joint.drive does (contact sets are not checked). With `z` the
+/// occurrence's axis is turned to point that way too. Reaches as far as it can: the reply says how
+/// close it got and what stopped it.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = reach_required)]
+pub struct ReachParams {
+ // `occurrence` and `point` are optional in the type and required in the schema
+ // (`reach_required`): left out, the handler refuses them with its own message.
+ /// The occurrence to move, by id or name.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "OccurrenceKey")]
+ pub occurrence: Option<OccurrenceKey>,
+ /// Where its point goes, in world coordinates (mm).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "WorldPoint")]
+ pub point: Option<[f64; 3]>,
+ /// The occurrence's point, in the world where it is now (mm). Default: the centre of the box
+ /// around its bodies.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "WorldPoint")]
+ pub at: Option<[f64; 3]>,
+ /// The way the occurrence's axis then points, a direction in the world. Without `z` the
+ /// occurrence is not turned, only moved.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "WorldDirection")]
+ pub z: Option<[f64; 3]>,
+ /// The occurrence's axis, a direction in the world now, that `z` is the way it points.
+ /// Default: its own z. Goes with `z`: refused without it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "WorldDirection")]
+ pub axis: Option<[f64; 3]>,
+ /// Only these joints move toward the point, each by id or name (at most 1000); the other joints
+ /// of a closed loop they are in follow. Default: every joint on its chain.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "JointKeyList")]
+ pub joints: Option<JointKeyList>,
+ /// Leave out `dof` and `fixed` in the reply. Default: false.
+ #[serde(default)]
+ pub quiet: Option<bool>,
+ /// A frame of a drag: the reply says `continuous`, and the app's command line doesn't echo it.
+ /// Default: false.
+ #[serde(default)]
+ pub continuous: Option<bool>,
+}
+
+fn reach_required(schema: &mut Schema) {
+ require(schema, "occurrence");
+ require(schema, "point");
+ // `axis` goes with `z`.
+ schema.insert("dependentRequired".into(), json!({"axis": ["z"]}));
+}
+
+impl<'de> Deserialize<'de> for ReachParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let m = keys(d)?;
+ // In the handler's order.
+ let occurrence = given(&m, "occurrence", OccurrenceKey::read)?;
+ let point = reach_vector(&m, "point", false)?;
+ let at = reach_vector(&m, "at", false)?;
+ let z = reach_vector(&m, "z", true)?;
+ let axis = reach_vector(&m, "axis", true)?;
+ let joints = given(&m, "joints", JointKeyList::read)?;
+ Ok(ReachParams { occurrence, point, at, z, axis, joints, quiet: flag(&m, "quiet")?, continuous: flag(&m, "continuous")? })
+ }
+}
+
+/// Which limit of a value a reach rests on.
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, JsonSchema)]
+#[serde(rename_all = "lowercase")]
+pub enum LimitSide {
+ /// The lowest the value goes.
+ Min,
+ /// The highest.
+ Max,
+}
+
+/// A limit a reach came to rest on, short of the point.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct LimitStop {
+ /// The joint, by name.
+ pub joint: String,
+ /// The coordinate that rests on its limit (angle, distance, …), by name.
+ pub value: Option<String>,
+ /// Which limit.
+ pub limit: LimitSide,
+}
+
+/// The closed loop that stopped a reach.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ReachLoopStop {
+ /// The joint that closes the loop, by name.
+ pub joint: String,
+}
+
+/// A joint a reach moved.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ReachedJoint {
+ /// The joint, by id.
+ pub joint: u64,
+ /// Its name.
+ pub name: String,
+ /// Its values now, as joint.list gives them.
+ pub values: Vec<NamedValue>,
+}
+
+/// What `joint.reach` returns: the solve, then how close the occurrence's point got.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ReachResult {
+ #[serde(flatten)]
+ pub solved: SolveReport,
+ /// The occurrence moved, by name.
+ pub occurrence: String,
+ /// Where its point is now, in world coordinates (mm).
+ pub point: [f64; 3],
+ /// How far that is from the target, in mm.
+ pub error_mm: f64,
+ /// With `z`: how far the axis points from where it was asked to, in degrees. Left out without.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub error_deg: Option<f64>,
+ /// Whether the point (and the axis, with `z`) is at the target, within tolerance.
+ pub reached: bool,
+ /// The joints that moved, with their values now.
+ pub values: Vec<ReachedJoint>,
+ /// Whether any occurrence moved.
+ pub moved: bool,
+ /// The limits it rests on short of the point; `null` when none.
+ pub stopped_by_limit: Option<Vec<LimitStop>>,
+ /// The closed loop that stopped it (its chain alone gets closer); `null` when none.
+ pub stopped_by_loop: Option<ReachLoopStop>,
+ /// Why nothing can move. Left out when the reach worked.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub reason: Option<String>,
+ /// True for a `continuous` call; left out otherwise.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub continuous: Option<bool>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// Tie one joint's value to another's: b = ratio · a + offset, in b's units, so that when a is
+/// driven b follows. The link starts at b's value now (the offset is `offset`, or 0). A joint
+/// follows one link at most, and two joints may not drive each other.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = motion_link_required)]
+pub struct MotionLinkParams {
+ // `a`, `b` and `ratio` are optional in the type and required in the schema: left out, the
+ // handler refuses them with its own message.
+ /// The driving joint, by id or name.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "JointKey")]
+ pub a: Option<JointKey>,
+ /// The driven joint, by id or name. Not the same joint as `a`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "JointKey")]
+ pub b: Option<JointKey>,
+ /// b's units per a's, per degree for an angle (mm per degree for an angle driving a distance,
+ /// degrees per mm the other way round).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "FiniteNumber")]
+ pub ratio: Option<f64>,
+ /// The offset in b's units (degrees for an angle, mm for a distance), or an expression.
+ /// Default: 0.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "JointValue")]
+ pub offset: Option<JointValue>,
+ /// Which of a's values drives, counted from zero (a negative number is 0). Default: 0.
+ #[serde(default)]
+ pub ia: Option<f64>,
+ /// Which of b's values follows, counted from zero (a negative number is 0). Default: 0.
+ #[serde(default)]
+ pub ib: Option<f64>,
+ /// Leave out `dof` and `fixed` in the reply. Default: false.
+ #[serde(default)]
+ pub quiet: Option<bool>,
+}
+
+fn motion_link_required(schema: &mut Schema) {
+ require(schema, "a");
+ require(schema, "b");
+ require(schema, "ratio");
+}
+
+/// A number below 1e9 in size. Only its schema.
+pub struct FiniteNumber;
+
+impl JsonSchema for FiniteNumber {
+ fn schema_name() -> Cow<'static, str> {
+ "FiniteNumber".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "A number below 1e9 in size.", "type": "number", "exclusiveMinimum": -1e9, "exclusiveMaximum": 1e9})
+ }
+}
+
+impl<'de> Deserialize<'de> for MotionLinkParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let m = keys(d)?;
+ // In the handler's order: the joints, the ratio, the indices, then the offset.
+ let (a, b) = joint_pair(&m)?;
+ let ratio = given(&m, "ratio", |v| match v {
+ Value::Number(n) => n.as_f64().and_then(params::finite).ok_or_else(|| "`ratio` must be a number".to_string()),
+ _ => Err("`ratio` must be a number".to_string()),
+ })?;
+ let (ia, ib) = (number(&m, "ia")?, number(&m, "ib")?);
+ let offset = given(&m, "offset", JointValue::read)?;
+ Ok(MotionLinkParams { a, b, ratio, offset, ia, ib, quiet: flag(&m, "quiet")? })
+ }
+}
+
+/// What the coupling commands return: the solve, then the motion link made and its ratio.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct CouplingResult {
+ #[serde(flatten)]
+ pub solved: SolveReport,
+ /// The motion link made (or replaced), by its index in `joint.list`'s `links`.
+ pub link: usize,
+ /// The ratio worked out: b's units per a's, per degree (mm per degree, or degrees per mm).
+ pub ratio: f64,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// Gear one turning joint to another: b turns the other way from a by the ratio of the pitch
+/// radii (the same way for an internal gear), and keeps where it is, so the teeth mesh at the pose
+/// they are in. The ratio follows the radii (an expression or a round face) as the design changes.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = gear_required)]
+pub struct GearParams {
+ // `a`, `b`, `ra` and `rb` are optional in the type and required in the schema: left out, the
+ // handler refuses them with its own message.
+ /// The driving joint, a revolute one, by id or name.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "JointKey")]
+ pub a: Option<JointKey>,
+ /// The driven joint, a revolute one, by id or name. Not the same joint as `a`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "JointKey")]
+ pub b: Option<JointKey>,
+ /// a's gear: its pitch radius (or tooth count), in mm, an expression, or the round face.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "CouplingSize")]
+ pub ra: Option<CouplingSize>,
+ /// b's gear, as `ra`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "CouplingSize")]
+ pub rb: Option<CouplingSize>,
+ /// One is a ring gear: both turn the same way. Default: false (b turns the other way).
+ #[serde(default)]
+ pub internal: Option<bool>,
+ /// Turn b the other way round. Default: false.
+ #[serde(default)]
+ pub reverse: Option<bool>,
+ /// Replace that motion link (its index in `joint.list`'s `links`) instead of adding one.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "u64")]
+ pub link: Option<u64>,
+ /// Leave out `dof` and `fixed` in the reply. Default: false.
+ #[serde(default)]
+ pub quiet: Option<bool>,
+}
+
+fn gear_required(schema: &mut Schema) {
+ for key in ["a", "b", "ra", "rb"] {
+ require(schema, key);
+ }
+}
+
+impl<'de> Deserialize<'de> for GearParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let m = keys(d)?;
+ let (a, b) = joint_pair(&m)?;
+ let (ra, rb) = (size(&m, "ra")?, size(&m, "rb")?);
+ let (internal, reverse) = (flag(&m, "internal")?, flag(&m, "reverse")?);
+ Ok(GearParams { a, b, ra, rb, internal, reverse, link: link_index(&m, "link")?, quiet: flag(&m, "quiet")? })
+ }
+}
+
+/// Couple a turning joint to a sliding one as a rack and pinion: the rack travels the pinion's
+/// radius times the turn in radians. b is driven by a, in either order of turning and sliding, and
+/// keeps where it is, so the teeth mesh at the pose they are in.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = rack_pinion_required)]
+pub struct RackPinionParams {
+ // `a`, `b` and `radius` are optional in the type and required in the schema: left out, the
+ // handler refuses them with its own message.
+ /// The driving joint by id or name: a revolute one (the pinion) or a slider (the rack).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "JointKey")]
+ pub a: Option<JointKey>,
+ /// The driven joint, the other kind from `a`, by id or name.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "JointKey")]
+ pub b: Option<JointKey>,
+ /// The pinion's pitch radius: mm, an expression, or the round face.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "CouplingSize")]
+ pub radius: Option<CouplingSize>,
+ /// Move the rack the other way round. Default: false.
+ #[serde(default)]
+ pub reverse: Option<bool>,
+ /// Replace that motion link (its index in `joint.list`'s `links`) instead of adding one.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "u64")]
+ pub link: Option<u64>,
+ /// Leave out `dof` and `fixed` in the reply. Default: false.
+ #[serde(default)]
+ pub quiet: Option<bool>,
+}
+
+fn rack_pinion_required(schema: &mut Schema) {
+ for key in ["a", "b", "radius"] {
+ require(schema, key);
+ }
+}
+
+impl<'de> Deserialize<'de> for RackPinionParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let m = keys(d)?;
+ let (a, b) = joint_pair(&m)?;
+ let radius = size(&m, "radius")?;
+ Ok(RackPinionParams { a, b, radius, reverse: flag(&m, "reverse")?, link: link_index(&m, "link")?, quiet: flag(&m, "quiet")? })
+ }
+}
+
+/// Couple a turn to a travel as a screw: one cylindrical joint whose turn drives its travel, or a
+/// joint that turns and one that slides, b driven by a. The travel is the pitch for each turn, and
+/// b keeps where it is.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = screw_required)]
+pub struct ScrewParams {
+ // `pitch`, and `joint` or `a` and `b`, are optional in the type and required in the schema:
+ // left out, the handler refuses them with its own message.
+ /// A cylindrical joint, by id or name, whose turn drives its travel. When given, `a` and `b` are
+ /// not read.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "JointKey")]
+ pub joint: Option<JointKey>,
+ /// The driving joint, by id or name: one that turns or one that slides. Read without `joint`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "JointKey")]
+ pub a: Option<JointKey>,
+ /// The driven joint, the other kind from `a`. Read without `joint`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "JointKey")]
+ pub b: Option<JointKey>,
+ /// The travel for each turn: mm, or an expression, or the round face (its radius).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "CouplingSize")]
+ pub pitch: Option<CouplingSize>,
+ /// A left-hand thread. Default: false.
+ #[serde(default)]
+ pub reverse: Option<bool>,
+ /// Replace that motion link (its index in `joint.list`'s `links`) instead of adding one.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "u64")]
+ pub link: Option<u64>,
+ /// Leave out `dof` and `fixed` in the reply. Default: false.
+ #[serde(default)]
+ pub quiet: Option<bool>,
+}
+
+fn screw_required(schema: &mut Schema) {
+ require(schema, "pitch");
+ // The handler refuses a call with neither form.
+ schema.insert("anyOf".into(), json!([{"required": ["joint"]}, {"required": ["a", "b"]}]));
+}
+
+impl<'de> Deserialize<'de> for ScrewParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let m = keys(d)?;
+ // `joint`, once given (`null` included), is the form; `a` and `b` are not read then.
+ let (joint, a, b) = match m.get("joint") {
+ Some(v) => (Some(JointKey::read(v).map_err(|e| D::Error::custom(whole(e)))?), None, None),
+ None => {
+ let (a, b) = joint_pair(&m)?;
+ (None, a, b)
+ }
+ };
+ let pitch = size(&m, "pitch")?;
+ Ok(ScrewParams { joint, a, b, pitch, reverse: flag(&m, "reverse")?, link: link_index(&m, "link")?, quiet: flag(&m, "quiet")? })
+ }
+}
+
+/// Drive a follower from a cam: the cam's turn sets the follower's travel (a slider, a translating
+/// follower) or turn (a revolute, an oscillating one) from the cam's outline, and the follower
+/// keeps where it is. The link is read again whenever the design changes.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = cam_required)]
+pub struct CamParams {
+ // `a`, `b` and `profile` are optional in the type and required in the schema: left out, the
+ // handler refuses them with its own message.
+ /// The cam's joint, a revolute one, by id or name.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "JointKey")]
+ pub a: Option<JointKey>,
+ /// The follower's joint, by id or name: a slider (a translating follower) or a revolute (an
+ /// oscillating one). Driven by `a`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "JointKey")]
+ pub b: Option<JointKey>,
+ /// The cam's outline: {sketch, index?} or {edges, occurrence?}.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "CamProfileParam")]
+ pub profile: Option<CamProfileParam>,
+ /// The follower's kind: knife, roller or flat (a face square to a slider's line). Default:
+ /// knife.
+ #[serde(default)]
+ pub follower: Option<CamFollower>,
+ /// The roller's radius: mm, an expression, or the roller's round face (which is its tip too).
+ /// Read only for a roller, which needs it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "CouplingSize")]
+ pub radius: Option<CouplingSize>,
+ /// A joint origin where the follower touches: its knife's point or its roller's centre, such as
+ /// {circle: [x, y, z]} on the roller. An oscillating follower needs it (unless its roller's
+ /// `radius` is a round face); a translating follower's line runs through it, by default along
+ /// its slider's axis.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "JointOriginArg")]
+ pub tip: Option<JointOriginArg>,
+ /// Ride the cam from the other side than the one the follower is on now. Default: false.
+ #[serde(default)]
+ pub flip: Option<bool>,
+ /// Replace that motion link (its index in `joint.list`'s `links`) instead of adding one.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "u64")]
+ pub link: Option<u64>,
+ /// Leave out `dof` and `fixed` in the reply. Default: false.
+ #[serde(default)]
+ pub quiet: Option<bool>,
+}
+
+fn cam_required(schema: &mut Schema) {
+ for key in ["a", "b", "profile"] {
+ require(schema, key);
+ }
+ // A roller needs its radius.
+ schema.insert("if".into(), json!({"properties": {"follower": {"const": "roller"}}, "required": ["follower"]}));
+ schema.insert("then".into(), json!({"required": ["radius"]}));
+}
+
+impl<'de> Deserialize<'de> for CamParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let m = keys(d)?;
+ // In the handler's order: the joints, the follower and its radius, the tip, the profile.
+ let (a, b) = joint_pair(&m)?;
+ let follower = match text(&m, "follower")?.as_deref() {
+ None => None,
+ Some("knife") => Some(CamFollower::Knife),
+ Some("roller") => Some(CamFollower::Roller),
+ Some("flat") => Some(CamFollower::Flat),
+ Some(_) => return Err(D::Error::custom(whole("`follower` is knife, roller or flat"))),
+ };
+ // Only a roller reads its radius.
+ let radius = if follower == Some(CamFollower::Roller) { size(&m, "radius")? } else { None };
+ let tip = given(&m, "tip", origin_arg)?;
+ let profile = given(&m, "profile", CamProfileParam::read)?;
+ Ok(CamParams { a, b, profile, follower, radius, tip, flip: flag(&m, "flip")?, link: link_index(&m, "link")?, quiet: flag(&m, "quiet")? })
+ }
+}
+
+/// What `joint.cam` returns: the solve, then the motion link made and the follower's travel.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct CamResult {
+ #[serde(flatten)]
+ pub solved: SolveReport,
+ /// The motion link made (or replaced), by its index in `joint.list`'s `links`.
+ pub link: usize,
+ /// The follower's travel over one turn of the cam; `null` when the link's table is not whole.
+ pub lift: Option<CamLift>,
+ /// Whether the follower rides the cam from the side `flip` chose, which the cam's direction of
+ /// turn decides.
+ pub reverse: bool,
+ /// For a translating follower: how far its line passes from the cam's axis, in mm. Left out for
+ /// an oscillating one.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub follower_offset: Option<f64>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
#[cfg(test)]
#[path = "joints_tests.rs"]
mod tests;
diff --git a/crates/engine/src/schema/joints_tests.rs b/crates/engine/src/schema/joints_tests.rs
index 298b9ea564..5db6982707 100644
--- a/crates/engine/src/schema/joints_tests.rs
+++ b/crates/engine/src/schema/joints_tests.rs
@@ -3,9 +3,10 @@ use solidcore_record::Vec3;
use solidcraft_doc::joints::JointKind;
use super::{
- AsBuiltJointParams, CreateJointParams, DeleteJointParams, DeleteJointResult, DriveJointParams, DriveJointResult, EditJointParams,
- InspectJointParams, InspectJointResult, JointAddedResult, JointKindName, JointLimitsParams, ListJointsParams, ListJointsResult,
- SolveJointsParams, SolveResult,
+ AsBuiltJointParams, CamParams, CamResult, CouplingResult, CreateJointParams, DeleteJointParams, DeleteJointResult, DriveJointParams,
+ DriveJointResult, EditJointParams, GearParams, InspectJointParams, InspectJointResult, JointAddedResult, JointKindName, JointLimitsParams,
+ ListJointsParams, ListJointsResult, MakeJointOriginParams, MakeJointOriginResult, MotionLinkParams, RackPinionParams, ReachParams, ReachResult,
+ RigidGroupParams, RigidGroupResult, ScrewParams, SolveJointsParams, SolveResult,
};
use crate::Session;
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
@@ -25,11 +26,39 @@ fn schemas_and_the_key_check_agree() {
assert_keys(input_schema_for::<ListJointsParams>(), &["quiet"]);
assert_keys(input_schema_for::<InspectJointParams>(), &["joint"]);
assert_keys(input_schema_for::<SolveJointsParams>(), &["quiet"]);
+ assert_keys(
+ input_schema_for::<MakeJointOriginParams>(),
+ &["body", "circle", "corner", "edge", "end", "face", "frame", "name", "occurrence", "on", "point", "x", "z"],
+ );
+ assert_keys(input_schema_for::<RigidGroupParams>(), &["occurrences"]);
+ assert_keys(input_schema_for::<ReachParams>(), &["at", "axis", "continuous", "joints", "occurrence", "point", "quiet", "z"]);
+ assert_keys(input_schema_for::<MotionLinkParams>(), &["a", "b", "ia", "ib", "offset", "quiet", "ratio"]);
+ assert_keys(input_schema_for::<GearParams>(), &["a", "b", "internal", "link", "quiet", "ra", "rb", "reverse"]);
+ assert_keys(input_schema_for::<RackPinionParams>(), &["a", "b", "link", "quiet", "radius", "reverse"]);
+ assert_keys(input_schema_for::<ScrewParams>(), &["a", "b", "joint", "link", "pitch", "quiet", "reverse"]);
+ assert_keys(input_schema_for::<CamParams>(), &["a", "b", "flip", "follower", "link", "profile", "quiet", "radius", "tip"]);
}
#[test]
fn the_commands_publish_their_schemas() {
- for id in ["joint.create", "joint.as_built", "joint.drive", "joint.limits", "joint.delete", "joint.list", "joint.inspect", "joint.solve"] {
+ for id in [
+ "joint.create",
+ "joint.as_built",
+ "joint.drive",
+ "joint.limits",
+ "joint.delete",
+ "joint.list",
+ "joint.inspect",
+ "joint.solve",
+ "joint.origin",
+ "joint.rigid_group",
+ "joint.reach",
+ "joint.motion_link",
+ "joint.gear",
+ "joint.rack_pinion",
+ "joint.screw",
+ "joint.cam",
+ ] {
let spec = crate::cmd::find_command(id).unwrap_or_else(|| panic!("{id}"));
assert!(spec.contract.is_some() && spec.output.is_some(), "{id}");
}
@@ -113,6 +142,66 @@ fn strict_keeps_todays_errors() {
("joint.delete", json!({"link": null})),
("joint.inspect", json!({"joint": true})),
("joint.inspect", json!({"joint": [1]})),
+ // joint.origin
+ ("joint.origin", json!({})),
+ ("joint.origin", json!({"face": [1, 2]})),
+ ("joint.origin", json!({"face": 7, "name": "N"})),
+ ("joint.origin", json!({"frame": {"z": [0, 0, 1]}})),
+ ("joint.origin", json!({"frame": null})),
+ ("joint.origin", json!({"face": "", "occurrence": 0})),
+ ("joint.origin", json!({"circle": "x".repeat(16385)})),
+ ("joint.origin", json!({"point": [0, 0, 0], "occurrence": null})),
+ ("joint.origin", json!({"point": [0, 0, 0], "occurrence": true})),
+ ("joint.origin", json!({"point": [0, 0, 0], "occurrence": 0, "x": "nonsense"})),
+ ("joint.origin", json!({"point": [0, 0, 0], "occurrence": 0, "x": [1, 0, 0], "end": "F1"})),
+ ("joint.origin", json!({"point": [0, 0, 0], "occurrence": 0, "end": 5})),
+ ("joint.origin", json!({"point": [0, 0, 0], "occurrence": 0, "end": null})),
+ ("joint.origin", json!({"point": [0, 0, 0], "occurrence": 0, "x": [0, 0, 0]})),
+ ("joint.origin", json!({"face": [0, 0, 0], "occurrence": 0, "x": {"face": null}})),
+ ("joint.origin", json!({"face": [0, 0, 0], "occurrence": 0, "x": {}})),
+ ("joint.origin", json!({"face": [0, 0, 0], "occurrence": 0, "end": "F1"})),
+ ("joint.origin", json!({"circle": [0, 0, 0], "occurrence": 0, "z": [0, 0, 0]})),
+ ("joint.origin", json!({"circle": [0, 0, 0], "occurrence": 0, "z": "up"})),
+ ("joint.origin", json!({"edge": [0, 0, 0], "occurrence": 0, "z": 5})),
+ ("joint.origin", json!({"frame": {"origin": [0, 0, 0]}, "occurrence": 0})),
+ // joint.rigid_group
+ ("joint.rigid_group", json!({})),
+ ("joint.rigid_group", json!({"occurrences": null})),
+ ("joint.rigid_group", json!({"occurrences": "A"})),
+ ("joint.rigid_group", json!({"occurrences": [0]})),
+ ("joint.rigid_group", json!({"occurrences": vec![0; 1001]})),
+ ("joint.rigid_group", json!({"occurrences": [0, true]})),
+ // joint.reach
+ ("joint.reach", json!({})),
+ ("joint.reach", json!({"occurrence": null, "point": [0, 0, 0]})),
+ ("joint.reach", json!({"occurrence": [0], "point": [0, 0, 0]})),
+ ("joint.reach", json!({"occurrence": 0})),
+ ("joint.reach", json!({"occurrence": 0, "point": [0, 0]})),
+ ("joint.reach", json!({"occurrence": 0, "point": [1e9, 0, 0]})),
+ ("joint.reach", json!({"occurrence": 0, "point": [0, 0, 0], "at": null})),
+ ("joint.reach", json!({"occurrence": 0, "point": [0, 0, 0], "at": "here"})),
+ ("joint.reach", json!({"occurrence": 0, "point": [0, 0, 0], "z": [0, 0, 0]})),
+ ("joint.reach", json!({"occurrence": 0, "point": [0, 0, 0], "z": null})),
+ ("joint.reach", json!({"occurrence": 0, "point": [0, 0, 0], "z": [0, 0, 1], "axis": 5})),
+ ("joint.reach", json!({"occurrence": 0, "point": [0, 0, 0], "axis": [0, 0, 1]})),
+ ("joint.reach", json!({"occurrence": 0, "point": [0, 0, 0], "joints": "Hinge"})),
+ ("joint.reach", json!({"occurrence": 0, "point": [0, 0, 0], "joints": null})),
+ ("joint.reach", json!({"occurrence": 0, "point": [0, 0, 0], "joints": [true]})),
+ ("joint.reach", json!({"occurrence": 0, "point": [0, 0, 0], "joints": vec![1; 1001]})),
+ // joint.motion_link, joint.gear, joint.rack_pinion, joint.screw and joint.cam
+ ("joint.motion_link", json!({})),
+ ("joint.motion_link", json!({"a": true, "b": 1, "ratio": 1})),
+ ("joint.motion_link", json!({"a": null, "b": 1, "ratio": 1})),
+ ("joint.gear", json!({})),
+ ("joint.gear", json!({"a": [1], "b": 1})),
+ ("joint.rack_pinion", json!({})),
+ ("joint.rack_pinion", json!({"a": {}, "b": 1})),
+ ("joint.screw", json!({})),
+ ("joint.screw", json!({"joint": null})),
+ ("joint.screw", json!({"joint": true, "pitch": 1})),
+ ("joint.screw", json!({"a": true, "b": 1, "pitch": 1})),
+ ("joint.cam", json!({})),
+ ("joint.cam", json!({"a": false, "b": 1})),
]);
}
@@ -705,3 +794,854 @@ fn strict_may_name_another_problem_first_and_refuses_ignored_wrong_types() {
assert!(works(ParamCheck::Off) && !works(ParamCheck::Strict), "{id} {p}");
}
}
+
+// ---------------------------------------------------------------------------------------------
+// joint.origin, joint.rigid_group, joint.reach, joint.motion_link, joint.gear, joint.rack_pinion,
+// joint.screw and joint.cam (#13185)
+// ---------------------------------------------------------------------------------------------
+
+fn put(s: &mut Session, id: &str, p: Value) -> Value {
+ s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
+}
+
+/// A joint between two parts as they are, at a world point with its z along `z`.
+fn pin(s: &mut Session, kind: &str, name: &str, base: &str, part: &str, p: [f64; 3], z: [f64; 3]) {
+ let at = |o: &str| json!({"occurrence": o, "point": p, "z": z});
+ put(s, "joint.create", json!({"type": kind, "a": at(base), "b": at(part), "flip": true, "name": name}));
+}
+
+/// A grounded base with two discs on hinges (G1, G2), a pinion's hinge (P) and its rack's slider
+/// (Rack), a screw's hinge and slider (K, Slide2), a cylindrical joint (Nut) and a spare hinge (X):
+/// a joint named for each part, for the couplings to tie.
+fn rig(level: ParamCheck) -> Session {
+ let mut s = Session { param_check: level, ..Session::default() };
+ let root = |s: &mut Session| put(s, "component.activate", json!({"component": "root"}));
+ root(&mut s);
+ let base = put(&mut s, "component.create", json!({"name": "Base", "grounded": false}));
+ put(&mut s, "solid.box", json!({"length": 200, "width": 120, "height": 20, "corner": [-100, -60, -20]}));
+ put(&mut s, "occurrence.ground", json!({"occurrence": base["occurrence"], "grounded": true}));
+ for (name, x, r) in [("G1", 0.0, 10.0), ("G2", 30.0, 20.0)] {
+ root(&mut s);
+ put(&mut s, "component.create", json!({"name": name, "grounded": false}));
+ put(&mut s, "solid.cylinder", json!({"base": [x, 0, 0], "axis": [0, 0, 1], "radius": r, "height": 5}));
+ }
+ for (name, x, y) in
+ [("P", -40.0, -5.0), ("Rack", -40.0, -35.0), ("K", 70.0, -5.0), ("Slide2", 70.0, 25.0), ("Nut", 100.0, -5.0), ("X", 130.0, -5.0)]
+ {
+ root(&mut s);
+ put(&mut s, "component.create", json!({"name": name, "grounded": false}));
+ put(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [x, y, 0]}));
+ }
+ let (z, x) = ([0.0, 0.0, 1.0], [1.0, 0.0, 0.0]);
+ pin(&mut s, "revolute", "G1", "Base", "G1", [0.0, 0.0, 0.0], z);
+ pin(&mut s, "revolute", "G2", "Base", "G2", [30.0, 0.0, 0.0], z);
+ pin(&mut s, "revolute", "P", "Base", "P", [-40.0, 0.0, 0.0], z);
+ pin(&mut s, "slider", "Rack", "Base", "Rack", [-40.0, -30.0, 0.0], x);
+ pin(&mut s, "revolute", "K", "Base", "K", [70.0, 0.0, 0.0], z);
+ pin(&mut s, "slider", "Slide2", "Base", "Slide2", [70.0, 30.0, 0.0], x);
+ pin(&mut s, "cylindrical", "Nut", "Base", "Nut", [100.0, 0.0, 0.0], z);
+ pin(&mut s, "revolute", "X", "Base", "X", [130.0, 0.0, 0.0], z);
+ s
+}
+
+/// Grounded base, a cam (a disc of radius 30 about (10, 0), in sketch `CamSketch`) on a hinge
+/// `Cam`, a tappet on a slider `Tappet` and an arm on a hinge `Arm`, for `joint.cam`.
+fn cam_rig(level: ParamCheck) -> Session {
+ let mut s = Session { param_check: level, ..Session::default() };
+ put(&mut s, "component.activate", json!({"component": "root"}));
+ let base = put(&mut s, "component.create", json!({"name": "Base", "grounded": false}));
+ put(&mut s, "solid.box", json!({"length": 180, "width": 180, "height": 20, "corner": [-90, -90, -20]}));
+ put(&mut s, "occurrence.ground", json!({"occurrence": base["occurrence"], "grounded": true}));
+ put(&mut s, "component.activate", json!({"component": "root"}));
+ put(&mut s, "component.create", json!({"name": "Cam"}));
+ put(&mut s, "sketch.create", json!({"plane": "XY", "name": "CamSketch"}));
+ put(&mut s, "sketch.circle.center", json!({"center": [10, 0], "radius": 30, "id": "c1"}));
+ put(&mut s, "sketch.finish", json!({}));
+ put(&mut s, "solid.extrude", json!({"distance": 5}));
+ pin(&mut s, "revolute", "Cam", "Base", "Cam", [0.0, 0.0, 0.0], [0.0, 0.0, 1.0]);
+ put(&mut s, "component.activate", json!({"component": "root"}));
+ put(&mut s, "component.create", json!({"name": "Tappet"}));
+ put(&mut s, "solid.box", json!({"length": 20, "width": 4, "height": 5, "corner": [45, -2, 0]}));
+ pin(&mut s, "slider", "Tappet", "Base", "Tappet", [0.0, 0.0, 2.5], [1.0, 0.0, 0.0]);
+ put(&mut s, "component.activate", json!({"component": "root"}));
+ put(&mut s, "component.create", json!({"name": "Arm"}));
+ put(&mut s, "solid.box", json!({"length": 4, "width": 4, "height": 5, "corner": [-52, 38, 0]}));
+ pin(&mut s, "revolute", "Arm", "Base", "Arm", [-50.0, 40.0, 2.5], [0.0, 0.0, 1.0]);
+ s
+}
+
+/// Both of `rig`'s sessions give a call the same error, with the check off and in strict.
+fn assert_strict_keeps_todays_errors_in(rig: fn(ParamCheck) -> Session, cases: &[(&str, Value)]) {
+ let (mut off, mut strict) = (rig(ParamCheck::Off), rig(ParamCheck::Strict));
+ for (id, p) in cases {
+ let today = off.execute(id, p).err().map(|e| e.to_string());
+ assert!(today.is_some(), "{id} {p} should fail today");
+ assert_eq!(strict.execute(id, p).err().map(|e| e.to_string()), today, "{id} {p}");
+ }
+}
+
+/// What the handlers refuse with a design to refuse it for: strict says the same.
+#[test]
+fn strict_keeps_todays_errors_with_the_couplings() {
+ let long = "x".repeat(1001);
+ assert_strict_keeps_todays_errors_in(
+ rig,
+ &[
+ ("joint.motion_link", json!({"a": "G1", "b": "G1", "ratio": 1})),
+ ("joint.motion_link", json!({"a": "G1", "b": "G2"})),
+ ("joint.motion_link", json!({"a": "G1", "b": "G2", "ratio": null})),
+ ("joint.motion_link", json!({"a": "G1", "b": "G2", "ratio": "2"})),
+ ("joint.motion_link", json!({"a": "G1", "b": "G2", "ratio": 1e12})),
+ ("joint.motion_link", json!({"a": "G1", "b": "G2", "ratio": 1, "offset": true})),
+ ("joint.motion_link", json!({"a": "G1", "b": "G2", "ratio": 1, "offset": null})),
+ ("joint.motion_link", json!({"a": "G1", "b": "G2", "ratio": 1, "offset": 1e12})),
+ ("joint.motion_link", json!({"a": "Missing", "b": "G2", "ratio": 1})),
+ ("joint.gear", json!({"a": "G1", "b": "G1", "ra": 1, "rb": 1})),
+ ("joint.gear", json!({"a": "G1", "b": "G2"})),
+ ("joint.gear", json!({"a": "G1", "b": "G2", "ra": true, "rb": 1})),
+ ("joint.gear", json!({"a": "G1", "b": "G2", "ra": null, "rb": 1})),
+ ("joint.gear", json!({"a": "G1", "b": "G2", "ra": long, "rb": 1})),
+ ("joint.gear", json!({"a": "G1", "b": "G2", "ra": 1})),
+ ("joint.gear", json!({"a": "G1", "b": "G2", "ra": 1, "rb": {"circle": 5}})),
+ ("joint.gear", json!({"a": "G1", "b": "G2", "ra": 1, "rb": {"circle": ""}})),
+ ("joint.gear", json!({"a": "G1", "b": "G2", "ra": 1, "rb": {"point": [1, 2, 3]}})),
+ ("joint.gear", json!({"a": "G1", "b": "G2", "ra": 1, "rb": 1, "link": -1})),
+ ("joint.gear", json!({"a": "G1", "b": "G2", "ra": 1, "rb": 1, "link": null})),
+ ("joint.gear", json!({"a": "G1", "b": "G2", "ra": 1, "rb": 1, "link": "0"})),
+ ("joint.gear", json!({"a": "G1", "b": "G2", "ra": 1, "rb": 1, "link": 0})),
+ ("joint.gear", json!({"a": "G1", "b": "Rack", "ra": 1, "rb": 1})),
+ ("joint.rack_pinion", json!({"a": "P", "b": "Rack"})),
+ ("joint.rack_pinion", json!({"a": "P", "b": "Rack", "radius": []})),
+ ("joint.rack_pinion", json!({"a": "P", "b": "Rack", "radius": 1, "link": 1.5})),
+ ("joint.rack_pinion", json!({"a": "P", "b": "G1", "radius": 1})),
+ ("joint.screw", json!({"joint": "Nut"})),
+ ("joint.screw", json!({"joint": "Nut", "pitch": {}})),
+ ("joint.screw", json!({"joint": "Nut", "pitch": 1, "link": "x"})),
+ ("joint.screw", json!({"joint": "G1", "pitch": 1})),
+ ("joint.screw", json!({"joint": 99, "pitch": 1})),
+ ("joint.screw", json!({"a": "K", "b": "Slide2", "pitch": null})),
+ ("joint.screw", json!({"a": "K", "b": "K", "pitch": 1})),
+ ("joint.screw", json!({"a": "K", "pitch": 1})),
+ ("joint.reach", json!({"occurrence": "G1", "point": [0, 0, 0], "joints": ["G1", true]})),
+ ("joint.reach", json!({"occurrence": "Missing", "point": [0, 0, 0]})),
+ ("joint.origin", json!({"occurrence": "Base", "face": "Missing"})),
+ ("joint.origin", json!({"occurrence": "Missing", "point": [0, 0, 0]})),
+ ],
+ );
+}
+
+/// What `joint.cam` refuses, with a cam and its followers in the design.
+#[test]
+fn strict_keeps_todays_errors_for_the_cam() {
+ let edges = |n: usize| json!({"edges": vec![[10, 30, 5]; n]});
+ assert_strict_keeps_todays_errors_in(
+ cam_rig,
+ &[
+ ("joint.cam", json!({"a": "Cam", "b": "Cam", "profile": {"sketch": "CamSketch"}})),
+ ("joint.cam", json!({"a": "Tappet", "b": "Cam", "profile": {"sketch": "CamSketch"}})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet"})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": null})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": "CamSketch"})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {}})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": null}})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": true}})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch", "index": "0"}})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch", "index": -1}})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch", "index": null}})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch", "index": 7}})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "Missing"}})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"edges": []}})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"edges": "x"}})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": edges(65)})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"edges": [[1, 2]]}})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"edges": [[10, 30, 5]], "occurrence": null}})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"edges": [[10, 30, 5]], "occurrence": [1]}})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "round"})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller"})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": true})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": null})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": {"circle": 5}})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "tip": 5})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "tip": null})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "tip": {"face": ""}})),
+ ("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "link": 3})),
+ ("joint.cam", json!({"a": "Cam", "b": "Arm", "profile": {"sketch": "CamSketch"}})),
+ ],
+ );
+}
+
+/// The couplings, reach, rigid groups and joint origins read each key as their handlers do, and in
+/// the cases the handlers read it.
+#[test]
+fn the_remaining_types_read_each_key_as_the_handlers_do() {
+ let none = Vec::<String>::new;
+ let why = "a joint origin needs face, circle, edge, point or frame [x, y, z], or a face's name";
+ let x_form = "`x` is a direction [x, y, z], a face's name, or {face: [x, y, z]}";
+ let end_name = "`end` is the name of a face a round end lies on";
+ let end_round = "`end` is for a round origin (`circle`)";
+ let origin = |p: Value| issues("joint.origin", p);
+
+ // joint.origin: the forms, each reading only its own keys.
+ for p in [
+ json!({"face": [1, 2, 3]}),
+ json!({"face": {"x": 1, "y": 2, "z": 3}, "occurrence": "A", "x": [1, 0, 0], "name": "N"}),
+ json!({"face": "F1"}),
+ json!({"face": "F1", "x": "F2", "body": "B", "occurrence": 3, "name": null}),
+ json!({"face": "F1", "x": {"face": [1, 2, 3]}}),
+ json!({"face": "F1", "x": {"face": "F2"}}),
+ json!({"face": "F1", "x": null, "z": "junk", "on": 1, "corner": 2, "frame": 3, "edge": 4, "point": 5}),
+ json!({"circle": "F1", "end": "F2", "x": "F3"}),
+ json!({"circle": [1, 2, 3], "end": "F2", "x": [0, 1, 0]}),
+ // A circle with a z: its end is tried and then a point, and neither refuses a bad end.
+ json!({"circle": [1, 2, 3], "z": [0, 0, 1], "end": 5}),
+ json!({"circle": [1, 2, 3], "z": {"x": 0, "y": 0, "z": 1}, "end": "F2"}),
+ json!({"circle": [1, 2, 3], "z": null}),
+ // An edge reads on, corner and z; with a z, end is not read.
+ json!({"edge": [1, 2, 3]}),
+ json!({"edge": [1, 2, 3], "on": [0, 0, 0], "corner": [1, 1, 1], "z": [0, 0, 1], "end": 7, "x": "junk", "body": 3}),
+ json!({"edge": [1, 2, 3], "on": null, "corner": null, "z": null}),
+ json!({"point": [1, 2, 3]}),
+ json!({"point": [1, 2, 3], "z": [0, 0, 1], "x": [1, 0, 0], "on": "junk"}),
+ json!({"point": [1, 2, 3], "z": [0, 0, 0], "x": null}),
+ json!({"frame": {"origin": [0, 0, 0], "z": [0, 0, 1]}}),
+ json!({"frame": {"origin": [0, 0, 0], "z": [0, 0, 1], "x": [1, 0, 0]}, "x": "junk", "z": "junk", "on": 1}),
+ json!({"frame": {"origin": [0, 0, 0], "z": [0, 0, 1], "x": null}}),
+ // A point wins over a frame; a name over a point; the first of face and circle given by name.
+ json!({"point": [1, 2, 3], "frame": 5}),
+ json!({"face": [1, 2], "point": [1, 2, 3]}),
+ json!({"face": [1, 2, 3], "circle": "C", "end": "E"}),
+ json!({"face": null, "circle": null, "point": [1, 2, 3]}),
+ ] {
+ assert_eq!(origin(p.clone()), none(), "{p}");
+ }
+ let refused = [
+ (json!({}), why),
+ (json!({"name": 5}), why),
+ (json!({"face": [1, 2]}), why),
+ (json!({"face": 7, "circle": null}), why),
+ (json!({"point": "x"}), why),
+ (json!({"frame": null}), "`frame` needs origin and z"),
+ (json!({"frame": {"z": [0, 0, 1]}}), "`frame` needs origin and z"),
+ (json!({"frame": {"origin": [0, 0, 0]}}), "`frame` needs a z axis"),
+ (json!({"frame": {"origin": [0, 0, 0], "z": [0, 0]}}), "`frame` needs a z axis"),
+ (json!({"frame": {"origin": [0, 0, 0], "z": [0, 0, 1], "x": 5}}), "`frame`'s x must be a direction [x, y, z]"),
+ (json!({"face": ""}), "a face name is 1…16384 characters"),
+ (json!({"circle": "x".repeat(16385)}), "a face name is 1…16384 characters"),
+ (json!({"face": "F", "body": 5}), "`body` must be text"),
+ (json!({"face": "F", "occurrence": true}), "an occurrence must be an id or a name"),
+ (json!({"face": "F", "occurrence": null}), "an occurrence must be an id or a name"),
+ (json!({"point": [1, 2, 3], "occurrence": [1]}), "an occurrence must be an id or a name"),
+ (json!({"face": "F", "x": 5}), x_form),
+ (json!({"face": "F", "x": ""}), x_form),
+ (json!({"face": "F", "x": [0, 0, 0]}), x_form),
+ (json!({"face": "F", "x": {}}), x_form),
+ (json!({"face": "F", "x": {"face": null}}), x_form),
+ (json!({"face": "F", "x": {"face": ""}}), x_form),
+ (json!({"face": [1, 2, 3], "x": true}), x_form),
+ (json!({"circle": [1, 2, 3], "x": "x".repeat(16385)}), x_form),
+ (json!({"face": "F", "end": "E"}), end_round),
+ (json!({"face": [1, 2, 3], "end": "E"}), end_round),
+ (json!({"point": [1, 2, 3], "end": "E"}), end_round),
+ (json!({"edge": [1, 2, 3], "end": "E"}), end_round),
+ (json!({"edge": [1, 2, 3], "z": null, "end": "E"}), end_round),
+ (json!({"frame": {"origin": [0, 0, 0], "z": [0, 0, 1]}, "end": "E"}), end_round),
+ (json!({"point": [1, 2, 3], "end": 5}), end_name),
+ (json!({"point": [1, 2, 3], "end": null}), end_name),
+ (json!({"circle": "C", "end": ""}), end_name),
+ (json!({"circle": "C", "end": 5}), end_name),
+ (json!({"circle": [1, 2, 3], "end": null}), end_name),
+ (json!({"circle": [1, 2, 3], "z": null, "end": 5}), end_name),
+ (json!({"circle": [1, 2, 3], "z": [0, 0, 0]}), "`z` is a direction [x, y, z]"),
+ (json!({"circle": [1, 2, 3], "z": "up", "end": "E"}), "`z` is a direction [x, y, z]"),
+ (json!({"edge": [1, 2, 3], "z": [1, 2]}), "`z` is a direction [x, y, z]"),
+ (json!({"edge": [1, 2, 3], "z": [0, 0, 0]}), "`z` is a direction [x, y, z]"),
+ (json!({"edge": [1, 2, 3], "on": 5}), "`on` must be a point [x, y, z]"),
+ (json!({"edge": [1, 2, 3], "corner": "c"}), "`corner` must be a point [x, y, z]"),
+ (json!({"point": [1, 2, 3], "z": "up"}), "`z` is a direction [x, y, z]"),
+ (json!({"point": [1, 2, 3], "x": 5}), "a point origin's `x` is a direction [x, y, z]"),
+ (json!({"point": [1, 2, 3], "x": "F"}), "a point origin's `x` is a direction [x, y, z]"),
+ (json!({"point": [1, 2, 3], "name": 5}), "`name` must be text"),
+ ];
+ for (p, message) in refused {
+ assert_eq!(origin(p.clone()), [message], "{p}");
+ }
+ assert_eq!(origin(json!({"face": "F", "circle": "C", "end": "E"})), [end_round]);
+ assert_eq!(origin(json!({"point": [1, 2, 3], "nme": "N"})), ["unknown key `nme`; did you mean `name`?"]);
+
+ // joint.rigid_group.
+ let group = |p: Value| issues("joint.rigid_group", p);
+ let list = "`occurrences` must list 2…1000 occurrences";
+ assert_eq!(group(json!({"occurrences": [0, "A", 3]})), none());
+ assert_eq!(group(json!({})), none());
+ assert_eq!(group(json!({"occurrences": vec![1; 1000]})), none());
+ for p in [json!(null), json!("A"), json!([]), json!([1]), json!({"0": 1}), json!(vec![1; 1001])] {
+ assert_eq!(group(json!({ "occurrences": p })), [list], "{p}");
+ }
+ assert_eq!(group(json!({"occurrences": [1, true]})), ["an occurrence must be an id or a name"]);
+ assert_eq!(group(json!({"occurrences": [1, null, 2]})), ["an occurrence must be an id or a name"]);
+
+ // joint.reach: a point and a direction as finite numbers under 1e9, `null` refused.
+ let reach = |extra: Value| {
+ let mut p = json!({"occurrence": "Arm", "point": [1, 2, 3]});
+ p.as_object_mut().into_iter().for_each(|o| o.extend(extra.as_object().cloned().unwrap_or_default()));
+ issues("joint.reach", p)
+ };
+ assert_eq!(reach(json!({})), none());
+ assert_eq!(
+ reach(json!({"at": {"x": 1, "y": 2, "z": 3}, "z": [0, 0, 5], "axis": [1, 1, 0], "joints": ["A", 1], "quiet": true, "continuous": false})),
+ none()
+ );
+ assert_eq!(reach(json!({"joints": []})), none());
+ assert_eq!(reach(json!({"axis": [1, 0, 0]})), none());
+ assert_eq!(reach(json!({"quiet": null, "continuous": null})), none());
+ assert_eq!(issues("joint.reach", json!({"point": [1, 2, 3]})), none());
+ assert_eq!(issues("joint.reach", json!({"occurrence": 2})), none());
+ assert_eq!(issues("joint.reach", json!({"occurrence": null, "point": [1, 2, 3]})), ["an occurrence must be an id or a name"]);
+ assert_eq!(issues("joint.reach", json!({"occurrence": 2, "point": null})), ["`point` must be [x, y, z]"]);
+ for bad in [json!([1, 2]), json!("x"), json!([1e9, 0, 0]), json!({"x": 1, "y": 2}), json!([1, 2, "3"])] {
+ assert_eq!(reach(json!({"point": bad.clone()})), ["`point` must be [x, y, z]"], "{bad}");
+ assert_eq!(reach(json!({"at": bad.clone()})), ["`at` must be [x, y, z]"], "{bad}");
+ }
+ assert_eq!(reach(json!({"at": null})), ["`at` must be [x, y, z]"]);
+ for key in ["z", "axis"] {
+ let message = format!("`{key}` must be a direction [x, y, z]");
+ for bad in [json!(null), json!([0, 0, 0]), json!([1, 2]), json!("up")] {
+ assert_eq!(reach(json!({ key: bad.clone() })), [message.as_str()], "{key} {bad}");
+ }
+ }
+ let joints = "`joints` must be a list of joints (ids or names), at most 1000";
+ for bad in [json!(null), json!("A"), json!(5), json!(vec![1; 1001])] {
+ assert_eq!(reach(json!({"joints": bad.clone()})), [joints], "{bad}");
+ }
+ assert_eq!(reach(json!({"joints": [true]})), ["`joint` must be an id or a name"]);
+ assert_eq!(reach(json!({"quiet": 1})), ["`quiet` must be true or false"]);
+ assert_eq!(reach(json!({"continuous": "yes"})), ["`continuous` must be true or false"]);
+ assert_eq!(reach(json!({"pont": 1})), ["unknown key `pont`; did you mean `point`?"]);
+
+ // joint.motion_link.
+ let link = |extra: Value| {
+ let mut p = json!({"a": "A", "b": 2, "ratio": 0.5});
+ p.as_object_mut().into_iter().for_each(|o| o.extend(extra.as_object().cloned().unwrap_or_default()));
+ issues("joint.motion_link", p)
+ };
+ assert_eq!(link(json!({})), none());
+ assert_eq!(link(json!({"ia": 1, "ib": -1.5, "offset": "w / 2", "quiet": true})), none());
+ assert_eq!(link(json!({"ia": null, "ib": null, "quiet": null})), none());
+ assert_eq!(link(json!({"ratio": -1e8})), none());
+ assert_eq!(issues("joint.motion_link", json!({})), none());
+ assert_eq!(issues("joint.motion_link", json!({"a": 1, "b": 2})), none());
+ for bad in [json!(null), json!("2"), json!(true), json!(1e9), json!(-1e12)] {
+ assert_eq!(link(json!({"ratio": bad.clone()})), ["`ratio` must be a number"], "{bad}");
+ }
+ assert_eq!(link(json!({"a": null})), ["`joint` must be an id or a name"]);
+ assert_eq!(link(json!({"b": [1]})), ["`joint` must be an id or a name"]);
+ assert_eq!(link(json!({"ia": "0"})), ["`ia` must be a number"]);
+ assert_eq!(link(json!({"ib": true})), ["`ib` must be a number"]);
+ assert_eq!(link(json!({"offset": null})), ["a joint value must be a number or an expression"]);
+ assert_eq!(link(json!({"offset": true})), ["a joint value must be a number or an expression"]);
+ assert_eq!(link(json!({"offset": 1e12})), ["a joint value must be a number between -1e9 and 1e9"]);
+ assert_eq!(link(json!({"quiet": "no"})), ["`quiet` must be true or false"]);
+
+ // The couplings: a length, a round face, a link to replace.
+ let size = "must be a length (mm or an expression) or a round face ({circle: [x, y, z]})";
+ let gear = |extra: Value| {
+ let mut p = json!({"a": "A", "b": "B", "ra": 20, "rb": "15 mm"});
+ p.as_object_mut().into_iter().for_each(|o| o.extend(extra.as_object().cloned().unwrap_or_default()));
+ issues("joint.gear", p)
+ };
+ assert_eq!(gear(json!({})), none());
+ assert_eq!(gear(json!({"internal": true, "reverse": false, "link": 0, "quiet": true})), none());
+ assert_eq!(gear(json!({"internal": null, "reverse": null})), none());
+ assert_eq!(gear(json!({"ra": {"circle": [10, 0, 2.5]}, "rb": {"circle": "F1", "occurrence": "G2"}})), none());
+ assert_eq!(gear(json!({"ra": {"circle": [10, 0, 2.5], "z": "junk"}})), none());
+ assert_eq!(gear(json!({"ra": "x".repeat(1000), "rb": -5})), none());
+ assert_eq!(issues("joint.gear", json!({"a": 1, "b": 2})), none());
+ assert_eq!(issues("joint.gear", json!({})), none());
+ for bad in [json!(null), json!(true), json!([1]), json!({}), json!({"point": [1, 2, 3]}), json!("x".repeat(1001))] {
+ assert_eq!(gear(json!({"ra": bad.clone()})), [format!("`ra` {size}")], "{bad}");
+ assert_eq!(gear(json!({"rb": bad.clone()})), [format!("`rb` {size}")], "{bad}");
+ }
+ assert_eq!(gear(json!({"ra": {"circle": 5}})), [why]);
+ assert_eq!(gear(json!({"rb": {"circle": ""}})), ["a face name is 1…16384 characters"]);
+ assert_eq!(gear(json!({"ra": {"circle": {"x": 1, "y": 2}}})), [why]);
+ for bad in [json!(-1), json!(null), json!("0"), json!(1.5), json!(true)] {
+ assert_eq!(gear(json!({"link": bad.clone()})), ["no such motion link"], "{bad}");
+ }
+ assert_eq!(gear(json!({"internal": 1})), ["`internal` must be true or false"]);
+ assert_eq!(gear(json!({"reverse": "yes"})), ["`reverse` must be true or false"]);
+ assert_eq!(gear(json!({"a": true})), ["`joint` must be an id or a name"]);
+ assert_eq!(gear(json!({"ra": 1, "a": null, "link": -1})), ["`joint` must be an id or a name"]);
+ let rack = |extra: Value| {
+ let mut p = json!({"a": "P", "b": "Rack", "radius": "r"});
+ p.as_object_mut().into_iter().for_each(|o| o.extend(extra.as_object().cloned().unwrap_or_default()));
+ issues("joint.rack_pinion", p)
+ };
+ assert_eq!(rack(json!({})), none());
+ assert_eq!(rack(json!({"radius": {"circle": [0, 0, 0]}, "reverse": true, "link": 3, "quiet": false})), none());
+ assert_eq!(rack(json!({"radius": null})), [format!("`radius` {size}")]);
+ assert_eq!(rack(json!({"link": 2.5})), ["no such motion link"]);
+ assert_eq!(issues("joint.rack_pinion", json!({"a": "P", "b": "Rack"})), none());
+
+ // joint.screw: `joint`, once given, is the form, and `a` and `b` are not read.
+ let screw = |p: Value| issues("joint.screw", p);
+ assert_eq!(screw(json!({"joint": "Nut", "pitch": 2})), none());
+ assert_eq!(screw(json!({"joint": 3, "a": true, "b": null, "pitch": "2 mm", "reverse": true, "link": 1, "quiet": true})), none());
+ assert_eq!(screw(json!({"a": "K", "b": 4, "pitch": {"circle": [1, 2, 3]}})), none());
+ assert_eq!(screw(json!({})), none());
+ assert_eq!(screw(json!({"joint": null, "pitch": 1})), ["`joint` must be an id or a name"]);
+ assert_eq!(screw(json!({"joint": true, "a": "K", "b": 4, "pitch": 1})), ["`joint` must be an id or a name"]);
+ assert_eq!(screw(json!({"a": true, "b": 4, "pitch": 1})), ["`joint` must be an id or a name"]);
+ assert_eq!(screw(json!({"a": "K", "b": null, "pitch": 1})), ["`joint` must be an id or a name"]);
+ assert_eq!(screw(json!({"joint": "Nut", "pitch": false})), [format!("`pitch` {size}")]);
+ assert_eq!(screw(json!({"joint": "Nut", "pitch": 1, "link": "0"})), ["no such motion link"]);
+
+ // joint.cam: the follower, its radius only for a roller, the tip, the profile.
+ let cam = |extra: Value| {
+ let mut p = json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "S"}});
+ p.as_object_mut().into_iter().for_each(|o| o.extend(extra.as_object().cloned().unwrap_or_default()));
+ issues("joint.cam", p)
+ };
+ assert_eq!(cam(json!({})), none());
+ assert_eq!(cam(json!({"follower": "knife", "radius": true, "flip": true, "link": 0, "quiet": true})), none());
+ assert_eq!(cam(json!({"follower": "flat", "radius": null})), none());
+ assert_eq!(cam(json!({"follower": null, "radius": []})), none());
+ assert_eq!(cam(json!({"follower": "roller", "radius": "5 mm", "tip": {"circle": [1, 2, 3]}})), none());
+ assert_eq!(cam(json!({"follower": "roller", "radius": {"circle": [1, 2, 3]}})), none());
+ assert_eq!(cam(json!({"tip": "Origin1"})), none());
+ assert_eq!(cam(json!({"tip": {"point": [1, 2, 3]}})), none());
+ assert_eq!(cam(json!({"flip": null})), none());
+ assert_eq!(issues("joint.cam", json!({"a": 1, "b": 2})), none());
+ assert_eq!(issues("joint.cam", json!({})), none());
+ assert_eq!(cam(json!({"follower": "round"})), ["`follower` is knife, roller or flat"]);
+ assert_eq!(cam(json!({"follower": "Roller"})), ["`follower` is knife, roller or flat"]);
+ assert_eq!(cam(json!({"follower": 5})), ["`follower` must be text"]);
+ assert_eq!(cam(json!({"follower": "roller"})), none());
+ assert_eq!(cam(json!({"follower": "roller", "radius": true})), [format!("`radius` {size}")]);
+ assert_eq!(cam(json!({"follower": "roller", "radius": null})), [format!("`radius` {size}")]);
+ assert_eq!(cam(json!({"tip": null})), [why]);
+ assert_eq!(cam(json!({"tip": 5})), [why]);
+ assert_eq!(cam(json!({"tip": {}})), [why]);
+ assert_eq!(cam(json!({"tip": {"face": ""}})), ["a face name is 1…16384 characters"]);
+ assert_eq!(cam(json!({"flip": "yes"})), ["`flip` must be true or false"]);
+ assert_eq!(cam(json!({"link": null})), ["no such motion link"]);
+ for ok in [
+ json!({"sketch": "S"}),
+ json!({"sketch": 4, "index": 2}),
+ json!({"sketch": "S", "edges": [], "occurrence": true}),
+ json!({"sketch": "S", "index": 0, "x": 1}),
+ json!({"edges": [[1, 2, 3]]}),
+ json!({"edges": [{"x": 1, "y": 2, "z": 3}], "occurrence": "Cam", "index": "x"}),
+ json!({"edges": vec![[1, 2, 3]; 64]}),
+ ] {
+ assert_eq!(cam(json!({"profile": ok.clone()})), none(), "{ok}");
+ }
+ let forms = "`profile` is {sketch: id|name} or {edges: [[x, y, z], …]}";
+ for (bad, message) in [
+ (json!(null), forms),
+ (json!("S"), forms),
+ (json!([1]), forms),
+ (json!({}), forms),
+ (json!({"edges": "x"}), forms),
+ (json!({"sketch": null}), "`profile.sketch` must be a sketch id or name"),
+ (json!({"sketch": [1]}), "`profile.sketch` must be a sketch id or name"),
+ (json!({"sketch": "S", "index": -1}), "the sketch has no such closed profile (an open curve makes none)"),
+ (json!({"sketch": "S", "index": "0"}), "the sketch has no such closed profile (an open curve makes none)"),
+ (json!({"sketch": "S", "index": null}), "the sketch has no such closed profile (an open curve makes none)"),
+ (json!({"edges": []}), "pick 1 to 64 edges"),
+ (json!({"edges": vec![[1, 2, 3]; 65]}), "pick 1 to 64 edges"),
+ (json!({"edges": [[1, 2]]}), "`edges` are finite [x, y, z] points"),
+ (json!({"edges": [[1, 2, 3], "x"]}), "`edges` are finite [x, y, z] points"),
+ (json!({"edges": [[1, 2, 3]], "occurrence": null}), "an occurrence must be an id or a name"),
+ (json!({"edges": [[1, 2, 3]], "occurrence": {}}), "an occurrence must be an id or a name"),
+ ] {
+ assert_eq!(cam(json!({"profile": bad.clone()})), [message], "{bad}");
+ }
+ assert_eq!(cam(json!({"profle": 1})), ["unknown key `profle`; did you mean `profile`?"]);
+}
+
+/// The schemas say what the handlers need, and take what they read.
+#[test]
+fn the_remaining_schemas_take_what_the_handlers_read() {
+ let takes = |schema: schemars::Schema, cases: &[(Value, bool)]| {
+ let schema = schema.as_value();
+ for (p, takes) in cases {
+ assert_eq!(conforms(schema, schema, p), *takes, "{p}");
+ }
+ };
+ takes(
+ input_schema_for::<MakeJointOriginParams>(),
+ &[
+ (json!({"face": [1, 2, 3]}), true),
+ (json!({"face": "F1", "x": "F2", "name": "Top", "body": "B", "occurrence": "A"}), true),
+ (json!({"circle": "F1", "end": "F2", "x": {"face": [1, 2, 3]}}), true),
+ (json!({"circle": [1, 2, 3], "z": [0, 0, 1], "x": null}), true),
+ (json!({"edge": [1, 2, 3], "on": [0, 0, 0], "corner": {"x": 1, "y": 2, "z": 3}, "z": [1, 0, 0]}), true),
+ (json!({"point": [1, 2, 3], "z": [0, 0, 1], "x": [1, 0, 0]}), true),
+ (json!({"frame": {"origin": [0, 0, 0], "z": [0, 0, 1], "x": [1, 0, 0]}}), true),
+ (json!({}), false),
+ (json!({"name": "N"}), false),
+ (json!({"face": [1, 2]}), false),
+ (json!({"point": [1, 2, 3], "end": 5}), false),
+ (json!({"frame": {"origin": [0, 0, 0]}}), false),
+ (json!({"point": [1, 2, 3], "x": 5}), false),
+ (json!({"point": [1, 2, 3], "nme": "N"}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<RigidGroupParams>(),
+ &[
+ (json!({"occurrences": ["A", 2]}), true),
+ (json!({"occurrences": ["A"]}), false),
+ (json!({"occurrences": vec![1; 1001]}), false),
+ (json!({"occurrences": [1, true]}), false),
+ (json!({}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<ReachParams>(),
+ &[
+ (json!({"occurrence": "Arm", "point": [1, 2, 3]}), true),
+ (
+ json!({"occurrence": 2, "point": {"x": 1, "y": 2, "z": 3}, "at": [0, 0, 0], "z": [0, 0, 1], "axis": [1, 0, 0], "joints": ["A", 3], "quiet": true, "continuous": true}),
+ true,
+ ),
+ (json!({"point": [1, 2, 3]}), false),
+ (json!({"occurrence": "Arm"}), false),
+ (json!({"occurrence": "Arm", "point": [1, 2]}), false),
+ (json!({"occurrence": "Arm", "point": [1, 2, 3], "joints": "A"}), false),
+ (json!({"occurrence": "Arm", "point": [1, 2, 3], "at": null}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<MotionLinkParams>(),
+ &[
+ (json!({"a": "A", "b": 2, "ratio": 0.5}), true),
+ (json!({"a": "A", "b": 2, "ratio": -2, "ia": 1, "ib": 0, "offset": "5 mm", "quiet": true}), true),
+ (json!({"a": "A", "b": 2}), false),
+ (json!({"a": "A", "ratio": 1}), false),
+ (json!({"a": "A", "b": 2, "ratio": "2"}), false),
+ (json!({"a": "A", "b": 2, "ratio": 1e12}), false),
+ (json!({"a": "A", "b": 2, "ratio": 1, "offset": true}), false),
+ ],
+ );
+ let gear = json!({"a": "A", "b": "B", "ra": 20, "rb": {"circle": [1, 2, 3], "occurrence": "G"}});
+ takes(
+ input_schema_for::<GearParams>(),
+ &[
+ (gear.clone(), true),
+ (json!({"a": 1, "b": 2, "ra": "r1", "rb": "15 mm", "internal": true, "reverse": true, "link": 0, "quiet": false}), true),
+ (json!({"a": "A", "b": "B", "ra": 20}), false),
+ (json!({"a": "A", "b": "B", "ra": 20, "rb": true}), false),
+ (json!({"a": "A", "b": "B", "ra": 20, "rb": {"point": [1, 2, 3]}}), false),
+ (json!({"a": "A", "b": "B", "ra": 20, "rb": 1, "link": -1}), false),
+ (json!({"a": "A", "b": "B", "ra": 20, "rb": 1, "link": "0"}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<RackPinionParams>(),
+ &[
+ (json!({"a": "P", "b": "Rack", "radius": 10}), true),
+ (json!({"a": "P", "b": "Rack", "radius": "r", "reverse": true, "link": 2}), true),
+ (json!({"a": "P", "b": "Rack"}), false),
+ (json!({"a": "P", "radius": 10}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<ScrewParams>(),
+ &[
+ (json!({"joint": "Nut", "pitch": 2}), true),
+ (json!({"a": "K", "b": "S", "pitch": "2 mm", "reverse": true, "link": 1}), true),
+ (json!({"joint": "Nut"}), false),
+ (json!({"pitch": 2}), false),
+ (json!({"a": "K", "pitch": 2}), false),
+ (json!({"joint": "Nut", "pitch": 2, "link": -1}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<CamParams>(),
+ &[
+ (json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "S"}}), true),
+ (
+ json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": 3, "index": 1}, "follower": "flat", "flip": true, "link": 0, "quiet": true}),
+ true,
+ ),
+ (
+ json!({"a": "Cam", "b": "Arm", "profile": {"edges": [[1, 2, 3]], "occurrence": "Cam"}, "follower": "roller", "radius": 5, "tip": {"circle": [1, 2, 3]}}),
+ true,
+ ),
+ (json!({"a": "Cam", "b": "Tappet", "profile": {"edges": []}}), false),
+ (json!({"a": "Cam", "b": "Tappet", "profile": {"edges": vec![[1, 2, 3]; 65]}}), false),
+ (json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "S", "index": -1}}), false),
+ (json!({"a": "Cam", "b": "Tappet", "profile": {}}), false),
+ (json!({"a": "Cam", "b": "Tappet"}), false),
+ (json!({"a": "Cam", "profile": {"sketch": "S"}}), false),
+ ],
+ );
+ // A roller needs its radius, a screw its joint or its two, a reach its axis's z, a joint
+ // origin one of its forms: said in the schema (`conforms` doesn't read these).
+ let cam = input_schema_for::<CamParams>();
+ assert_eq!(cam.as_value()["if"], json!({"properties": {"follower": {"const": "roller"}}, "required": ["follower"]}));
+ assert_eq!(cam.as_value()["then"], json!({"required": ["radius"]}));
+ let screw = input_schema_for::<ScrewParams>();
+ assert_eq!(screw.as_value()["anyOf"], json!([{"required": ["joint"]}, {"required": ["a", "b"]}]));
+ assert_eq!(input_schema_for::<ReachParams>().as_value()["dependentRequired"], json!({"axis": ["z"]}));
+ assert_eq!(input_schema_for::<MakeJointOriginParams>().as_value()["anyOf"].as_array().map(Vec::len), Some(5));
+}
+
+/// A design with the pieces the couplings join, and a tray with a hole for the joint origins by
+/// name: each command run in Warn in every form it takes gives a reply that matches its output
+/// schema, with no warning.
+#[test]
+fn replies_of_the_rest_match_the_output_schema() {
+ let ok = |schema: schemars::Schema, id: &str, reply: &Value| matches(schema, id, reply);
+
+ // joint.origin, in the forms of a face, a circle, an edge, a point and a frame.
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ put(&mut s, "component.create", json!({"name": "Tray"}));
+ put(&mut s, "solid.box", json!({"length": 300, "width": 100, "height": 1, "corner": [0, 0, 0]}));
+ put(&mut s, "solid.hole", json!({"position": [280, 50, 1], "diameter": 6}));
+ let name_at = |s: &mut Session, p: Vec3, circle: bool| {
+ let st = s.model.state();
+ let c = s.doc.find_component("Tray").unwrap_or(0);
+ solidcraft_doc::joints::face_name_at(&s.doc, &st, c, p, circle).unwrap_or_default()
+ };
+ let wall = name_at(&mut s, Vec3::new(283.0, 50.0, 0.5), false);
+ let top = name_at(&mut s, Vec3::new(150.0, 50.0, 1.0), false);
+ let right = name_at(&mut s, Vec3::new(300.0, 50.0, 0.5), false);
+ assert!(![&wall, &top, &right].iter().any(|n| n.is_empty()));
+ let schema = || output_schema_for::<MakeJointOriginResult>();
+ let mut made = Vec::new();
+ for p in [
+ json!({"occurrence": "Tray", "face": [150, 50, 1], "name": "TopPoint"}),
+ json!({"face": [150, 50, 1], "x": [0, 1, 0]}),
+ json!({"face": top.clone(), "name": "TopName", "x": right.clone()}),
+ json!({"face": top.clone(), "occurrence": "Tray", "body": null, "x": {"face": [300, 50, 0.5]}, "name": " Padded "}),
+ json!({"circle": wall.clone(), "end": top.clone(), "x": right.clone(), "name": "Hole"}),
+ json!({"circle": [283, 50, 0.5], "name": "HoleAt"}),
+ json!({"circle": [283, 50, 0.5], "z": [0, 0, 1], "name": "HoleOut", "end": "not checked here"}),
+ json!({"circle": [283, 50, 0.5], "end": top.clone(), "x": [1, 0, 0], "name": "HoleEnd"}),
+ json!({"edge": [150, 0, 1], "name": "Edge"}),
+ json!({"edge": [150, 0, 1], "on": [150, 50, 1], "corner": [299, 0, 1], "name": "Corner"}),
+ json!({"edge": [150, 0, 1], "z": [1, 0, 0], "end": 5, "name": "EdgeZ"}),
+ json!({"point": [10, 10, 1], "z": [0, 0, 1], "x": [1, 0, 0], "name": "Point"}),
+ json!({"point": [10, 10, 1], "occurrence": "Tray", "name": null}),
+ json!({"frame": {"origin": [5, 5, 1], "z": [0, 0, 1], "x": [1, 0, 0]}, "occurrence": "Tray", "name": "Frame"}),
+ json!({"frame": {"origin": [5, 5, 1], "z": [0, 0, 1]}, "occurrence": 0}),
+ ] {
+ let r = put(&mut s, "joint.origin", p.clone());
+ ok(schema(), "joint.origin", &r);
+ made.push(r["origin"].as_str().unwrap_or_default().to_string());
+ }
+ assert_eq!(made[0], "TopPoint");
+ assert_eq!(made[1], "Joint Origin1");
+ assert_eq!(made[3], "Padded");
+ assert_eq!(made[12], "Joint Origin2");
+ assert_eq!(s.doc.assembly.origins.len(), made.len());
+
+ // joint.rigid_group, by name and by id.
+ let mut g = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ let mut ids = Vec::new();
+ for (name, x) in [("A", 0), ("B", 20), ("C", 40), ("D", 60)] {
+ put(&mut g, "component.activate", json!({"component": "root"}));
+ let made = put(&mut g, "component.create", json!({"name": name, "grounded": false}));
+ put(&mut g, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0]}));
+ ids.push(made["occurrence"].clone());
+ }
+ let group = put(&mut g, "joint.rigid_group", json!({"occurrences": ["A", "B", "C"]}));
+ ok(output_schema_for::<RigidGroupResult>(), "joint.rigid_group", &group);
+ assert!(group["joints"].as_array().is_some_and(|j| j.len() == 2 && j.iter().all(Value::is_u64)), "{group}");
+ let by_id = put(&mut g, "joint.rigid_group", json!({"occurrences": [ids[3].clone(), 0]}));
+ ok(output_schema_for::<RigidGroupResult>(), "joint.rigid_group", &by_id);
+ assert!(by_id["joints"].as_array().is_some_and(|j| j.len() == 1), "{by_id}");
+
+ // The couplings and motion links.
+ let mut s = rig(ParamCheck::Warn);
+ let coupled = |s: &mut Session, id: &str, p: Value| {
+ let r = put(s, id, p.clone());
+ ok(output_schema_for::<CouplingResult>(), id, &r);
+ let quiet = p["quiet"] == json!(true);
+ assert!(r["link"].is_u64() && r["ratio"].is_number() && r.get("dof").is_some() != quiet, "{id} {p}: {r}");
+ r
+ };
+ let gear = coupled(&mut s, "joint.gear", json!({"a": "G1", "b": "G2", "ra": 10, "rb": "20 mm"}));
+ assert!(gear["link"] == 0 && gear["ratio"].as_f64().is_some_and(|r| (r + 0.5).abs() < 1e-9), "{gear}");
+ let again = coupled(
+ &mut s,
+ "joint.gear",
+ json!({"a": "G1", "b": "G2", "ra": {"occurrence": "G1", "circle": [10, 0, 2.5]}, "rb": {"occurrence": "G2", "circle": [50, 0, 2.5]},
+ "internal": true, "reverse": true, "link": 0}),
+ );
+ assert_eq!(again["link"], 0, "{again}");
+ let quiet = coupled(&mut s, "joint.gear", json!({"a": "G1", "b": "G2", "ra": 10, "rb": 20, "link": 0, "quiet": true, "internal": null}));
+ assert!(quiet.get("dof").is_none() && quiet.get("fixed").is_none(), "{quiet}");
+ let rack = coupled(&mut s, "joint.rack_pinion", json!({"a": "P", "b": "Rack", "radius": 10}));
+ assert_eq!(rack["link"], 1, "{rack}");
+ coupled(&mut s, "joint.rack_pinion", json!({"a": "Rack", "b": "P", "radius": "10 mm", "reverse": true, "link": 1}));
+ let screw = coupled(&mut s, "joint.screw", json!({"joint": "Nut", "pitch": 2}));
+ assert_eq!(screw["link"], 2, "{screw}");
+ coupled(&mut s, "joint.screw", json!({"joint": "Nut", "pitch": "2 mm", "reverse": true, "link": 2, "a": true}));
+ let apart = coupled(&mut s, "joint.screw", json!({"a": "K", "b": "Slide2", "pitch": 3}));
+ assert_eq!(apart["link"], 3, "{apart}");
+ let linked = put(&mut s, "joint.motion_link", json!({"a": "G1", "b": "X", "ratio": 2}));
+ ok(output_schema_for::<SolveResult>(), "joint.motion_link", &linked);
+ let quiet = put(&mut s, "joint.motion_link", json!({"a": "G1", "b": "K", "ratio": 1, "offset": "5 deg", "ia": 0, "ib": 0, "quiet": true}));
+ ok(output_schema_for::<SolveResult>(), "joint.motion_link", &quiet);
+ assert!(quiet.get("dof").is_none() && quiet.get("fixed").is_none(), "{quiet}");
+ let list = put(&mut s, "joint.list", json!({}));
+ assert!(list["links"].as_array().is_some_and(|l| l.len() == 6), "{list}");
+
+ // joint.reach: an arm.
+ let mut a = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ put(&mut a, "component.activate", json!({"component": "root"}));
+ let base = put(&mut a, "component.create", json!({"name": "Base", "grounded": false}));
+ put(&mut a, "solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": [-1, -1, -1]}));
+ put(&mut a, "occurrence.ground", json!({"occurrence": base["occurrence"], "grounded": true}));
+ for (name, x) in [("Upper", 30), ("Fore", 80)] {
+ put(&mut a, "component.activate", json!({"component": "root"}));
+ put(&mut a, "component.create", json!({"name": name, "grounded": false}));
+ put(&mut a, "solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": [x, -1, -1]}));
+ }
+ pin(&mut a, "revolute", "Shoulder", "Base", "Upper", [0.0, 0.0, 0.0], [0.0, 0.0, 1.0]);
+ pin(&mut a, "revolute", "Elbow", "Upper", "Fore", [60.0, 0.0, 0.0], [0.0, 0.0, 1.0]);
+ put(&mut a, "joint.drive", json!({"joint": "Elbow", "value": 30}));
+ let reach = |a: &mut Session, p: Value| {
+ let r = put(a, "joint.reach", p.clone());
+ ok(output_schema_for::<ReachResult>(), "joint.reach", &r);
+ r
+ };
+ // Fore's tip, with the elbow at 30°.
+ let tip = json!([60.0 + 40.0 * 30f64.to_radians().cos(), 20.0, 0.0]);
+ let moved = reach(&mut a, json!({"occurrence": "Fore", "at": tip, "point": [50, 50, 0]}));
+ assert!(moved["reached"] == json!(true) && moved["moved"] == json!(true) && moved["occurrence"] == "Fore:1", "{moved}");
+ assert!(moved["stopped_by_limit"].is_null() && moved["stopped_by_loop"].is_null() && moved.get("error_deg").is_none(), "{moved}");
+ assert!(moved["values"].as_array().is_some_and(|v| v.len() == 2 && v[0]["values"][0]["unit"] == "deg"), "{moved}");
+ let default_at =
+ reach(&mut a, json!({"occurrence": 2, "point": {"x": 40, "y": 30, "z": 0}, "quiet": true, "continuous": true, "joints": ["Shoulder"]}));
+ assert!(default_at["continuous"] == json!(true) && default_at.get("dof").is_none(), "{default_at}");
+ let turned = reach(&mut a, json!({"occurrence": "Fore", "point": [30, 70, 0], "z": [0, 1, 0], "axis": [1, 0, 0]}));
+ assert!(turned["error_deg"].is_number(), "{turned}");
+ let turned = reach(&mut a, json!({"occurrence": "Fore", "point": [0, 80, 0], "z": [0, 1, 0]}));
+ assert!(turned["error_deg"].is_number() && turned["reached"].is_boolean(), "{turned}");
+ put(&mut a, "joint.limits", json!({"joint": "Elbow", "min": 20, "max": 40}));
+ let limited = reach(&mut a, json!({"occurrence": "Fore", "point": [-150, 0, 0]}));
+ assert!(limited["stopped_by_limit"].as_array().is_some_and(|l| !l.is_empty() && l[0]["limit"] == "min"), "{limited}");
+ // A four-bar's rocker pulled past its toggle position: the loop that stops it is named.
+ let mut f = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ let (o4, p0) = ((45.0f64, 0.0f64), (0.0f64, 20.0f64));
+ let (dx, dy) = (o4.0 - p0.0, o4.1 - p0.1);
+ let l = dx.hypot(dy);
+ let along = (50.0f64.powi(2) - 40.0f64.powi(2) + l * l) / (2.0 * l);
+ let off = (50.0f64.powi(2) - along * along).sqrt();
+ let q0 = (p0.0 + dx * along / l - dy * off / l, p0.1 + dy * along / l + dx * off / l);
+ for (name, c) in [("Ground", (0.0, 0.0)), ("Crank", p0), ("Coupler", ((p0.0 + q0.0) / 2.0, (p0.1 + q0.1) / 2.0)), ("Rocker", q0)] {
+ put(&mut f, "component.activate", json!({"component": "root"}));
+ let made = put(&mut f, "component.create", json!({"name": name, "grounded": false}));
+ put(&mut f, "solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": [c.0, c.1, -5]}));
+ if name == "Ground" {
+ put(&mut f, "occurrence.ground", json!({"occurrence": made["occurrence"], "grounded": true}));
+ }
+ }
+ let z = [0.0, 0.0, 1.0];
+ pin(&mut f, "revolute", "Crank", "Ground", "Crank", [0.0, 0.0, 0.0], z);
+ pin(&mut f, "revolute", "Crank pin", "Crank", "Coupler", [p0.0, p0.1, 0.0], z);
+ pin(&mut f, "revolute", "Rocker pin", "Coupler", "Rocker", [q0.0, q0.1, 0.0], z);
+ pin(&mut f, "revolute", "Rocker", "Ground", "Rocker", [o4.0, o4.1, 0.0], z);
+ let start = (q0.1 - o4.1).atan2(q0.0 - o4.0) + 100f64.to_radians();
+ let past = [o4.0 + 40.0 * start.cos(), o4.1 + 40.0 * start.sin(), 0.0];
+ let stuck = reach(&mut f, json!({"occurrence": "Rocker", "at": [q0.0, q0.1, 0.0], "point": past}));
+ assert_eq!(stuck["stopped_by_loop"], json!({"joint": "Rocker pin"}), "{stuck}");
+ let fixed = reach(&mut a, json!({"occurrence": "Base", "point": [50, 50, 0]}));
+ assert!(fixed["reason"].is_string() && fixed["reached"] == json!(false) && fixed["values"] == json!([]), "{fixed}");
+}
+
+/// A cam in every form: a sketch's profile or picked edges, a knife, a roller and a flat face, a
+/// translating and an oscillating follower, a link replaced. The replies match the output schema.
+#[test]
+fn cam_replies_match_the_output_schema() {
+ let mut s = cam_rig(ParamCheck::Warn);
+ let cam = |s: &mut Session, p: Value| {
+ let r = put(s, "joint.cam", p.clone());
+ matches(output_schema_for::<CamResult>(), "joint.cam", &r);
+ assert!(r["link"].is_u64() && r["lift"]["unit"].is_string() && r["reverse"].is_boolean() && r.get("ratio").is_none(), "{p}: {r}");
+ r
+ };
+ let knife = cam(&mut s, json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}}));
+ assert!(knife["lift"]["unit"] == "mm" && knife["follower_offset"].is_number(), "{knife}");
+ let sized = cam(
+ &mut s,
+ json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch", "index": 0}, "follower": "roller", "radius": "5 mm", "link": 0, "quiet": true}),
+ );
+ assert!(sized.get("dof").is_none(), "{sized}");
+ cam(
+ &mut s,
+ json!({"a": "Cam", "b": "Tappet", "profile": {"edges": [[10, 30, 5]], "occurrence": "Cam"}, "follower": "flat", "flip": true, "link": 0}),
+ );
+ cam(
+ &mut s,
+ json!({"a": "Cam", "b": "Tappet", "profile": {"edges": [[10, 30, 5]]}, "follower": "knife", "radius": true, "tip": {"occurrence": "Tappet", "point": [45, 0, 2.5]}, "link": 0}),
+ );
+ // An oscillating follower: its tip, no offset in the reply.
+ // The roller's centre is where the arm's circle (50 about the pivot) meets the circle of
+ // radius 30 + 5 about the cam's centre.
+ let (pivot, centre) = ((-50.0f64, 40.0f64), (10.0f64, 0.0f64));
+ let (dx, dy) = (centre.0 - pivot.0, centre.1 - pivot.1);
+ let l = dx.hypot(dy);
+ let a = (50.0f64.powi(2) - 35.0f64.powi(2) + l * l) / (2.0 * l);
+ let h = (50.0f64.powi(2) - a * a).sqrt();
+ let start = [pivot.0 + dx * a / l - dy * h / l, pivot.1 + dy * a / l + dx * h / l, 2.5];
+ let swing = cam(
+ &mut s,
+ json!({"a": "Cam", "b": "Arm", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": 5, "tip": {"occurrence": "Arm", "point": start}}),
+ );
+ assert!(swing["lift"]["unit"] == "deg" && swing.get("follower_offset").is_none(), "{swing}");
+}
+
+/// A misspelt key still runs in Warn, says so, and the reply still matches its schema.
+#[test]
+fn a_misspelt_key_is_reported_in_warn_for_the_rest() {
+ let mut s = rig(ParamCheck::Warn);
+ let calls = [
+ ("joint.origin", json!({"occurrence": "Base", "point": [0, 0, 0], "nme": "A"}), "name"),
+ ("joint.rigid_group", json!({"occurrences": ["G1", "G2"], "occurences": 1}), "occurrences"),
+ ("joint.reach", json!({"occurrence": "G2", "point": [30, 20, 0], "quiet": true, "quet": true}), "quiet"),
+ ("joint.motion_link", json!({"a": "P", "b": "X", "ratio": 1, "ratjo": 1}), "ratio"),
+ ("joint.gear", json!({"a": "G1", "b": "G2", "ra": 10, "rb": 20, "internl": true}), "internal"),
+ ("joint.rack_pinion", json!({"a": "P", "b": "Rack", "radius": 10, "reverce": true}), "reverse"),
+ ("joint.screw", json!({"joint": "Nut", "pitch": 2, "pich": 2}), "pitch"),
+ ];
+ for (id, p, near) in calls {
+ let reply = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ let warnings = reply["param_warnings"].as_array().cloned().unwrap_or_default();
+ assert!(warnings.len() == 1 && warnings[0].as_str().is_some_and(|w| w.contains("unknown key") && w.contains(near)), "{id}: {reply}");
+ let out = crate::cmd::find_command(id).and_then(|c| c.output).map(|f| f()).unwrap_or_else(|| panic!("{id}"));
+ assert!(conforms(out.as_value(), out.as_value(), &reply), "{id}: {reply} doesn't match {}", out.as_value());
+ }
+ let mut c = cam_rig(ParamCheck::Warn);
+ let p = json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follwer": "flat"});
+ let reply = put(&mut c, "joint.cam", p);
+ assert!(reply["param_warnings"].as_array().is_some_and(|w| w.len() == 1 && w[0].as_str().is_some_and(|w| w.contains("follower"))), "{reply}");
+ let out = output_schema_for::<CamResult>();
+ assert!(conforms(out.as_value(), out.as_value(), &reply), "{reply}");
+}
+
+/// A wrong-typed key the handlers read as if it were left out is refused in strict (the stricter
+/// reading), and the call works with the check off.
+#[test]
+fn strict_refuses_wrong_types_the_handlers_ignore_in_the_rest() {
+ let cases = [
+ ("joint.origin", json!({"occurrence": "Base", "point": [0, 0, 0], "name": 5})),
+ ("joint.origin", json!({"occurrence": "Base", "point": [0, 0, 0], "z": "up"})),
+ ("joint.reach", json!({"occurrence": "G2", "point": [30, 20, 0], "quiet": "yes"})),
+ ("joint.motion_link", json!({"a": "G1", "b": "X", "ratio": 1, "ia": "0"})),
+ ("joint.gear", json!({"a": "G1", "b": "G2", "ra": 10, "rb": 20, "reverse": "no"})),
+ ("joint.rack_pinion", json!({"a": "P", "b": "Rack", "radius": 10, "quiet": 1})),
+ ("joint.screw", json!({"joint": "Nut", "pitch": 2, "reverse": "x"})),
+ ];
+ for (id, p) in cases {
+ let works = |level| rig(level).execute(id, &p).is_ok();
+ assert!(works(ParamCheck::Off) && !works(ParamCheck::Strict), "{id} {p}");
+ }
+ let cam = json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": 5});
+ let works = |level| cam_rig(level).execute("joint.cam", &cam).is_ok();
+ assert!(works(ParamCheck::Off) && !works(ParamCheck::Strict), "{cam}");
+}
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index f3abb04177..3805c527a0 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -20,14 +20,6 @@ file.save
file.save_as
file.save_mesh
file.slicers
-joint.cam
-joint.gear
-joint.motion_link
-joint.origin
-joint.rack_pinion
-joint.reach
-joint.rigid_group
-joint.screw
joint.sweep
mesh.convert
motion.export_animation