Skip to main content

sim_netlist/
linkage.rs

1//! `LinkageMachine`: a planar parallel linkage built from a machine file's `[[machine.linkage]]` node: two motor-driven
2//! arms in the vertical x-z plane, one at each side of the base, each carrying a pair of forearms down to a plate that
3//! keeps its orientation (a five-bar whose lower links are parallelograms: the planar delta). The tool is the plate's
4//! centre; the node's two axes are its x (across) and z (up).
5//!
6//! The registered planar delta's equations, for any lengths and masses the node names (the crate's module comment
7//! derives them). Arm k points along s_k x (s_1 = +1, s_2 = -1); e = base radius - platform radius, the arm angle
8//! theta_k (0 horizontal, positive down), upper arm L_a, forearm L_b:
9//!
10//! ```text
11//! elbow     c_k = (s_k (e + L_a cos theta), -L_a sin theta)
12//! inverse   A cos theta + B sin theta + C = 0, A = -2 L_a (x' - e), B = 2 L_a z, C = (x' - e)^2 + z^2 + L_a^2 - L_b^2
13//!           theta = 2 atan((-B - sqrt(A^2 + B^2 - C^2)) / (C - A))     (elbow out; x' = s_k x)
14//! forward   p = the lower of the two points at L_b from both elbows
15//! Jacobian  J_x p' = J_q theta', J_x rows u_k = p - c_k, J_q = diag(u_k . dc_k/dtheta_k); J = J_x^-1 J_q
16//! dynamics  M(theta) theta'' = tau_gear + Q_g - m_nt J^T J_x^-1 w + tau_joint,   M = I_b 1 + m_nt J^T J
17//!           I_b = I_arm + L_a^2 (m_elbow + r m_fb),   Q_g,k = g m_LG cos theta_k - m_nt g J_zk
18//!           m_LG = m_arm l_cg + L_a (m_elbow + r m_fb),   m_nt = plate + payload + 2 (1 - r) m_fb
19//! ```
20//!
21//! Each arm's joint is a `RotaryJoint` read from its motor's own config (`catalog::motor_config`: `[motor]`,
22//! `[gearbox]` with `[motor.<id>]`, `[gearbox.<id>]` over them) and the shared `[joint]` (bearing friction, stops),
23//! elastic or rigid with effects.joint_elasticity. The machine is the crate's, line for line, so that the file
24//! `machines/planar-delta.toml` gives the crate's numbers (crates/sim-machines/tests/machine_file_linkage.rs).
25
26use crate::machine::intern;
27use crate::netlist::{AxisNode, Kind, MotorNode, NODES, Netlist, Node, Transmission, number};
28use sim_components::catalog::motor_config;
29use sim_components::joint::RotaryJoint;
30use sim_components::mech::ThermalFeedback;
31use sim_core::{
32    AxisInfo, Config, ConfigError, ENERGY_PARTS, LOSS_PREFIX, Label, Machine, MotorInfo, Part, Scene, Shape,
33    SignalInfo, TORQUE_PARTS, ThermalPart,
34};
35use toml::Value;
36
37const G: f64 = 9.80665;
38
39/// Values of the node that have to be above 0; `top_z_m` may be anything, every other value at least 0. The range's
40/// half width is the planar linkage's, its radius the spatial one's.
41const POSITIVE: [&str; 11] = [
42    "base_radius_m",
43    "upper_arm_m",
44    "forearm_m",
45    "upper_arm_kg",
46    "upper_arm_inertia_kgm2",
47    "platform_kg",
48    "half_width_m",
49    "radius_m",
50    "height_edge_m",
51    "height_centre_m",
52    "max_condition_number",
53];
54
55/// Values only the spatial linkage (three arms) reads: the range's radius, the rods' spin, the upper arms' bending.
56pub const SPATIAL_ONLY: [&str; 6] = [
57    "radius_m",
58    "forearm_rod_spin_inertia_kgm2",
59    "bending_stiffness_nm_rad",
60    "bending_damping_nm_s_rad",
61    "lateral_stiffness_n_m",
62    "lateral_damping_n_s_m",
63];
64
65/// The linkage node, read and checked: its number fields by name (an optional one left out is 0), and per arm the
66/// gearbox node's id (arm k's motor is the netlist's motor k). Two arms: the planar linkage (`LinkageMachine`); three:
67/// the spatial one (`crate::spatial::Delta`).
68pub struct LinkageNode {
69    pub id: String,
70    pub gearboxes: Vec<String>,
71    /// The node's path in the file, `machine.linkage[<id>]`, for errors.
72    path: String,
73    values: Vec<(&'static str, f64)>,
74}
75
76impl LinkageNode {
77    /// The value of a number field of the node.
78    pub fn value(&self, name: &str) -> f64 {
79        self.values.iter().find(|(n, _)| *n == name).map_or(0.0, |(_, v)| *v)
80    }
81}
82
83/// Where a linkage reads its numbers: a crate's tables by their paths (`geometry.forearm_m`), or a file's linkage node
84/// by the path's last part (`forearm_m`), so that one constructor serves both.
85pub trait Numbers {
86    /// Any finite number.
87    fn number(&self, path: &str) -> Result<f64, ConfigError>;
88    /// The error that refuses the value at `path`.
89    fn invalid(&self, path: &str) -> ConfigError;
90    fn positive(&self, path: &str) -> Result<f64, ConfigError> {
91        let v = self.number(path)?;
92        if v > 0.0 { Ok(v) } else { Err(self.invalid(path)) }
93    }
94    fn non_negative(&self, path: &str) -> Result<f64, ConfigError> {
95        let v = self.number(path)?;
96        if v >= 0.0 { Ok(v) } else { Err(self.invalid(path)) }
97    }
98}
99
100impl Numbers for Config {
101    fn number(&self, path: &str) -> Result<f64, ConfigError> {
102        Config::f64(self, path)
103    }
104    fn invalid(&self, path: &str) -> ConfigError {
105        ConfigError::Invalid(path.into())
106    }
107}
108
109impl Numbers for LinkageNode {
110    fn number(&self, path: &str) -> Result<f64, ConfigError> {
111        Ok(self.value(path.rsplit('.').next().unwrap_or(path)))
112    }
113    fn invalid(&self, path: &str) -> ConfigError {
114        ConfigError::Invalid(format!("{}.{}", self.path, path.rsplit('.').next().unwrap_or(path)))
115    }
116}
117
118/// A linkage's drives and names: per arm its joint, its motor and its gearbox's id for its warmth (`gearbox_<motor>`, as
119/// its loss is named); per axis of the tool its id and key.
120pub struct Arms<const N: usize> {
121    pub joints: [RotaryJoint; N],
122    pub motors: [MotorInfo; N],
123    pub gearboxes: [&'static str; N],
124    pub axes: [(&'static str, &'static str); N],
125}
126
127impl<const N: usize> Arms<N> {
128    /// A crate's: one joint for every arm from `[joint]`, `[motor]` and `[gearbox]`; motors `1`, `2`, ... (keys
129    /// `motor-arm-k`), gearboxes `gearbox_k`; the axes as given.
130    pub fn shared(cfg: &Config, axes: [(&'static str, &'static str); N]) -> Result<Self, ConfigError> {
131        let joint = RotaryJoint::from_config(cfg)?;
132        Ok(Self {
133            joints: std::array::from_fn(|_| joint.clone()),
134            motors: std::array::from_fn(|k| MotorInfo {
135                id: ["1", "2", "3"][k],
136                key: ["motor-arm-1", "motor-arm-2", "motor-arm-3"][k],
137            }),
138            gearboxes: std::array::from_fn(|k| ["gearbox_1", "gearbox_2", "gearbox_3"][k]),
139            axes,
140        })
141    }
142
143    /// A file's: per arm the joint of its motor's own config (`catalog::motor_config`), the netlist's motors and axes.
144    pub fn of_file(cfg: &Config, net: &Netlist) -> Result<Self, ConfigError> {
145        let joints = (0..N)
146            .map(|k| RotaryJoint::from_config(&motor_config(cfg, &net.motors[k].id)?))
147            .collect::<Result<Vec<_>, _>>()?;
148        Ok(Self {
149            joints: joints.try_into().unwrap_or_else(|_| unreachable!("N joints")),
150            motors: std::array::from_fn(|k| MotorInfo {
151                id: intern(&net.motors[k].id),
152                key: intern(&net.motors[k].key),
153            }),
154            // The warmth's id is that of the gearbox's loss, `power.gearbox_<motor>`.
155            gearboxes: std::array::from_fn(|k| intern(&format!("gearbox_{}", net.motors[k].id))),
156            axes: std::array::from_fn(|k| (intern(&net.axes[k].id), intern(&net.axes[k].key))),
157        })
158    }
159
160    /// Axis k's limits from `[axis.<id>]`, its range `min` to `max`, in m.
161    pub fn axis(&self, cfg: &Config, k: usize, min: f64, max: f64) -> Result<AxisInfo, ConfigError> {
162        let (id, key) = self.axes[k];
163        Ok(AxisInfo {
164            id,
165            key,
166            unit: "m",
167            min,
168            max,
169            max_vel: cfg.positive(&format!("axis.{id}.max_velocity_m_s"))?,
170            max_acc: cfg.positive(&format!("axis.{id}.max_acceleration_m_s2"))?,
171            max_jerk: cfg.positive(&format!("axis.{id}.max_jerk_m_s3"))?,
172        })
173    }
174}
175
176/// The netlist of a file with a linkage: its axes (across, then up; or x, y, z), its arms' motors in the order of the
177/// node's `arms`, and the linkage. Two arms make the planar linkage, three the spatial one. Such a file has axes,
178/// motors, gearboxes and one linkage, nothing else (`others`: the other node lists), and no belt effect switched on.
179pub(crate) fn read(
180    cfg: &Config,
181    axes: &[Node],
182    motors: &[Node],
183    gearboxes: &[Node],
184    linkages: &[Node],
185    others: &[&[Node]],
186) -> Result<Netlist, ConfigError> {
187    let node = match linkages {
188        [node] => node,
189        _ => return Err(ConfigError::Invalid(format!("{} (one linkage per file)", linkages[1].path))),
190    };
191    if let Some(other) = others.iter().find_map(|nodes| nodes.first()) {
192        return Err(ConfigError::Invalid(format!(
193            "{} (a file with a linkage has axes, motors, gearboxes and the linkage only)",
194            other.path
195        )));
196    }
197    // A linkage has no belt: a belt effect switched on would otherwise be ignored without a word.
198    let effects = cfg.get("effects").ok().and_then(Value::as_table);
199    for (effect, on) in effects.into_iter().flatten() {
200        if effect.starts_with("belt_") && on.as_bool() == Some(true) {
201            return Err(ConfigError::Invalid(format!("effects.{effect} (a linkage has no belt: switch it off)")));
202        }
203    }
204    let id_of = |n: &Node| n.table["id"].as_str().unwrap_or_default().to_string();
205    let by_id = |nodes: &'_ [Node], field: &str, id: &str| -> Result<usize, ConfigError> {
206        nodes
207            .iter()
208            .position(|n| n.table["id"].as_str() == Some(id))
209            .ok_or_else(|| ConfigError::Invalid(format!("{} = \"{id}\"", node.at(field))))
210    };
211    // Two or three of each, as many as the arms, every one named once.
212    let arm_count = node.id_list("arms")?.len();
213    let all = |field: &str, nodes: &[Node], list: &str| -> Result<Vec<usize>, ConfigError> {
214        let ids = node.id_list(field)?;
215        let found = ids.iter().map(|id| by_id(nodes, field, id)).collect::<Result<Vec<_>, _>>()?;
216        let distinct = found.iter().enumerate().all(|(i, a)| !found[..i].contains(a));
217        if (2..=3).contains(&found.len()) && found.len() == arm_count && distinct && nodes.len() == found.len() {
218            Ok(found)
219        } else {
220            Err(ConfigError::Invalid(format!(
221                "{} (two or three machine.{list} nodes, as many as the arms, each once; the file has {})",
222                node.at(field),
223                nodes.len()
224            )))
225        }
226    };
227    let spatial = arm_count == 3;
228
229    let fields = NODES.iter().find(|(list, ..)| *list == "linkage").map_or(&[][..], |(_, _, f)| *f);
230    let mut refs = Vec::new();
231    let mut values = Vec::new();
232    for f in fields.iter().filter(|f| f.kind == Kind::Number) {
233        // The planar linkage's range has a half width, the spatial one's a radius; each refuses the other's values.
234        let own = if spatial { f.name != "half_width_m" } else { !SPATIAL_ONLY.contains(&f.name) };
235        if !own {
236            if node.get(f.name).is_some() {
237                let arms = if spatial { "three" } else { "two" };
238                return Err(ConfigError::Invalid(format!("{} (not for a linkage of {arms} arms)", node.at(f.name))));
239            }
240            continue;
241        }
242        let v = node.get(f.name).map(|v| number(cfg, v, &node.at(f.name), &mut refs)).transpose()?;
243        // Required by one kind of linkage only, so not marked required in `NODES`.
244        let wanted =
245            ["half_width_m", "radius_m", "bending_stiffness_nm_rad", "lateral_stiffness_n_m"].contains(&f.name);
246        let v = match v {
247            Some(v) => v,
248            None if wanted => return Err(ConfigError::Missing(node.at(f.name))),
249            None => 0.0,
250        };
251        let ok = if POSITIVE.contains(&f.name) { v > 0.0 } else { f.name == "top_z_m" || v >= 0.0 };
252        if !ok {
253            return Err(ConfigError::Invalid(node.at(f.name)));
254        }
255        values.push((f.name, v));
256    }
257    let value = |name: &str| values.iter().find(|(n, _)| *n == name).map_or(0.0, |(_, v)| *v);
258    for (field, bad, why) in [
259        ("forearm_m", value("forearm_m") <= value("upper_arm_m"), "longer than the upper arm"),
260        ("forearm_elbow_share", value("forearm_elbow_share") > 1.0, "a share, 0 to 1"),
261        ("height_centre_m", value("height_centre_m") < value("height_edge_m"), "at least height_edge_m"),
262    ] {
263        if bad {
264            return Err(ConfigError::Invalid(format!("{} ({why})", node.at(field))));
265        }
266    }
267
268    let mut axis_nodes = Vec::new();
269    let tool_axes = all("axes", axes, "axis")?;
270    let count = tool_axes.len();
271    for (k, i) in tool_axes.into_iter().enumerate() {
272        let axis = &axes[i];
273        for field in ["stroke_m", "stroke_rad", "incline_deg", "cable_chain"] {
274            if axis.get(field).is_some() {
275                return Err(ConfigError::Invalid(format!(
276                    "{} (a linkage's axes take their range from the linkage's working range)",
277                    axis.at(field)
278                )));
279            }
280        }
281        let id = id_of(axis);
282        let key = axis.text("key")?.map_or_else(|| format!("axis-{id}"), str::to_string);
283        // The range across (each way across on the spatial linkage), and up from the bottom at the centre.
284        let stroke = match (k + 1 == count, spatial) {
285            (true, _) => value("height_centre_m"),
286            (false, false) => 2.0 * value("half_width_m"),
287            (false, true) => 2.0 * value("radius_m"),
288        };
289        axis_nodes.push(AxisNode { id, key, stroke, incline_deg: 0.0, cable_chain: false, rotary: false });
290    }
291
292    let mut motor_nodes: Vec<MotorNode> = Vec::new();
293    let arms = all("arms", gearboxes, "gearbox")?;
294    for &i in &arms {
295        let gearbox = &gearboxes[i];
296        let motor = gearbox.text("motor")?.unwrap_or_default();
297        let m = motors
298            .iter()
299            .position(|n| n.table["id"].as_str() == Some(motor))
300            .ok_or_else(|| ConfigError::Invalid(format!("{} = \"{motor}\"", gearbox.at("motor"))))?;
301        let id = id_of(&motors[m]);
302        let key = motors[m].text("key")?.map_or_else(|| format!("motor-{id}"), str::to_string);
303        if motor_nodes.iter().any(|o| o.id == id) {
304            break;
305        }
306        // What drives the arm is the linkage, which the netlist's transmissions do not describe: nothing reads these.
307        motor_nodes.push(MotorNode {
308            id,
309            key,
310            radius: 1.0,
311            inertia: 0.0,
312            pulley: String::new(),
313            at: None,
314            body: None,
315            clockwise: false,
316            transmission: Transmission::Belt,
317            axis: None,
318            worm: None,
319        });
320    }
321    if motors.len() != arms.len() || motor_nodes.len() != arms.len() {
322        return Err(ConfigError::Invalid(format!("{} (one motor per arm, each with its gearbox)", node.at("arms"))));
323    }
324    Ok(Netlist {
325        axes: axis_nodes,
326        motors: motor_nodes,
327        sections: Vec::new(),
328        bodies: Vec::new(),
329        guides: Vec::new(),
330        idlers: Vec::new(),
331        frame: None,
332        spans: Vec::new(),
333        lean: None,
334        gantry: None,
335        tcp: None,
336        refs,
337        values: Vec::new(),
338        linkage: Some(LinkageNode {
339            id: id_of(node),
340            gearboxes: arms.iter().map(|&i| id_of(&gearboxes[i])).collect(),
341            path: node.path.clone(),
342            values,
343        }),
344        scissor: None,
345    })
346}
347
348/// Effects that take energy out or put it in, as on the registered planar delta: the standard suite runs with them
349/// off.
350pub const LOSSY_EFFECTS: [&str; 7] = [
351    "joint_friction",
352    "motor_friction",
353    "gearbox_drag",
354    "gearbox_lost_motion",
355    "gearbox_efficiency",
356    "torque_ripple",
357    "holding_brake",
358];
359
360/// A vector in the x-z plane, (x, z).
361pub type V2 = [f64; 2];
362pub type M2 = [[f64; 2]; 2];
363
364pub fn dot(a: V2, b: V2) -> f64 {
365    a[0] * b[0] + a[1] * b[1]
366}
367
368pub fn sub(a: V2, b: V2) -> V2 {
369    [a[0] - b[0], a[1] - b[1]]
370}
371
372pub fn norm(a: V2) -> f64 {
373    dot(a, a).sqrt()
374}
375
376pub fn mul(m: &M2, v: V2) -> V2 {
377    [dot(m[0], v), dot(m[1], v)]
378}
379
380pub fn transpose(m: &M2) -> M2 {
381    [[m[0][0], m[1][0]], [m[0][1], m[1][1]]]
382}
383
384/// The inverse of a 2 x 2 matrix; `None` where it is singular.
385pub fn inverse(m: &M2) -> Option<M2> {
386    let det = m[0][0] * m[1][1] - m[0][1] * m[1][0];
387    if !(det.abs() > 1e-300) || !det.is_finite() {
388        return None;
389    }
390    Some([[m[1][1] / det, -m[0][1] / det], [-m[1][0] / det, m[0][0] / det]])
391}
392
393/// The gearbox's loss factor at a steady speed `w` where it passes `output` to the arm: `rigid_solve` takes it of the
394/// torque that goes in, output / loss, so it is found by fixed point (the efficiency's fade over the power makes the
395/// two differ by 1e-3 of the torque at 0.01 m/s on the linkage).
396pub fn steady_loss(gearbox: &sim_components::mech::Gearbox, output: f64, w: f64) -> f64 {
397    sim_components::mech::settled_loss([1.0], |&[loss]| [gearbox.loss_factor(output / loss, w)])[0]
398}
399
400/// The 2-norm condition number of a 2 x 2 matrix: the square root of the larger over the smaller eigenvalue of
401/// J^T J, m +- sqrt(((a - c) / 2)^2 + b^2) with m = (a + c) / 2 for J^T J = [[a, b], [b, c]].
402pub fn condition_number(j: &M2) -> f64 {
403    let (a, b, c) = (
404        j[0][0] * j[0][0] + j[1][0] * j[1][0],
405        j[0][0] * j[0][1] + j[1][0] * j[1][1],
406        j[0][1] * j[0][1] + j[1][1] * j[1][1],
407    );
408    let (mean, half) = ((a + c) / 2.0, ((a - c) / 2.0).hypot(b));
409    if mean - half <= 0.0 { f64::INFINITY } else { ((mean + half) / (mean - half)).sqrt() }
410}
411
412/// The side each arm points to along x.
413pub const SIDE: [f64; 2] = [1.0, -1.0];
414
415/// The legs' geometry and the kinematics, apart from masses and drives.
416#[derive(Debug, Clone)]
417pub struct Legs {
418    /// Base radius less platform radius, upper arm, forearm.
419    pub e: f64,
420    pub la: f64,
421    pub lb: f64,
422}
423
424impl Legs {
425    pub fn new(e: f64, la: f64, lb: f64) -> Self {
426        Self { e, la, lb }
427    }
428
429    /// The elbow of leg i at arm angle t, and its first and second derivative by t, as (x, z).
430    pub fn elbow(&self, i: usize, t: f64) -> [V2; 3] {
431        let (s, c) = t.sin_cos();
432        let (la, side) = (self.la, SIDE[i]);
433        [[side * (self.e + la * c), -la * s], [-side * la * s, -la * c], [-side * la * c, la * s]]
434    }
435
436    /// Arm angles for a plate position (x, z), elbows out; `None` out of reach.
437    pub fn inverse(&self, p: V2) -> Option<V2> {
438        let mut out = [0.0; 2];
439        for (i, t) in out.iter_mut().enumerate() {
440            let (x, z) = (SIDE[i] * p[0], p[1]);
441            let (a, b, c) = (
442                -2.0 * self.la * (x - self.e),
443                2.0 * self.la * z,
444                (x - self.e).powi(2) + z * z + self.la * self.la - self.lb * self.lb,
445            );
446            let d = a * a + b * b - c * c;
447            if !(d >= 0.0) {
448                return None;
449            }
450            // a cos t + b sin t + c = 0 by u = tan(t / 2): (c - a) u^2 + 2 b u + (a + c) = 0, the root
451            // (-b - sqrt d) / (c - a) = (a + c) / (sqrt d - b). Below the base (b = 2 L_a z < 0) the second form stays
452            // finite where c = a, at which the first is 0 / 0 (as in `spatial::Legs::inverse_moved`).
453            let s = d.sqrt();
454            *t = if b <= 0.0 { 2.0 * (a + c).atan2(s - b) } else { 2.0 * ((-b - s) / (c - a)).atan() };
455        }
456        Some(out)
457    }
458
459    /// The plate position for arm angles: the lower point at a forearm's length from both elbows. `None` where the
460    /// legs cannot be assembled.
461    pub fn forward(&self, t: V2) -> Option<V2> {
462        let (c0, c1) = (self.elbow(0, t[0])[0], self.elbow(1, t[1])[0]);
463        let along = sub(c1, c0);
464        let d = norm(along);
465        let h2 = self.lb * self.lb - d * d / 4.0;
466        if !(d > 1e-12 && h2 >= 0.0) {
467            return None;
468        }
469        // Midway between the elbows, then h along the normal to the line joining them.
470        let (mid, h) = ([0.5 * (c0[0] + c1[0]), 0.5 * (c0[1] + c1[1])], h2.sqrt());
471        let normal = [-along[1] / d, along[0] / d];
472        let (one, other) =
473            ([mid[0] + h * normal[0], mid[1] + h * normal[1]], [mid[0] - h * normal[0], mid[1] - h * normal[1]]);
474        Some(if one[1] < other[1] { one } else { other })
475    }
476
477    /// J_x (rows: the forearm vectors u_i = p - c_i) and the diagonal of J_q (u_i . dc_i/dt).
478    fn constraint(&self, t: V2, p: V2) -> (M2, V2) {
479        let rows = [self.elbow(0, t[0]), self.elbow(1, t[1])];
480        let jx = rows.map(|e| sub(p, e[0]));
481        (jx, [dot(jx[0], rows[0][1]), dot(jx[1], rows[1][1])])
482    }
483
484    /// The Jacobian J[i][j] = dp_i / dtheta_j (rows x and z); `None` at a direct singularity.
485    pub fn jacobian(&self, t: V2, p: V2) -> Option<M2> {
486        let (jx, jq) = self.constraint(t, p);
487        let inv = inverse(&jx)?;
488        Some(std::array::from_fn(|i| std::array::from_fn(|j| inv[i][j] * jq[j])))
489    }
490
491    /// J' theta' = J_x^-1 w: the plate's acceleration at arm speeds `wt` and no arm acceleration.
492    pub fn velocity_term(&self, t: V2, p: V2, wt: V2, pv: V2) -> Option<V2> {
493        let (jx, _) = self.constraint(t, p);
494        let inv = inverse(&jx)?;
495        let w: V2 = std::array::from_fn(|i| {
496            let [_, d1, d2] = self.elbow(i, t[i]);
497            let rel = sub(pv, d1.map(|v| v * wt[i]));
498            wt[i] * wt[i] * dot(jx[i], d2) - dot(rel, rel)
499        });
500        Some(mul(&inv, w))
501    }
502}
503
504pub struct LinkageMachine {
505    legs: Legs,
506    /// The geometry as configured, for the scene: base and platform radius, the rods' spacing.
507    base_radius: f64,
508    platform_radius: f64,
509    rod_spacing: f64,
510    elastic: bool,
511    g: f64,
512    /// I_b without the rotor, m_LG, plate mass without and with payload (forearm share included).
513    arm_inertia: f64,
514    arm_moment: f64,
515    m_platform: f64,
516    /// The same two for the weight: the potential energy of a rod is its mass at its middle, so the forearms' weight splits
517    /// half to the elbow and half to the plate whatever share their inertia is split by.
518    weight_moment: f64,
519    weight_platform: f64,
520    /// Each forearm pair's mass and the share of it the inertia puts at the elbow, for the frame momentum (the rods'
521    /// own, `frame_momentum`).
522    m_forearms: f64,
523    forearm_share: f64,
524    m_payload: f64,
525    payload_attached: bool,
526    brake_engaged: bool,
527    /// An obstacle's push on the plate (`Machine::set_tool_force`), along x and z, N; held until changed.
528    tool_push: V2,
529    joints: [RotaryJoint; 2],
530    thermal: Option<ThermalFeedback>,
531    /// The working range: half width, top, bottom circle's centre height and radius; the condition number refused above.
532    half_width: f64,
533    top: f64,
534    circle: (f64, f64),
535    max_condition: f64,
536    axes: [AxisInfo; 2],
537    motors: [MotorInfo; 2],
538    /// The gearbox nodes' ids, for their warmth.
539    gearbox_ids: [&'static str; 2],
540    /// `Machine::setpoint_slack`, worked out once (`rest_sag`).
541    rest_slack: f64,
542}
543
544// Elastic state: [theta 1, 2, omega 1, 2, rotor angle 1, 2, rotor speed 1, 2, brake 1, 2].
545const N_ELASTIC: usize = 10;
546// Rigid state: [theta 1, 2, omega 1, 2, brake 1, 2].
547const N_RIGID: usize = 6;
548
549/// The losses of one moment: per joint its friction, its motor's friction with the brake, its gearbox; the stops and
550/// what the ripple gives off; and per joint the gearbox loss as a torque at the rotor.
551struct Losses {
552    powers: [f64; 8],
553    gear_at_rotor: V2,
554}
555
556impl LinkageMachine {
557    /// The plate at `p` (x, z) and the payload under it, as `scene` draws them.
558    fn on_platform(&self, p: V2) -> Vec<Part> {
559        let size = 2.4 * self.platform_radius.max(0.03);
560        let mut parts = vec![Part::new(
561            "platform",
562            Shape::Box { size: [size, self.rod_spacing.max(0.06) + 0.03, 0.03] },
563            [p[0], 0.0, p[1]],
564            [0.55, 0.55, 0.6],
565        )];
566        if self.payload_attached && self.m_payload > 0.0 {
567            parts.push(Part::new(
568                "payload",
569                Shape::Box { size: [0.12, 0.12, 0.1] },
570                [p[0], 0.0, p[1] - 0.07],
571                [0.2, 0.7, 0.3],
572            ));
573        }
574        parts
575    }
576
577    /// The planar linkage of a crate's tables: `[geometry]`, `[mass]`, `[workspace]`, one `[joint]` for both arms, the
578    /// axes `x` and `z`.
579    pub fn new(cfg: &Config) -> Result<Self, ConfigError> {
580        Self::build(cfg, cfg, Arms::shared(cfg, [("x", "axis-x"), ("z", "axis-z")])?)
581    }
582
583    /// The planar linkage of a machine file's node.
584    pub fn from_node(cfg: &Config, net: &Netlist, node: &LinkageNode) -> Result<Self, ConfigError> {
585        Self::build(cfg, node, Arms::of_file(cfg, net)?)
586    }
587
588    /// The machine from its numbers (`n`, by their paths in a crate's tables) and its drives; the effects from `cfg`.
589    pub fn build(cfg: &Config, n: &dyn Numbers, arms: Arms<2>) -> Result<Self, ConfigError> {
590        let base_radius = n.positive("geometry.base_radius_m")?;
591        let platform_radius = n.non_negative("geometry.platform_radius_m")?;
592        let (la, lb) = (n.positive("geometry.upper_arm_m")?, n.positive("geometry.forearm_m")?);
593        if lb <= la {
594            return Err(n.invalid("geometry.forearm_m"));
595        }
596        let share = n.non_negative("mass.forearm_elbow_share")?;
597        if share > 1.0 {
598            return Err(n.invalid("mass.forearm_elbow_share"));
599        }
600        let (m_arm, cg, i_arm) = (
601            n.positive("mass.upper_arm_kg")?,
602            n.non_negative("mass.upper_arm_cg_m")?,
603            n.positive("mass.upper_arm_inertia_kgm2")?,
604        );
605        let (m_elbow, m_fb) = (n.non_negative("mass.elbow_kg")?, n.non_negative("mass.forearm_pair_kg")?);
606        let elbow = m_elbow + share * m_fb;
607        let (half_width, top) = (n.positive("workspace.half_width_m")?, n.number("workspace.top_z_m")?);
608        let (edge, centre) = (n.positive("workspace.height_edge_m")?, n.positive("workspace.height_centre_m")?);
609        if centre < edge {
610            return Err(n.invalid("workspace.height_centre_m"));
611        }
612        // The bottom: a circle through the centre's depth and both edges; flat where both heights are the same.
613        let sag = centre - edge;
614        let circle = if sag > 0.0 {
615            let r = (half_width * half_width + sag * sag) / (2.0 * sag);
616            (top - centre + r, r)
617        } else {
618            (f64::INFINITY, f64::INFINITY)
619        };
620        let mut machine = Self {
621            legs: Legs::new(base_radius - platform_radius, la, lb),
622            base_radius,
623            platform_radius,
624            rod_spacing: n.non_negative("geometry.forearm_spacing_m")?,
625            elastic: cfg.bool("effects.joint_elasticity")?,
626            g: if cfg.bool("effects.gravity")? { G } else { 0.0 },
627            arm_inertia: i_arm + la * la * elbow,
628            arm_moment: m_arm * cg + la * elbow,
629            m_platform: n.positive("mass.platform_kg")? + 2.0 * (1.0 - share) * m_fb,
630            weight_moment: m_arm * cg + la * (m_elbow + 0.5 * m_fb),
631            weight_platform: n.positive("mass.platform_kg")? + m_fb,
632            m_forearms: m_fb,
633            forearm_share: share,
634            m_payload: if cfg.bool("effects.payload")? { n.non_negative("mass.payload_kg")? } else { 0.0 },
635            payload_attached: true,
636            brake_engaged: false,
637            tool_push: [0.0; 2],
638            thermal: ThermalFeedback::from_config(cfg)?,
639            half_width,
640            top,
641            circle,
642            max_condition: n.positive("workspace.max_condition_number")?,
643            axes: [arms.axis(cfg, 0, -half_width, half_width)?, arms.axis(cfg, 1, top - centre, top)?],
644            motors: arms.motors,
645            gearbox_ids: arms.gearboxes,
646            joints: arms.joints,
647            rest_slack: 0.0,
648        };
649        machine.rest_slack = machine.rest_sag();
650        Ok(machine)
651    }
652
653    /// How far the motors' pose can be from the tool's at rest anywhere in the working range, payload on or off: each
654    /// gearbox twisted by the torque it holds against gravity over its stiffness, plus half its backlash either way
655    /// (all four combinations), through the forward kinematics. Over a grid of the range, 41 columns of 9 heights and
656    /// the bottom; plus a tenth for what the grid steps over and the joints' friction. At least 0.1 mm; that alone in
657    /// the rigid model, whose gearboxes do not twist.
658    fn rest_sag(&self) -> f64 {
659        if !self.elastic {
660            return 1e-4;
661        }
662        let mut most = 0f64;
663        for column in 0..=40 {
664            let x = self.half_width * (column as f64 / 20.0 - 1.0);
665            let lowest = self.bottom(x);
666            for z in (0..=8).map(|k| lowest + (self.top - lowest) * k as f64 / 8.0) {
667                let p = [x, z];
668                if !self.in_envelope(&p, 1e-9) {
669                    continue;
670                }
671                let Some(t) = self.legs.inverse(p) else { continue };
672                let Some(j) = self.legs.jacobian(t, p) else { continue };
673                for m in [self.weight_platform, self.weight_platform + self.m_payload] {
674                    let twist: V2 = std::array::from_fn(|k| {
675                        let held = -(self.g * self.weight_moment * t[k].cos() - m * self.g * j[1][k])
676                            - self.joints[k].output_torque(t[k], 0.0);
677                        self.joints[k].gearbox.spring_twist_signed(held)
678                    });
679                    for signs in 0..4 {
680                        let half = |k: usize| {
681                            (if signs >> k & 1 == 1 { 1.0 } else { -1.0 }) * self.joints[k].gearbox.half_backlash
682                        };
683                        if let Some(q) = self.legs.forward(std::array::from_fn(|k| t[k] + twist[k] + half(k))) {
684                            most = most.max(norm(sub(q, p)));
685                        }
686                    }
687                }
688            }
689        }
690        (1.1 * most).max(1e-4)
691    }
692
693    pub fn legs(&self) -> &Legs {
694        &self.legs
695    }
696
697    /// The point mass at the plate.
698    pub fn m_nt(&self) -> f64 {
699        self.m_platform + if self.payload_attached { self.m_payload } else { 0.0 }
700    }
701
702    /// The arm's inertia about its joint, elbow share of the forearms included, rotor not.
703    pub fn arm_inertia(&self) -> f64 {
704        self.arm_inertia
705    }
706
707    /// m_LG: the arm's gravity torque is g m_LG cos(theta).
708    pub fn arm_moment(&self) -> f64 {
709        self.arm_moment
710    }
711
712    /// Arm angles and speeds of a state.
713    fn arms(&self, s: &[f64]) -> (V2, V2) {
714        ([s[0], s[1]], [s[2], s[3]])
715    }
716
717    /// Rotor angles and speeds of a state.
718    fn rotors(&self, s: &[f64]) -> (V2, V2) {
719        if self.elastic {
720            ([s[4], s[5]], [s[6], s[7]])
721        } else {
722            let i: V2 = std::array::from_fn(|k| self.joints[k].ratio());
723            ([s[0] * i[0], s[1] * i[1]], [s[2] * i[0], s[3] * i[1]])
724        }
725    }
726
727    fn brakes(&self, s: &[f64]) -> V2 {
728        let at = if self.elastic { 8 } else { 4 };
729        [s[at], s[at + 1]]
730    }
731
732    /// Where the plate is and the Jacobian there, for arm angles; NaN where the legs cannot be assembled.
733    pub fn pose(&self, t: V2) -> (V2, M2) {
734        self.legs
735            .forward(t)
736            .and_then(|p| Some((p, self.legs.jacobian(t, p)?)))
737            .unwrap_or(([f64::NAN; 2], [[f64::NAN; 2]; 2]))
738    }
739
740    /// The load's mass matrix M, the velocity term m_nt J^T J' theta', and the generalised gravity Q_g at arm angles t
741    /// and speeds w.
742    fn load(&self, t: V2, w: V2) -> (M2, V2, V2) {
743        let (p, j) = self.pose(t);
744        let jt = transpose(&j);
745        let m = self.m_nt();
746        let mass: M2 = std::array::from_fn(|r| {
747            std::array::from_fn(|c| m * dot(jt[r], jt[c]) + if r == c { self.arm_inertia } else { 0.0 })
748        });
749        let pv = mul(&j, w);
750        let velocity = self.legs.velocity_term(t, p, w, pv).map_or([f64::NAN; 2], |a| mul(&jt, a.map(|v| m * v)));
751        let mw = self.weight_platform + if self.payload_attached { self.m_payload } else { 0.0 };
752        let gravity: V2 = std::array::from_fn(|k| self.g * self.weight_moment * t[k].cos() - mw * self.g * j[1][k]);
753        (mass, velocity, gravity)
754    }
755
756    /// An obstacle's push on the plate F (`set_tool_force`) on the arms, J^T F: in the equations of motion only, not
757    /// in the feedforward or the state at rest (as the machine files' process force and push).
758    fn push(&self, t: V2) -> V2 {
759        mul(&transpose(&self.pose(t).1), self.tool_push)
760    }
761
762    /// Rigid model: the arms' acceleration, and per joint the torque into its gearbox (after the rotor's own
763    /// acceleration) and out of it, at the arm.
764    fn rigid_solve(&self, s: &[f64], torque: &[f64]) -> (V2, V2, V2) {
765        let (t, w) = self.arms(s);
766        let (rotor, rotor_speed) = self.rotors(s);
767        let brakes = self.brakes(s);
768        let (mass, velocity, gravity) = self.load(t, w);
769        let drive: V2 = std::array::from_fn(|k| {
770            self.joints[k].rigid_drive(torque[k], rotor[k], rotor_speed[k], brakes[k], self.brake_engaged).0
771        });
772        let push = self.push(t);
773        let rest: V2 =
774            std::array::from_fn(|k| gravity[k] + push[k] - velocity[k] + self.joints[k].output_torque(t[k], w[k]));
775        let solve = |loss: V2| -> V2 {
776            let m: M2 = std::array::from_fn(|r| {
777                std::array::from_fn(|c| {
778                    mass[r][c] + if r == c { loss[r] * self.joints[r].reflected_inertia() } else { 0.0 }
779                })
780            });
781            let rhs: V2 = std::array::from_fn(|k| loss[k] * drive[k] + rest[k]);
782            inverse(&m).map_or([f64::NAN; 2], |inv| mul(&inv, rhs))
783        };
784        // The loss factors of the torques going in, at their fixed point (`mech::settled_loss`).
785        let loss = sim_components::mech::settled_loss([1.0; 2], |loss| {
786            let acc = solve(*loss);
787            std::array::from_fn(|k| {
788                self.joints[k].gearbox.loss_factor(drive[k] - self.joints[k].reflected_inertia() * acc[k], w[k])
789            })
790        });
791        let acc = solve(loss);
792        let into: V2 = std::array::from_fn(|k| drive[k] - self.joints[k].reflected_inertia() * acc[k]);
793        (acc, into, std::array::from_fn(|k| loss[k] * into[k]))
794    }
795
796    /// The arms' acceleration in either model.
797    fn arm_acceleration(&self, s: &[f64], torque: &[f64]) -> V2 {
798        if self.elastic {
799            let mut d = [0.0; N_ELASTIC];
800            self.derivatives(s, torque, &mut d);
801            [d[2], d[3]]
802        } else {
803            self.rigid_solve(s, torque).0
804        }
805    }
806
807    /// The torque each gearbox passes to its arm.
808    fn gear_output(&self, s: &[f64], torque: &[f64]) -> V2 {
809        if self.elastic {
810            std::array::from_fn(|k| self.joints[k].gearbox.torque(s[4 + k], s[6 + k], s[k], s[2 + k]).output)
811        } else {
812            self.rigid_solve(s, torque).2
813        }
814    }
815
816    pub fn energy_parts(&self, s: &[f64]) -> [f64; 3] {
817        let (t, w) = self.arms(s);
818        let (mass, ..) = self.load(t, w);
819        let mut kinetic = 0.5 * dot(w, mul(&mass, w));
820        let (p, _) = self.pose(t);
821        let mw = self.weight_platform + if self.payload_attached { self.m_payload } else { 0.0 };
822        let potential = self.g * (mw * p[1] - self.weight_moment * (t[0].sin() + t[1].sin()));
823        let mut elastic: f64 = (0..2).map(|k| self.joints[k].stop_energy(t[k])).sum();
824        if self.elastic {
825            for k in 0..2 {
826                kinetic += 0.5 * self.joints[k].rotor_inertia * s[6 + k] * s[6 + k];
827                elastic += self.joints[k].gearbox.energy(s[4 + k], s[k]);
828            }
829        } else {
830            kinetic += 0.5 * (0..2).map(|k| self.joints[k].reflected_inertia() * w[k] * w[k]).sum::<f64>();
831        }
832        [kinetic, potential, elastic]
833    }
834
835    fn losses(&self, s: &[f64], torque: &[f64]) -> Losses {
836        let (t, w) = self.arms(s);
837        let (rotor, rotor_speed) = self.rotors(s);
838        let brakes = self.brakes(s);
839        let mut powers = [0.0; 8];
840        let mut gear_at_rotor = [0.0; 2];
841        let rigid = (!self.elastic).then(|| self.rigid_solve(s, torque));
842        let (mut stops, mut other) = (0.0, 0.0);
843        for k in 0..2 {
844            let joint = &self.joints[k];
845            let [friction, stop, shaft, drag] = joint.losses(t[k], w[k], rotor_speed[k], brakes[k], self.brake_engaged);
846            let gear = match &rigid {
847                Some((_, into, out)) => {
848                    gear_at_rotor[k] = (into[k] - out[k]) / joint.ratio();
849                    (into[k] - out[k]) * w[k]
850                }
851                None => {
852                    let g = joint.gearbox.torque(s[4 + k], s[6 + k], s[k], s[2 + k]);
853                    gear_at_rotor[k] = g.rotor - g.output / joint.ratio();
854                    joint.gearbox.loss_power(s[4 + k], s[6 + k], s[k], s[2 + k])
855                }
856            };
857            powers[3 * k..3 * k + 3].copy_from_slice(&[friction, shaft, gear + drag]);
858            stops += stop;
859            other += (torque[k] - joint.ripple.apply(torque[k], rotor[k])) * rotor_speed[k];
860        }
861        powers[6] = stops;
862        powers[7] = other;
863        Losses { powers, gear_at_rotor }
864    }
865
866    /// The working range's bottom below x: on the circle, or flat.
867    fn bottom(&self, x: f64) -> f64 {
868        let (centre, r) = self.circle;
869        if centre.is_finite() { centre - (r * r - x * x).max(0.0).sqrt() } else { self.axes[1].min }
870    }
871
872    /// Whether a pose is within the working range (the band |x| <= half width below the top, above the bottom
873    /// circle), widened by `slack`.
874    fn in_envelope(&self, p: &[f64], slack: f64) -> bool {
875        let (centre, r) = self.circle;
876        let above =
877            if centre.is_finite() { p[0].hypot(p[1] - centre) <= r + slack } else { p[1] >= self.axes[1].min - slack };
878        p[0].abs() <= self.half_width + slack && p[1] <= self.top + slack && above
879    }
880
881    /// The torque breakdown, loss powers, energies of the effect views.
882    fn view_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
883        let (t, w) = self.arms(s);
884        let (_, rotor_speed) = self.rotors(s);
885        let brakes = self.brakes(s);
886        let (mass, velocity, gravity) = self.load(t, w);
887        let acc = self.arm_acceleration(s, torque);
888        let moving = mul(&mass, acc);
889        let losses = self.losses(s, torque);
890        for k in 0..2 {
891            let joint = &self.joints[k];
892            let i = joint.ratio();
893            let held = joint.brake.torque(self.brake_engaged, rotor_speed[k], brakes[k]).0;
894            let parts = [
895                (moving[k] + velocity[k] + joint.reflected_inertia() * acc[k]) / i,
896                -gravity[k] / i,
897                joint.shaft.torque(rotor_speed[k]) + held + losses.gear_at_rotor[k] + joint.friction.torque(w[k]) / i,
898            ];
899            out.extend(parts);
900            out.push(torque[k] - parts.iter().sum::<f64>());
901        }
902        out.extend(losses.powers);
903        out.extend(self.energy_parts(s));
904        for k in 0..2 {
905            out.extend(self.joints[k].friction_signals(w[k]));
906        }
907    }
908
909    fn effect_infos(&self, out: &mut Vec<SignalInfo>) {
910        for motor in &self.motors {
911            out.extend(TORQUE_PARTS.map(|part| {
912                SignalInfo::new(
913                    format!("motor.{}.torque_{part}", motor.id),
914                    motor.key,
915                    &format!("quantity-torque-{part}"),
916                    "N m",
917                )
918            }));
919        }
920        for (k, motor) in self.motors.iter().enumerate() {
921            let arm = ["arm-1", "arm-2"][k];
922            let gear = if self.joints[k].gearbox.is_coupling() {
923                "quantity-coupling-loss-power"
924            } else {
925                "quantity-gearbox-loss-power"
926            };
927            out.push(SignalInfo::new(format!("{LOSS_PREFIX}joint_{}", motor.id), arm, "quantity-friction-power", "W"));
928            out.push(SignalInfo::new(
929                format!("{LOSS_PREFIX}shaft_{}", motor.id),
930                motor.key,
931                "quantity-shaft-friction-power",
932                "W",
933            ));
934            out.push(SignalInfo::new(format!("{LOSS_PREFIX}gearbox_{}", motor.id), motor.key, gear, "W"));
935        }
936        out.push(SignalInfo::new(format!("{LOSS_PREFIX}hard_stops"), "group-joint", "quantity-damping-power", "W"));
937        out.push(SignalInfo::new(format!("{LOSS_PREFIX}other"), "loss-other", "quantity-power-given-off", "W"));
938        out.extend(ENERGY_PARTS.map(|part| {
939            SignalInfo::new(format!("energy.{part}"), "group-energy", &format!("quantity-energy-{part}"), "J")
940        }));
941        for k in 0..2 {
942            out.extend(RotaryJoint::friction_infos(JOINT_CONTACTS[k], ["arm-1", "arm-2"][k]));
943        }
944    }
945
946    /// The arms whose gearbox is one (not a coupling), in the order of `thermal_parts`.
947    fn geared(&self) -> impl Iterator<Item = usize> + '_ {
948        (0..2).filter(|&k| !self.joints[k].gearbox.is_coupling())
949    }
950}
951
952/// The ids of the arms' friction contacts (`<id>.friction_<part>`), in the motors' order.
953const JOINT_CONTACTS: [&str; 2] = ["joint.1", "joint.2"];
954
955impl Machine for LinkageMachine {
956    /// As the registered planar delta's: the plate at the tool, the arms turning about their joints at the base radius,
957    /// the rotors about the joints' axes (+-y). The forearms are the rods they are, whatever share of their inertia the
958    /// dynamics lump at the elbow: a rod's momentum, first moment and angular momentum (its turn in the plane included)
959    /// are those of a sixth of it at each end and two thirds at its middle, so its weight sits where the potential has
960    /// it. What does not move is left out (see `FrameMomentum`).
961    fn frame_momentum(&self, s: &[f64]) -> Option<sim_core::FrameMomentum> {
962        use sim_components::base::{add_point, add_spin, add_turning};
963        let mut f = sim_core::FrameMomentum { gravity: [0.0, 0.0, -self.g], ..Default::default() };
964        let (t, w) = self.arms(s);
965        let (p, j) = self.pose(t);
966        let pv = mul(&j, w);
967        let (la, m_fb) = (self.legs.la, self.m_forearms);
968        // What the lumped split puts at the elbow and at the plate beyond a rod's sixth at each end.
969        let (at_elbow, at_plate) = ((self.forearm_share - 1.0 / 6.0) * m_fb, (5.0 / 6.0 - self.forearm_share) * m_fb);
970        add_point(&mut f, self.m_nt() - 2.0 * at_plate, [p[0], 0.0, p[1]], [pv[0], 0.0, pv[1]]);
971        let rotor_speed = self.rotors(s).1;
972        for i in 0..2 {
973            let (side, (sin, cos)) = (SIDE[i], t[i].sin_cos());
974            let (dir, ddir) = ([side * cos, 0.0, -sin], [-side * sin, 0.0, -cos]);
975            let joint = [side * self.base_radius, 0.0, 0.0];
976            add_turning(
977                &mut f,
978                joint,
979                dir,
980                ddir,
981                w[i],
982                self.arm_inertia - la * la * at_elbow,
983                self.arm_moment - la * at_elbow,
984            );
985            let middle: [f64; 3] = std::array::from_fn(|k| {
986                0.5 * (joint[k] + la * dir[k] + [p[0] + side * self.platform_radius, 0.0, p[1]][k])
987            });
988            let speed: [f64; 3] = std::array::from_fn(|k| 0.5 * (la * w[i] * ddir[k] + [pv[0], 0.0, pv[1]][k]));
989            add_point(&mut f, 2.0 / 3.0 * m_fb, middle, speed);
990            add_spin(&mut f, [0.0, side, 0.0], self.joints[i].rotor_inertia, rotor_speed[i]);
991        }
992        // An obstacle's push on the plate is not in the outside force: a compliant base takes it through the tool's
993        // shift (`base::Based`), and here it pushed the base a second time.
994        f.external_at = [p[0], 0.0, p[1]];
995        Some(f)
996    }
997    fn axes(&self) -> &[AxisInfo] {
998        &self.axes
999    }
1000    fn motors(&self) -> &[MotorInfo] {
1001        &self.motors
1002    }
1003
1004    /// NaN where the pose is out of reach: the controller never asks for one (see `unreachable`).
1005    fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
1006        let t = self.legs.inverse([tool[0], tool[1]]).unwrap_or([f64::NAN; 2]);
1007        for k in 0..2 {
1008            motors[k] = self.joints[k].ratio() * t[k];
1009        }
1010    }
1011    fn forward(&self, motors: &[f64], tool: &mut [f64]) {
1012        let t = std::array::from_fn(|k| motors[k] / self.joints[k].ratio());
1013        let p = self.legs.forward(t).unwrap_or([f64::NAN; 2]);
1014        tool[..2].copy_from_slice(&p);
1015    }
1016
1017    fn state_len(&self) -> usize {
1018        if self.elastic { N_ELASTIC } else { N_RIGID }
1019    }
1020
1021    fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
1022        let t = self.legs.inverse([tool[0], tool[1]]).unwrap_or([f64::NAN; 2]);
1023        let (_, _, gravity) = self.load(t, [0.0; 2]);
1024        state.clear();
1025        state.extend(t);
1026        state.extend([0.0; 2]);
1027        for k in 0..2 {
1028            let joint = &self.joints[k];
1029            // At rest the gearbox holds the arm against gravity and the stops.
1030            let out = -gravity[k] - joint.output_torque(t[k], 0.0);
1031            let rotor = joint.ratio() * (t[k] + if self.elastic { joint.gearbox.static_twist(out) } else { 0.0 });
1032            if self.elastic {
1033                state.push(rotor);
1034            }
1035            torque[k] = joint.ripple.invert(out / joint.ratio(), rotor);
1036        }
1037        // Rotor speeds and brakes at rest.
1038        state.resize(self.state_len(), 0.0);
1039    }
1040
1041    fn derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
1042        if !self.elastic {
1043            let (acc, ..) = self.rigid_solve(s, torque);
1044            let (_, rotor_speed) = self.rotors(s);
1045            let brakes = self.brakes(s);
1046            out[..2].copy_from_slice(&s[2..4]);
1047            out[2..4].copy_from_slice(&acc);
1048            for k in 0..2 {
1049                out[4 + k] = self.joints[k].brake.torque(self.brake_engaged, rotor_speed[k], brakes[k]).1;
1050            }
1051            return;
1052        }
1053        let (t, w) = self.arms(s);
1054        let ((mass, velocity, gravity), push) = (self.load(t, w), self.push(t));
1055        let mut rhs = [0.0; 2];
1056        for k in 0..2 {
1057            let joint = &self.joints[k];
1058            let (gear, rotor_acc, brake_rate) =
1059                joint.rotor(torque[k], s[4 + k], s[6 + k], t[k], w[k], s[8 + k], self.brake_engaged);
1060            rhs[k] = gear.output + gravity[k] + push[k] - velocity[k] + joint.output_torque(t[k], w[k]);
1061            out[4 + k] = s[6 + k];
1062            out[6 + k] = rotor_acc;
1063            out[8 + k] = brake_rate;
1064        }
1065        let acc = inverse(&mass).map_or([f64::NAN; 2], |inv| mul(&inv, rhs));
1066        out[..2].copy_from_slice(&s[2..4]);
1067        out[2..4].copy_from_slice(&acc);
1068    }
1069
1070    fn tool_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1071        let (t, w) = self.arms(s);
1072        let (p, j) = self.pose(t);
1073        pos[..2].copy_from_slice(&p);
1074        vel[..2].copy_from_slice(&mul(&j, w));
1075    }
1076    fn set_tool_velocity(&self, s: &mut [f64], vel: &[f64]) {
1077        let (t, _) = self.arms(s);
1078        let (_, j) = self.pose(t);
1079        let w = inverse(&j).map_or([f64::NAN; 2], |inv| mul(&inv, [vel[0], vel[1]]));
1080        s[2..4].copy_from_slice(&w);
1081        if self.elastic {
1082            for k in 0..2 {
1083                s[6 + k] = self.joints[k].ratio() * w[k];
1084            }
1085        }
1086    }
1087    fn motor_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1088        let (rotor, speed) = self.rotors(s);
1089        pos[..2].copy_from_slice(&rotor);
1090        vel[..2].copy_from_slice(&speed);
1091    }
1092
1093    /// Rigid, loss-free, at rest: M theta'' - Q_g at the arm over the ratio, plus the rotor's own J_rotor i theta''.
1094    fn feedforward_torque(&self, pos: &[f64], acc: &[f64], out: &mut [f64]) {
1095        let t = self.legs.inverse([pos[0], pos[1]]).unwrap_or([f64::NAN; 2]);
1096        let (mass, _, gravity) = self.load(t, [0.0; 2]);
1097        let (_, j) = self.pose(t);
1098        let arm_acc = inverse(&j).map_or([f64::NAN; 2], |inv| mul(&inv, [acc[0], acc[1]]));
1099        let at_arm = mul(&mass, arm_acc);
1100        for k in 0..2 {
1101            let joint = &self.joints[k];
1102            out[k] = (at_arm[k] - gravity[k]) / joint.ratio() + joint.rotor_inertia * joint.ratio() * arm_acc[k];
1103        }
1104    }
1105
1106    /// With the speed: theta' = J^-1 p', theta'' = J^-1 (p'' - J_x^-1 w), and at the arm I_b theta'' + m_nt J^T p'' -
1107    /// Q_g, over the ratio, plus the rotor's own J_rotor i theta''.
1108    fn feedforward_torque_moving(&self, pos: &[f64], vel: &[f64], acc: &[f64], out: &mut [f64]) {
1109        let p = [pos[0], pos[1]];
1110        let t = self.legs.inverse(p).unwrap_or([f64::NAN; 2]);
1111        let (_, _, gravity) = self.load(t, [0.0; 2]);
1112        let (_, j) = self.pose(t);
1113        let inv = inverse(&j).unwrap_or([[f64::NAN; 2]; 2]);
1114        let (pv, pa) = ([vel[0], vel[1]], [acc[0], acc[1]]);
1115        let w = mul(&inv, pv);
1116        let bend = self.legs.velocity_term(t, p, w, pv).unwrap_or([f64::NAN; 2]);
1117        let arm_acc = mul(&inv, [pa[0] - bend[0], pa[1] - bend[1]]);
1118        let force = transpose(&j).map(|column| self.m_nt() * dot(column, pa));
1119        for k in 0..2 {
1120            let joint = &self.joints[k];
1121            out[k] = (self.arm_inertia * arm_acc[k] + force[k] - gravity[k]) / joint.ratio()
1122                + joint.rotor_inertia * joint.ratio() * arm_acc[k];
1123        }
1124    }
1125
1126    /// The rigid model at a steady speed, theta' = J^-1 p': per arm the joint's friction f(theta') through the gearbox
1127    /// as `rigid_solve` takes it, f / (i loss), plus the motor shaft's friction (with the gearbox's drag) at i theta'.
1128    /// The loss factor is the one of what the gearbox passes at rest, f - Q_g, as in `rigid_solve`; the weight's lossless torque
1129    /// is the rigid feedforward's, so the loss on the weight is part of what this returns; so is the loss on the speed's
1130    /// own torque at the arm, I_b theta'' at p'' = 0 with theta'' = -J^-1 J_x^-1 w (the feedforward's, loss-free). The
1131    /// brake is released and the stops are not touched in a move.
1132    fn steady_friction(&self, pos: &[f64], vel: &[f64], out: &mut [f64]) {
1133        let p = [pos[0], pos[1]];
1134        let t = self.legs.inverse(p).unwrap_or([f64::NAN; 2]);
1135        let (_, j) = self.pose(t);
1136        let inv = inverse(&j).unwrap_or([[f64::NAN; 2]; 2]);
1137        let pv = [vel[0], vel[1]];
1138        let w = mul(&inv, pv);
1139        let bend = self.legs.velocity_term(t, p, w, pv).unwrap_or([f64::NAN; 2]);
1140        let arm_acc = mul(&inv, bend.map(|b| -b));
1141        let gravity = self.load(t, [0.0; 2]).2;
1142        for k in 0..2 {
1143            let joint = &self.joints[k];
1144            let moving = self.arm_inertia * arm_acc[k];
1145            let passed = moving + joint.friction.torque(w[k]) - gravity[k];
1146            let loss = steady_loss(&joint.gearbox, passed, w[k]);
1147            // The loss acts on the weight and the speed's torque too: what it adds over their lossless torques (the
1148            // rigid feedforward's) is friction.
1149            out[k] = joint.shaft.torque(joint.ratio() * w[k]) + (passed / loss - moving + gravity[k]) / joint.ratio();
1150        }
1151    }
1152
1153    /// With effects.joint_elasticity: per arm its gearbox's spring between the rotor and the rest of the motor's rigid
1154    /// inertia at the pose (`RotaryJoint::train`).
1155    fn trains(&self, tool_pose: &[f64]) -> Vec<Option<sim_core::Train>> {
1156        if !self.elastic {
1157            return Vec::new();
1158        }
1159        let whole = sim_components::control::rigid_inertias(self, tool_pose);
1160        let mut out: Vec<_> = self.joints.iter().zip(whole).map(|(j, whole)| j.train(whole)).collect();
1161        out.resize(self.motors().len(), None);
1162        out
1163    }
1164
1165    fn energy(&self, s: &[f64]) -> f64 {
1166        self.energy_parts(s).iter().sum()
1167    }
1168
1169    fn set_payload_attached(&mut self, attached: bool) {
1170        self.payload_attached = attached;
1171    }
1172    /// The push acts on the plate, the tool (`push`): its generalised forces J^T F on the arms, whose power F . v is
1173    /// the plate's speed times it.
1174    fn set_tool_force(&mut self, force: &[f64]) -> bool {
1175        self.tool_push = [force[0], force[1]];
1176        true
1177    }
1178    fn set_brake_engaged(&mut self, engaged: bool) {
1179        self.brake_engaged = engaged;
1180    }
1181    /// A stop met within the step (`HardStop::substeps`, `RotaryJoint::stop_substeps`).
1182    fn substeps_wanted(&self, s: &[f64], _torque: &[f64], dt: f64, _substeps: u32) -> u32 {
1183        let (t, w) = self.arms(s);
1184        (0..t.len()).map(|k| self.joints[k].stop_substeps(t[k], w[k], dt)).max().unwrap_or(1)
1185    }
1186
1187    /// The gearboxes, in the order of `thermal_parts`.
1188    /// The gearboxes' hysteresis states move on to where the step ended (`Gearbox::commit`).
1189    fn after_step(&mut self, s: &mut [f64], _dt: f64) {
1190        if self.elastic {
1191            for k in 0..2 {
1192                self.joints[k].gearbox.commit(s[4 + k], s[k]);
1193            }
1194        }
1195    }
1196    fn memory(&self) -> Vec<f64> {
1197        sim_components::mech::Gearbox::anchors(self.joints.iter().map(|j| &j.gearbox))
1198    }
1199    fn set_memory(&mut self, memory: &[f64]) {
1200        sim_components::mech::Gearbox::set_anchors(self.joints.iter_mut().map(|j| &mut j.gearbox), memory)
1201    }
1202
1203    fn set_part_temperatures(&mut self, rises: &[f64]) {
1204        let Some(law) = &self.thermal else { return };
1205        let geared: Vec<usize> = self.geared().collect();
1206        for (k, rise) in geared.into_iter().zip(rises) {
1207            self.joints[k].gearbox.efficiency = law.gearbox_efficiency(*rise);
1208            self.joints[k].shaft.set_oil(law.viscosity_factor(*rise));
1209        }
1210    }
1211
1212    /// What the gearboxes can sag at rest anywhere in the working range (`rest_sag`).
1213    fn setpoint_slack(&self) -> f64 {
1214        self.rest_slack
1215    }
1216
1217    fn unreachable(&self, tool: &[f64], slack: f64) -> Option<&'static str> {
1218        if tool.len() != 2 {
1219            return Some("error-target-out-of-range");
1220        }
1221        let p = [tool[0], tool[1]];
1222        if !self.in_envelope(&p, slack) {
1223            return Some("error-delta-outside-envelope");
1224        }
1225        let Some(t) = self.legs.inverse(p) else { return Some("error-delta-out-of-reach") };
1226        if (0..2).any(|k| t[k] < self.joints[k].range.0 || t[k] > self.joints[k].range.1) {
1227            return Some("error-delta-joint-stop");
1228        }
1229        match self.legs.jacobian(t, p) {
1230            Some(j) if condition_number(&j) <= self.max_condition => None,
1231            _ => Some("error-delta-singularity"),
1232        }
1233    }
1234
1235    fn signal_infos(&self) -> Vec<SignalInfo> {
1236        let mut out = Vec::new();
1237        for (k, motor) in self.motors.iter().enumerate() {
1238            let arm = ["arm-1", "arm-2"][k];
1239            out.push(SignalInfo::new(format!("arm.{}.angle", motor.id), arm, "quantity-arm-angle", "rad"));
1240            out.push(SignalInfo::new(
1241                format!("gearbox.{}.output_torque", motor.id),
1242                motor.key,
1243                "quantity-gearbox-torque",
1244                "N m",
1245            ));
1246        }
1247        out.push(SignalInfo::new("kinematics.condition", "group-kinematics", "quantity-condition-number", ""));
1248        self.effect_infos(&mut out);
1249        out
1250    }
1251
1252    fn base_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1253        let (t, _) = self.arms(s);
1254        let gear = self.gear_output(s, torque);
1255        for k in 0..2 {
1256            out.extend([t[k], gear[k]]);
1257        }
1258        let (_, j) = self.pose(t);
1259        out.push(condition_number(&j));
1260    }
1261    fn effect_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1262        self.view_signals(s, torque, out);
1263    }
1264    fn loss_powers(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1265        out.extend(self.losses(s, torque).powers);
1266    }
1267
1268    /// The two arms' bearing friction, rotary contacts (N m over rad/s at the arm).
1269    fn friction_contacts(&self) -> Vec<sim_core::FrictionContact> {
1270        (0..2).map(|k| sim_core::FrictionContact { id: JOINT_CONTACTS[k], owner_key: ["arm-1", "arm-2"][k] }).collect()
1271    }
1272    fn friction_rotary(&self, _i: usize) -> bool {
1273        true
1274    }
1275    fn friction_curve(&self, i: usize, speed: f64, _load_scale: f64) -> [f64; 3] {
1276        self.joints.get(i).map_or([0.0; 3], |j| j.friction_split(speed))
1277    }
1278    /// The arm turns at its motor's highest speed over the gearbox's ratio.
1279    fn friction_speed_limit(&self, i: usize, motor_speed: &[f64]) -> Option<f64> {
1280        Some(motor_speed.get(i)? / self.joints.get(i)?.ratio())
1281    }
1282
1283    /// The gearboxes that are not couplings, by their nodes' ids.
1284    fn thermal_parts(&self) -> Vec<ThermalPart> {
1285        self.geared()
1286            .map(|k| ThermalPart {
1287                id: self.gearbox_ids[k],
1288                kind: "gearbox",
1289                owner_key: self.motors[k].key,
1290                scene_part: "gearbox",
1291                scene_index: k,
1292            })
1293            .collect()
1294    }
1295
1296    /// The machine in the plane y = 0 of the scene: base beam, per arm a motor and a gearbox box with a bar turned by
1297    /// the rotor angle, the arm, the forearm pair's two rods (apart along y, the joints' axis), the plate, the payload.
1298    fn scene(&self, s: &[f64], out: &mut Scene) {
1299        let (t, _) = self.arms(s);
1300        let (rotor, rotor_speed) = self.rotors(s);
1301        let (p, _) = self.pose(t);
1302        out.parts.clear();
1303        out.labels.clear();
1304        let grey = [0.62, 0.64, 0.68];
1305        out.parts.push(Part::new(
1306            "base",
1307            Shape::Box { size: [2.0 * self.base_radius + 0.2, 0.2, 0.04] },
1308            [0.0, 0.0, 0.1],
1309            grey,
1310        ));
1311        for k in 0..2 {
1312            let side = SIDE[k];
1313            let shoulder = [side * self.base_radius, 0.0, 0.0];
1314            // The elbow drawn where the arm ends: the legs' elbow is at e, the arm's end at the base radius.
1315            let [elbow, ..] = self.legs.elbow(k, t[k]);
1316            let arm_end = [elbow[0] + side * self.platform_radius, 0.0, elbow[1]];
1317            let at = |z: f64| [side * self.base_radius, 0.0, z];
1318            out.parts.push(Part::new(
1319                sim_core::scene::MOTOR_PART,
1320                Shape::Box { size: [0.09, 0.09, 0.12] },
1321                at(0.16),
1322                [0.9, 0.45, 0.1],
1323            ));
1324            out.parts.push(Part::new("gearbox", Shape::Box { size: [0.09, 0.09, 0.06] }, at(0.05), [0.25, 0.25, 0.28]));
1325            out.parts.push(
1326                Part::new("rotor-bar", Shape::Box { size: [0.07, 0.004, 0.012] }, at(0.225), [0.1, 0.1, 0.1])
1327                    .turned(rotor[k]),
1328            );
1329            out.parts.push(Part::new("arm", Shape::Segment { to: arm_end, width: 0.04 }, shoulder, [0.2, 0.22, 0.26]));
1330            let platform_end = [p[0] + side * self.platform_radius, 0.0, p[1]];
1331            for half in [-0.5 * self.rod_spacing, 0.5 * self.rod_spacing] {
1332                let (from, to) = ([arm_end[0], half, arm_end[2]], [platform_end[0], half, platform_end[2]]);
1333                out.parts.push(Part::new("forearm", Shape::Segment { to, width: 0.012 }, from, [0.15, 0.15, 0.15]));
1334            }
1335            out.labels.push(Label {
1336                pos: at(0.3),
1337                owner_key: self.motors[k].key,
1338                value: rotor_speed[k] * 60.0 / std::f64::consts::TAU,
1339                unit_key: "unit-rpm",
1340                decimals: 0,
1341            });
1342        }
1343        out.parts.extend(self.on_platform(p));
1344        out.labels.push(Label {
1345            pos: [p[0], 0.0, p[1] - 0.17],
1346            owner_key: self.axes[1].key,
1347            value: p[1],
1348            unit_key: "unit-m",
1349            decimals: 3,
1350        });
1351    }
1352
1353    /// The plate's centre, in the plane y = 0.
1354    fn scene_point(&self, tool_pose: &[f64]) -> Option<[f64; 3]> {
1355        Some([tool_pose[0], 0.0, tool_pose[1]])
1356    }
1357
1358    /// The plate and the payload under it, where `scene` draws them. The forearms are left out.
1359    fn collision_bodies(&self, s: &[f64]) -> Vec<sim_core::Aabb> {
1360        let (t, _) = self.arms(s);
1361        sim_core::scene::scene_boxes(&self.on_platform(self.pose(t).0), &["platform", "payload"])
1362    }
1363}