SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Agents and scripts: Create, Delete, List, Inspect, Limits, Drive, Solve and As-Built Joint describe their exact parameters and reply (#12503) (#12596)
PeppaWutzbeaa43cb4031
diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rsindex 2d7c30a62f..7968f18bc6 100644--- a/crates/engine/src/cmd/joints.rs+++ b/crates/engine/src/cmd/joints.rs@@ -15,11 +15,24 @@ use solidcraft_geom::Aabb3;use super::CommandSpec;use crate::params::{bad, bool_, num, str_, vec3};-use crate::schema::joints::EditJointResult;+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,+};use crate::schema::{TypedContract, output_schema_for};use crate::{EngineError, Result, Session};const EDIT_CONTRACT: TypedContract<crate::schema::joints::EditJointParams> = TypedContract::new();+const CREATE_CONTRACT: TypedContract<CreateJointParams> = TypedContract::new();+const AS_BUILT_CONTRACT: TypedContract<AsBuiltJointParams> = TypedContract::new();+const DRIVE_CONTRACT: TypedContract<DriveJointParams> = TypedContract::new();+const LIMITS_CONTRACT: TypedContract<JointLimitsParams> = TypedContract::new();+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();#[path = "joints_inspect.rs"]mod inspect;@@ -28,7 +41,13 @@ pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("joint.origin", "Joint Origin", joint_origin).at("SOLID", "CREATE").icon("joint_origin").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", joint).at("SOLID", "ASSEMBLE").icon("joint").key("J").params(+ CommandSpec::new("joint.create", "Joint", crate::checked!("joint.create", joint))+ .at("SOLID", "ASSEMBLE")+ .icon("joint")+ .key("J")+ .contract(&CREATE_CONTRACT)+ .output(output_schema_for::<JointAddedResult>)+ .params("type: rigid|revolute|slider|cylindrical|pin_slot|planar|ball, or a relation: parallel|perpendicular|angle|point_on_plane|point_on_line|line_on_plane \(ties only some directions or points, made where the parts are; several between two parts add up); a, b: joint origins ({occurrence, face|circle|edge|point: [x,y,z] in world, or face|circle: \"<face name>\"; z? for a point, end?, x? as joint.origin} | origin name); \values?: [angles in deg or expressions, distances]; limits?: [[min, max] | null…]; flip?: bool (default false: the origins are mated, \@@ -40,12 +59,22 @@ pub static COMMANDS: &[CommandSpec] = &[kept with the joint and worked out again whenever the design changes, so the joint follows the parameters it names; a joint whose \expression no longer works out (a parameter deleted) is left out of the solve with the reason in its errors",),- CommandSpec::new("joint.as_built", "As-Built Joint", as_built).at("SOLID", "ASSEMBLE").icon("as_built").params(+ CommandSpec::new("joint.as_built", "As-Built Joint", crate::checked!("joint.as_built", as_built))+ .at("SOLID", "ASSEMBLE")+ .icon("as_built")+ .contract(&AS_BUILT_CONTRACT)+ .output(output_schema_for::<JointAddedResult>)+ .params("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.drive", "Drive Joints", drive).at("SOLID", "ASSEMBLE").icon("drive").params(+ CommandSpec::new("joint.drive", "Drive Joints", crate::checked!("joint.drive", drive))+ .at("SOLID", "ASSEMBLE")+ .icon("drive")+ .contract(&DRIVE_CONTRACT)+ .output(output_schema_for::<DriveJointResult>)+ .params("joint: id|name; value | values: [angles in deg or expressions, distances] (values not given keep theirs; a value driven drops the expression joint.create gave it; clamped to the limits; the other joints of a \closed loop follow, and the motion stops where the loop can no longer close → stopped_by_loop); quiet?: bool (leave out dof \and fixed) → values: [{name, value, unit: deg|mm, limits}] as joint.list gives them; requested: the values asked for, in the same form; \@@ -83,7 +112,11 @@ pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("joint.cam", "Cam", cam_cmd).at("SOLID", "ASSEMBLE").icon("cam").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", limits).icon("joint").params("joint; index?: value index (default 0); min?, max? (omit both to clear)"),+ CommandSpec::new("joint.limits", "Joint Limits", crate::checked!("joint.limits", limits))+ .icon("joint")+ .contract(&LIMITS_CONTRACT)+ .output(output_schema_for::<SolveResult>)+ .params("joint; index?: value index (default 0); min?, max? (omit both to clear)"),CommandSpec::new("joint.edit", "Edit Joint", crate::checked!("joint.edit", edit)).icon("edit").contract(&EDIT_CONTRACT)@@ -94,12 +127,26 @@ pub static COMMANDS: &[CommandSpec] = &[its limits and expressions (a relation's values start again where its parts are); an edit that places it again (not a rename alone) \meets a loop it closes as joint.create does, turning an angle a half turn where only that meets it",),- CommandSpec::new("joint.delete", "Delete Joint", delete).icon("delete").params("joint: id|name (or origin: name, link: index)"),- CommandSpec::new("joint.list", "List Joints", list).icon("list").noundo().params(+ CommandSpec::new("joint.delete", "Delete Joint", crate::checked!("joint.delete", delete))+ .icon("delete")+ .contract(&DELETE_CONTRACT)+ .output(output_schema_for::<DeleteJointResult>)+ .params("joint: id|name (or origin: name, link: index)"),+ CommandSpec::new("joint.list", "List Joints", crate::checked!("joint.list", list))+ .icon("list")+ .noundo()+ .contract(&LIST_CONTRACT)+ .output(output_schema_for::<ListJointsResult>)+ .params("→ joints (type, occurrences, values, limits; expressions: {offset?, angle?, values?} when they were typed as expressions), origins, links, degrees of freedom, conflicts, floating: [{occurrences, joints}] \(joint chains joined to nothing grounded: the solver places none of them, so driving them moves nothing)",),- CommandSpec::new("joint.inspect", "Inspect Joint", inspect::inspect).icon("inspect").noundo().params(+ CommandSpec::new("joint.inspect", "Inspect Joint", crate::checked!("joint.inspect", inspect::inspect))+ .icon("inspect")+ .noundo()+ .contract(&INSPECT_CONTRACT)+ .output(output_schema_for::<InspectJointResult>)+ .params("joint?: id|name (default: every joint) → joints: [{id, name, type, suppressed, visible, flip, offset (mm), angle (deg), values: as joint.list \gives them, dofs, expressions?: {offset?, angle?, values?}, a, b: {occurrence, occurrence_name, component, component_name, path \(occurrence names from the top, `/` between), snap (as saved: type, pick, face, end, edge, corner, x, point, z, in the component's \@@ -108,7 +155,11 @@ pub static COMMANDS: &[CommandSpec] = &[unverified?: a name saved before exact names}], resolves, frame?: {origin, z, x} in the world, error?: why the origin is lost}, \links: [{index, role: driver|driven, …as joint.list}], errors, conflicts}] (reads only: nothing changes)",),- CommandSpec::new("joint.solve", "Solve Joints", solve_cmd).icon("compute").params("re-place the occurrences from the joints → conflicts, errors, dof"),+ CommandSpec::new("joint.solve", "Solve Joints", crate::checked!("joint.solve", solve_cmd))+ .icon("compute")+ .contract(&SOLVE_CONTRACT)+ .output(output_schema_for::<SolveResult>)+ .params("re-place the occurrences from the joints → conflicts, errors, dof"),CommandSpec::new("inspect.interference", "Interference", crate::checked!("inspect.interference", super::interference::interference)).contract(&crate::schema::TypedContract::<crate::schema::interference::InterferenceParams>::new()).output(crate::schema::output_schema_for::<crate::schema::interference::InterferenceResult>)@@ -228,30 +279,57 @@ fn response_analysis(p: &Value) -> joints::Analysis {}/// A solve's answer; `quiet: true` in the command's params leaves out the per-occurrence lists.-fn sol_json(sol: &joints::Solution, p: &Value) -> Value {- let mut out = json!({- "conflicts": sol.conflicts.iter().map(|(id, n, w)| json!({"joint": id, "name": n, "why": w})).collect::<Vec<_>>(),- "errors": sol.errors.iter().map(|(id, n, w)| json!({"joint": id, "name": n, "why": w})).collect::<Vec<_>>(),- });- if !bool_(p, "quiet").unwrap_or(false) {- out["dof"] = sol.dof.iter().map(|(o, d)| json!({"occurrence": o, "dof": d})).collect();- out["fixed"] = json!(sol.fixed);+fn solve_report(sol: &joints::Solution, p: &Value) -> SolveReport {+ let problems = |list: &[(u64, String, String)]| -> Vec<JointProblem> {+ list.iter().map(|(joint, name, why)| JointProblem { joint: *joint, name: name.clone(), why: why.clone() }).collect()+ };+ let quiet = bool_(p, "quiet").unwrap_or(false);+ SolveReport {+ conflicts: problems(&sol.conflicts),+ errors: problems(&sol.errors),+ dof: (!quiet).then(|| sol.dof.iter().map(|(o, d)| OccurrenceDof { occurrence: *o, dof: *d }).collect()),+ fixed: (!quiet).then(|| sol.fixed.clone()),}- out+}++/// [`solve_report`] as JSON, for the commands that add to it.+fn sol_json(sol: &joints::Solution, p: &Value) -> Value {+ serde_json::to_value(solve_report(sol, p)).unwrap_or_default()+}++/// A command's reply as JSON: the joint commands that have output schemas build their replies from+/// the types those describe, so the two can't drift apart.+fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {+ serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))}/// 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().iter().enumerate().map(|(i, n)| {let (v, angle) = (q.get(i).copied().unwrap_or(0.0), j.kind.is_angle(i));- json!({"name": n, "value": expr::round_reported(if angle { v.to_degrees() } else { v }), "unit": if angle { "deg" } else { "mm" },- "limits": j.limits.get(i).copied().flatten().map(|(a, b)| if angle { [expr::round_reported(a.to_degrees()), expr::round_reported(b.to_degrees())] } else { [expr::round_reported(a), expr::round_reported(b)] })})+ NamedValue {+ name: (*n).to_string(),+ value: expr::round_reported(if angle { v.to_degrees() } else { v }),+ unit: if angle { ValueUnit::Deg } else { ValueUnit::Mm },+ limits: j.limits.get(i).copied().flatten().map(|(a, b)| {+ if angle {+ [expr::round_reported(a.to_degrees()), expr::round_reported(b.to_degrees())]+ } else {+ [expr::round_reported(a), expr::round_reported(b)]+ }+ }),+ }}).collect()}@@ -259,9 +337,14 @@ pub(crate) fn named_values(j: &Joint, q: &[f64]) -> Vec<Value> {/// A joint's values as the solver places it (after motion links, so a screw's travel follows its/// turn), named as `joint.list` gives them.pub(crate) fn effective_values(s: &Session, id: u64) -> Option<Vec<Value>> {+ effective_value_list(s, id).map(|list| list.into_iter().map(|v| serde_json::to_value(v).unwrap_or_default()).collect())+}++/// [`effective_values`], typed.+fn effective_value_list(s: &Session, id: u64) -> Option<Vec<NamedValue>> {let j = s.doc.assembly.joints.iter().find(|j| j.id == id)?;let vals = joints::joint_values(&s.doc.assembly);- Some(named_values(j, vals.get(&id).map(Vec::as_slice).unwrap_or(&j.values)))+ Some(named_value_list(j, vals.get(&id).map(Vec::as_slice).unwrap_or(&j.values)))}fn occurrence_name(s: &Session, id: u64) -> String {@@ -293,7 +376,7 @@ pub(crate) fn cannot_move(s: &Session, sol: &joints::Solution, id: u64) -> Optio/// Joint chains joined to nothing grounded, which the solver places none of: each chain's/// occurrences and joints, by name.-fn floating_chains(s: &Session, sol: &joints::Solution) -> Vec<Value> {+fn floating_chains(s: &Session, sol: &joints::Solution) -> Vec<FloatingChain> {let placed = |o: u64| o == 0 || sol.world.contains_key(&o);let errors: BTreeSet<u64> = sol.errors.iter().map(|e| e.0).collect();let mut next: BTreeMap<u64, Vec<(u64, &Joint)>> = BTreeMap::new();@@ -319,8 +402,10 @@ fn floating_chains(s: &Session, sol: &joints::Solution) -> Vec<Value> {}}}- out.push(json!({"occurrences": occs.iter().map(|o| occurrence_name(s, *o)).collect::<Vec<_>>(),- "joints": js.iter().map(|(_, n)| *n).collect::<Vec<_>>()}));+ out.push(FloatingChain {+ occurrences: occs.iter().map(|o| occurrence_name(s, *o)).collect(),+ joints: js.iter().map(|(_, n)| (*n).to_string()).collect(),+ });}out}@@ -754,21 +839,27 @@ fn add_joint(s: &mut Session, mut j: Joint, p: &Value) -> Result<Value> {let mut q = j.values.clone();q.resize(j.kind.dofs().len(), 0.0);joints::clamp(&j, &mut q);- let round = |v: &Value| v.as_f64().map(|x| (x * 1e6).round() / 1e6).unwrap_or(f64::NAN);- let warnings: Vec<String> = named_values(&j, &q)+ let round = |v: f64| (v * 1e6).round() / 1e6;+ // As the reply shows them: a value that is not a number reads as null, and null is null.+ let same = |a: f64, b: f64| a == b || (a.is_nan() && b.is_nan());+ let warnings: Vec<String> = named_value_list(&j, &q).iter()- .zip(named_values(&j, &j.values))- .filter(|(now, was)| now["value"] != was["value"])+ .zip(named_value_list(&j, &j.values))+ .filter(|(now, was)| !same(now.value, was.value)).map(|(now, was)| {- let unit = now["unit"].as_str().unwrap_or("");+ let unit = match now.unit {+ ValueUnit::Deg => "deg",+ ValueUnit::Mm => "mm",+ };+ let [lo, hi] = now.limits.unwrap_or([f64::NAN; 2]);format!("{} {} starts at {} {unit}, inside its limits [{}, {}], not at {} {unit}: the part moved there as it was joined",j.name,- now["name"].as_str().unwrap_or(""),- round(&now["value"]),- round(&now["limits"][0]),- round(&now["limits"][1]),- round(&was["value"])+ now.name,+ round(now.value),+ round(lo),+ round(hi),+ round(was.value))}).collect();@@ -782,13 +873,7 @@ fn add_joint(s: &mut Session, mut j: Joint, p: &Value) -> Result<Value> {if sol.conflicts.iter().any(|(c, ..)| *c == id) && close_by_half_turn(s, id, &sol) {sol = resolve(s);}- let mut out = sol_json(&sol, p);- out["joint"] = json!(id);- out["name"] = json!(name);- if !warnings.is_empty() {- out["warnings"] = json!(warnings);- }- Ok(out)+ reply("joint.create", JointAddedResult { solved: solve_report(&sol, p), joint: id, name, warnings, param_warnings: Vec::new() })}/// Sets of angle values a new loop-closing joint tries a half turn round, at most.@@ -1087,41 +1172,48 @@ fn drive(s: &mut Session, p: &Value) -> Result<Value> {if let Some(index) = index { super::motion::drive_joint_index(s, id, q, index)? } else { super::motion::drive_joint(s, id, q, given)? }};let sol = solution(s, &BTreeMap::new(), response_analysis(p));- let mut out = sol_json(&sol, p);- out["joint"] = json!(id);- out["values"] = json!(effective_values(s, id));- if bool_(p, "continuous") == Some(true) {- out["continuous"] = json!(true);- }- out["stopped_by_contact"] = r["stopped_by_contact"].clone();- out["stopped_by_loop"] = r["stopped_by_loop"].clone();- let moved = super::motion::moved(&before, &super::motion::positions(s)).next().is_some();- out["moved"] = json!(moved);+ // How motion stopped, as `motion::drive_with_contact` says: an object, or null.+ let stop = |key: &str| r.get(key).filter(|v| v.is_object()).cloned();+ let stopped_by_contact =+ stop("stopped_by_contact").map(serde_json::from_value::<ContactStop>).transpose().map_err(|e| bad(cmd, e.to_string()))?;+ let stopped_by_loop = stop("stopped_by_loop").map(serde_json::from_value::<LoopStop>).transpose().map_err(|e| bad(cmd, e.to_string()))?;+ let mut out = DriveJointResult {+ solved: solve_report(&sol, p),+ joint: id,+ values: effective_value_list(s, id),+ continuous: (bool_(p, "continuous") == Some(true)).then_some(true),+ stopped_by_contact,+ stopped_by_loop,+ moved: super::motion::moved(&before, &super::motion::positions(s)).next().is_some(),+ requested: None,+ held: None,+ reason: None,+ unconnected: None,+ param_warnings: Vec::new(),+ };if let Some(j) = s.doc.assembly.joints.iter().find(|j| j.id == id) {- out["requested"] = json!(named_values(j, &requested));+ out.requested = Some(named_value_list(j, &requested));let held = if hold { Vec::new() } else { held_values(s, j, &requested, &driven, &r) };if let Some(first) = held.first()- && !moved+ && !out.moved{- out["reason"] = first["why"].clone();+ out.reason = Some(first.why.clone());}if !held.is_empty() {- out["held"] = json!(held);+ out.held = Some(held);}}if let Some((why, unconnected)) = cannot_move(s, &sol, id) {- out["reason"] = json!(why);- if let Some(o) = unconnected {- out["unconnected"] = json!(o);- }+ out.reason = Some(why);+ out.unconnected = unconnected;}- Ok(out)+ reply(cmd, out)}/// The driven values of `j` that ended up other than `requested`, each with why: a motion link/// sets it from another coordinate (a screw's travel follows its turn), a limit holds it, or/// contact or a closed loop stopped the motion short. Degrees and mm, as `values` (#9742).-fn held_values(s: &Session, j: &Joint, requested: &[f64], driven: &[usize], r: &Value) -> Vec<Value> {+fn held_values(s: &Session, j: &Joint, requested: &[f64], driven: &[usize], r: &Value) -> Vec<HeldValue> {let now = joints::joint_values(&s.doc.assembly).remove(&j.id).unwrap_or_else(|| j.values.clone());let names = j.kind.dofs();let mut out = Vec::new();@@ -1159,7 +1251,13 @@ fn held_values(s: &Session, j: &Joint, requested: &[f64], driven: &[usize], r: &} else {continue;};- out.push(json!({"name": name, "requested": shown(want), "value": shown(got), "unit": if angle { "deg" } else { "mm" }, "why": why}));+ out.push(HeldValue {+ name: name.to_string(),+ requested: shown(want),+ value: shown(got),+ unit: if angle { ValueUnit::Deg } else { ValueUnit::Mm },+ why,+ });}out}@@ -1422,14 +1520,19 @@ fn cam_cmd(s: &mut Session, p: &Value) -> Result<Value> {/// 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.+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 {- return Value::Null;+ return None;}let unit = |v: f64| if angle { v.to_degrees() } else { v };let (lo, hi) = l.lift.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(*v), hi.max(*v)));let (lo, hi) = (unit(lo + l.offset), unit(hi + l.offset));- json!({"min": lo, "max": hi, "rise": hi - lo, "unit": if angle { "deg" } else { "mm" }})+ Some(CamLift { min: lo, max: hi, rise: hi - lo, unit: if angle { ValueUnit::Deg } else { ValueUnit::Mm } })}/// A cam's profile: a sketch's closed profile (kept by its outer loop's curve ids, so the sketch's@@ -1585,7 +1688,7 @@ fn limits(s: &mut Session, p: &Value) -> Result<Value> {joints::clamp(j, &mut q);j.values = q;let sol = resolve(s);- Ok(sol_json(&sol, p))+ reply(cmd, SolveResult { solved: solve_report(&sol, p), param_warnings: Vec::new() })}fn edit(s: &mut Session, p: &Value) -> Result<Value> {@@ -1711,7 +1814,10 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {if doc.assembly.origins.len() == before {return Err(bad(cmd, format!("no joint origin `{name}`")));}- return Ok(json!({"deleted_origin": name, "joints": used}));+ return reply(+ cmd,+ DeleteJointResult { deleted: JointDeleted::Origin { deleted_origin: name.to_string(), joints: used }, param_warnings: Vec::new() },+ );}if let Some(i) = num(p, "link") {let i = i.max(0.0) as usize;@@ -1720,72 +1826,83 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {return Err(bad(cmd, "no such motion link"));}doc.assembly.links.remove(i);- return Ok(json!({"deleted_link": i}));+ return reply(cmd, DeleteJointResult { deleted: JointDeleted::Link { deleted_link: i }, param_warnings: Vec::new() });}let id = joint_id(s, p.get("joint"), cmd)?;delete_joints(s.doc_mut(), &[id]);let sol = resolve(s);- let mut out = sol_json(&sol, p);- out["deleted"] = json!(id);- Ok(out)+ reply(cmd, DeleteJointResult { deleted: JointDeleted::Joint { solved: solve_report(&sol, p), deleted: id }, param_warnings: Vec::new() })}fn list(s: &mut Session, p: &Value) -> Result<Value> {let st = s.model.state();let sol = joints::solve(&s.doc, &st);let vals = joints::joint_values(&s.doc.assembly);- let js: Vec<Value> = s+ let js: Vec<ListedJoint> = s.doc.assembly.joints.iter().map(|j| {- let named = named_values(j, vals.get(&j.id).map(Vec::as_slice).unwrap_or_default());- let world = |o: &JointOrigin| s.doc.origin_world(&st, o).ok().map(|m| json!({"origin": [m[3][0], m[3][1], m[3][2]], "z": [m[2][0], m[2][1], m[2][2]]}));- let mut out = json!({"id": j.id, "name": j.name, "type": j.kind, "a": j.a.occurrence, "b": j.b.occurrence, "values": named,- "flip": j.flip, "offset": j.offset, "suppressed": j.suppressed, "visible": s.joint_visible(j.id), "frame_a": world(&j.a), "frame_b": world(&j.b)});- if !j.exprs.is_empty() {- out["expressions"] = json!(j.exprs);+ let world = |o: &JointOrigin| {+ s.doc.origin_world(&st, o).ok().map(|m| JointFrame { origin: [m[3][0], m[3][1], m[3][2]], z: [m[2][0], m[2][1], m[2][2]] })+ };+ ListedJoint {+ id: j.id,+ name: j.name.clone(),+ kind: j.kind,+ a: j.a.occurrence,+ b: j.b.occurrence,+ values: named_value_list(j, vals.get(&j.id).map(Vec::as_slice).unwrap_or_default()),+ flip: j.flip,+ offset: j.offset,+ suppressed: j.suppressed,+ visible: s.joint_visible(j.id),+ frame_a: world(&j.a),+ frame_b: world(&j.b),+ expressions: (!j.exprs.is_empty()).then(|| j.exprs.clone()),}- out}).collect();- let links: Vec<Value> = s.doc.assembly.links.iter().map(|l| link_json(s, &st, l)).collect();- let origins: Vec<Value> = s.doc.assembly.origins.iter().map(|o| json!({"name": o.name, "occurrence": o.origin.occurrence})).collect();- let mut out = sol_json(&sol, p);- out["joints"] = json!(js);- out["links"] = json!(links);- out["origins"] = json!(origins);- out["floating"] = json!(floating_chains(s, &sol));- Ok(out)+ let out = ListJointsResult {+ solved: solve_report(&sol, p),+ joints: js,+ links: s.doc.assembly.links.iter().map(|l| link_info(s, &st, l)).collect(),+ origins: s.doc.assembly.origins.iter().map(|o| ListedOrigin { name: o.name.clone(), occurrence: o.origin.occurrence }).collect(),+ floating: floating_chains(s, &sol),+ param_warnings: Vec::new(),+ };+ reply("joint.list", out)}/// A motion link as `joint.list` and `joint.inspect` give it: ratio per degree, offset in b's/// units, a coupling's definition (and why it can't be worked out), a cam's lift in place of a ratio.-fn link_json(s: &Session, st: &solidcraft_doc::ModelState, l: &MotionLink) -> Value {+fn link_info(s: &Session, st: &solidcraft_doc::ModelState, l: &MotionLink) -> LinkInfo {let angle = is_angle(s, l.b, l.ib);let offset = if angle { l.offset.to_degrees() } else { l.offset };let ratio = l.ratio / ratio_scale(s, l.a, l.ia, l.b, l.ib);- let mut v = json!({"a": l.a, "ia": l.ia, "b": l.b, "ib": l.ib, "ratio": ratio, "offset": offset, "unit": if angle { "deg" } else { "mm" }});- if let Some(c) = &l.coupling {- v["coupling"] = json!(c);- if let Some(Err(e)) = joints::coupling_values(&s.doc, st, l) {- v["error"] = json!(e.to_string());- }- }// A cam's follower follows its table, not a ratio: its travel instead.- if matches!(l.coupling, Some(Coupling::Cam(_)))- && let Some(o) = v.as_object_mut()- {- o.remove("ratio");- o.insert("lift".into(), lift_json(l, angle));+ let cam = matches!(l.coupling, Some(Coupling::Cam(_)));+ LinkInfo {+ a: l.a,+ ia: l.ia,+ b: l.b,+ ib: l.ib,+ ratio: (!cam).then_some(ratio),+ offset,+ unit: if angle { ValueUnit::Deg } else { ValueUnit::Mm },+ coupling: l.coupling.clone(),+ error: match &l.coupling {+ Some(_) => joints::coupling_values(&s.doc, st, l).and_then(|r| r.err()).map(|e| e.to_string()),+ None => None,+ },+ lift: cam.then(|| lift_info(l, angle)),}- v}fn solve_cmd(s: &mut Session, p: &Value) -> Result<Value> {let sol = resolve(s);- Ok(sol_json(&sol, p))+ reply("joint.solve", SolveResult { solved: solve_report(&sol, p), param_warnings: Vec::new() })}/// Index pairs `(i, j)`, `i < j`, whose boxes overlap or touch (sort and sweep along X), at mostdiff --git a/crates/engine/src/cmd/joints_inspect.rs b/crates/engine/src/cmd/joints_inspect.rsindex 86d96d3f4f..a37fddbeba 100644--- a/crates/engine/src/cmd/joints_inspect.rs+++ b/crates/engine/src/cmd/joints_inspect.rs@@ -3,13 +3,17 @@//! persistent name refers to), whether each origin is found today and why not, its kind, offset,//! angle, flip, limits, values, expressions and the motion links it takes part in. Reads only.-use serde_json::{Value, json};+use serde_json::Value;use solidcraft_doc::joints::{self, Joint, JointOrigin, Snap, XRef};use solidcraft_doc::naming::legacy_name;use solidcraft_doc::persistent_name::{Base, EdgeName, FaceName, Role};use solidcraft_doc::{Document, MAX_PLACEMENT_DEPTH, ModelState};-use super::{component_of, joint_id, link_json, named_values, occurrence_name};+use super::{component_of, joint_id, link_info, named_value_list, occurrence_name, reply};+use crate::schema::joints::{+ EdgeReference, FaceReference, InspectJointResult, InspectedJoint, JointLink, JointSide, LinkRole, MadeBy, Reference, ReferenceRole, Referent,+ SweptFrom, WorldFrame,+};use crate::{Result, Session};pub(super) fn inspect(s: &mut Session, p: &Value) -> Result<Value> {@@ -21,7 +25,7 @@ pub(super) fn inspect(s: &mut Session, p: &Value) -> Result<Value> {let st = s.model.state();let sol = joints::solve(&s.doc, &st);let vals = joints::joint_values(&s.doc.assembly);- let out: Vec<Value> = ids+ let out: Vec<InspectedJoint> = ids.iter().filter_map(|id| s.doc.assembly.joints.iter().find(|j| j.id == *id)).map(|j| {@@ -29,50 +33,42 @@ pub(super) fn inspect(s: &mut Session, p: &Value) -> Result<Value> {joint_json(s, &st, &sol, j, q)}).collect();- Ok(json!({ "joints": out }))+ reply(cmd, InspectJointResult { joints: out, param_warnings: Vec::new() })}-fn joint_json(s: &Session, st: &ModelState, sol: &joints::Solution, j: &Joint, q: &[f64]) -> Value {- let links: Vec<Value> = s+fn joint_json(s: &Session, st: &ModelState, sol: &joints::Solution, j: &Joint, q: &[f64]) -> InspectedJoint {+ let links: Vec<JointLink> = s.doc.assembly.links.iter().enumerate().filter(|(_, l)| l.a == j.id || l.b == j.id)- .map(|(i, l)| {- let mut v = link_json(s, st, l);- v["index"] = json!(i);- v["role"] = json!(if l.b == j.id { "driven" } else { "driver" });- v- })+ .map(|(i, l)| JointLink { index: i, role: if l.b == j.id { LinkRole::Driven } else { LinkRole::Driver }, link: link_info(s, st, l) }).collect();let why = |list: &[(u64, String, String)]| list.iter().filter(|(id, ..)| *id == j.id).map(|(.., why)| why.clone()).collect::<Vec<_>>();- let mut v = json!({- "id": j.id,- "name": j.name,- "type": j.kind,- "suppressed": j.suppressed,- "visible": s.joint_visible(j.id),- "flip": j.flip,- "offset": j.offset,- "angle": j.angle.to_degrees(),- "values": named_values(j, q),- "dofs": j.kind.dofs(),- "a": side_json(s, st, &j.a),- "b": side_json(s, st, &j.b),- "links": links,- "errors": why(&sol.errors),- "conflicts": why(&sol.conflicts),- });- if !j.exprs.is_empty() {- v["expressions"] = json!(j.exprs);+ InspectedJoint {+ id: j.id,+ name: j.name.clone(),+ kind: j.kind,+ suppressed: j.suppressed,+ visible: s.joint_visible(j.id),+ flip: j.flip,+ offset: j.offset,+ angle: j.angle.to_degrees(),+ values: named_value_list(j, q),+ dofs: j.kind.dofs().iter().map(|d| (*d).to_string()).collect(),+ a: side_json(s, st, &j.a),+ b: side_json(s, st, &j.b),+ links,+ errors: why(&sol.errors),+ conflicts: why(&sol.conflicts),+ expressions: (!j.exprs.is_empty()).then(|| j.exprs.clone()),}- v}/// One of a joint's origins: what it sits on, what it refers to, and where it is now.-fn side_json(s: &Session, st: &ModelState, o: &JointOrigin) -> Value {+fn side_json(s: &Session, st: &ModelState, o: &JointOrigin) -> JointSide {let component = component_of(s, o.occurrence);let component_name = if component == 0 {"root".to_string()@@ -80,24 +76,24 @@ fn side_json(s: &Session, st: &ModelState, o: &JointOrigin) -> Value {s.doc.components.iter().find(|c| c.id == component).map(|c| c.name.clone()).unwrap_or_default()};let occurrence_name = if o.occurrence == 0 { "root".to_string() } else { occurrence_name(s, o.occurrence) };- let mut v = json!({- "occurrence": o.occurrence,- "occurrence_name": occurrence_name,- "component": component,- "component_name": component_name,- "path": occurrence_path(&s.doc, o.occurrence),- "snap": o.snap,- "references": references(&s.doc, &o.snap),- });+ let mut v = JointSide {+ occurrence: o.occurrence,+ occurrence_name,+ component,+ component_name,+ path: occurrence_path(&s.doc, o.occurrence),+ snap: o.snap.clone(),+ references: references(&s.doc, &o.snap),+ resolves: false,+ frame: None,+ error: None,+ };match s.doc.origin_world(st, o) {Ok(m) => {- v["resolves"] = json!(true);- v["frame"] = json!({"origin": [m[3][0], m[3][1], m[3][2]], "z": [m[2][0], m[2][1], m[2][2]], "x": [m[0][0], m[0][1], m[0][2]]});- }- Err(e) => {- v["resolves"] = json!(false);- v["error"] = json!(e.to_string());+ v.resolves = true;+ v.frame = Some(WorldFrame { origin: [m[3][0], m[3][1], m[3][2]], z: [m[2][0], m[2][1], m[2][2]], x: [m[0][0], m[0][1], m[0][2]] });}+ Err(e) => v.error = Some(e.to_string()),}v}@@ -118,36 +114,36 @@ fn occurrence_path(doc: &Document, occurrence: u64) -> String {}/// Every persistent name the snap holds, with what it refers to.-fn references(doc: &Document, snap: &Snap) -> Vec<Value> {+fn references(doc: &Document, snap: &Snap) -> Vec<Reference> {let mut out = Vec::new();- let mut face = |role: &str, name: &Option<String>| {+ let mut face = |role: ReferenceRole, name: &Option<String>| {if let Some(n) = name {- out.push(with_role(role, face_ref(doc, n)));+ out.push(Reference { role, to: Referent::Face(face_ref(doc, n)) });}};match snap {Snap::FaceCenter { face: f, x, .. } => {- face("face", f);+ face(ReferenceRole::Face, f);if let Some(XRef::Face { face: n, .. }) = x {- face("x", &Some(n.clone()));+ face(ReferenceRole::X, &Some(n.clone()));}}Snap::CircleCenter { face: f, end, x, .. } => {- face("face", f);- face("end", end);+ face(ReferenceRole::Face, f);+ face(ReferenceRole::End, end);if let Some(XRef::Face { face: n, .. }) = x {- face("x", &Some(n.clone()));+ face(ReferenceRole::X, &Some(n.clone()));}}Snap::Edge { edge, face: f, corner, .. } => {if let Some(e) = edge {- out.push(with_role("edge", edge_ref(doc, e)));+ out.push(Reference { role: ReferenceRole::Edge, to: Referent::Edge(edge_ref(doc, e)) });}if let Some(n) = f {- out.push(with_role("face", face_ref(doc, n)));+ out.push(Reference { role: ReferenceRole::Face, to: Referent::Face(face_ref(doc, n)) });}if let Some(e) = corner {- out.push(with_role("corner", edge_ref(doc, e)));+ out.push(Reference { role: ReferenceRole::Corner, to: Referent::Edge(edge_ref(doc, e)) });}}Snap::Frame { .. } | Snap::Point { .. } => {}@@ -155,19 +151,14 @@ fn references(doc: &Document, snap: &Snap) -> Vec<Value> {out}-fn with_role(role: &str, mut v: Value) -> Value {- v["role"] = json!(role);- v-}-/// What a face's persistent name refers to: `F<feature>:<role>` names the feature that made the/// face, and a side `side:<curve>` (or a later profile's `side:s<k>.<curve>`) the sketch curve/// it was swept from. Names of another form are given as they are.-fn face_ref(doc: &Document, name: &str) -> Value {- let mut v = json!({ "name": name });+fn face_ref(doc: &Document, name: &str) -> FaceReference {+ let mut v = FaceReference { name: name.to_string(), unverified: None, role_in_feature: None, feature: None, sketch: None };let bare = match legacy_name(name) {Some(n) => {- v["unverified"] = json!(true);+ v.unverified = Some(true);n}None => name,@@ -175,38 +166,36 @@ fn face_ref(doc: &Document, name: &str) -> Value {let Ok(face) = FaceName::parse(bare) else { return v };let Some(fid) = face.made_by().map(|id| id.0) else { return v };let stem = face.stem().to_string();- v["role_in_feature"] = json!(stem.strip_prefix(&format!("F{fid}:")).unwrap_or(&stem));+ v.role_in_feature = Some(stem.strip_prefix(&format!("F{fid}:")).unwrap_or(&stem).to_string());let Some(f) = doc.feature(fid) else {- v["feature"] = json!({"id": fid, "error": format!("feature {fid} is gone")});+ v.feature = Some(MadeBy::Gone { id: fid, error: format!("feature {fid} is gone") });return v;};- v["feature"] = json!({"id": f.id, "name": f.name, "type": f.kind.type_name()});+ v.feature = Some(MadeBy::Feature { id: f.id, name: f.name.clone(), kind: f.kind.type_name().to_string() });// A side swept from a sketch curve (a later profile's too, `side:s<k>.<curve>`).if let Base::Made { role: Role::Side { curve, .. }, .. } = &face.base {let found = f.kind.input_sketches().into_iter().find_map(|id| {// design-only: a joint names a curve of one of the design's sketches.let sk = doc.sketch(id).ok()?;let c = sk.curves.iter().find(|c| c.id == *curve)?;- let curve_type = serde_json::to_value(&c.kind).ok().and_then(|k| k.get("type").cloned()).unwrap_or(Value::Null);+ let curve_type = serde_json::to_value(&c.kind).ok().and_then(|k| k.get("type").and_then(Value::as_str).map(str::to_string));let name = doc.feature(id).map(|f| f.name.clone()).unwrap_or_default();- Some(json!({"id": id, "name": name, "curve": curve, "curve_type": curve_type}))+ Some(SweptFrom::Curve { id, name, curve: curve.clone(), curve_type })});- v["sketch"] = found.unwrap_or_else(|| json!({"curve": curve, "error": format!("no sketch of {} has a curve `{curve}`", f.name)}));+ v.sketch = Some(+ found.unwrap_or_else(|| SweptFrom::Missing { curve: curve.clone(), error: format!("no sketch of {} has a curve `{curve}`", f.name) }),+ );}v}/// An edge's persistent name (`<face A>|<face B>`, `~k` for one of several between them) with/// what each of its faces refers to.-fn edge_ref(doc: &Document, name: &str) -> Value {+fn edge_ref(doc: &Document, name: &str) -> EdgeReference {let bare = legacy_name(name).unwrap_or(name);- let faces: Vec<Value> = match EdgeName::parse(bare) {+ let faces: Vec<FaceReference> = match EdgeName::parse(bare) {Ok(e) => e.faces.iter().map(|f| face_ref(doc, &f.to_string())).collect(),Err(_) => Vec::new(),};- let mut v = json!({"name": name, "faces": faces});- if legacy_name(name).is_some() {- v["unverified"] = json!(true);- }- v+ EdgeReference { name: name.to_string(), faces, unverified: legacy_name(name).is_some().then_some(true) }}diff --git a/crates/engine/src/schema/joints.rs b/crates/engine/src/schema/joints.rsindex 81c0afd61e..1041b1a83e 100644--- a/crates/engine/src/schema/joints.rs+++ b/crates/engine/src/schema/joints.rs@@ -5,9 +5,13 @@ use std::borrow::Cow;use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};use serde::de::Error as _;use serde::{Deserialize, Deserializer, Serialize};-use serde_json::Value;+use serde_json::{Map, Value, json};+use solidcraft_doc::joints::{Coupling, JointExprs, JointKind, Snap};+use super::check::whole;+use super::motion::require;use super::types::{AngleExpr, IdOrName, LengthExpr, present};+use crate::params;/// A joint origin as joint.create takes it: a joint origin's name, or an object with the snap/// (`occurrence`, then `face`, `circle`, `edge` or `point`, or a `frame`). Kept as given, for the@@ -80,15 +84,20 @@ pub struct EditJointParams {/// A joint the solve reports: its id, name and why.#[derive(Debug, Serialize, JsonSchema)]pub struct JointProblem {+ /// The joint, by id.pub joint: u64,+ /// The joint's name.pub name: String,+ /// Why it conflicts or could not be applied.pub why: String,}/// The degrees of freedom one occurrence keeps (6 free, 0 fixed).#[derive(Debug, Serialize, JsonSchema)]pub struct OccurrenceDof {+ /// The occurrence, by id (0 is the root).pub occurrence: u64,+ /// Its remaining degrees of freedom.pub dof: usize,}@@ -108,6 +117,1296 @@ pub struct EditJointResult {pub param_warnings: Vec<String>,}+// ---------------------------------------------------------------------------------------------+// joint.create, joint.as_built, joint.drive, joint.limits, joint.delete, joint.list,+// joint.inspect and joint.solve (#12503).+//+// The handlers read their parameters from the raw JSON, so each key here reads as its handler+// reads it and fails with the handler's message. Whether a joint, an occurrence, a joint origin+// or a face exists stays the handler's to check. A key the handler refuses when it is left out+// (`type`, `a`, `b`, `joint`) is optional in the type and required in the schema, so that the+// handler's message, not the check's "is required", is what a caller sees. A handler that reads+// a key only in some cases (`value` when `values` is a list, `joint` when `origin` or `link` is+// given) has its contract read it in the same cases, so a call that works today gets no warning.+// ---------------------------------------------------------------------------------------------++/// A joint by its id (a number) or its name, as `joint_id` reads it.+#[derive(Clone, Debug, PartialEq)]+pub struct JointKey(pub String);++impl JointKey {+ fn read(v: &Value) -> Result<Self, String> {+ match v {+ Value::Number(n) => Ok(JointKey(n.to_string())),+ Value::String(s) => Ok(JointKey(s.clone())),+ _ => Err("`joint` must be an id or a name".into()),+ }+ }+}++impl JsonSchema for JointKey {+ fn schema_name() -> Cow<'static, str> {+ "JointKey".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({"description": "A joint's id (a number) or its name.", "type": ["number", "string"]})+ }+}++/// An occurrence by its id (a number) or its name, as `occurrence_id` reads it.+#[derive(Clone, Debug, PartialEq)]+pub struct OccurrenceKey(pub String);++impl OccurrenceKey {+ fn read(v: &Value) -> Result<Self, String> {+ match v {+ Value::Number(n) => Ok(OccurrenceKey(n.to_string())),+ Value::String(s) => Ok(OccurrenceKey(s.clone())),+ _ => Err("an occurrence must be an id or a name".into()),+ }+ }+}++impl JsonSchema for OccurrenceKey {+ fn schema_name() -> Cow<'static, str> {+ "OccurrenceKey".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "An occurrence by id or name (0 or `root`: the root), or the name of a component: its first occurrence.",+ "type": ["number", "string"]+ })+ }+}++/// A joint's type, as `kind_param` reads it: ignoring case, spaces, `_` and `-`, with the aliases+/// the engine takes.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct JointTypeParam(pub JointKind);++const TYPE_MESSAGE: &str = "`type` must be rigid, revolute, slider, cylindrical, pin_slot, planar, ball, parallel, perpendicular, angle, point_on_plane, point_on_line or line_on_plane";++/// The spellings `JointKind::parse` takes, canonical ones first.+const JOINT_TYPES: &[&str] = &[+ "rigid",+ "revolute",+ "slider",+ "cylindrical",+ "pin_slot",+ "planar",+ "ball",+ "parallel",+ "perpendicular",+ "angle",+ "point_on_plane",+ "point_on_line",+ "line_on_plane",+ "rotate",+ "slide",+ "square",+ "point_on_face",+ "point_on_axis",+ "line_on_face",+];++impl JointTypeParam {+ fn read(v: &Value) -> Result<Self, String> {+ v.as_str().and_then(JointKind::parse).map(JointTypeParam).ok_or_else(|| TYPE_MESSAGE.to_string())+ }+}++impl JsonSchema for JointTypeParam {+ fn schema_name() -> Cow<'static, str> {+ "JointType".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "A joint's type: rigid, revolute (turns), slider (slides), cylindrical (both), pin_slot, planar or ball; or a relation that ties only some directions or points, made where the parts are: parallel, perpendicular, angle, point_on_plane, point_on_line or line_on_plane. Case, spaces, `_` and `-` are ignored, and rotate, slide, square, point_on_face, point_on_axis and line_on_face are also taken.",+ "type": "string",+ "examples": JOINT_TYPES+ })+ }+}++/// A joint value: a number (degrees for an angle, mm for a distance), or an expression, as+/// `joints::value` reads it.+#[derive(Clone, Debug, PartialEq)]+pub struct JointValue(pub Value);++impl JointValue {+ fn check(v: &Value) -> Result<(), String> {+ match v {+ Value::Number(n) if n.as_f64().is_some_and(|x| x.is_finite() && x.abs() < 1e9) => Ok(()),+ Value::String(_) => Ok(()),+ _ => Err(format!("a joint value {}", params::expr_problem(Some(v)))),+ }+ }+ fn read(v: &Value) -> Result<Self, String> {+ Self::check(v).map(|()| JointValue(v.clone()))+ }+}++impl JsonSchema for JointValue {+ fn schema_name() -> Cow<'static, str> {+ "JointValue".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "A number (degrees for an angle, mm for a distance; below 1e9 in size), or an expression (text) over the design's parameters, such as \"width / 2\" or \"30 deg\".",+ "anyOf": [+ {"type": "number", "exclusiveMinimum": -1e9, "exclusiveMaximum": 1e9},+ {"type": "string"}+ ]+ })+ }+}++/// The values of a joint, one per coordinate in the order `joint.list` names them.+#[derive(Clone, Debug, PartialEq)]+pub struct JointValues(pub Vec<Value>);++impl JointValues {+ fn read(v: &Value) -> Result<Self, String> {+ match v {+ Value::Array(items) => items.iter().try_for_each(JointValue::check).map(|()| JointValues(items.clone())),+ _ => Err("`values` must be a list of joint values".into()),+ }+ }+}++impl JsonSchema for JointValues {+ fn schema_name() -> Cow<'static, str> {+ "JointValues".into()+ }+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {+ let item = generator.subschema_for::<JointValue>();+ json_schema!({+ "description": "A list of values, one for each of the joint's coordinates in order (the angle first for a cylindrical joint). Angles in degrees, distances in mm, or expressions.",+ "type": "array",+ "items": item+ })+ }+}++/// A joint's limits: one `[min, max]` pair for each value, `null` for a value with no limit.+#[derive(Clone, Debug, PartialEq)]+pub struct JointLimits(pub Vec<Value>);++impl JointLimits {+ fn read(v: &Value) -> Result<Self, String> {+ let Value::Array(items) = v else { return Err("`limits` must be a list of [min, max] pairs, with null for a value without limits".into()) };+ for item in items {+ match item {+ Value::Null => {}+ // A list of fewer than two is left out by the handler; of two or more, the first two+ // are read.+ Value::Array(pair) if pair.len() >= 2 => pair.iter().take(2).try_for_each(JointValue::check)?,+ Value::Array(_) => {}+ _ => return Err("`limits` must be a list of [min, max] pairs, with null for a value without limits".into()),+ }+ }+ Ok(JointLimits(items.clone()))+ }+}++impl JsonSchema for JointLimits {+ fn schema_name() -> Cow<'static, str> {+ "JointLimits".into()+ }+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {+ let value = generator.subschema_for::<JointValue>();+ json_schema!({+ "description": "The limits of each value in order: [min, max] (degrees or mm, or expressions), or null for a value without limits. Not more pairs than the joint has values.",+ "type": "array",+ "items": {+ "anyOf": [+ {"type": "null"},+ {"type": "array", "prefixItems": [value, value]}+ ]+ }+ })+ }+}++/// A joint origin as `joint.create` reads a side: a joint origin's name, or an object that says+/// where (`face`, `circle`, `edge` or `point`: a point in world coordinates, or for the first two+/// a face's name; or a `frame`). Kept as given, for the handler.+#[derive(Clone, Debug, PartialEq)]+pub struct JointOriginArg(pub Value);++impl JointOriginArg {+ fn read(v: &Value) -> Result<Self, String> {+ if v.is_string() {+ return Ok(JointOriginArg(v.clone()));+ }+ let named = ["face", "circle"].iter().any(|k| v.get(*k).and_then(Value::as_str).is_some());+ let picked = ["face", "circle", "edge", "point"].iter().any(|k| v.get(*k).and_then(params::vec3).is_some());+ if named || picked {+ return Ok(JointOriginArg(v.clone()));+ }+ match v.get("frame") {+ Some(f) if f.get("origin").and_then(params::vec3).is_some() => Ok(JointOriginArg(v.clone())),+ Some(_) => Err("`frame` needs origin and z".into()),+ None => Err("a joint origin needs face, circle, edge, point or frame [x, y, z], or a face's name".into()),+ }+ }+}++impl JsonSchema for JointOriginArg {+ fn schema_name() -> Cow<'static, str> {+ "JointOriginArg".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ // `params::vec3` reads [x, y, z] and {x, y, z}.+ let forms = [+ json!({"type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3}),+ json!({"type": "object", "properties": {"x": {"type": "number"}, "y": {"type": "number"}, "z": {"type": "number"}}, "required": ["x", "y", "z"]}),+ ];+ let point = json!({"anyOf": forms});+ let at = |description: &str| json!({"description": description, "anyOf": forms});+ json_schema!({+ "description": "A joint origin: the name of a joint origin made with joint.origin, or an object that says where it is, in world coordinates. Give one of face, circle, edge or point (a point [x, y, z]; for face and circle also a face's name, as model.faces lists it), or a frame {origin, z, x?}.",+ "anyOf": [+ {"type": "string", "description": "The name of a joint origin."},+ {+ "type": "object",+ "properties": {+ "occurrence": {"description": "The occurrence the origin is on, by id or name. Default: found from the point, or the named face's component.", "type": ["number", "string"]},+ "face": {"description": "The centre of a planar face: a point on it [x, y, z], or its name.", "anyOf": [point, {"type": "string"}]},+ "circle": {"description": "The centre of a round end: a point [x, y, z] on its wall, rim or centre, or the round face's name.", "anyOf": [point, {"type": "string"}]},+ "edge": at("A point [x, y, z] on an edge of a planar face."),+ "point": at("A point [x, y, z]."),+ "frame": {"description": "An explicit frame {origin: [x, y, z], z: [x, y, z], x?: [x, y, z]}.", "type": "object"},+ "z": at("The frame's z axis, a direction [x, y, z], where it is not the face's normal."),+ "x": {"description": "The frame's turn about z: a direction [x, y, z], a face's name or {face: [x, y, z]}.", "anyOf": [point, {"type": "string"}, {"type": "object"}]},+ "end": {"description": "A circle's end: the name of the face across its rim there.", "type": "string"},+ "on": at("An edge origin: a point on the face to use."),+ "corner": at("An edge origin: a point near one end of the edge, for the corner there."),+ "body": {"description": "The body a face name is on.", "type": "string"}+ }+ }+ ]+ })+ }+}++macro_rules! read_with {+ ($($t:ty),*) => {$(+ impl<'de> Deserialize<'de> for $t {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ Self::read(&Value::deserialize(d)?).map_err(|m| D::Error::custom(whole(m)))+ }+ }+ )*};+}++read_with!(JointKey, OccurrenceKey, JointTypeParam, JointValue, JointValues, JointLimits, JointOriginArg);++/// The call's keys as an object. (`TypedContract::check` has refused anything else already.)+fn keys<'de, D: Deserializer<'de>>(d: D) -> Result<Map<String, Value>, D::Error> {+ Map::<String, Value>::deserialize(d)+}++/// `key`, read by `read` when it is given (`null` included).+fn given<T, E: serde::de::Error>(m: &Map<String, Value>, key: &str, read: fn(&Value) -> Result<T, String>) -> Result<Option<T>, E> {+ m.get(key).map(|v| read(v).map_err(|e| E::custom(whole(e)))).transpose()+}++/// `key` as the handlers' `bool_` reads it, but refusing a value that is not a boolean, which the+/// handlers read as if the key were left out. `null` is left out.+fn flag<E: serde::de::Error>(m: &Map<String, Value>, key: &str) -> Result<Option<bool>, E> {+ match m.get(key) {+ None | Some(Value::Null) => Ok(None),+ Some(Value::Bool(b)) => Ok(Some(*b)),+ Some(_) => Err(E::custom(whole(format!("`{key}` must be true or false")))),+ }+}++/// `key` as the handlers' `str_` reads it, but refusing a value that is not text.+fn text<E: serde::de::Error>(m: &Map<String, Value>, key: &str) -> Result<Option<String>, E> {+ match m.get(key) {+ None | Some(Value::Null) => Ok(None),+ Some(Value::String(s)) => Ok(Some(s.clone())),+ Some(_) => Err(E::custom(whole(format!("`{key}` must be text")))),+ }+}++/// `key` as the handlers' `num` reads it, but refusing a value that is not a number.+fn number<E: serde::de::Error>(m: &Map<String, Value>, key: &str) -> Result<Option<f64>, E> {+ match m.get(key) {+ None | Some(Value::Null) => Ok(None),+ Some(Value::Number(n)) => Ok(n.as_f64()),+ Some(_) => Err(E::custom(whole(format!("`{key}` must be a number")))),+ }+}++/// `key` when it is not `null`, read by `read` (a list the handlers ignore unless it is one).+fn listed<T, E: serde::de::Error>(m: &Map<String, Value>, key: &str, read: fn(&Value) -> Result<T, String>) -> Result<Option<T>, E> {+ match m.get(key) {+ None | Some(Value::Null) => Ok(None),+ Some(v) => read(v).map(Some).map_err(|e| E::custom(whole(e))),+ }+}++/// Add a joint between two occurrences, mated at two joint origins, and re-solve. A relation type+/// (parallel, perpendicular, angle, point_on_plane, point_on_line, line_on_plane) ties only some+/// directions or points and is made where the parts are. An expression given for `offset`,+/// `angle` or a value is kept with the joint and worked out again whenever the design changes. The+/// joint starts at its values inside its limits, and a part moved to a limit is said so in+/// `warnings`. One undo step.+#[derive(Debug, JsonSchema)]+#[schemars(deny_unknown_fields, transform = create_required)]+pub struct CreateJointParams {+ // `type`, `a` and `b` are optional in the type and required in the schema+ // (`create_required`): left out, the handler refuses them with its own message.+ /// The joint's type.+ #[serde(default, rename = "type", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "JointTypeParam")]+ pub kind: Option<JointTypeParam>,+ /// Side a: a joint origin, as an object in world coordinates or a joint origin's name. The+ /// two sides must be on different occurrences.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "JointOriginArg")]+ pub a: Option<JointOriginArg>,+ /// Side b: a joint origin, as `a`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "JointOriginArg")]+ pub b: Option<JointOriginArg>,+ /// The joint's values to start at: one per coordinate (angles in degrees, distances in mm, or+ /// expressions the joint then follows). Default: 0 for each, or for a relation or a joint that+ /// closes a loop, where the parts are. Wins over `value`.+ #[serde(default)]+ pub values: Option<JointValues>,+ /// One value, for the joint's first coordinate, when `values` is not a list. Ignored (and not+ /// checked) when `values` is a list.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "JointValue")]+ pub value: Option<JointValue>,+ /// The limits of each value: [min, max] pairs, with null for a value without limits. Default:+ /// none.+ #[serde(default)]+ pub limits: Option<JointLimits>,+ /// Whether b's z lies along a's instead of against it. Default: false (the origins are mated,+ /// b's z against a's as two faces meet); true keeps two origins given at one point with the+ /// same z and x as they are. A point origin without x takes its x from z, so give x on both,+ /// or use joint.as_built, to keep a turned part where it is.+ #[serde(default)]+ pub flip: Option<bool>,+ /// The distance from a's frame to b's along z, in mm or an expression. Default: 0.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "JointValue")]+ pub offset: Option<JointValue>,+ /// The turn about that distance, in degrees or an expression; for an angle relation, its tilt+ /// from mated. Default: none, or a half turn where that turns b less, so faces that already+ /// meet stay as they are.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "JointValue")]+ pub angle: Option<JointValue>,+ /// The joint's name. Default: its type, `Joint` and the first number no joint's name has.+ /// Blank text gives the default.+ #[serde(default)]+ pub name: Option<String>,+ /// Leave out `dof` and `fixed` in the reply. Default: false.+ #[serde(default)]+ pub quiet: Option<bool>,+}++fn create_required(schema: &mut Schema) {+ require(schema, "type");+ require(schema, "a");+ require(schema, "b");+}++impl<'de> Deserialize<'de> for CreateJointParams {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let m = keys(d)?;+ // In the handler's order: the type, the sides, then the numbers.+ let kind = given(&m, "type", JointTypeParam::read)?;+ let a = given(&m, "a", JointOriginArg::read)?;+ let b = given(&m, "b", JointOriginArg::read)?;+ let offset = given(&m, "offset", JointValue::read)?;+ let angle = given(&m, "angle", JointValue::read)?;+ let values = listed(&m, "values", JointValues::read)?;+ // `value` is read only when `values` is not a list.+ let value = if values.is_some() { None } else { given(&m, "value", JointValue::read)? };+ let limits = listed(&m, "limits", JointLimits::read)?;+ Ok(CreateJointParams {+ kind,+ a,+ b,+ values,+ value,+ limits,+ flip: flag(&m, "flip")?,+ offset,+ angle,+ name: text(&m, "name")?,+ quiet: flag(&m, "quiet")?,+ })+ }+}++/// Add a joint between two occurrences that stay where they are: its frame is a joint origin+/// (`at`, default b's origin), and the joint starts with the origins coinciding as they are. An+/// origin on a or b is kept on its face or hole there, so the joint follows it as the design+/// changes. One undo step.+#[derive(Debug, JsonSchema)]+#[schemars(deny_unknown_fields, transform = as_built_required)]+pub struct AsBuiltJointParams {+ // `type`, `a` and `b` are optional in the type and required in the schema+ // (`as_built_required`), as in `CreateJointParams`.+ /// The joint's type, as joint.create takes it.+ #[serde(default, rename = "type", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "JointTypeParam")]+ pub kind: Option<JointTypeParam>,+ /// Occurrence a, by id or name; it stays where it is.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "OccurrenceKey")]+ pub a: Option<OccurrenceKey>,+ /// Occurrence b, by id or name; it stays where it is.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "OccurrenceKey")]+ pub b: Option<OccurrenceKey>,+ /// The joint's frame: a joint origin, as joint.create takes one. Default: b's origin.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "JointOriginArg")]+ pub at: Option<JointOriginArg>,+ /// The joint's name. Default: its type, `Joint` and the first number no joint's name has.+ /// Blank text gives the default.+ #[serde(default)]+ pub name: Option<String>,+ /// The limits of each value: [min, max] pairs, with null for a value without limits. Default:+ /// none.+ #[serde(default)]+ pub limits: Option<JointLimits>,+ /// Leave out `dof` and `fixed` in the reply. Default: false.+ #[serde(default)]+ pub quiet: Option<bool>,+ /// Not a value of this joint, which starts at zero: only whether `values` is given matters.+ /// Given, a relation type is not started from where its parts are.+ #[serde(default)]+ pub values: Option<Value>,+ /// Like `values`: only whether it is given matters.+ #[serde(default)]+ pub value: Option<Value>,+}++fn as_built_required(schema: &mut Schema) {+ require(schema, "type");+ require(schema, "a");+ require(schema, "b");+}++impl<'de> Deserialize<'de> for AsBuiltJointParams {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let m = keys(d)?;+ Ok(AsBuiltJointParams {+ kind: given(&m, "type", JointTypeParam::read)?,+ a: given(&m, "a", OccurrenceKey::read)?,+ b: given(&m, "b", OccurrenceKey::read)?,+ at: given(&m, "at", JointOriginArg::read)?,+ limits: listed(&m, "limits", JointLimits::read)?,+ name: text(&m, "name")?,+ quiet: flag(&m, "quiet")?,+ values: m.get("values").cloned(),+ value: m.get("value").cloned(),+ })+ }+}++/// Set a joint's values by hand, as far as its limits, contact sets and closed loops allow; the+/// other joints of a closed loop follow, and the motion stops where the loop can no longer close.+/// A value driven drops the expression joint.create gave it. Give `value` or `values`, or `index`+/// with `value` to drive one coordinate while the others follow.+#[derive(Debug, JsonSchema)]+#[schemars(deny_unknown_fields, transform = drive_required)]+pub struct DriveJointParams {+ // `joint` is optional in the type and required in the schema (`drive_required`): left out,+ // the handler refuses it with its own message.+ /// The joint, by id or name. A rigid joint does not move.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "JointKey")]+ pub joint: Option<JointKey>,+ /// The values to drive to: one per coordinate (angles in degrees, distances in mm, or+ /// expressions worked out once). A value not given keeps its own. Not with `index`.+ #[serde(default)]+ pub values: Option<JointValues>,+ /// One value: the joint's first coordinate, or with `index` the one that `index` names. Used+ /// when `values` is not a list; ignored (and not checked) when it is.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "JointValue")]+ pub value: Option<JointValue>,+ /// Drive only this coordinate, counted from zero (0 for a revolute joint's angle); the others+ /// follow. Goes with `value`, not `values`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "u64")]+ pub index: Option<u64>,+ /// 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 drive_required(schema: &mut Schema) {+ require(schema, "joint");+ // The handler refuses a call with neither (`give value or values`), and one with `index` and+ // `values`.+ schema.insert("anyOf".into(), json!([{"required": ["value"]}, {"required": ["values"]}]));+ schema.insert("not".into(), json!({"required": ["index", "values"]}));+}++impl<'de> Deserialize<'de> for DriveJointParams {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let m = keys(d)?;+ let joint = given(&m, "joint", JointKey::read)?;+ // `index`, once given (`null` included), must name a coordinate of the joint.+ let index = match m.get("index") {+ None => None,+ Some(v) => Some(v.as_u64().ok_or_else(|| D::Error::custom(whole("index is outside this joint's coordinates")))?),+ };+ let (values, value) = if index.is_some() {+ // One coordinate: `values` is refused, whatever it holds, and `value` is read.+ if m.contains_key("values") {+ return Err(D::Error::custom(whole("index goes with value, not values")));+ }+ (None, given(&m, "value", JointValue::read)?)+ } else {+ let values = listed(&m, "values", JointValues::read)?;+ // `value` is read only when `values` is not a list.+ let value = if values.is_some() { None } else { given(&m, "value", JointValue::read)? };+ (values, value)+ };+ Ok(DriveJointParams { joint, values, value, index, quiet: flag(&m, "quiet")?, continuous: flag(&m, "continuous")? })+ }+}++/// Set one of a joint's value limits, or clear it. A value already past the new limit moves to+/// it. Give `min` and `max` together, or neither to clear.+#[derive(Debug, JsonSchema)]+#[schemars(deny_unknown_fields, transform = limits_required)]+pub struct JointLimitsParams {+ // `joint` is optional in the type and required in the schema, as in `DriveJointParams`.+ /// The joint, by id or name.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "JointKey")]+ pub joint: Option<JointKey>,+ /// Which value, counted from zero (0 for a revolute joint's angle); a negative number is 0.+ /// Default: 0.+ #[serde(default)]+ pub index: Option<f64>,+ /// The lowest the value goes, in degrees or mm, or an expression. With `max`; leave both out+ /// to clear the limit.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "JointValue")]+ pub min: Option<JointValue>,+ /// The highest the value goes, as `min`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "JointValue")]+ pub max: Option<JointValue>,+ /// Leave out `dof` and `fixed` in the reply. Default: false.+ #[serde(default)]+ pub quiet: Option<bool>,+}++fn limits_required(schema: &mut Schema) {+ require(schema, "joint");+ schema.insert("dependentRequired".into(), json!({"min": ["max"], "max": ["min"]}));+}++impl<'de> Deserialize<'de> for JointLimitsParams {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let m = keys(d)?;+ let joint = given(&m, "joint", JointKey::read)?;+ let index = number(&m, "index")?;+ // Both or neither, `null` counted as given; the minimum is read first.+ let (min, max) = match (m.get("min"), m.get("max")) {+ (Some(lo), Some(hi)) => {+ let lo = JointValue::read(lo).map_err(|e| D::Error::custom(whole(e)))?;+ (Some(lo), Some(JointValue::read(hi).map_err(|e| D::Error::custom(whole(e)))?))+ }+ (None, None) => (None, None),+ _ => return Err(D::Error::custom(whole("give both `min` and `max`, or neither to clear"))),+ };+ Ok(JointLimitsParams { joint, index, min, max, quiet: flag(&m, "quiet")? })+ }+}++/// Delete a joint (and the motion links it is in), a joint origin or a motion link. Give+/// `origin` to delete a joint origin, or else `link` to delete a motion link, or else `joint`.+/// With `origin` or `link` the other keys are not read. One undo step.+#[derive(Debug, JsonSchema)]+#[schemars(deny_unknown_fields, transform = delete_required)]+pub struct DeleteJointParams {+ /// The joint origin to delete, by name. Wins over `link` and `joint`.+ #[serde(default)]+ pub origin: Option<String>,+ /// The motion link to delete, by its index in `joint.list`'s `links` (a negative number is+ /// 0). Wins over `joint`; not read when `origin` is given.+ #[serde(default)]+ pub link: Option<f64>,+ /// The joint to delete, by id or name. Read only without `origin` and `link`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "JointKey")]+ pub joint: Option<JointKey>,+ /// Leave out `dof` and `fixed` in the reply. Read only when a joint is deleted. Default:+ /// false.+ #[serde(default)]+ pub quiet: Option<bool>,+}++fn delete_required(schema: &mut Schema) {+ // The handler refuses a call with none of them (`joint must be an id or a name`).+ schema.insert("anyOf".into(), json!([{"required": ["origin"]}, {"required": ["link"]}, {"required": ["joint"]}]));+}++impl<'de> Deserialize<'de> for DeleteJointParams {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let m = keys(d)?;+ let unread = |origin, link| DeleteJointParams { origin, link, joint: None, quiet: None };+ // The modes, in the handler's order: a joint origin's name, a link's number, a joint.+ match m.get("origin") {+ Some(Value::String(name)) => return Ok(unread(Some(name.clone()), None)),+ None | Some(Value::Null) => {}+ Some(_) => return Err(D::Error::custom(whole("`origin` must be the name of a joint origin"))),+ }+ match m.get("link") {+ Some(Value::Number(n)) if n.as_f64().and_then(params::finite).is_some() => return Ok(unread(None, n.as_f64())),+ None | Some(Value::Null) | Some(Value::Number(_)) => {}+ Some(_) => return Err(D::Error::custom(whole("`link` must be a motion link's index, a number"))),+ }+ Ok(DeleteJointParams { origin: None, link: None, joint: given(&m, "joint", JointKey::read)?, quiet: flag(&m, "quiet")? })+ }+}++/// What every joint command that moves parts reports: the joints that disagree with the solved+/// placement, and those it could not apply.+/// Unless `quiet`, also each occurrence's degrees of freedom and the occurrences fixed in place.+#[derive(Debug, Serialize, JsonSchema)]+pub struct SolveReport {+ /// The joints that disagree with the placement found through others.+ pub conflicts: Vec<JointProblem>,+ /// The joints that could not be applied (a lost origin, an expression that no longer works).+ pub errors: Vec<JointProblem>,+ /// Each occurrence's remaining degrees of freedom (6 free, 0 fixed). Left out with `quiet`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub dof: Option<Vec<OccurrenceDof>>,+ /// The occurrences fixed in place (grounded, or the root), by id. Left out with `quiet`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub fixed: Option<Vec<u64>>,+}++/// What `joint.limits` and `joint.solve` return: the solve.+#[derive(Debug, Serialize, JsonSchema)]+pub struct SolveResult {+ #[serde(flatten)]+ pub solved: SolveReport,+ /// 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>,+}++/// What `joint.create` and `joint.as_built` return: the solve after the joint is added.+#[derive(Debug, Serialize, JsonSchema)]+pub struct JointAddedResult {+ #[serde(flatten)]+ pub solved: SolveReport,+ /// The new joint, by id.+ pub joint: u64,+ /// Its name.+ pub name: String,+ /// A value that starts inside its limits, not where it was given: the part moved there as it+ /// was joined. Left out when there is none.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub warnings: Vec<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>,+}++/// The unit of a joint value.+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]+#[serde(rename_all = "lowercase")]+pub enum ValueUnit {+ /// Degrees: an angle.+ Deg,+ /// Millimetres: a distance.+ Mm,+}++/// One of a joint's values, as `joint.list` gives it (rounded for reading).+#[derive(Debug, Serialize, JsonSchema)]+pub struct NamedValue {+ /// The coordinate's name (angle, distance, slide, …).+ pub name: String,+ /// Its value, in `unit`.+ pub value: f64,+ /// `deg` for an angle, `mm` for a distance.+ pub unit: ValueUnit,+ /// Its limits [min, max] in `unit`, or `null` for none.+ pub limits: Option<[f64; 2]>,+}++/// A joint's type as the replies name it.+#[derive(Clone, Copy, Debug, PartialEq, Serialize, JsonSchema)]+#[serde(rename_all = "snake_case")]+pub enum JointKindName {+ Rigid,+ Revolute,+ Slider,+ Cylindrical,+ PinSlot,+ Planar,+ Ball,+ Parallel,+ Perpendicular,+ Angle,+ PointOnPlane,+ PointOnLine,+ LineOnPlane,+}++/// The expressions a joint's numbers follow, over the design's parameters.+#[derive(Debug, Serialize, JsonSchema)]+pub struct JointExpressions {+ /// The offset's expression.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub offset: Option<String>,+ /// The angle's expression.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub angle: Option<String>,+ /// The expression of each value by index, `null` for a value that is a number.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub values: Vec<Option<String>>,+}++/// A joint origin's snap as saved, in the component's coordinates.+pub struct SnapShape;++impl JsonSchema for SnapShape {+ fn schema_name() -> Cow<'static, str> {+ "Snap".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ let point = json!({"type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3});+ json_schema!({+ "description": "Where a joint origin sits on its component's geometry, as saved: `type` is frame, face_center, circle_center, edge or point, with the keys that type holds: origin, pick, point, z or x as [x, y, z] (x may also be a face reference), face, end, edge and corner as persistent names, and for an edge origin its axis.",+ "type": "object",+ "properties": {+ "type": {"enum": ["frame", "face_center", "circle_center", "edge", "point"]},+ "origin": point, "pick": point, "point": point, "z": point,+ "x": {"description": "A direction [x, y, z], or {face, pick?}: a face the turn is taken from."},+ "face": {"type": "string"}, "end": {"type": "string"}, "edge": {"type": "string"}, "corner": {"type": "string"},+ "axis": {"type": "object"}+ },+ "required": ["type"]+ })+ }+}++/// A motion link's coupling: the geometry its ratio comes from.+pub struct CouplingShape;++impl JsonSchema for CouplingShape {+ fn schema_name() -> Cow<'static, str> {+ "Coupling".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "What the link's ratio is worked out from: `type` is gear (ra, rb, internal?, reverse?), rack_pinion (radius, reverse?), screw (pitch, reverse?) or cam (profile, follower, tip?, reverse?), with the keys that type holds.",+ "type": "object",+ "properties": {"type": {"enum": ["gear", "rack_pinion", "screw", "cam"]}},+ "required": ["type"]+ })+ }+}++/// A cam's follower travel over one turn of the cam.+#[derive(Debug, Serialize, JsonSchema)]+pub struct CamLift {+ /// The follower's lowest value, in `unit`.+ pub min: f64,+ /// Its highest value.+ pub max: f64,+ /// `max` less `min`.+ pub rise: f64,+ /// `deg` for an oscillating follower, `mm` for a translating one.+ pub unit: ValueUnit,+}++/// A motion link, as `joint.list` and `joint.inspect` give it: b's value follows a's.+#[derive(Debug, Serialize, JsonSchema)]+pub struct LinkInfo {+ /// The driving joint, by id.+ pub a: u64,+ /// The driving value's index.+ pub ia: usize,+ /// The driven joint, by id.+ pub b: u64,+ /// The driven value's index.+ pub ib: usize,+ /// b's units per a's, per degree: b = ratio · a + offset. A cam has a `lift` instead.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub ratio: Option<f64>,+ /// In b's units (`unit`).+ pub offset: f64,+ /// b's unit.+ pub unit: ValueUnit,+ /// What the ratio is worked out from, for a gear, a rack and pinion, a screw or a cam.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "CouplingShape")]+ pub coupling: Option<Coupling>,+ /// Why the coupling can't be worked out now.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub error: Option<String>,+ /// A cam's follower travel: `null` when its table is not whole (a hand-edited file). Only for+ /// a cam.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub lift: Option<Option<CamLift>>,+}++/// A joint origin's frame in the world.+#[derive(Debug, Serialize, JsonSchema)]+pub struct JointFrame {+ /// The origin [x, y, z], in mm.+ pub origin: [f64; 3],+ /// The z axis [x, y, z].+ pub z: [f64; 3],+}++/// A joint as `joint.list` gives it.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ListedJoint {+ /// The joint, by id.+ pub id: u64,+ /// Its name.+ pub name: String,+ /// Its type.+ #[serde(rename = "type")]+ #[schemars(with = "JointKindName")]+ pub kind: JointKind,+ /// Side a's occurrence, by id.+ pub a: u64,+ /// Side b's occurrence, by id.+ pub b: u64,+ /// Its values as the solver places them (after motion links), with their limits.+ pub values: Vec<NamedValue>,+ /// Whether b's z lies along a's.+ pub flip: bool,+ /// The distance from a's frame to b's along z, in mm.+ pub offset: f64,+ /// Whether the joint is suppressed (it places nothing).+ pub suppressed: bool,+ /// Whether the joint is shown in the viewport.+ pub visible: bool,+ /// Side a's frame in the world, `null` when its origin is lost.+ pub frame_a: Option<JointFrame>,+ /// Side b's frame in the world, `null` when its origin is lost.+ pub frame_b: Option<JointFrame>,+ /// The expressions the joint follows. Left out when it has none.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "JointExpressions")]+ pub expressions: Option<JointExprs>,+}++/// A named joint origin.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ListedOrigin {+ /// Its name.+ pub name: String,+ /// The occurrence it is on, by id.+ pub occurrence: u64,+}++/// Joints joined to nothing grounded, which the solver places none of.+#[derive(Debug, Serialize, JsonSchema)]+pub struct FloatingChain {+ /// The chain's occurrences, by name.+ pub occurrences: Vec<String>,+ /// Its joints, by name. Driving them moves nothing.+ pub joints: Vec<String>,+}++/// What `joint.list` returns: the solve, then every joint, motion link and joint origin.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ListJointsResult {+ #[serde(flatten)]+ pub solved: SolveReport,+ /// Every joint.+ pub joints: Vec<ListedJoint>,+ /// Every motion link, by its index.+ pub links: Vec<LinkInfo>,+ /// Every named joint origin.+ pub origins: Vec<ListedOrigin>,+ /// Joint chains joined to nothing grounded.+ pub floating: Vec<FloatingChain>,+ /// 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>,+}++/// List the joints, motion links and joint origins, with the solve.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct ListJointsParams {+ /// Leave out `dof` and `fixed` in the reply. Default: false.+ #[serde(default)]+ pub quiet: Option<bool>,+}++/// Re-place the occurrences from the joints, and report conflicts, errors and degrees of freedom.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct SolveJointsParams {+ /// Leave out `dof` and `fixed` in the reply. Default: false.+ #[serde(default)]+ pub quiet: Option<bool>,+}++/// Say what a joint is defined by and attached to: its two origins (the snap as saved, and the+/// feature, face, edge or sketch curve each name refers to), whether each is found today and why+/// not, its type, offset, angle, flip, values, expressions and motion links. Reads only: nothing+/// changes.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct InspectJointParams {+ /// The joint, by id or name. Default: every joint.+ #[serde(default)]+ pub joint: Option<JointKey>,+}++/// What a face reference says about the feature that made the face.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(untagged)]+pub enum MadeBy {+ /// The feature.+ Feature {+ /// Its id.+ id: u64,+ /// Its name.+ name: String,+ /// Its type.+ #[serde(rename = "type")]+ kind: String,+ },+ /// The feature is gone.+ Gone {+ /// The id the name refers to.+ id: u64,+ /// Why there is none.+ error: String,+ },+}++/// The sketch curve a face was swept from.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(untagged)]+pub enum SweptFrom {+ /// The curve, in a sketch the feature takes.+ Curve {+ /// The sketch feature's id.+ id: u64,+ /// Its name.+ name: String,+ /// The curve's id in the sketch.+ curve: String,+ /// The curve's type (line, arc, circle, …).+ curve_type: Option<String>,+ },+ /// No sketch of the feature has the curve.+ Missing {+ /// The curve's id.+ curve: String,+ /// Why there is no such curve.+ error: String,+ },+}++/// What a face's persistent name refers to.+#[derive(Debug, Serialize, JsonSchema)]+pub struct FaceReference {+ /// The persistent name, as saved.+ pub name: String,+ /// A name saved before exact names, so it may not be found again.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub unverified: Option<bool>,+ /// What the face is in the feature that made it (top, side:c1, …).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub role_in_feature: Option<String>,+ /// The feature that made the face.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub feature: Option<MadeBy>,+ /// The sketch curve a side face was swept from.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub sketch: Option<SweptFrom>,+}++/// What an edge's persistent name refers to: its two faces.+#[derive(Debug, Serialize, JsonSchema)]+pub struct EdgeReference {+ /// The persistent name, as saved.+ pub name: String,+ /// What each of the edge's faces refers to.+ pub faces: Vec<FaceReference>,+ /// A name saved before exact names.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub unverified: Option<bool>,+}++/// What a reference names.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(untagged)]+pub enum Referent {+ /// A face.+ Face(FaceReference),+ /// An edge.+ Edge(EdgeReference),+}++/// What part of the snap a reference is.+#[derive(Clone, Copy, Debug, PartialEq, Serialize, JsonSchema)]+#[serde(rename_all = "lowercase")]+pub enum ReferenceRole {+ /// The face the origin is on.+ Face,+ /// A round origin's end face.+ End,+ /// The face its x axis is taken from.+ X,+ /// The edge an edge origin is on.+ Edge,+ /// The edge that gives an edge origin's corner.+ Corner,+}++/// A persistent name a joint origin holds, with what it refers to.+#[derive(Debug, Serialize, JsonSchema)]+pub struct Reference {+ /// The part of the snap that holds the name.+ pub role: ReferenceRole,+ #[serde(flatten)]+ pub to: Referent,+}++/// A joint origin's frame in the world.+#[derive(Debug, Serialize, JsonSchema)]+pub struct WorldFrame {+ /// The origin [x, y, z], in mm.+ pub origin: [f64; 3],+ /// The z axis [x, y, z].+ pub z: [f64; 3],+ /// The x axis [x, y, z].+ pub x: [f64; 3],+}++/// One of a joint's origins.+#[derive(Debug, Serialize, JsonSchema)]+pub struct JointSide {+ /// The occurrence the origin is on, by id (0 is the root).+ pub occurrence: u64,+ /// Its name (`root` for the root).+ pub occurrence_name: String,+ /// The component it places, by id.+ pub component: u64,+ /// The component's name (`root` for the root).+ pub component_name: String,+ /// The occurrence names from the top of the assembly down, with `/` between.+ pub path: String,+ /// The snap as saved, in the component's coordinates.+ #[schemars(with = "SnapShape")]+ pub snap: Snap,+ /// The persistent names the snap holds.+ pub references: Vec<Reference>,+ /// Whether the origin is found now.+ pub resolves: bool,+ /// Where it is in the world. Left out when it is not found.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub frame: Option<WorldFrame>,+ /// Why the origin is lost. Left out when it is found.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub error: Option<String>,+}++/// Which end of a motion link a joint is.+#[derive(Clone, Copy, Debug, PartialEq, Serialize, JsonSchema)]+#[serde(rename_all = "lowercase")]+pub enum LinkRole {+ /// The joint drives the link.+ Driver,+ /// The joint is driven by it.+ Driven,+}++/// A motion link a joint takes part in.+#[derive(Debug, Serialize, JsonSchema)]+pub struct JointLink {+ /// The link's index.+ pub index: usize,+ /// Whether the joint drives it or is driven by it.+ pub role: LinkRole,+ #[serde(flatten)]+ pub link: LinkInfo,+}++/// A joint as `joint.inspect` gives it.+#[derive(Debug, Serialize, JsonSchema)]+pub struct InspectedJoint {+ /// The joint, by id.+ pub id: u64,+ /// Its name.+ pub name: String,+ /// Its type.+ #[serde(rename = "type")]+ #[schemars(with = "JointKindName")]+ pub kind: JointKind,+ /// Whether the joint is suppressed.+ pub suppressed: bool,+ /// Whether the joint is shown in the viewport.+ pub visible: bool,+ /// Whether b's z lies along a's.+ pub flip: bool,+ /// The distance from a's frame to b's along z, in mm.+ pub offset: f64,+ /// The turn about that distance, in degrees.+ pub angle: f64,+ /// Its values as the solver places them, as joint.list gives them.+ pub values: Vec<NamedValue>,+ /// The names of its coordinates.+ pub dofs: Vec<String>,+ /// Side a.+ pub a: JointSide,+ /// Side b.+ pub b: JointSide,+ /// The motion links it takes part in.+ pub links: Vec<JointLink>,+ /// Why the solve could not apply it.+ pub errors: Vec<String>,+ /// Where it disagrees with the placement found through other joints.+ pub conflicts: Vec<String>,+ /// The expressions it follows. Left out when it has none.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "JointExpressions")]+ pub expressions: Option<JointExprs>,+}++/// What `joint.inspect` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct InspectJointResult {+ /// The joint asked for, or every joint.+ pub joints: Vec<InspectedJoint>,+ /// 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>,+}++/// One driven value that ended up elsewhere than asked.+#[derive(Debug, Serialize, JsonSchema)]+pub struct HeldValue {+ /// The coordinate's name.+ pub name: String,+ /// The value asked for, in `unit`.+ pub requested: f64,+ /// The value it has, in `unit`.+ pub value: f64,+ /// `deg` or `mm`.+ pub unit: ValueUnit,+ /// Why: a motion link sets it, a limit holds it, contact or a closed loop stopped it.+ pub why: String,+}++/// Where contact stopped a drive.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]+pub struct ContactStop {+ /// One of the bodies that touch.+ pub a: String,+ /// The other.+ pub b: String,+ /// How far from the start to the asked-for values the drive got (0 to 1).+ pub fraction: f64,+}++/// Where a closed loop stopped a drive.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]+pub struct LoopStop {+ /// The joint whose loop opens first, by name.+ pub joint: String,+ /// How far from the start to the asked-for values the drive got (0 to 1).+ pub fraction: f64,+}++/// What `joint.drive` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct DriveJointResult {+ #[serde(flatten)]+ pub solved: SolveReport,+ /// The joint driven, by id.+ pub joint: u64,+ /// Its values now, as joint.list gives them.+ pub values: Option<Vec<NamedValue>>,+ /// True for a `continuous` call; left out otherwise.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub continuous: Option<bool>,+ /// The bodies that touched, when contact stopped the drive short; `null` otherwise.+ pub stopped_by_contact: Option<ContactStop>,+ /// The closed loop that stopped the drive short; `null` otherwise.+ pub stopped_by_loop: Option<LoopStop>,+ /// Whether any occurrence moved.+ pub moved: bool,+ /// The values asked for, in the same form as `values`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub requested: Option<Vec<NamedValue>>,+ /// Each driven value that ended up elsewhere than asked, and why. Left out when there is none.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub held: Option<Vec<HeldValue>>,+ /// Why the joint can move nothing: it is suppressed, its origins are lost, its chain joins+ /// nothing grounded, or, when nothing moved, the first held value's reason.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reason: Option<String>,+ /// The occurrence joined to nothing grounded, when that is the reason.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub unconnected: Option<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>,+}++/// What `joint.delete` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct DeleteJointResult {+ #[serde(flatten)]+ pub deleted: JointDeleted,+ /// 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>,+}++/// What was deleted.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(untagged)]+pub enum JointDeleted {+ /// A joint origin (`origin`).+ Origin {+ /// The origin's name.+ deleted_origin: String,+ /// How many joints there are (the joints are not deleted with it).+ joints: usize,+ },+ /// A motion link (`link`).+ Link {+ /// The link's index.+ deleted_link: usize,+ },+ /// A joint, with the motion links it was in; the rest is re-solved.+ Joint {+ #[serde(flatten)]+ solved: SolveReport,+ /// The joint's id.+ deleted: u64,+ },+}+#[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.rsindex 5fc406abcf..298b9ea564 100644--- a/crates/engine/src/schema/joints_tests.rs+++ b/crates/engine/src/schema/joints_tests.rs@@ -1,27 +1,707 @@-use serde_json::json;+use serde_json::{Value, json};+use solidcore_record::Vec3;+use solidcraft_doc::joints::JointKind;-use super::{EditJointParams, EditJointResult};+use super::{+ AsBuiltJointParams, CreateJointParams, DeleteJointParams, DeleteJointResult, DriveJointParams, DriveJointResult, EditJointParams,+ InspectJointParams, InspectJointResult, JointAddedResult, JointKindName, JointLimitsParams, ListJointsParams, ListJointsResult,+ SolveJointsParams, SolveResult,+};use crate::Session;-use crate::schema::tests::{assert_keys, conforms};-use crate::schema::{input_schema_for, output_schema_for};+use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};+use crate::schema::{ParamCheck, input_schema_for, output_schema_for};#[test]fn schemas_and_the_key_check_agree() {assert_keys(input_schema_for::<EditJointParams>(), &["a", "angle", "b", "flip", "joint", "name", "offset", "quiet", "suppressed", "type"]);+ assert_keys(+ input_schema_for::<CreateJointParams>(),+ &["a", "angle", "b", "flip", "limits", "name", "offset", "quiet", "type", "value", "values"],+ );+ assert_keys(input_schema_for::<AsBuiltJointParams>(), &["a", "at", "b", "limits", "name", "quiet", "type", "value", "values"]);+ assert_keys(input_schema_for::<DriveJointParams>(), &["continuous", "index", "joint", "quiet", "value", "values"]);+ assert_keys(input_schema_for::<JointLimitsParams>(), &["index", "joint", "max", "min", "quiet"]);+ assert_keys(input_schema_for::<DeleteJointParams>(), &["joint", "link", "origin", "quiet"]);+ assert_keys(input_schema_for::<ListJointsParams>(), &["quiet"]);+ assert_keys(input_schema_for::<InspectJointParams>(), &["joint"]);+ assert_keys(input_schema_for::<SolveJointsParams>(), &["quiet"]);}#[test]-fn replies_match_the_output_schema() {- let schema = output_schema_for::<EditJointResult>();+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"] {+ let spec = crate::cmd::find_command(id).unwrap_or_else(|| panic!("{id}"));+ assert!(spec.contract.is_some() && spec.output.is_some(), "{id}");+ }+}++/// The replies name a joint's type as the document does.+#[test]+fn every_joint_type_has_its_reply_name() {+ let names = output_schema_for::<JointKindName>();+ let names: Vec<&str> = names.as_value()["oneOf"]+ .as_array()+ .into_iter()+ .flatten()+ .chain(names.as_value()["enum"].as_array().into_iter().flatten())+ .filter_map(|v| v.get("const").or(Some(v)).and_then(Value::as_str))+ .collect();+ for spelling in [+ "rigid",+ "revolute",+ "slider",+ "cylindrical",+ "pin_slot",+ "planar",+ "ball",+ "parallel",+ "perpendicular",+ "angle",+ "point_on_plane",+ "point_on_line",+ "line_on_plane",+ ] {+ let kind = JointKind::parse(spelling).unwrap_or_else(|| panic!("{spelling}"));+ assert_eq!(serde_json::to_value(kind).ok(), Some(json!(spelling)));+ assert!(names.contains(&spelling), "{spelling} in {names:?}");+ }+}++#[test]+fn strict_keeps_todays_errors() {+ let at = |o: u64, x: f64| json!({"occurrence": o, "point": [x, 0, 0]});+ assert_strict_keeps_todays_errors(&[+ ("joint.create", json!({})),+ ("joint.create", json!({"type": "nope"})),+ ("joint.create", json!({"type": 5})),+ ("joint.create", json!({"type": null})),+ ("joint.create", json!({"type": "rigid"})),+ ("joint.create", json!({"type": "rigid", "a": 5, "b": at(0, 1.0)})),+ ("joint.create", json!({"type": "rigid", "a": null, "b": at(0, 1.0)})),+ ("joint.create", json!({"type": "rigid", "a": {}, "b": at(0, 1.0)})),+ ("joint.create", json!({"type": "rigid", "a": {"frame": 1}, "b": at(0, 1.0)})),+ ("joint.create", json!({"type": "rigid", "a": {"face": [1, 2]}, "b": at(0, 1.0)})),+ ("joint.create", json!({"type": "rigid", "a": at(0, 0.0)})),+ ("joint.create", json!({"type": "rigid", "a": at(0, 0.0), "b": at(0, 1.0), "offset": true})),+ ("joint.create", json!({"type": "rigid", "a": at(0, 0.0), "b": at(0, 1.0), "offset": null})),+ ("joint.create", json!({"type": "rigid", "a": at(0, 0.0), "b": at(0, 1.0), "angle": [1]})),+ ("joint.create", json!({"type": "revolute", "a": at(0, 0.0), "b": at(0, 1.0), "values": [true]})),+ ("joint.create", json!({"type": "revolute", "a": at(0, 0.0), "b": at(0, 1.0), "value": {}})),+ ("joint.create", json!({"type": "revolute", "a": at(0, 0.0), "b": at(0, 1.0), "values": [1e12]})),+ ("joint.create", json!({"type": "revolute", "a": at(0, 0.0), "b": at(0, 1.0), "limits": [[true, 1]]})),+ ("joint.create", json!({"type": "revolute", "a": at(0, 0.0), "b": at(0, 1.0), "limits": [[0, 1e12]]})),+ ("joint.as_built", json!({})),+ ("joint.as_built", json!({"type": "rigid"})),+ ("joint.as_built", json!({"type": "rigid", "a": true, "b": 0})),+ ("joint.as_built", json!({"type": "rigid", "a": 0, "b": null})),+ ("joint.as_built", json!({"type": "rigid", "a": [1], "b": 0})),+ ("joint.as_built", json!({"type": "rigid", "a": 0, "b": 0, "at": null})),+ ("joint.as_built", json!({"type": "rigid", "a": 0, "b": 0, "at": 3})),+ ("joint.as_built", json!({"type": "rigid", "a": 0, "b": 0, "at": {"frame": {}}})),+ ("joint.as_built", json!({"type": "revolute", "a": 0, "b": 0, "limits": [[true, 1]]})),+ ("joint.drive", json!({})),+ ("joint.drive", json!({"joint": true})),+ ("joint.drive", json!({"joint": null})),+ ("joint.drive", json!({"joint": [1]})),+ ("joint.limits", json!({})),+ ("joint.limits", json!({"joint": {}})),+ ("joint.delete", json!({})),+ ("joint.delete", json!({"joint": true})),+ ("joint.delete", json!({"joint": null})),+ ("joint.delete", json!({"origin": "nothing"})),+ ("joint.delete", json!({"link": 4})),+ ("joint.delete", json!({"link": null})),+ ("joint.inspect", json!({"joint": true})),+ ("joint.inspect", json!({"joint": [1]})),+ ]);+}++/// A design with a grounded plate and a hinged leaf, a joint origin, and a third part joined as+/// built, for the calls that need joints to fail on.+fn hinged(level: ParamCheck) -> Session {+ let mut s = Session { param_check: level, ..Session::default() };+ let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));+ for name in ["LeafA", "LeafB"] {+ run("component.activate", json!({"component": "root"}));+ let made = run("component.create", json!({"name": name, "grounded": false}));+ run("solid.box", json!({"length": 40, "width": 30, "height": 3, "corner": [0, 0, 0]}));+ run("solid.cylinder", json!({"base": [0, 33, 4], "axis": [1, 0, 0], "radius": 4, "height": 40, "operation": "new"}));+ if name == "LeafA" {+ run("occurrence.ground", json!({"occurrence": made["occurrence"], "grounded": true}));+ }+ }+ run(+ "joint.create",+ json!({"type": "revolute", "a": {"occurrence": "LeafA", "circle": [1, 37, 4]}, "b": {"occurrence": "LeafB", "circle": [1, 37, 4]},+ "flip": true, "name": "Hinge", "limits": [[-90, 90]]}),+ );+ run("joint.origin", json!({"occurrence": "LeafA", "face": [20, 15, 3], "name": "Top"}));+ s+}++/// What the handlers refuse, with a joint in the design to refuse it for: strict says the same.+#[test]+fn strict_keeps_todays_errors_with_joints() {+ let cases = [+ ("joint.drive", json!({"joint": "Hinge"})),+ ("joint.drive", json!({"joint": "Hinge", "value": true})),+ ("joint.drive", json!({"joint": "Hinge", "values": [true]})),+ ("joint.drive", json!({"joint": "Hinge", "values": [1e12]})),+ ("joint.drive", json!({"joint": "Hinge", "index": null, "value": 5})),+ ("joint.drive", json!({"joint": "Hinge", "index": "0", "value": 5})),+ ("joint.drive", json!({"joint": "Hinge", "index": -1, "value": 5})),+ ("joint.drive", json!({"joint": "Hinge", "index": 0, "values": [5]})),+ ("joint.drive", json!({"joint": "Hinge", "index": 0, "values": null, "value": 5})),+ ("joint.drive", json!({"joint": "Hinge", "index": 0, "value": null})),+ ("joint.drive", json!({"joint": "Hinge", "index": 0, "value": "1 +"})),+ ("joint.limits", json!({"joint": "Hinge", "min": 1})),+ ("joint.limits", json!({"joint": "Hinge", "max": 1})),+ ("joint.limits", json!({"joint": "Hinge", "min": null, "max": 1})),+ ("joint.limits", json!({"joint": "Hinge", "min": 1, "max": true})),+ ("joint.limits", json!({"joint": "Hinge", "min": true, "max": 1})),+ ("joint.limits", json!({"joint": "Hinge", "min": 1e12, "max": 1})),+ ("joint.limits", json!({"joint": "Hinge", "index": 3, "min": 1, "max": 2})),+ ("joint.delete", json!({"joint": "Hinge", "origin": "Missing"})),+ ("joint.delete", json!({"link": 7, "joint": "Hinge"})),+ ("joint.create", json!({"type": "rigid", "a": "Top", "b": "Top"})),+ ("joint.create", json!({"type": "rigid", "a": "Missing", "b": "Top"})),+ ("joint.as_built", json!({"type": "rigid", "a": "LeafA", "b": "LeafA"})),+ ("joint.as_built", json!({"type": "rigid", "a": "LeafA", "b": "Missing"})),+ ("joint.inspect", json!({"joint": "Missing"})),+ ];+ for (id, p) in cases {+ let off = hinged(ParamCheck::Off).execute(id, &p).err().map(|e| e.to_string());+ assert!(off.is_some(), "{id} {p} should fail today");+ assert_eq!(hinged(ParamCheck::Strict).execute(id, &p).err().map(|e| e.to_string()), off, "{id} {p}");+ }+}++fn issues(id: &str, p: Value) -> Vec<String> {+ crate::schema::issues(id, &p).into_iter().map(|i| i.message).collect()+}++/// The types read each key as its handler does, and in the cases the handler reads it.+#[test]+fn the_types_read_each_key_as_the_handlers_do() {+ let none = Vec::<String>::new;+ let sides = json!({"a": {"occurrence": 0, "point": [0, 0, 0]}, "b": "Origin"});+ let create = |extra: Value| {+ let mut p = json!({"type": "revolute"});+ p.as_object_mut().into_iter().for_each(|o| {+ o.extend(sides.as_object().cloned().unwrap_or_default());+ o.extend(extra.as_object().cloned().unwrap_or_default());+ });+ issues("joint.create", p)+ };+ // The forms of a side, and the key left out, which the handler refuses with its own message.+ assert_eq!(create(json!({})), none());+ for side in [+ json!("Name"),+ json!({"face": "F1"}),+ json!({"circle": "F1", "occurrence": "A"}),+ json!({"face": [0, 0, 0]}),+ json!({"edge": {"x": 0, "y": 0, "z": 0}, "z": [0, 0, 1]}),+ json!({"point": [1, 2, 3], "x": [1, 0, 0]}),+ json!({"frame": {"origin": [0, 0, 0], "z": [0, 0, 1]}}),+ ] {+ assert_eq!(create(json!({"a": side})), none(), "{side}");+ }+ assert_eq!(issues("joint.create", json!({"type": "rigid"})), none());+ let why = "a joint origin needs face, circle, edge, point or frame [x, y, z], or a face's name";+ for side in [json!(5), json!(null), json!([1, 2, 3]), json!({}), json!({"face": [1, 2]}), json!({"face": 7})] {+ assert_eq!(create(json!({"a": side})), [why], "{side}");+ }+ assert_eq!(create(json!({"b": {"frame": {"z": [0, 0, 1]}}})), ["`frame` needs origin and z"]);+ // The type: any spelling `JointKind::parse` takes.+ for t in ["Revolute", "pin-slot", "POINT ON PLANE", "rotate", "square"] {+ assert_eq!(issues("joint.create", json!({"type": t, "a": "A", "b": "B"})), none(), "{t}");+ }+ assert_eq!(issues("joint.create", json!({"type": "hinge", "a": "A", "b": "B"})).len(), 1);+ // `value` is read only when `values` is not a list; `values` and `limits` only as lists.+ assert_eq!(create(json!({"values": [1, "w / 2"], "value": true})), none());+ assert_eq!(create(json!({"value": true})), ["a joint value must be a number or an expression"]);+ assert_eq!(create(json!({"value": "5 mm"})), none());+ assert_eq!(create(json!({"values": null, "value": 4})), none());+ assert_eq!(create(json!({"values": [true]})), ["a joint value must be a number or an expression"]);+ assert_eq!(create(json!({"values": [1e12]})), ["a joint value must be a number between -1e9 and 1e9"]);+ assert_eq!(create(json!({"values": 5})), ["`values` must be a list of joint values"]);+ for limits in [json!([[0, 90]]), json!([null, ["-1 mm", "w"]]), json!([[1]]), json!([[]]), json!([[0, 1, true]]), json!(null), json!([])] {+ assert_eq!(create(json!({"limits": limits})), none(), "{limits}");+ }+ for limits in [json!([[true, 1]]), json!([[0, {}]]), json!([5]), json!({"a": 1}), json!("x")] {+ assert_eq!(create(json!({"limits": limits})).len(), 1, "{limits}");+ }+ // Numbers: `offset` and `angle` read `null` as a value, the flags and the name as absent.+ assert_eq!(create(json!({"offset": "w", "angle": 30, "flip": true, "name": "J", "quiet": false})), none());+ assert_eq!(create(json!({"offset": null})), ["a joint value must be a number or an expression"]);+ assert_eq!(create(json!({"angle": {}})), ["a joint value must be a number or an expression"]);+ assert_eq!(create(json!({"flip": null, "name": null, "quiet": null})), none());+ assert_eq!(create(json!({"flip": "yes"})), ["`flip` must be true or false"]);+ assert_eq!(create(json!({"name": 3})), ["`name` must be text"]);+ assert_eq!(create(json!({"quiet": 1})), ["`quiet` must be true or false"]);+ assert_eq!(create(json!({"nme": "J"})), ["unknown key `nme`; did you mean `name`?"]);++ // joint.as_built: occurrences by id or name, `at` a joint origin, `values` only by being there.+ let built = |extra: Value| {+ let mut p = json!({"type": "rigid", "a": 0, "b": "Part"});+ p.as_object_mut().into_iter().for_each(|o| o.extend(extra.as_object().cloned().unwrap_or_default()));+ issues("joint.as_built", p)+ };+ assert_eq!(built(json!({})), none());+ assert_eq!(built(json!({"at": {"face": "F"}, "name": "N", "limits": [[0, 1]], "quiet": true, "values": "anything", "value": {"x": 1}})), none());+ assert_eq!(built(json!({"a": true})), ["an occurrence must be an id or a name"]);+ assert_eq!(built(json!({"b": null})), ["an occurrence must be an id or a name"]);+ assert_eq!(built(json!({"at": null})), [why]);+ assert_eq!(built(json!({"at": []})), [why]);+ assert_eq!(issues("joint.as_built", json!({"type": "rigid"})), none());++ // joint.drive: one coordinate with `index`, else `value` or a list of `values`.+ let drive = |p: Value| {+ let mut all = json!({"joint": "Hinge"});+ all.as_object_mut().into_iter().for_each(|o| o.extend(p.as_object().cloned().unwrap_or_default()));+ issues("joint.drive", all)+ };+ assert_eq!(drive(json!({"value": 45})), none());+ assert_eq!(drive(json!({"value": "pi rad", "quiet": true, "continuous": true})), none());+ assert_eq!(drive(json!({"values": [10, "w"]})), none());+ assert_eq!(drive(json!({"values": [10], "value": true})), none());+ assert_eq!(drive(json!({"values": null, "value": 5})), none());+ assert_eq!(drive(json!({})), none());+ assert_eq!(drive(json!({"index": 1, "value": 5})), none());+ assert_eq!(drive(json!({"index": 1, "value": 5, "values": [1]})), ["index goes with value, not values"]);+ assert_eq!(drive(json!({"index": 1, "values": null})), ["index goes with value, not values"]);+ assert_eq!(drive(json!({"index": 1})), none());+ assert_eq!(drive(json!({"index": "1", "value": 5})), ["index is outside this joint's coordinates"]);+ assert_eq!(drive(json!({"index": null, "value": 5})), ["index is outside this joint's coordinates"]);+ assert_eq!(drive(json!({"index": -1, "value": 5})), ["index is outside this joint's coordinates"]);+ assert_eq!(drive(json!({"index": 0, "value": true})), ["a joint value must be a number or an expression"]);+ assert_eq!(drive(json!({"value": null})), ["a joint value must be a number or an expression"]);+ assert_eq!(drive(json!({"values": [null]})), ["a joint value must be a number or an expression"]);+ assert_eq!(drive(json!({"values": "x"})), ["`values` must be a list of joint values"]);+ assert_eq!(issues("joint.drive", json!({"value": 1})), none());+ assert_eq!(issues("joint.drive", json!({"joint": null, "value": 1})), ["`joint` must be an id or a name"]);+ assert_eq!(issues("joint.drive", json!({"joint": 3, "value": 1})), none());++ // joint.limits: both or neither, the minimum read first; `index` a number.+ let limits = |p: Value| {+ let mut all = json!({"joint": 2});+ all.as_object_mut().into_iter().for_each(|o| o.extend(p.as_object().cloned().unwrap_or_default()));+ issues("joint.limits", all)+ };+ assert_eq!(limits(json!({})), none());+ assert_eq!(limits(json!({"min": -90, "max": "w / 2", "index": 0, "quiet": true})), none());+ assert_eq!(limits(json!({"index": -3.5})), none());+ assert_eq!(limits(json!({"min": 1})), ["give both `min` and `max`, or neither to clear"]);+ assert_eq!(limits(json!({"max": null})), ["give both `min` and `max`, or neither to clear"]);+ assert_eq!(limits(json!({"min": null, "max": 1})), ["a joint value must be a number or an expression"]);+ assert_eq!(limits(json!({"min": 0, "max": true})), ["a joint value must be a number or an expression"]);+ assert_eq!(limits(json!({"index": "0"})), ["`index` must be a number"]);+ assert_eq!(limits(json!({"index": null})), none());++ // joint.delete: a joint origin's name, else a motion link, else a joint; each mode reads only+ // its own keys.+ assert_eq!(issues("joint.delete", json!({"origin": "Top"})), none());+ assert_eq!(issues("joint.delete", json!({"origin": "Top", "joint": true, "link": "x", "quiet": 5})), none());+ assert_eq!(issues("joint.delete", json!({"link": 1})), none());+ assert_eq!(issues("joint.delete", json!({"link": 1, "joint": [1], "quiet": "no"})), none());+ assert_eq!(issues("joint.delete", json!({"link": 1e12, "joint": "Hinge"})), none());+ assert_eq!(issues("joint.delete", json!({"joint": "Hinge", "quiet": true})), none());+ assert_eq!(issues("joint.delete", json!({"origin": null, "link": null, "joint": 4})), none());+ assert_eq!(issues("joint.delete", json!({})), none());+ assert_eq!(issues("joint.delete", json!({"joint": true})), ["`joint` must be an id or a name"]);+ assert_eq!(issues("joint.delete", json!({"link": 1e12, "joint": true})), ["`joint` must be an id or a name"]);+ assert_eq!(issues("joint.delete", json!({"joint": 1, "quiet": 5})), ["`quiet` must be true or false"]);+ assert_eq!(issues("joint.delete", json!({"origin": 5, "joint": 1})), ["`origin` must be the name of a joint origin"]);+ assert_eq!(issues("joint.delete", json!({"link": "1", "joint": 1})), ["`link` must be a motion link's index, a number"]);++ // joint.list, joint.solve and joint.inspect.+ for id in ["joint.list", "joint.solve"] {+ assert_eq!(issues(id, json!({"quiet": true})), none());+ assert_eq!(issues(id, json!({"quiet": null})), none());+ assert_eq!(issues(id, json!({"quiet": "x"})), ["`quiet` must be true or false"]);+ assert_eq!(issues(id, json!({"quet": true})), ["unknown key `quet`; did you mean `quiet`?"]);+ }+ assert_eq!(issues("joint.inspect", json!({})), none());+ assert_eq!(issues("joint.inspect", json!({"joint": null})), none());+ assert_eq!(issues("joint.inspect", json!({"joint": 4})), none());+ assert_eq!(issues("joint.inspect", json!({"joint": "Hinge"})), none());+ assert_eq!(issues("joint.inspect", json!({"joint": false})), ["`joint` must be an id or a name"]);+}++/// The schemas say what the handlers need: the keys a handler refuses without are required, the+/// modes are shown, and the values a handler reads are the ones the schemas take.+#[test]+fn the_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}");+ }+ };+ let sides = json!({"a": {"face": [0, 0, 0]}, "b": "Origin"});+ let mut full = sides.clone();+ full["type"] = json!("revolute");+ let with = |extra: Value| {+ let mut p = full.clone();+ p.as_object_mut().into_iter().for_each(|o| o.extend(extra.as_object().cloned().unwrap_or_default()));+ p+ };+ takes(+ input_schema_for::<CreateJointParams>(),+ &[+ (full.clone(), true),+ (with(json!({"values": [1, "w"], "limits": [[0, 90], null], "flip": true, "offset": "w", "angle": 5, "name": "J", "quiet": true})), true),+ (with(json!({"value": 3})), true),+ (+ json!({"type": "revolute", "a": {"edge": {"x": 0, "y": 0, "z": 0}, "z": {"x": 0, "y": 0, "z": 1}}, "b": {"point": {"x": 1, "y": 2, "z": 3}}}),+ true,+ ),+ (json!({"type": "revolute", "a": {"edge": {"x": 0, "y": 0}}, "b": "Origin"}), false),+ (json!({"a": {"face": [0, 0, 0]}, "b": "Origin"}), false),+ (json!({"type": "revolute", "b": "Origin"}), false),+ (json!({"type": "revolute", "a": 5, "b": "Origin"}), false),+ (with(json!({"values": 5})), false),+ // The schema can't spell the type's leniency; the type refuses "hinge" (see above).+ (with(json!({"type": 5})), false),+ (with(json!({"type": "Pin Slot"})), true),+ (with(json!({"type": "REVOLUTE"})), true),+ (with(json!({"offset": true})), false),+ (with(json!({"limits": [[true, 1]]})), false),+ (with(json!({"nme": "J"})), false),+ ],+ );+ takes(+ input_schema_for::<AsBuiltJointParams>(),+ &[+ (json!({"type": "rigid", "a": 0, "b": "Part"}), true),+ (json!({"type": "rigid", "a": "A", "b": 3, "at": {"circle": [0, 0, 0]}, "limits": [null], "values": [1]}), true),+ (json!({"type": "rigid", "a": 0}), false),+ (json!({"type": "rigid", "a": true, "b": 0}), false),+ ],+ );+ takes(+ input_schema_for::<DriveJointParams>(),+ &[+ (json!({"joint": "Hinge", "value": 45}), true),+ (json!({"joint": 1, "values": [1, "w"], "quiet": true, "continuous": true}), true),+ (json!({"joint": 1, "index": 1, "value": "w"}), true),+ (json!({"value": 45}), false),+ (json!({"joint": "Hinge"}), false),+ (json!({"joint": "Hinge", "index": 0, "values": [1]}), false),+ (json!({"joint": "Hinge", "index": -1, "value": 1}), false),+ ],+ );+ takes(+ input_schema_for::<JointLimitsParams>(),+ &[+ (json!({"joint": "Hinge"}), true),+ (json!({"joint": 1, "index": 1, "min": -1, "max": "w"}), true),+ (json!({"index": 1}), false),+ (json!({"joint": 1, "min": true, "max": 1}), false),+ ],+ );+ takes(+ input_schema_for::<DeleteJointParams>(),+ &[+ (json!({"joint": "Hinge", "quiet": true}), true),+ (json!({"origin": "Top"}), true),+ (json!({"link": 2}), true),+ (json!({}), false),+ (json!({"quiet": true}), false),+ (json!({"joint": true}), false),+ ],+ );+ takes(+ input_schema_for::<InspectJointParams>(),+ &[(json!({}), true), (json!({"joint": "J"}), true), (json!({"joint": 4}), true), (json!({"joint": true}), false)],+ );+ takes(input_schema_for::<ListJointsParams>(), &[(json!({}), true), (json!({"quiet": false}), true), (json!({"quiet": 1}), false)]);+ takes(input_schema_for::<SolveJointsParams>(), &[(json!({}), true), (json!({"quiet": false}), true), (json!({"quiet": 1}), false)]);+}++fn matches(schema: schemars::Schema, id: &str, reply: &Value) {let schema = schema.as_value();- let mut s = Session::default();- s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap_or_else(|e| panic!("{e}"));- s.execute("component.create", &json!({"name": "B", "grounded": false})).unwrap_or_else(|e| panic!("{e}"));- s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0]})).unwrap_or_else(|e| panic!("{e}"));- s.execute("joint.create", &json!({"type": "rigid", "name": "Stack", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}}))- .unwrap_or_else(|e| panic!("{e}"));- let full = s.execute("joint.edit", &json!({"joint": "Stack", "flip": true})).unwrap_or_else(|e| panic!("{e}"));- assert!(conforms(schema, schema, &full), "{full} doesn't match {schema}");- let quiet = s.execute("joint.edit", &json!({"joint": "Stack", "quiet": true})).unwrap_or_else(|e| panic!("{e}"));- assert!(quiet.get("dof").is_none() && conforms(schema, schema, &quiet), "{quiet}");+ assert!(conforms(schema, schema, reply), "{id}: {reply} doesn't match {schema}");+ assert!(reply.get("param_warnings").is_none(), "{id}: {reply}");+}++/// Hinge leaves, a slider, a screw, a joint origin and two loose parts joined to each other: each+/// command, run in Warn in every form it takes, gives a reply that matches its output schema and+/// carries no warning.+#[test]+fn replies_match_the_output_schema() {+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };+ let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));+ for name in ["LeafA", "LeafB", "LeafC", "LeafD", "LeafE"] {+ run("component.activate", json!({"component": "root"}));+ let made = run("component.create", json!({"name": name, "grounded": false}));+ run("solid.box", json!({"length": 40, "width": 30, "height": 3, "corner": [0, 0, 0]}));+ run("solid.cylinder", json!({"base": [0, 33, 4], "axis": [1, 0, 0], "radius": 4, "height": 40, "operation": "new"}));+ if name == "LeafA" {+ run("occurrence.ground", json!({"occurrence": made["occurrence"], "grounded": true}));+ }+ }+ let hinge = |a: &str, b: &str, name: &str| json!({"type": "revolute", "a": {"occurrence": a, "circle": [1, 37, 4]}, "b": {"occurrence": b, "circle": [1, 37, 4]}, "flip": true, "name": name});++ // joint.create, in the forms of a side, with a value held inside its limits, and as built.+ let made = run("joint.create", with_limits(hinge("LeafA", "LeafB", "Hinge"), json!([[-90, 90]])));+ matches(output_schema_for::<JointAddedResult>(), "joint.create", &made);+ assert!(made.get("warnings").is_none() && made["name"] == "Hinge" && made.get("dof").is_some(), "{made}");+ let quiet = run("joint.create", with_extra(hinge("LeafC", "LeafB", "Quiet"), json!({"quiet": true, "value": 30, "limits": [null]})));+ matches(output_schema_for::<JointAddedResult>(), "joint.create", &quiet);+ assert!(quiet.get("dof").is_none() && quiet.get("fixed").is_none(), "{quiet}");+ run("joint.delete", json!({"joint": "Quiet"}));+ let clamped = run("joint.create", with_extra(hinge("LeafD", "LeafE", "Clamped"), json!({"values": [100], "limits": [[-10, 10]]})));+ assert!(clamped["warnings"].as_array().is_some_and(|w| w.len() == 1), "{clamped}");+ matches(output_schema_for::<JointAddedResult>(), "joint.create", &clamped);+ run("joint.origin", json!({"occurrence": "LeafA", "face": [20, 15, 3], "name": "Top"}));+ let by_origin = run(+ "joint.create",+ json!({"type": "rigid", "a": "Top", "b": {"occurrence": "LeafC", "face": [20, 15, 0]}, "name": "Stack", "offset": "0 mm", "angle": 0}),+ );+ matches(output_schema_for::<JointAddedResult>(), "joint.create", &by_origin);+ let built = run("joint.as_built", json!({"type": "slider", "a": "LeafB", "b": "LeafC", "name": "Slide", "limits": [[0, 10]], "quiet": false}));+ matches(output_schema_for::<JointAddedResult>(), "joint.as_built", &built);+ let at = run("joint.as_built", json!({"type": "rigid", "a": "LeafA", "b": "LeafD", "at": {"point": [0, 0, 0]}, "values": [1]}));+ matches(output_schema_for::<JointAddedResult>(), "joint.as_built", &at);+ run("joint.delete", json!({"joint": at["joint"]}));++ // A screw ties Slide's travel to Hinge's turn: a coupling for the list.+ run("joint.screw", json!({"a": "Hinge", "b": "Slide", "pitch": 2}));++ let list = run("joint.list", json!({}));+ matches(output_schema_for::<ListJointsResult>(), "joint.list", &list);+ assert!(list["links"].as_array().is_some_and(|l| l.len() == 1) && list["links"][0]["coupling"]["type"] == "screw", "{list}");+ assert!(list["joints"].as_array().is_some_and(|j| j.len() == 4) && list["origins"][0]["name"] == "Top", "{list}");+ assert!(list["floating"].as_array().is_some_and(|f| f.len() == 1), "{list}");+ let quiet = run("joint.list", json!({"quiet": true}));+ matches(output_schema_for::<ListJointsResult>(), "joint.list", &quiet);+ assert!(quiet.get("dof").is_none(), "{quiet}");++ for p in [json!({}), json!({"joint": "Slide"}), json!({"joint": null}), json!({"joint": made["joint"]})] {+ let inspected = run("joint.inspect", p);+ matches(output_schema_for::<InspectJointResult>(), "joint.inspect", &inspected);+ }+ let inspected = run("joint.inspect", json!({"joint": "Hinge"}));+ assert!(inspected["joints"][0]["links"][0]["role"] == "driver" && inspected["joints"][0]["a"]["references"].as_array().is_some(), "{inspected}");++ // joint.drive: a value, a list, one coordinate, past a limit, a drag frame, a suppressed joint+ // and one joined to nothing grounded.+ for p in [+ json!({"joint": "Hinge", "value": 45}),+ json!({"joint": "Hinge", "values": [30]}),+ json!({"joint": "Hinge", "index": 0, "value": "20 deg", "quiet": true}),+ json!({"joint": "Hinge", "value": 50, "continuous": true}),+ json!({"joint": "Slide", "value": 3}),+ ] {+ let driven = run("joint.drive", p);+ matches(output_schema_for::<DriveJointResult>(), "joint.drive", &driven);+ }+ let held = run("joint.drive", json!({"joint": "Hinge", "value": 200}));+ assert!(held["held"][0]["why"].as_str().is_some_and(|w| w.contains("limits")), "{held}");+ matches(output_schema_for::<DriveJointResult>(), "joint.drive", &held);+ let linked = run("joint.drive", json!({"joint": "Slide", "value": 5}));+ assert!(linked["held"][0]["why"].as_str().is_some_and(|w| w.contains("motion link")), "{linked}");+ matches(output_schema_for::<DriveJointResult>(), "joint.drive", &linked);+ let loose = run("joint.drive", json!({"joint": "Clamped", "value": 5}));+ assert!(loose["unconnected"].is_string() && loose["reason"].is_string(), "{loose}");+ matches(output_schema_for::<DriveJointResult>(), "joint.drive", &loose);+ run("joint.edit", json!({"joint": "Stack", "type": "revolute"}));+ let turned = run("joint.drive", json!({"joint": "Stack", "value": 1}));+ matches(output_schema_for::<DriveJointResult>(), "joint.drive", &turned);+ run("joint.edit", json!({"joint": "Stack", "suppressed": true}));+ let hidden = run("joint.drive", json!({"joint": "Stack", "value": 2}));+ assert!(hidden["reason"].as_str().is_some_and(|r| r.contains("suppressed")), "{hidden}");+ matches(output_schema_for::<DriveJointResult>(), "joint.drive", &hidden);++ // joint.limits and joint.solve.+ for p in [+ json!({"joint": "Hinge", "min": -45, "max": "45 deg"}),+ json!({"joint": "Hinge", "index": 0, "min": -10, "max": 10, "quiet": true}),+ json!({"joint": "Hinge"}),+ ] {+ let limited = run("joint.limits", p);+ matches(output_schema_for::<SolveResult>(), "joint.limits", &limited);+ }+ for p in [json!({}), json!({"quiet": true})] {+ let solved = run("joint.solve", p);+ matches(output_schema_for::<SolveResult>(), "joint.solve", &solved);+ }++ // joint.delete: a motion link, a joint origin, a joint.+ let link = run("joint.delete", json!({"link": 0}));+ assert_eq!(link["deleted_link"], 0, "{link}");+ matches(output_schema_for::<DeleteJointResult>(), "joint.delete", &link);+ let origin = run("joint.delete", json!({"origin": "Top", "joint": true, "link": "x"}));+ assert_eq!((origin["deleted_origin"].clone(), origin["joints"].clone()), (json!("Top"), json!(4)), "{origin}");+ matches(output_schema_for::<DeleteJointResult>(), "joint.delete", &origin);+ let deleted = run("joint.delete", json!({"joint": "Stack"}));+ assert!(deleted["deleted"].is_u64() && deleted.get("dof").is_some(), "{deleted}");+ matches(output_schema_for::<DeleteJointResult>(), "joint.delete", &deleted);+ let quiet = run("joint.delete", json!({"joint": "Clamped", "quiet": true}));+ assert!(quiet.get("dof").is_none() && quiet["deleted"].is_u64(), "{quiet}");+ matches(output_schema_for::<DeleteJointResult>(), "joint.delete", &quiet);+}++fn with_limits(mut p: Value, limits: Value) -> Value {+ p["limits"] = limits;+ p+}++fn with_extra(mut p: Value, extra: Value) -> Value {+ if let (Some(o), Some(e)) = (p.as_object_mut(), extra.as_object()) {+ o.extend(e.clone());+ }+ p+}++/// 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() {+ let mut s = hinged(ParamCheck::Warn);+ let calls = [+ ("joint.create", json!({"type": "rigid", "a": "Top", "b": {"occurrence": "LeafB", "face": [20, 15, 0]}, "nme": "J"}), "name"),+ ("joint.as_built", json!({"type": "rigid", "a": "LeafA", "b": "LeafB", "nam": "As built"}), "name"),+ ("joint.drive", json!({"joint": "Hinge", "valu": 10, "value": 10}), "value"),+ ("joint.limits", json!({"joint": "Hinge", "mn": 1, "min": -10, "max": 10}), "min"),+ ("joint.list", json!({"quet": true}), "quet"),+ ("joint.inspect", json!({"joynt": "Hinge"}), "joint"),+ ("joint.solve", json!({"quet": true}), "quet"),+ ("joint.delete", json!({"origin": "Top", "oringin": 1}), "origin"),+ ];+ 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());+ }+}++/// A cam on a revolute joint: `joint.list` and `joint.inspect` give its follower's lift, a table+/// that is not whole as `null`, and the replies match their schemas.+#[test]+fn a_cam_link_shows_its_lift() {+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };+ let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));+ let part = |run: &mut dyn FnMut(&str, Value) -> Value, name: &str, corner: [f64; 3]| {+ run("component.activate", json!({"component": "root"}));+ let made = run("component.create", json!({"name": name, "grounded": false}));+ run("solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": corner}));+ made["occurrence"].clone()+ };+ let pin = |run: &mut dyn FnMut(&str, Value) -> Value, kind: &str, name: &str, a: &str, b: &str, p: Vec3, z: Vec3| {+ let at = |o: &str| json!({"occurrence": o, "point": [p.x, p.y, p.z], "z": [z.x, z.y, z.z]});+ run("joint.create", json!({"type": kind, "a": at(a), "b": at(b), "flip": true, "name": name}));+ };+ let occurrence = part(&mut run, "Base", [-90.0, -90.0, -20.0]);+ run("occurrence.ground", json!({"occurrence": occurrence, "grounded": true}));+ run("component.activate", json!({"component": "root"}));+ run("component.create", json!({"name": "Cam"}));+ run("sketch.create", json!({"plane": "XY", "name": "CamSketch"}));+ run("sketch.circle.center", json!({"center": [10, 0], "radius": 30, "id": "c1"}));+ run("sketch.finish", json!({}));+ run("solid.extrude", json!({"distance": 5}));+ pin(&mut run, "revolute", "Cam", "Base", "Cam", Vec3::ZERO, Vec3::Z);+ run("component.activate", json!({"component": "root"}));+ run("component.create", json!({"name": "Tappet"}));+ run("solid.box", json!({"length": 20, "width": 4, "height": 5, "corner": [40, -2, 0]}));+ pin(&mut run, "slider", "Tappet", "Base", "Tappet", Vec3::new(0.0, 0.0, 2.5), Vec3::X);+ run("joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}}));+ let list = run("joint.list", json!({}));+ let schema = output_schema_for::<ListJointsResult>();+ assert!(list["links"][0]["lift"]["rise"].is_number() && list["links"][0].get("ratio").is_none(), "{list}");+ assert!(list["links"][0]["coupling"]["type"] == "cam" && conforms(schema.as_value(), schema.as_value(), &list), "{list}");+ let inspected = run("joint.inspect", json!({"joint": "Tappet"}));+ let schema = output_schema_for::<InspectJointResult>();+ assert!(inspected["joints"][0]["links"][0]["role"] == "driven" && conforms(schema.as_value(), schema.as_value(), &inspected), "{inspected}");+ // A table that is not whole moves nothing, and says `null`.+ if let Some(l) = s.doc_mut().assembly.links.first_mut() {+ l.lift.truncate(3);+ }+ let broken = s.execute("joint.list", &json!({})).unwrap_or_else(|e| panic!("{e}"));+ let schema = output_schema_for::<ListJointsResult>();+ assert!(broken["links"][0]["lift"].is_null() && broken["links"][0].get("lift").is_some(), "{broken}");+ assert!(conforms(schema.as_value(), schema.as_value(), &broken), "{broken}");+}++/// A slider stopped by contact: the bodies that touched and how far it got, in the reply.+#[test]+fn a_drive_stopped_by_contact_matches_the_output_schema() {+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };+ let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));+ for (name, x) in [("A", 0), ("B", 20)] {+ run("component.activate", json!({"component": 0}));+ let made = run("component.create", json!({"name": name}));+ run("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0]}));+ if name == "A" {+ run("occurrence.ground", json!({"occurrence": made["occurrence"], "grounded": true}));+ }+ }+ run("joint.create", json!({"type": "slider", "a": {"face": [10, 5, 5]}, "b": {"face": [20, 5, 5]}, "name": "Rail"}));+ run("contact.create", json!({"occurrences": ["A", "B"]}));+ let free = run("joint.drive", json!({"joint": "Rail", "value": 10}));+ assert!(free["stopped_by_contact"].is_null() && free["stopped_by_loop"].is_null(), "{free}");+ matches(output_schema_for::<DriveJointResult>(), "joint.drive", &free);+ let stopped = run("joint.drive", json!({"joint": "Rail", "value": -30}));+ assert!(stopped["stopped_by_contact"]["fraction"].is_number() && stopped["stopped_by_contact"]["a"].is_string(), "{stopped}");+ assert!(stopped["held"][0]["why"].as_str().is_some_and(|w| w.contains("contact")), "{stopped}");+ matches(output_schema_for::<DriveJointResult>(), "joint.drive", &stopped);+}++/// An origin on an edge names the edge and its two faces; a round origin on an extruded circle+/// names the sketch curve its wall was swept from.+#[test]+fn inspect_names_what_edges_and_swept_faces_refer_to() {+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };+ let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));+ let panel = run("component.create", json!({"name": "Panel"}));+ run("solid.box", json!({"length": 400, "width": 300, "height": 2, "corner": [0, 0, 0]}));+ run("occurrence.ground", json!({"occurrence": panel["occurrence"], "grounded": true}));+ run("component.activate", json!({"component": "root"}));+ run("component.create", json!({"name": "Pin"}));+ run("sketch.create", json!({"plane": "XY", "name": "PinSketch"}));+ run("sketch.circle.center", json!({"center": [100, 0], "radius": 5, "id": "c1"}));+ run("sketch.finish", json!({}));+ run("solid.extrude", json!({"distance": 20}));+ run(+ "joint.create",+ json!({"type": "revolute", "name": "Edge", "a": {"occurrence": "Panel", "edge": [200, 0, 2]}, "b": {"occurrence": "Pin", "circle": [105, 0, 20]}}),+ );+ let inspected = run("joint.inspect", json!({"joint": "Edge"}));+ matches(output_schema_for::<InspectJointResult>(), "joint.inspect", &inspected);+ let side = |s: &str, role: &str| inspected["joints"][0][s]["references"].as_array().and_then(|r| r.iter().find(|r| r["role"] == role)).cloned();+ let edge = side("a", "edge").unwrap_or_default();+ assert!(edge["faces"].as_array().is_some_and(|f| f.len() == 2 && f[0]["feature"]["type"] == "BoxFeature"), "{inspected}");+ let wall = side("b", "face").unwrap_or_default();+ assert_eq!((wall["sketch"]["name"].clone(), wall["sketch"]["curve_type"].clone()), (json!("PinSketch"), json!("circle")), "{inspected}");+ // The extrude goes: the names are kept, and say what is gone.+ run("timeline.delete", json!({"feature": "Extrude1"}));+ let gone = run("joint.inspect", json!({"joint": "Edge"}));+ assert!(gone["joints"][0]["b"]["resolves"] == false && gone["joints"][0]["b"]["error"].is_string(), "{gone}");+ matches(output_schema_for::<InspectJointResult>(), "joint.inspect", &gone);+}++/// The contract looks at every key before the handler looks at the design, so a call with two+/// problems may name another one in strict than the handler does (the documented difference), and+/// a call the handler ignores a wrong-typed key in is refused (the stricter reading).+#[test]+fn strict_may_name_another_problem_first_and_refuses_ignored_wrong_types() {+ let strict = |id: &str, p: Value| hinged(ParamCheck::Strict).execute(id, &p).err().map(|e| e.to_string());+ let off = |id: &str, p: Value| hinged(ParamCheck::Off).execute(id, &p).err().map(|e| e.to_string());+ for (id, p) in+ [("joint.drive", json!({"joint": "nope", "index": "x", "value": 1})), ("joint.limits", json!({"joint": "Hinge", "index": 9, "min": 0}))]+ {+ assert!(off(id, p.clone()).is_some() && strict(id, p.clone()).is_some() && off(id, p.clone()) != strict(id, p), "{id}");+ }+ for (id, p) in [+ ("joint.limits", json!({"joint": "Hinge", "limits": [5]})),+ ("joint.limits", json!({"joint": "Hinge", "index": "0", "min": 1, "max": 2})),+ ("joint.solve", json!({"quiet": "yes"})),+ ("joint.delete", json!({"joint": "Hinge", "link": "x"})),+ ("joint.delete", json!({"joint": "Hinge", "origin": 5})),+ ] {+ let works = |level| hinged(level).execute(id, &p).is_ok();+ assert!(works(ParamCheck::Off) && !works(ParamCheck::Strict), "{id} {p}");+ }}diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txtindex cb091d6760..375d3c8abf 100644--- a/crates/engine/src/schema/unconverted.txt+++ b/crates/engine/src/schema/unconverted.txt@@ -36,22 +36,14 @@ frame.profile.insertframe.profile.listframe.profile.propertiesinspect.measure-joint.as_builtjoint.cam-joint.create-joint.delete-joint.drivejoint.gear-joint.inspect-joint.limits-joint.listjoint.motion_linkjoint.originjoint.rack_pinionjoint.reachjoint.rigid_groupjoint.screw-joint.solvejoint.sweepmaterial.assignmaterial.list