Skip to main content

machine_parallel_scara/
lib.rs

1//! Parallel SCARA: two motor-driven arms turning about vertical axes in the horizontal x-y plane, one at each side of
2//! the base, each carrying a pair of forearms to a plate that keeps its orientation (a five-bar whose outer links are
3//! parallelograms), as Mitsubishi's RP series or the parallel SCARAs with a five-bar. At the plate an optional Z stroke
4//! on a ball screw (`[z_axis]`, motor 3) and an optional turn of the tool about z (`[tool_turn]`, motor 4). The tool
5//! pose is (x, y[, z][, c]).
6//!
7//! The five-bar follows the D2's (the planar delta picker), laid flat: the same equations, copied, as a machine crate
8//! may not use another's. Leg i points along s_i x (s_1 = +1, s_2 = -1); e = base radius - platform radius (the
9//! plate's offset folded into the base, as it never turns), the arm angle theta_i (0 along x, positive towards -y),
10//! upper arm L_a, forearm L_b:
11//!
12//! ```text
13//! elbow     c_i = (s_i (e + L_a cos theta), -L_a sin theta)
14//! constraint |p - c_i|^2 = L_b^2
15//! inverse   A cos theta + B sin theta + C = 0, A = -2 L_a (x' - e), B = 2 L_a y, C = (x' - e)^2 + y^2 + L_a^2 - L_b^2
16//!           theta = 2 atan((-B - sqrt(A^2 + B^2 - C^2)) / (C - A))     (elbow out; x' = s_i x)
17//! forward   p = the one of the two points at L_b from both elbows further from the shoulders (two circles)
18//! Jacobian  J_x p' = J_q theta', J_x rows u_i = p - c_i, J_q = diag(u_i . dc_i/dtheta_i); p' = J theta', J = J_x^-1 J_q
19//!           J_x p'' = J_q theta'' + w, w_i = theta_i'^2 (u_i . c_i'') - |p' - c_i' theta_i'|^2
20//! ```
21//!
22//! Dynamics (Codourey 1998, Olsson 2009): each forearm pair's mass split, a share r at the elbow and 1 - r at the
23//! plate; two arms about their joints plus a point mass at the plate, m_nt = plate + payload + 2 (1 - r) m_fb + what
24//! the plate carries (the Z and C units, the carriage), and
25//!
26//! ```text
27//! M(theta) theta'' = tau_gear - m_nt J^T J_x^-1 w + tau_joint,   M = I_b 1 + m_nt J^T J
28//! I_b = I_arm + L_a^2 (m_elbow + r m_fb)
29//! ```
30//!
31//! Gravity acts along -z, out of the plane, on the joints' bearings: it gives the arms no torque. Each arm's joint is a
32//! `RotaryJoint`, elastic or rigid (effects.joint_elasticity). The Z stroke and the tool's turn are rigid
33//! `RotaryJoint`s from their motors' own config (`[motor.<id>]`, `[gearbox.<id>]`): the stroke's nut lifts the
34//! carriage, m_z q'' = F - m_z g, the turn spins the tool, J_c c'' = T. Both are perpendicular to the plane and about
35//! its normal, so the plane's motors feel their masses (in m_nt) and nothing else. With effects.joint_elasticity both
36//! are elastic as the arms' joints are (`Extra`): the rotor is a body of its own and the gearbox's spring (the screw's
37//! and the coupling's stiffness in series for the stroke) passes the force between rotor and carriage.
38
39use sim_components::catalog::motor_config;
40use sim_components::joint::RotaryJoint;
41use sim_components::mech::{GearTorque, HardStop, ShaftFriction, ThermalFeedback};
42use sim_components::transmission::BallScrew;
43use sim_core::{
44    AxisInfo, Config, ConfigError, ENERGY_PARTS, LOSS_PREFIX, Label, Machine, MachineEntry, MotorInfo, Part,
45    RatingCheck, Scene, Shape, SignalInfo, TORQUE_PARTS, ThermalPart,
46};
47
48const I18N: &[(&str, &str)] = &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))];
49
50pub static ENTRY: MachineEntry = MachineEntry {
51    id: "parallel-scara",
52    key: "machine-parallel-scara",
53    default_config: include_str!("../default.toml"),
54    i18n: I18N,
55    build,
56    suite_configs,
57};
58
59const G: f64 = 9.80665;
60
61/// Effects that take energy out or put it in; the standard suite runs with them off. The stops stay, without their
62/// damping.
63pub const LOSSY_EFFECTS: [&str; 7] = [
64    "joint_friction",
65    "motor_friction",
66    "gearbox_drag",
67    "gearbox_lost_motion",
68    "gearbox_efficiency",
69    "torque_ripple",
70    "holding_brake",
71];
72
73fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
74    sim_components::base::mount(cfg, Box::new(ParallelScara::new(cfg)?))
75}
76
77/// The default config with every loss switched off.
78pub fn lossless_config() -> Config {
79    let mut cfg = ENTRY.config();
80    for effect in LOSSY_EFFECTS {
81        cfg.set_text(&format!("effects.{effect} = false")).unwrap();
82    }
83    for key in ["gearbox.damping_nm_s_rad", "joint.stop_damping_nm_s_rad", "slide.stop_damping_n_s_m"] {
84        cfg.set_text(&format!("{key} = 0.0")).unwrap();
85    }
86    cfg
87}
88
89/// Loss-free rigid and elastic models, with and without the payload, and the elastic one with part heating and the
90/// temperature feedback (no loss, so the gearboxes stay at ambient).
91fn suite_configs() -> Vec<Config> {
92    let mut out = Vec::new();
93    for (elastic, payload) in [(false, true), (false, false), (true, true), (true, false)] {
94        let mut cfg = lossless_config();
95        cfg.set_text(&format!("effects.joint_elasticity = {elastic}")).unwrap();
96        cfg.set_text(&format!("effects.payload = {payload}")).unwrap();
97        cfg.set_text(&format!("effects.part_heating = {}", elastic && payload)).unwrap();
98        cfg.set_text(&format!("effects.thermal_feedback = {}", elastic && payload)).unwrap();
99        out.push(cfg);
100    }
101    out
102}
103
104/// A vector in the plane, (x, y).
105type V2 = [f64; 2];
106type M2 = [[f64; 2]; 2];
107
108fn dot(a: V2, b: V2) -> f64 {
109    a[0] * b[0] + a[1] * b[1]
110}
111
112fn sub(a: V2, b: V2) -> V2 {
113    [a[0] - b[0], a[1] - b[1]]
114}
115
116fn norm(a: V2) -> f64 {
117    dot(a, a).sqrt()
118}
119
120fn mul(m: &M2, v: V2) -> V2 {
121    [dot(m[0], v), dot(m[1], v)]
122}
123
124fn transpose(m: &M2) -> M2 {
125    [[m[0][0], m[1][0]], [m[0][1], m[1][1]]]
126}
127
128/// The inverse of a 2 x 2 matrix; `None` where it is singular.
129fn inverse(m: &M2) -> Option<M2> {
130    let det = m[0][0] * m[1][1] - m[0][1] * m[1][0];
131    if !(det.abs() > 1e-300) || !det.is_finite() {
132        return None;
133    }
134    Some([[m[1][1] / det, -m[0][1] / det], [-m[1][0] / det, m[0][0] / det]])
135}
136
137/// The 2-norm condition number of a 2 x 2 matrix: the square root of the larger over the smaller eigenvalue of
138/// J^T J, m +- sqrt(((a - c) / 2)^2 + b^2) with m = (a + c) / 2 for J^T J = [[a, b], [b, c]].
139pub fn condition_number(j: &M2) -> f64 {
140    let (a, b, c) = (
141        j[0][0] * j[0][0] + j[1][0] * j[1][0],
142        j[0][0] * j[0][1] + j[1][0] * j[1][1],
143        j[0][1] * j[0][1] + j[1][1] * j[1][1],
144    );
145    let (mean, half) = ((a + c) / 2.0, ((a - c) / 2.0).hypot(b));
146    if mean - half <= 0.0 { f64::INFINITY } else { ((mean + half) / (mean - half)).sqrt() }
147}
148
149/// A gearbox's stiffness for a mode: K1, the stiffness of the moves that excite it; for a small vibration (`small`)
150/// with hysteresis K1 + sigma, which a reversal shows.
151fn spring(g: &sim_components::mech::Gearbox, small: bool) -> f64 {
152    g.stiffness + if small && g.hysteresis > 0.0 { g.dahl_stiffness } else { 0.0 }
153}
154
155/// The shape v of (K - lambda M) v = 0, K = diag(k): orthogonal to the larger row; any shape where both rows vanish
156/// (M a multiple of K).
157fn mode_vector(k: V2, m: &M2, lambda: f64) -> V2 {
158    let rows = [[k[0] - lambda * m[0][0], -lambda * m[0][1]], [-lambda * m[1][0], k[1] - lambda * m[1][1]]];
159    let row = if norm(rows[0]) >= norm(rows[1]) { rows[0] } else { rows[1] };
160    if norm(row) > 0.0 { [-row[1], row[0]] } else { [1.0, 0.0] }
161}
162
163/// The leg geometry and the kinematics, apart from masses and drives.
164#[derive(Debug, Clone)]
165pub struct Legs {
166    /// Base radius less platform radius, upper arm, forearm.
167    pub e: f64,
168    pub la: f64,
169    pub lb: f64,
170}
171
172/// The side each leg points to along x.
173pub const SIDE: [f64; 2] = [1.0, -1.0];
174
175impl Legs {
176    pub fn new(e: f64, la: f64, lb: f64) -> Self {
177        Self { e, la, lb }
178    }
179
180    /// The elbow of leg i at arm angle t, and its first and second derivative by t, as (x, y).
181    pub fn elbow(&self, i: usize, t: f64) -> [V2; 3] {
182        let (s, c) = t.sin_cos();
183        let (la, side) = (self.la, SIDE[i]);
184        [[side * (self.e + la * c), -la * s], [-side * la * s, -la * c], [-side * la * c, la * s]]
185    }
186
187    /// Arm angles for a plate position (x, y), elbows out; `None` out of reach.
188    pub fn inverse(&self, p: V2) -> Option<V2> {
189        let mut out = [0.0; 2];
190        for (i, t) in out.iter_mut().enumerate() {
191            let (x, y) = (SIDE[i] * p[0], p[1]);
192            let (a, b, c) = (
193                -2.0 * self.la * (x - self.e),
194                2.0 * self.la * y,
195                (x - self.e).powi(2) + y * y + self.la * self.la - self.lb * self.lb,
196            );
197            let d = a * a + b * b - c * c;
198            if !(d >= 0.0) {
199                return None;
200            }
201            *t = 2.0 * ((-b - d.sqrt()) / (c - a)).atan();
202        }
203        Some(out)
204    }
205
206    /// The plate position for arm angles: the point at a forearm's length from both elbows further from the shoulders.
207    /// `None` where the legs cannot be assembled.
208    pub fn forward(&self, t: V2) -> Option<V2> {
209        let (c0, c1) = (self.elbow(0, t[0])[0], self.elbow(1, t[1])[0]);
210        let along = sub(c1, c0);
211        let d = norm(along);
212        let h2 = self.lb * self.lb - d * d / 4.0;
213        if !(d > 1e-12 && h2 >= 0.0) {
214            return None;
215        }
216        // Midway between the elbows, then h along the normal to the line joining them.
217        let (mid, h) = ([0.5 * (c0[0] + c1[0]), 0.5 * (c0[1] + c1[1])], h2.sqrt());
218        let normal = [-along[1] / d, along[0] / d];
219        let (one, other) =
220            ([mid[0] + h * normal[0], mid[1] + h * normal[1]], [mid[0] - h * normal[0], mid[1] - h * normal[1]]);
221        Some(if one[1] < other[1] { one } else { other })
222    }
223
224    /// J_x (rows: the forearm vectors u_i = p - c_i) and the diagonal of J_q (u_i . dc_i/dt).
225    fn constraint(&self, t: V2, p: V2) -> (M2, V2) {
226        let rows = [self.elbow(0, t[0]), self.elbow(1, t[1])];
227        let jx = rows.map(|e| sub(p, e[0]));
228        (jx, [dot(jx[0], rows[0][1]), dot(jx[1], rows[1][1])])
229    }
230
231    /// The Jacobian J[i][j] = dp_i / dtheta_j (rows x and y) at arm angles t and plate position p; `None` at a direct
232    /// singularity.
233    pub fn jacobian(&self, t: V2, p: V2) -> Option<M2> {
234        let (jx, jq) = self.constraint(t, p);
235        let inv = inverse(&jx)?;
236        Some(std::array::from_fn(|i| std::array::from_fn(|j| inv[i][j] * jq[j])))
237    }
238
239    /// J' theta' = J_x^-1 w: the plate's acceleration at arm speeds `wt` and no arm acceleration.
240    pub fn velocity_term(&self, t: V2, p: V2, wt: V2, pv: V2) -> Option<V2> {
241        let (jx, _) = self.constraint(t, p);
242        let inv = inverse(&jx)?;
243        let w: V2 = std::array::from_fn(|i| {
244            let [_, d1, d2] = self.elbow(i, t[i]);
245            let rel = sub(pv, d1.map(|v| v * wt[i]));
246            wt[i] * wt[i] * dot(jx[i], d2) - dot(rel, rel)
247        });
248        Some(mul(&inv, w))
249    }
250}
251
252/// An axis at the plate beside the plane's two: the Z stroke on its ball screw (in N and m), or the
253/// tool's turn about z. Its state is [position, speed, brake]; with effects.joint_elasticity also [rotor angle, rotor
254/// speed]: the joint's gearbox (stiffness, damping and backlash as configured; for the stroke `Converter::apply` has put
255/// the nut's, the shaft's (at its softest place) and the bearings' stiffness in series with the coupling's, K = 1 / (1 /
256/// K_coupling + 1 / K_screw) in N/m) is a spring between the rotor (a body of its own, J_rotor) and the carriage (the
257/// tool): m q'' = F_gear + stops and friction + weight, J_rotor w' = motor torque - gear torque, as the arms' joints
258/// have it. With the rotor held the carriage rings at sqrt(K / m) / 2 pi (`Machine::modes`); at rest the spring carries
259/// the weight, a twist F / K (`equilibrium`). The coupling's damper bridges its own spring, not the screw's: with it the
260/// state ends in the gear's Maxwell arm's (`Gearbox::arm`), and so does every extra axis's.
261struct Extra {
262    elastic: bool,
263    joint: RotaryJoint,
264    /// What it moves (kg on the stroke, kg m^2 on the turn), and the payload's share while it is held.
265    load: f64,
266    payload: f64,
267    /// Gravity along it: g on the stroke, 0 on the turn.
268    g: f64,
269    /// The stroke's screw; `None` on the turn.
270    screw: Option<BallScrew>,
271    thermal: Option<ThermalFeedback>,
272    /// An obstacle's push on its axis of the tool (`Machine::set_tool_force`), N or N m, held until changed.
273    push: f64,
274}
275
276impl Extra {
277    fn mass(&self, attached: bool) -> f64 {
278        self.load + if attached { self.payload } else { 0.0 }
279    }
280
281    /// The weight along the joint (negative: down).
282    fn weight(&self, attached: bool) -> f64 {
283        -self.g * self.mass(attached)
284    }
285
286    fn ratio(&self) -> f64 {
287        self.joint.ratio()
288    }
289
290    /// The rotor's angle and speed.
291    fn rotor(&self, x: &[f64]) -> (f64, f64) {
292        if self.elastic { (x[3], x[4]) } else { (x[0] * self.ratio(), x[1] * self.ratio()) }
293    }
294
295    /// The gear has a Maxwell arm (a damped coupling before the screw), its state x[5].
296    fn relaxes(&self) -> bool {
297        self.elastic && self.joint.gearbox.relax_stiffness > 0.0
298    }
299
300    fn arm(&self, x: &[f64]) -> f64 {
301        if self.relaxes() { x[5] } else { 0.0 }
302    }
303
304    /// The elastic gear's torques, its arm with them.
305    fn gear(&self, x: &[f64]) -> GearTorque {
306        self.joint.gearbox.torque_with(x[3], x[4], x[0], x[1], self.arm(x))
307    }
308
309    /// The acceleration, and the force (torque) into the gearbox after the rotor's own acceleration and out of it. Rigid,
310    /// as the arms' `rigid_solve`: (m + eta i^2 J_rotor) q'' = eta drive + weight + stops and friction. Elastic: the
311    /// gearbox's spring between the rotor and the carriage, m q'' = F_gear + weight + stops and friction.
312    fn solve(&self, x: &[f64], torque: f64, engaged: bool, attached: bool) -> (f64, f64, f64) {
313        let (j, i) = (&self.joint, self.ratio());
314        if self.elastic {
315            let gear = self.gear(x);
316            let acc =
317                (gear.output + j.output_torque(x[0], x[1]) + self.weight(attached) + self.push) / self.mass(attached);
318            return (acc, gear.rotor * i, gear.output);
319        }
320        let drive = j.rigid_drive(torque, x[0] * i, x[1] * i, x[2], engaged).0;
321        let rest = self.weight(attached) + j.output_torque(x[0], x[1]) + self.push;
322        let (m, r) = (self.mass(attached), j.reflected_inertia());
323        // The loss factor of the torque going in, at its fixed point (`mech::settled_loss`).
324        let solve = |loss: f64| (loss * drive + rest) / (m + loss * r);
325        let [loss] =
326            sim_components::mech::settled_loss([1.0], |&[loss]| [j.gearbox.loss_factor(drive - r * solve(loss), x[1])]);
327        let acc = (loss * drive + rest) / (m + loss * r);
328        let into = drive - r * acc;
329        (acc, into, loss * into)
330    }
331
332    /// Kinetic, potential and elastic (stops) energy.
333    fn energy(&self, x: &[f64], attached: bool) -> [f64; 3] {
334        if self.elastic {
335            let kinetic = 0.5 * self.mass(attached) * x[1] * x[1] + 0.5 * self.joint.rotor_inertia * x[4] * x[4];
336            let spring = self.joint.stop_energy(x[0]) + self.joint.gearbox.energy_with(x[3], x[0], self.arm(x));
337            return [kinetic, -self.weight(attached) * x[0], spring];
338        }
339        let kinetic = 0.5 * (self.mass(attached) + self.joint.reflected_inertia()) * x[1] * x[1];
340        [kinetic, -self.weight(attached) * x[0], self.joint.stop_energy(x[0])]
341    }
342
343    /// Powers lost in its friction, its motor's friction with the brake, its gearbox (coupling and screw), its stops
344    /// and what the ripple gives off; and the gearbox's loss as a torque at the rotor.
345    fn losses(&self, x: &[f64], torque: f64, engaged: bool, attached: bool) -> ([f64; 5], f64) {
346        let i = self.ratio();
347        let (rotor, speed) = self.rotor(x);
348        let [friction, stop, shaft, drag] = self.joint.losses(x[0], x[1], speed, x[2], engaged);
349        let other = (torque - self.joint.ripple.apply(torque, rotor)) * speed;
350        if self.elastic {
351            let g = self.gear(x);
352            let loss = self.joint.gearbox.loss_power_with(rotor, speed, x[0], x[1], self.arm(x));
353            return ([friction, shaft, loss + drag, stop, other], g.rotor - g.output / i);
354        }
355        let (_, into, out) = self.solve(x, torque, engaged, attached);
356        ([friction, shaft, (into - out) * x[1] + drag, stop, other], (into - out) / i)
357    }
358
359    /// The motor torque's parts (`TORQUE_PARTS`), as the arms'.
360    fn torque_parts(&self, x: &[f64], torque: f64, engaged: bool, attached: bool) -> [f64; 4] {
361        let (j, i) = (&self.joint, self.ratio());
362        let (acc, ..) = self.solve(x, torque, engaged, attached);
363        let (_, gear_at_rotor) = self.losses(x, torque, engaged, attached);
364        let speed = self.rotor(x).1;
365        let held = j.brake.torque(engaged, speed, x[2]).0;
366        // Elastic, the rotor accelerates on its own: m q'' / i + J_rotor w'.
367        let inertia = if self.elastic {
368            let rotor_acc = j.rotor_under(torque, x[3], x[4], self.gear(x), x[2], engaged).0;
369            self.mass(attached) * acc / i + j.rotor_inertia * rotor_acc
370        } else {
371            (self.mass(attached) + j.reflected_inertia()) * acc / i
372        };
373        let parts = [
374            inertia,
375            -self.weight(attached) / i,
376            j.shaft.torque(speed) + held + gear_at_rotor + j.friction.torque(x[1]) / i,
377        ];
378        [parts[0], parts[1], parts[2], torque - parts.iter().sum::<f64>()]
379    }
380
381    /// Rigid, loss-free: (m q'' - weight) / i + J_rotor i q'' (also for the elastic joint, as the arms': the spring's
382    /// twist is not known to the feed-forward).
383    fn feedforward(&self, acc: f64, attached: bool) -> f64 {
384        (self.mass(attached) * acc - self.weight(attached)) / self.ratio()
385            + self.joint.rotor_inertia * self.ratio() * acc
386    }
387}
388
389/// How far the tool's flange hangs below the plate with the stroke at its top (or without a stroke), m (view only).
390const TOOL_DROP: f64 = 0.1;
391
392pub struct ParallelScara {
393    legs: Legs,
394    /// The geometry as configured, for the scene: base and platform radius, the rods' spacing.
395    base_radius: f64,
396    platform_radius: f64,
397    rod_spacing: f64,
398    elastic: bool,
399    /// The Z stroke and the tool's turn, where there are, in that order: axes and motors 3 and 4 on.
400    extras: Vec<Extra>,
401    required_life: Option<f64>,
402    /// I_b without the rotor, plate mass without and with payload (forearm share and what it carries included).
403    arm_inertia: f64,
404    /// The arm's first moment about its joint, elbow share included (for `frame_momentum`), and gravity.
405    arm_moment: f64,
406    g: f64,
407    m_platform: f64,
408    /// Each forearm pair's mass and the share of it the inertia puts at the elbow, for the frame momentum (the rods'
409    /// own, `frame_momentum`).
410    m_forearms: f64,
411    forearm_share: f64,
412    m_payload: f64,
413    payload_attached: bool,
414    brake_engaged: bool,
415    /// An obstacle's push on the tool in the plane (`Machine::set_tool_force`), held until changed; the extra axes'
416    /// parts are theirs.
417    push: V2,
418    joints: [RotaryJoint; 2],
419    thermal: Option<ThermalFeedback>,
420    /// The working range: half width, its near edge (y), its far arc's centre and radius; the condition number refused
421    /// above.
422    half_width: f64,
423    top: f64,
424    circle: (f64, f64),
425    max_condition: f64,
426    axes: Vec<AxisInfo>,
427    motors: Vec<MotorInfo>,
428    /// `Machine::setpoint_slack`, worked out once (`rest_sag`).
429    rest_slack: f64,
430}
431
432// Elastic state: [theta 1, 2, omega 1, 2, rotor angle 1, 2, rotor speed 1, 2, brake 1, 2].
433const N_ELASTIC: usize = 10;
434// Rigid state: [theta 1, 2, omega 1, 2, brake 1, 2].
435const N_RIGID: usize = 6;
436
437/// The losses of one moment: per joint its friction, its motor's friction with the brake, its gearbox; the stops and
438/// what the ripple gives off; and per joint the gearbox loss as a torque at the rotor.
439struct Losses {
440    powers: [f64; 8],
441    gear_at_rotor: V2,
442}
443
444impl ParallelScara {
445    /// The plate at the tool pose, the quill hanging from it down to the tool's flange, and the payload under that, as
446    /// `scene` draws them.
447    fn on_platform(&self, tool: &[f64]) -> Vec<Part> {
448        let (p, size) = ([tool[0], tool[1]], 2.4 * self.platform_radius.max(0.03));
449        {
450            let flange = self.flange_z(tool);
451            let mut parts = vec![
452                Part::new(
453                    "platform",
454                    Shape::Box { size: [size, 0.06, self.rod_spacing.max(0.06) + 0.03] },
455                    [p[0], p[1], 0.0],
456                    [0.55, 0.55, 0.6],
457                ),
458                Part::new("quill", Shape::Box { size: [0.025, 0.025, -flange] }, [p[0], p[1], 0.5 * flange], [0.7; 3]),
459                Part::new("tool", Shape::Box { size: [0.06, 0.06, 0.02] }, [p[0], p[1], flange - 0.01], [0.3; 3]),
460            ];
461            if self.payload_attached && self.m_payload > 0.0 {
462                parts.push(Part::new(
463                    "payload",
464                    Shape::Box { size: [0.12, 0.12, 0.1] },
465                    [p[0], p[1], flange - 0.07],
466                    [0.2, 0.7, 0.3],
467                ));
468            }
469            parts
470        }
471    }
472
473    /// The height of the tool's flange in the scene, the stroke's top `TOOL_DROP` below the plate.
474    fn flange_z(&self, tool: &[f64]) -> f64 {
475        match self.extras.iter().position(|x| x.screw.is_some()) {
476            Some(e) => tool[2 + e] - self.axes[2 + e].max - TOOL_DROP,
477            None => -TOOL_DROP,
478        }
479    }
480
481    /// The tool pose of a state: the plate's, then the stroke's and the turn's positions.
482    fn tool_pose(&self, s: &[f64]) -> Vec<f64> {
483        let (p, _) = self.pose(self.arms(s).0);
484        let mut tool = p.to_vec();
485        tool.extend((0..self.extras.len()).map(|e| self.extra_state(s, e)[0]));
486        tool
487    }
488
489    /// The state of extra axis `e`: [position, speed, brake] and with elastic gearboxes [rotor angle, rotor speed], after
490    /// the arms', and where an extra axis's gear has a Maxwell arm (`Extra::relaxes`) each one's arm (0 on the others).
491    fn extra_state<'a>(&self, s: &'a [f64], e: usize) -> &'a [f64] {
492        let at = self.planar_len() + self.extra_len() * e;
493        &s[at..at + self.extra_len()]
494    }
495
496    /// The number of states of each extra axis: 3, 5 with elastic gearboxes, 6 with an arm.
497    fn extra_len(&self) -> usize {
498        if self.extras.iter().any(Extra::relaxes) {
499            6
500        } else if self.elastic {
501            5
502        } else {
503            3
504        }
505    }
506
507    fn planar_len(&self) -> usize {
508        if self.elastic { N_ELASTIC } else { N_RIGID }
509    }
510
511    /// The Z stroke (motor 3): the carriage on a ball screw behind a coupling, `[slide]` and `[screw]` as for a screw
512    /// axis, with motor 3's own config; the unit (Z motor, screw, housing) and the carriage at the plate.
513    fn z_axis(cfg: &Config, payload: f64, g: f64) -> Result<(Extra, AxisInfo, f64), ConfigError> {
514        let own = motor_config(cfg, "3")?;
515        let mut joint = RotaryJoint::linear_from_config(&own)?;
516        let screw = BallScrew::from_config(&own)?;
517        if screw.length < joint.range.1 {
518            return Err(ConfigError::Invalid("screw.length_m".into()));
519        }
520        let carriage = cfg.non_negative("z_axis.carriage_kg")?;
521        // The carriage on the nut's spring, without the payload (`Converter::apply_back`'s damper of the screw).
522        screw.converter(screw.softest_position()).apply_to(&own, &mut joint, carriage)?;
523        // The nut's preload drags like friction in the guides, as a force at the nut.
524        if own.bool("effects.joint_friction")? {
525            joint.friction.coulomb += screw.preload_torque() * screw.ratio();
526        }
527        let axis = Self::axis_info(cfg, "z", "axis-z", "m", joint.range)?;
528        let carried = cfg.non_negative("z_axis.unit_kg")? + carriage;
529        let elastic = cfg.bool("effects.joint_elasticity")?;
530        let extra = Extra { elastic, joint, load: carriage, payload, g, screw: Some(screw), thermal: None, push: 0.0 };
531        Ok((extra, axis, carried))
532    }
533
534    /// The tool's turn (motor 4) through its gearbox, with no stops: the tool, and the payload's inertia while held;
535    /// the unit (C motor and gearbox) at the plate.
536    fn tool_turn(cfg: &Config, payload: bool) -> Result<(Extra, AxisInfo, f64), ConfigError> {
537        let own = motor_config(cfg, "4")?;
538        let on = cfg.bool("effects.joint_friction")?;
539        let friction = ShaftFriction {
540            coulomb: if on { cfg.non_negative("tool_turn.friction_coulomb_nm")? } else { 0.0 },
541            viscous: if on { cfg.non_negative("tool_turn.friction_viscous_nm_s_rad")? } else { 0.0 },
542            smoothing: cfg.positive("tool_turn.friction_smoothing_rad_s")?,
543            ..ShaftFriction::NONE
544        };
545        let range = (cfg.f64("axis.c.min_angle_deg")?.to_radians(), cfg.f64("axis.c.max_angle_deg")?.to_radians());
546        if range.0 >= range.1 {
547            return Err(ConfigError::Invalid("axis.c.max_angle_deg".into()));
548        }
549        let joint = RotaryJoint::with(&own, friction, HardStop { stiffness: 0.0, damping: 0.0 }, range)?;
550        let extra = Extra {
551            elastic: cfg.bool("effects.joint_elasticity")?,
552            joint,
553            load: cfg.positive("tool_turn.inertia_kgm2")?,
554            payload: if payload { cfg.non_negative("tool_turn.payload_inertia_kgm2")? } else { 0.0 },
555            g: 0.0,
556            screw: None,
557            thermal: ThermalFeedback::from_config(&own)?,
558            push: 0.0,
559        };
560        Ok((extra, Self::axis_info(cfg, "c", "axis-c", "rad", range)?, cfg.non_negative("tool_turn.unit_kg")?))
561    }
562
563    /// An axis from `[axis.<id>]`, its limits in m or rad.
564    fn axis_info(
565        cfg: &Config,
566        id: &'static str,
567        key: &'static str,
568        unit: &'static str,
569        (min, max): (f64, f64),
570    ) -> Result<AxisInfo, ConfigError> {
571        Ok(AxisInfo {
572            id,
573            key,
574            unit,
575            min,
576            max,
577            max_vel: cfg.positive(&format!("axis.{id}.max_velocity_{unit}_s"))?,
578            max_acc: cfg.positive(&format!("axis.{id}.max_acceleration_{unit}_s2"))?,
579            max_jerk: cfg.positive(&format!("axis.{id}.max_jerk_{unit}_s3"))?,
580        })
581    }
582
583    pub fn new(cfg: &Config) -> Result<Self, ConfigError> {
584        let base_radius = cfg.positive("geometry.base_radius_m")?;
585        let platform_radius = cfg.non_negative("geometry.platform_radius_m")?;
586        let (la, lb) = (cfg.positive("geometry.upper_arm_m")?, cfg.positive("geometry.forearm_m")?);
587        if lb <= la {
588            return Err(ConfigError::Invalid("geometry.forearm_m".into()));
589        }
590        let share = cfg.non_negative("mass.forearm_elbow_share")?;
591        if share > 1.0 {
592            return Err(ConfigError::Invalid("mass.forearm_elbow_share".into()));
593        }
594        let i_arm = cfg.positive("mass.upper_arm_inertia_kgm2")?;
595        let (m_elbow, m_fb) = (cfg.non_negative("mass.elbow_kg")?, cfg.non_negative("mass.forearm_pair_kg")?);
596        let elbow = m_elbow + share * m_fb;
597        let (half_width, top) = (cfg.positive("workspace.half_width_m")?, cfg.f64("workspace.near_y_m")?);
598        let (edge, centre) = (cfg.positive("workspace.depth_edge_m")?, cfg.positive("workspace.depth_centre_m")?);
599        if centre < edge {
600            return Err(ConfigError::Invalid("workspace.depth_centre_m".into()));
601        }
602        // The far edge ("bottom", "top" the near edge): a circle through the centre's depth and both edges; straight
603        // where both depths are the same.
604        let sag = centre - edge;
605        let circle = if sag > 0.0 {
606            let r = (half_width * half_width + sag * sag) / (2.0 * sag);
607            (top - centre + r, r)
608        } else {
609            (f64::INFINITY, f64::INFINITY)
610        };
611        let joint = RotaryJoint::from_config(cfg)?;
612        let g = if cfg.bool("effects.gravity")? { G } else { 0.0 };
613        let payload = cfg.bool("effects.payload")?;
614        let m_payload = if payload { cfg.non_negative("mass.payload_kg")? } else { 0.0 };
615        let mut axes = vec![
616            Self::axis_info(cfg, "x", "axis-x", "m", (-half_width, half_width))?,
617            Self::axis_info(cfg, "y", "axis-y", "m", (top - centre, top))?,
618        ];
619        let mut motors = vec![MotorInfo { id: "1", key: "motor-arm-1" }, MotorInfo { id: "2", key: "motor-arm-2" }];
620        let (mut extras, mut carried) = (Vec::new(), 0.0);
621        let mut add = |(extra, axis, mass): (Extra, AxisInfo, f64), motor: MotorInfo| {
622            extras.push(extra);
623            axes.push(axis);
624            motors.push(motor);
625            carried += mass;
626        };
627        if cfg.bool("z_axis.enabled")? {
628            add(Self::z_axis(cfg, m_payload, g)?, MotorInfo { id: "3", key: "motor-z" });
629        }
630        if cfg.bool("tool_turn.enabled")? {
631            add(Self::tool_turn(cfg, payload)?, MotorInfo { id: "4", key: "motor-tool" });
632        }
633        let mut scara = Self {
634            legs: Legs::new(base_radius - platform_radius, la, lb),
635            base_radius,
636            platform_radius,
637            rod_spacing: cfg.non_negative("geometry.forearm_spacing_m")?,
638            elastic: cfg.bool("effects.joint_elasticity")?,
639            extras,
640            required_life: cfg.f64("ratings.required_life_h").ok(),
641            arm_inertia: i_arm + la * la * elbow,
642            // The tube's first moment m c about its joint (as on the D3). Its weight is out of the plane, so only the
643            // frame's momentum takes it.
644            arm_moment: cfg.positive("mass.upper_arm_kg")? * cfg.non_negative("mass.upper_arm_cg_m")? + la * elbow,
645            g,
646            m_platform: cfg.positive("mass.platform_kg")? + 2.0 * (1.0 - share) * m_fb + carried,
647            m_forearms: m_fb,
648            forearm_share: share,
649            m_payload,
650            payload_attached: true,
651            brake_engaged: false,
652            push: [0.0; 2],
653            joints: [joint.clone(), joint],
654            thermal: ThermalFeedback::from_config(cfg)?,
655            half_width,
656            top,
657            circle,
658            max_condition: cfg.positive("workspace.max_condition_number")?,
659            axes,
660            motors,
661            rest_slack: 0.0,
662        };
663        scara.rest_slack = scara.rest_sag();
664        Ok(scara)
665    }
666
667    /// How far the motors' pose can be from the tool's at rest anywhere in the working range: each gearbox at either
668    /// side of its backlash (all four combinations; nothing loads them at rest, gravity being out of the plane),
669    /// through the forward kinematics. Over a grid of the range, 41 columns of 9 depths and the far edge; plus a tenth for what
670    /// the grid steps over and the joints' friction. The stroke's screw twisted by the carriage's and the payload's weight
671    /// (`Gearbox::static_twist`, m, with the screw where it is softest on the stroke, `Gearbox::softest`) and the turn at
672    /// either side of its play (rad: nothing loads it), each on its own axis, where more. At least the default 0.1 mm;
673    /// that alone in the rigid model.
674    fn rest_sag(&self) -> f64 {
675        if !self.elastic {
676            return 1e-4;
677        }
678        let twist = |x: &Extra| {
679            let gear = x.joint.gearbox.softest(x.joint.range);
680            gear.static_twist(-x.weight(true)).abs().max(gear.half_backlash)
681        };
682        let mut most = self.extras.iter().map(twist).fold(0f64, f64::max);
683        for column in 0..=40 {
684            let x = self.half_width * (column as f64 / 20.0 - 1.0);
685            let lowest = self.bottom(x);
686            for z in (0..=8).map(|k| lowest + (self.top - lowest) * k as f64 / 8.0) {
687                let p = [x, z];
688                if !self.in_envelope(&p, 1e-9) {
689                    continue;
690                }
691                let Some(t) = self.legs.inverse(p) else { continue };
692                for signs in 0..4 {
693                    let half =
694                        |k: usize| if signs >> k & 1 == 1 { 1.0 } else { -1.0 } * self.joints[k].gearbox.half_backlash;
695                    if let Some(q) = self.legs.forward(std::array::from_fn(|k| t[k] + half(k))) {
696                        most = most.max(norm(sub(q, p)));
697                    }
698                }
699            }
700        }
701        (1.1 * most).max(1e-4)
702    }
703
704    /// The plane's two modes with the motors held: the arms on their gearboxes' springs K = diag(k_1, k_2) against the
705    /// load's mass matrix M at the pose (`load`), the roots of det(K - lambda M) = det M lambda^2 - (k_1 M_22 + k_2 M_11)
706    /// lambda + k_1 k_2 = 0, w^2 = lambda, lowest first; each with its shape v from (K - lambda M) v = 0 and the damping
707    /// ratio v'Cv / (2 w v'Mv), C = diag(c_1, c_2) (as `sim-netlist`'s spatial delta takes it). Empty in the rigid model
708    /// or out of reach.
709    fn plane_modes(&self, tool: &[f64], small: bool) -> Vec<sim_core::Mode> {
710        let Some(t) = self.legs.inverse([tool[0], tool[1]]).filter(|_| self.elastic) else { return Vec::new() };
711        let (m, _) = self.load(t, [0.0; 2]);
712        let k: V2 = std::array::from_fn(|i| spring(&self.joints[i].gearbox, small));
713        let (det, b) = (m[0][0] * m[1][1] - m[0][1] * m[1][0], k[0] * m[1][1] + k[1] * m[0][0]);
714        let root = (b * b - 4.0 * det * k[0] * k[1]).max(0.0).sqrt();
715        // The lower root as 2 c / (b + root): no cancellation.
716        [2.0 * k[0] * k[1] / (b + root), (b + root) / (2.0 * det)]
717            .map(|lambda| {
718                let v = mode_vector(k, &m, lambda);
719                let w = lambda.sqrt();
720                let damped: f64 = (0..2).map(|i| self.joints[i].gearbox.damping * v[i] * v[i]).sum();
721                sim_core::Mode { hz: w / std::f64::consts::TAU, damping: damped / (2.0 * w * dot(v, mul(&m, v))) }
722            })
723            .into_iter()
724            .filter(|mode| mode.hz.is_finite())
725            .collect()
726    }
727
728    /// With elastic gearboxes: the plane's two (`plane_modes`), and the stroke's carriage on its screw and the tool on
729    /// its turn gearbox, each with its rotor held, sqrt(K / m) / 2 pi, K the gearbox's stiffness at the joint (the
730    /// screw's and the coupling's in series, N/m) and m what it moves, damping ratio c / (2 sqrt(K m)); lowest first.
731    /// `small`: with the hysteresis stiffness (`spring`).
732    fn modes_at(&self, tool: &[f64], small: bool) -> Vec<sim_core::Mode> {
733        let mut modes = self.plane_modes(tool, small);
734        if self.elastic {
735            modes.extend(self.extras.iter().enumerate().map(|(e, x)| {
736                let (k, m) = (spring(&x.joint.gearbox.at(tool[2 + e]), small), x.mass(self.payload_attached));
737                sim_core::Mode {
738                    hz: (k / m).sqrt() / std::f64::consts::TAU,
739                    damping: x.joint.gearbox.at(tool[2 + e]).damping_at((k / m).sqrt()) / (2.0 * (k * m).sqrt()),
740                }
741            }));
742        }
743        modes.retain(|mode| mode.hz.is_finite());
744        modes.sort_by(|a, b| a.hz.total_cmp(&b.hz));
745        modes
746    }
747
748    pub fn legs(&self) -> &Legs {
749        &self.legs
750    }
751
752    fn ratio(&self) -> f64 {
753        self.joints[0].ratio()
754    }
755
756    /// The point mass at the plate.
757    pub fn m_nt(&self) -> f64 {
758        self.m_platform + if self.payload_attached { self.m_payload } else { 0.0 }
759    }
760
761    /// The arm's inertia about its joint, elbow share of the forearms included, rotor not.
762    pub fn arm_inertia(&self) -> f64 {
763        self.arm_inertia
764    }
765
766    /// Arm angles and speeds of a state.
767    fn arms(&self, s: &[f64]) -> (V2, V2) {
768        ([s[0], s[1]], [s[2], s[3]])
769    }
770
771    /// Rotor angles and speeds of a state.
772    fn rotors(&self, s: &[f64]) -> (V2, V2) {
773        if self.elastic {
774            ([s[4], s[5]], [s[6], s[7]])
775        } else {
776            let i = self.ratio();
777            ([s[0] * i, s[1] * i], [s[2] * i, s[3] * i])
778        }
779    }
780
781    fn brakes(&self, s: &[f64]) -> V2 {
782        let at = if self.elastic { 8 } else { 4 };
783        [s[at], s[at + 1]]
784    }
785
786    /// Where the plate is and the Jacobian there, for arm angles; NaN where the legs cannot be assembled.
787    fn pose(&self, t: V2) -> (V2, M2) {
788        self.legs
789            .forward(t)
790            .and_then(|p| Some((p, self.legs.jacobian(t, p)?)))
791            .unwrap_or(([f64::NAN; 2], [[f64::NAN; 2]; 2]))
792    }
793
794    /// The load's mass matrix M and the velocity term m_nt J^T J' theta' at arm angles t and speeds w.
795    fn load(&self, t: V2, w: V2) -> (M2, V2) {
796        let (p, j) = self.pose(t);
797        let jt = transpose(&j);
798        let m = self.m_nt();
799        let mass: M2 = std::array::from_fn(|r| {
800            std::array::from_fn(|c| m * dot(jt[r], jt[c]) + if r == c { self.arm_inertia } else { 0.0 })
801        });
802        let pv = mul(&j, w);
803        let velocity = self.legs.velocity_term(t, p, w, pv).map_or([f64::NAN; 2], |a| mul(&jt, a.map(|v| m * v)));
804        (mass, velocity)
805    }
806
807    /// Rigid model: the arms' acceleration, and per joint the torque into its gearbox (after the rotor's own
808    /// acceleration) and out of it, at the arm.
809    /// The push at the tool in the plane on the arms: its virtual power per unit of each arm's speed, through the
810    /// Jacobian (`sim_core::tool_force_on_rates`); zero without a push.
811    fn pushed(&self, s: &[f64]) -> V2 {
812        let force = [self.push[0], self.push[1], 0.0, 0.0];
813        let force = &force[..2 + self.extras.len()];
814        sim_core::tool_force_on_rates(self, s, force, 2..4).map_or([0.0; 2], |q| [q[0], q[1]])
815    }
816
817    fn rigid_solve(&self, s: &[f64], torque: &[f64]) -> (V2, V2, V2) {
818        let (t, w) = self.arms(s);
819        let (rotor, rotor_speed) = self.rotors(s);
820        let brakes = self.brakes(s);
821        let (mass, velocity) = self.load(t, w);
822        let drive: V2 = std::array::from_fn(|k| {
823            self.joints[k].rigid_drive(torque[k], rotor[k], rotor_speed[k], brakes[k], self.brake_engaged).0
824        });
825        let push = self.pushed(s);
826        let rest: V2 = std::array::from_fn(|k| self.joints[k].output_torque(t[k], w[k]) - velocity[k] + push[k]);
827        let solve = |loss: V2| -> V2 {
828            let m: M2 = std::array::from_fn(|r| {
829                std::array::from_fn(|c| {
830                    mass[r][c] + if r == c { loss[r] * self.joints[r].reflected_inertia() } else { 0.0 }
831                })
832            });
833            let rhs: V2 = std::array::from_fn(|k| loss[k] * drive[k] + rest[k]);
834            inverse(&m).map_or([f64::NAN; 2], |inv| mul(&inv, rhs))
835        };
836        // The loss factors of the torques going in, at their fixed point (`mech::settled_loss`).
837        let loss = sim_components::mech::settled_loss([1.0; 2], |loss| {
838            let acc = solve(*loss);
839            std::array::from_fn(|k| {
840                self.joints[k].gearbox.loss_factor(drive[k] - self.joints[k].reflected_inertia() * acc[k], w[k])
841            })
842        });
843        let acc = solve(loss);
844        let into: V2 = std::array::from_fn(|k| drive[k] - self.joints[k].reflected_inertia() * acc[k]);
845        (acc, into, std::array::from_fn(|k| loss[k] * into[k]))
846    }
847
848    /// The arms' acceleration in either model.
849    fn arm_acceleration(&self, s: &[f64], torque: &[f64]) -> V2 {
850        if self.elastic {
851            let mut d = vec![0.0; self.state_len()];
852            self.derivatives(s, torque, &mut d);
853            [d[2], d[3]]
854        } else {
855            self.rigid_solve(s, torque).0
856        }
857    }
858
859    /// The torque each gearbox passes to its arm.
860    fn gear_output(&self, s: &[f64], torque: &[f64]) -> V2 {
861        if self.elastic {
862            std::array::from_fn(|k| self.joints[k].gearbox.torque(s[4 + k], s[6 + k], s[k], s[2 + k]).output)
863        } else {
864            self.rigid_solve(s, torque).2
865        }
866    }
867
868    fn energy_parts(&self, s: &[f64]) -> [f64; 3] {
869        let (t, w) = self.arms(s);
870        let (mass, ..) = self.load(t, w);
871        let mut kinetic = 0.5 * dot(w, mul(&mass, w));
872        // Nothing in the plane rises or falls: the potential energy is the Z stroke's alone.
873        let potential = 0.0;
874        let mut elastic: f64 = (0..2).map(|k| self.joints[k].stop_energy(t[k])).sum();
875        if self.elastic {
876            for k in 0..2 {
877                kinetic += 0.5 * self.joints[k].rotor_inertia * s[6 + k] * s[6 + k];
878                elastic += self.joints[k].gearbox.energy(s[4 + k], s[k]);
879            }
880        } else {
881            kinetic += 0.5 * (0..2).map(|k| self.joints[k].reflected_inertia() * w[k] * w[k]).sum::<f64>();
882        }
883        let mut parts = [kinetic, potential, elastic];
884        for (e, x) in self.extras.iter().enumerate() {
885            let own = x.energy(self.extra_state(s, e), self.payload_attached);
886            (0..3).for_each(|i| parts[i] += own[i]);
887        }
888        parts
889    }
890
891    fn losses(&self, s: &[f64], torque: &[f64]) -> Losses {
892        let (t, w) = self.arms(s);
893        let (rotor, rotor_speed) = self.rotors(s);
894        let brakes = self.brakes(s);
895        let mut powers = [0.0; 8];
896        let mut gear_at_rotor = [0.0; 2];
897        let rigid = (!self.elastic).then(|| self.rigid_solve(s, torque));
898        let (mut stops, mut other) = (0.0, 0.0);
899        for k in 0..2 {
900            let joint = &self.joints[k];
901            let [friction, stop, shaft, drag] = joint.losses(t[k], w[k], rotor_speed[k], brakes[k], self.brake_engaged);
902            let gear = match &rigid {
903                Some((_, into, out)) => {
904                    gear_at_rotor[k] = (into[k] - out[k]) / joint.ratio();
905                    (into[k] - out[k]) * w[k]
906                }
907                None => {
908                    let g = joint.gearbox.torque(s[4 + k], s[6 + k], s[k], s[2 + k]);
909                    gear_at_rotor[k] = g.rotor - g.output / joint.ratio();
910                    joint.gearbox.loss_power(s[4 + k], s[6 + k], s[k], s[2 + k])
911                }
912            };
913            powers[3 * k..3 * k + 3].copy_from_slice(&[friction, shaft, gear + drag]);
914            stops += stop;
915            other += (torque[k] - joint.ripple.apply(torque[k], rotor[k])) * rotor_speed[k];
916        }
917        // The extra axes' own losses are their signals; their stops and ripple join the arms'.
918        for (e, x) in self.extras.iter().enumerate() {
919            let ([.., stop, ripple], _) =
920                x.losses(self.extra_state(s, e), torque[2 + e], self.brake_engaged, self.payload_attached);
921            stops += stop;
922            other += ripple;
923        }
924        powers[6] = stops;
925        powers[7] = other;
926        Losses { powers, gear_at_rotor }
927    }
928
929    /// The working range's bottom below x: on the circle, or flat.
930    fn bottom(&self, x: f64) -> f64 {
931        let (centre, r) = self.circle;
932        if centre.is_finite() { centre - (r * r - x * x).max(0.0).sqrt() } else { self.axes[1].min }
933    }
934
935    /// Whether a pose is within the working range (the band |x| <= half width below the top, above the bottom
936    /// circle), widened by `slack`.
937    fn in_envelope(&self, p: &[f64], slack: f64) -> bool {
938        let (centre, r) = self.circle;
939        let above =
940            if centre.is_finite() { p[0].hypot(p[1] - centre) <= r + slack } else { p[1] >= self.axes[1].min - slack };
941        p[0].abs() <= self.half_width + slack && p[1] <= self.top + slack && above
942    }
943
944    /// The torque breakdown, loss powers, energies of the effect views.
945    fn view_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
946        let (t, w) = self.arms(s);
947        let (_, rotor_speed) = self.rotors(s);
948        let brakes = self.brakes(s);
949        let (mass, velocity) = self.load(t, w);
950        let acc = self.arm_acceleration(s, torque);
951        let moving = mul(&mass, acc);
952        let losses = self.losses(s, torque);
953        for k in 0..2 {
954            let joint = &self.joints[k];
955            let i = joint.ratio();
956            let held = joint.brake.torque(self.brake_engaged, rotor_speed[k], brakes[k]).0;
957            let parts = [
958                (moving[k] + velocity[k] + joint.reflected_inertia() * acc[k]) / i,
959                // Gravity acts out of the plane, on the joints' bearings.
960                0.0,
961                joint.shaft.torque(rotor_speed[k]) + held + losses.gear_at_rotor[k] + joint.friction.torque(w[k]) / i,
962            ];
963            out.extend(parts);
964            out.push(torque[k] - parts.iter().sum::<f64>());
965        }
966        out.extend(losses.powers);
967        out.extend(self.energy_parts(s));
968        for (e, x) in self.extras.iter().enumerate() {
969            let (state, at) = (self.extra_state(s, e), (torque[2 + e], self.brake_engaged, self.payload_attached));
970            out.extend(x.torque_parts(state, at.0, at.1, at.2));
971            out.extend(&x.losses(state, at.0, at.1, at.2).0[..3]);
972        }
973        for k in 0..2 {
974            out.extend(self.joints[k].friction_signals(w[k]));
975        }
976    }
977
978    /// The extra axes' loss powers, in the order of their signals.
979    fn extra_losses(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
980        for (e, x) in self.extras.iter().enumerate() {
981            let state = self.extra_state(s, e);
982            out.extend(&x.losses(state, torque[2 + e], self.brake_engaged, self.payload_attached).0[..3]);
983        }
984    }
985
986    /// The torque parts and loss powers of motor `motor` (the arms' with `joint` their arm's key).
987    fn motor_infos(motor: &MotorInfo, joint: &str, coupled: bool) -> (Vec<SignalInfo>, Vec<SignalInfo>) {
988        let parts = TORQUE_PARTS.map(|part| {
989            SignalInfo::new(
990                format!("motor.{}.torque_{part}", motor.id),
991                motor.key,
992                &format!("quantity-torque-{part}"),
993                "N m",
994            )
995        });
996        let gear = if coupled { "quantity-coupling-loss-power" } else { "quantity-gearbox-loss-power" };
997        let losses = vec![
998            SignalInfo::new(format!("{LOSS_PREFIX}joint_{}", motor.id), joint, "quantity-friction-power", "W"),
999            SignalInfo::new(
1000                format!("{LOSS_PREFIX}shaft_{}", motor.id),
1001                motor.key,
1002                "quantity-shaft-friction-power",
1003                "W",
1004            ),
1005            SignalInfo::new(format!("{LOSS_PREFIX}gearbox_{}", motor.id), motor.key, gear, "W"),
1006        ];
1007        (parts.to_vec(), losses)
1008    }
1009
1010    fn effect_infos(&self, out: &mut Vec<SignalInfo>) {
1011        let arms: Vec<_> = (0..2)
1012            .map(|k| Self::motor_infos(&self.motors[k], ["arm-1", "arm-2"][k], self.joints[k].gearbox.is_coupling()))
1013            .collect();
1014        out.extend(arms.iter().flat_map(|(parts, _)| parts.clone()));
1015        out.extend(arms.into_iter().flat_map(|(_, losses)| losses));
1016        out.push(SignalInfo::new(format!("{LOSS_PREFIX}hard_stops"), "group-joint", "quantity-damping-power", "W"));
1017        out.push(SignalInfo::new(format!("{LOSS_PREFIX}other"), "loss-other", "quantity-power-given-off", "W"));
1018        out.extend(ENERGY_PARTS.map(|part| {
1019            SignalInfo::new(format!("energy.{part}"), "group-energy", &format!("quantity-energy-{part}"), "J")
1020        }));
1021        for (e, x) in self.extras.iter().enumerate() {
1022            let (parts, losses) = Self::motor_infos(&self.motors[2 + e], self.axes[2 + e].key, x.joint.coupled);
1023            out.extend(parts);
1024            out.extend(losses);
1025        }
1026        for k in 0..2 {
1027            out.extend(RotaryJoint::friction_infos(JOINT_CONTACTS[k], ARMS[k]));
1028        }
1029    }
1030}
1031
1032/// The ids of the arms' friction contacts (`<id>.friction_<part>`) and their keys, in the motors' order.
1033const JOINT_CONTACTS: [&str; 2] = ["joint.1", "joint.2"];
1034const ARMS: [&str; 2] = ["arm-1", "arm-2"];
1035
1036impl Machine for ParallelScara {
1037    /// In the tool's frame (x, y in the plane, z up): the plate with all it carries at the tool's (x, y), of it the Z
1038    /// stroke's carriage and payload moving up at the tool's z; the arms turning about their joints at +-base radius,
1039    /// about -+z, their rotors with them; the stroke's rotor, the tool's turn and its rotor about z.
1040    fn frame_momentum(&self, s: &[f64]) -> Option<sim_core::FrameMomentum> {
1041        use sim_components::base::{add_point, add_spin, add_turning};
1042        let mut f = sim_core::FrameMomentum { gravity: [0.0, 0.0, -self.g], ..Default::default() };
1043        let (t, w) = self.arms(s);
1044        let (p, j) = self.pose(t);
1045        let pv = mul(&j, w);
1046        let mut plate = self.m_nt();
1047        let rotor_speed = self.rotors(s).1;
1048        for (e, x) in self.extras.iter().enumerate() {
1049            let state = self.extra_state(s, e);
1050            let (q, v, spin) = (state[0], state[1], x.rotor(state).1);
1051            let rotor = x.joint.rotor_inertia;
1052            if x.screw.is_some() {
1053                let moved = x.mass(self.payload_attached);
1054                plate -= moved;
1055                add_point(&mut f, moved, [p[0], p[1], q], [pv[0], pv[1], v]);
1056            } else {
1057                add_spin(&mut f, [0.0, 0.0, 1.0], x.mass(self.payload_attached), v);
1058            }
1059            add_spin(&mut f, [0.0, 0.0, 1.0], rotor, spin);
1060        }
1061        // The forearms as the rods they are, whatever share of their inertia the lumped dynamics put at the elbow: a
1062        // sixth at each end and two thirds at the middle give a rod's momentum, first moment and angular momentum. What
1063        // the split puts at the elbow and at the plate beyond those sixths:
1064        let (la, m_fb) = (self.legs.la, self.m_forearms);
1065        let (at_elbow, at_plate) = ((self.forearm_share - 1.0 / 6.0) * m_fb, (5.0 / 6.0 - self.forearm_share) * m_fb);
1066        add_point(&mut f, plate - 2.0 * at_plate, [p[0], p[1], 0.0], [pv[0], pv[1], 0.0]);
1067        for k in 0..2 {
1068            let (side, (sin, cos)) = (SIDE[k], t[k].sin_cos());
1069            let (dir, ddir) = ([side * cos, -sin, 0.0], [-side * sin, -cos, 0.0]);
1070            let joint = [side * self.base_radius, 0.0, 0.0];
1071            let (inertia, moment) = (self.arm_inertia - la * la * at_elbow, self.arm_moment - la * at_elbow);
1072            add_turning(&mut f, joint, dir, ddir, w[k], inertia, moment);
1073            let end = [p[0] + side * self.platform_radius, p[1], 0.0];
1074            let middle: [f64; 3] = std::array::from_fn(|i| 0.5 * (joint[i] + la * dir[i] + end[i]));
1075            let speed: [f64; 3] = std::array::from_fn(|i| 0.5 * (la * w[k] * ddir[i] + [pv[0], pv[1], 0.0][i]));
1076            add_point(&mut f, 2.0 / 3.0 * m_fb, middle, speed);
1077            add_spin(&mut f, [0.0, 0.0, -side], self.joints[k].rotor_inertia, rotor_speed[k]);
1078        }
1079        Some(f)
1080    }
1081    fn axes(&self) -> &[AxisInfo] {
1082        &self.axes
1083    }
1084    fn motors(&self) -> &[MotorInfo] {
1085        &self.motors
1086    }
1087
1088    /// NaN where the pose is out of reach: the controller never asks for one (see `unreachable`).
1089    fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
1090        let t = self.legs.inverse([tool[0], tool[1]]).unwrap_or([f64::NAN; 2]);
1091        for k in 0..2 {
1092            motors[k] = self.ratio() * t[k];
1093        }
1094        for (e, x) in self.extras.iter().enumerate() {
1095            motors[2 + e] = x.ratio() * tool[2 + e];
1096        }
1097    }
1098    fn forward(&self, motors: &[f64], tool: &mut [f64]) {
1099        let i = self.ratio();
1100        let p = self.legs.forward([motors[0] / i, motors[1] / i]).unwrap_or([f64::NAN; 2]);
1101        tool[..2].copy_from_slice(&p);
1102        for (e, x) in self.extras.iter().enumerate() {
1103            tool[2 + e] = motors[2 + e] / x.ratio();
1104        }
1105    }
1106
1107    fn state_len(&self) -> usize {
1108        self.planar_len() + self.extra_len() * self.extras.len()
1109    }
1110
1111    fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
1112        let t = self.legs.inverse([tool[0], tool[1]]).unwrap_or([f64::NAN; 2]);
1113        state.clear();
1114        state.extend(t);
1115        state.extend([0.0; 2]);
1116        for k in 0..2 {
1117            let joint = &self.joints[k];
1118            // At rest the gearbox holds the arm against the stops; gravity gives it nothing to hold.
1119            let out = -joint.output_torque(t[k], 0.0);
1120            let rotor = joint.ratio() * (t[k] + if self.elastic { joint.gearbox.static_twist(out) } else { 0.0 });
1121            if self.elastic {
1122                state.push(rotor);
1123            }
1124            torque[k] = joint.ripple.invert(out / joint.ratio(), rotor);
1125        }
1126        // Rotor speeds and brakes at rest.
1127        state.resize(self.planar_len(), 0.0);
1128        for (e, x) in self.extras.iter().enumerate() {
1129            // The stroke holds the carriage's weight; the turn holds nothing.
1130            let (q, i) = (tool[2 + e], x.ratio());
1131            let out = -x.weight(self.payload_attached) - x.joint.output_torque(q, 0.0);
1132            // Elastic, the spring holds it: the rotor is ahead by the static twist (`Gearbox::static_twist`).
1133            let rotor = i * (q + if self.elastic { x.joint.gearbox.static_twist_at(q, out) } else { 0.0 });
1134            let held = if self.elastic { x.joint.gearbox.held_at(q, out) } else { out };
1135            torque[2 + e] = x.joint.ripple.invert(held / i, rotor);
1136            state.extend([q, 0.0, 0.0]);
1137            if self.elastic {
1138                state.extend([rotor, 0.0]);
1139            }
1140            if self.extra_len() == 6 {
1141                state.push(x.joint.gearbox.arm_rest(rotor, q));
1142            }
1143        }
1144    }
1145
1146    /// As `Machine::adopt_state`, the same tool pose and speed with the gears as at rest there; but from an elastic
1147    /// model to an elastic one each arm's gearbox keeps the twist it had at its motor: laid flat, nothing holds an arm
1148    /// to one side of its play, and rebuilt at rest one driven on a flank was put back in the middle of it (the tool
1149    /// lost 0.121 mm taking the play up anew after a 1 % change of the ratio during a move).
1150    fn adopt_state(&self, old: &dyn Machine, old_state: &[f64]) -> Vec<f64> {
1151        let (m, n) = (self.axes.len(), self.motors.len());
1152        let (mut pos, mut vel, mut before, mut after) = (vec![0.0; m], vec![0.0; m], vec![0.0; n], vec![0.0; n]);
1153        old.tool_state(old_state, &mut pos, &mut vel);
1154        old.inverse(&pos, &mut before);
1155        self.inverse(&pos, &mut after);
1156        if old_state.len() == self.state_len() && before == after {
1157            return old_state.to_vec();
1158        }
1159        let mut state = Vec::new();
1160        self.equilibrium(&pos, &mut state, &mut vec![0.0; n]);
1161        self.set_tool_velocity(&mut state, &vel);
1162        if self.elastic && old_state.len() == self.state_len() {
1163            let (mut rotor, mut speed) = (vec![0.0; n], vec![0.0; n]);
1164            old.motor_state(old_state, &mut rotor, &mut speed);
1165            for k in 0..2 {
1166                state[4 + k] = after[k] + rotor[k] - before[k];
1167            }
1168            // The stroke's and the turn's gearboxes the same way, their rotor angle after position, speed and brake.
1169            for e in 0..self.extras.len() {
1170                let at = self.planar_len() + self.extra_len() * e + 3;
1171                state[at] = after[2 + e] + rotor[2 + e] - before[2 + e];
1172                // The gear's arm keeps its stretch over the twist it had.
1173                if self.extras[e].relaxes() {
1174                    let (g, q) = (&self.extras[e].joint.gearbox, state[at - 3]);
1175                    let stretch = g.arm_rest(old_state[at], old_state[at - 3]) - old_state[at + 2];
1176                    state[at + 2] = g.arm_rest(state[at], q) - stretch;
1177                }
1178            }
1179        }
1180        state
1181    }
1182
1183    fn derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
1184        for (e, x) in self.extras.iter().enumerate() {
1185            let (state, at) = (self.extra_state(s, e), self.planar_len() + self.extra_len() * e);
1186            out[at] = state[1];
1187            out[at + 1] = x.solve(state, torque[2 + e], self.brake_engaged, self.payload_attached).0;
1188            out[at + 2] = x.joint.brake.torque(self.brake_engaged, x.rotor(state).1, state[2]).1;
1189            if self.elastic {
1190                let (j, engaged) = (&x.joint, self.brake_engaged);
1191                let rotor_acc = j.rotor_under(torque[2 + e], state[3], state[4], x.gear(state), state[2], engaged).0;
1192                (out[at + 3], out[at + 4]) = (state[4], rotor_acc);
1193                if self.extra_len() == 6 {
1194                    out[at + 5] = j.gearbox.arm(state[3], state[0], x.arm(state)).1;
1195                }
1196            }
1197        }
1198        if !self.elastic {
1199            let (acc, ..) = self.rigid_solve(s, torque);
1200            let (_, rotor_speed) = self.rotors(s);
1201            let brakes = self.brakes(s);
1202            out[..2].copy_from_slice(&s[2..4]);
1203            out[2..4].copy_from_slice(&acc);
1204            for k in 0..2 {
1205                out[4 + k] = self.joints[k].brake.torque(self.brake_engaged, rotor_speed[k], brakes[k]).1;
1206            }
1207            return;
1208        }
1209        let (t, w) = self.arms(s);
1210        let (mass, velocity) = self.load(t, w);
1211        let (mut rhs, push) = ([0.0; 2], self.pushed(s));
1212        for k in 0..2 {
1213            let joint = &self.joints[k];
1214            let (gear, rotor_acc, brake_rate) =
1215                joint.rotor(torque[k], s[4 + k], s[6 + k], t[k], w[k], s[8 + k], self.brake_engaged);
1216            rhs[k] = gear.output - velocity[k] + joint.output_torque(t[k], w[k]) + push[k];
1217            out[4 + k] = s[6 + k];
1218            out[6 + k] = rotor_acc;
1219            out[8 + k] = brake_rate;
1220        }
1221        let acc = inverse(&mass).map_or([f64::NAN; 2], |inv| mul(&inv, rhs));
1222        out[..2].copy_from_slice(&s[2..4]);
1223        out[2..4].copy_from_slice(&acc);
1224    }
1225
1226    fn tool_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1227        let (t, w) = self.arms(s);
1228        let (p, j) = self.pose(t);
1229        pos[..2].copy_from_slice(&p);
1230        vel[..2].copy_from_slice(&mul(&j, w));
1231        for e in 0..self.extras.len() {
1232            (pos[2 + e], vel[2 + e]) = (self.extra_state(s, e)[0], self.extra_state(s, e)[1]);
1233        }
1234    }
1235    fn set_tool_velocity(&self, s: &mut [f64], vel: &[f64]) {
1236        let (t, _) = self.arms(s);
1237        let (_, j) = self.pose(t);
1238        let w = inverse(&j).map_or([f64::NAN; 2], |inv| mul(&inv, [vel[0], vel[1]]));
1239        s[2..4].copy_from_slice(&w);
1240        if self.elastic {
1241            for k in 0..2 {
1242                s[6 + k] = self.joints[k].ratio() * w[k];
1243            }
1244        }
1245        for (e, x) in self.extras.iter().enumerate() {
1246            let at = self.planar_len() + self.extra_len() * e;
1247            s[at + 1] = vel[2 + e];
1248            if self.elastic {
1249                s[at + 4] = x.ratio() * vel[2 + e];
1250            }
1251        }
1252    }
1253    fn motor_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1254        let (rotor, speed) = self.rotors(s);
1255        pos[..2].copy_from_slice(&rotor);
1256        vel[..2].copy_from_slice(&speed);
1257        for (e, x) in self.extras.iter().enumerate() {
1258            (pos[2 + e], vel[2 + e]) = x.rotor(self.extra_state(s, e));
1259        }
1260    }
1261
1262    /// Rigid, loss-free, at rest: M theta'' at the arm over the ratio, plus the rotor's own J_rotor i theta''; the Z
1263    /// stroke's and the turn's (m q'' - weight) / i + J_rotor i q''.
1264    fn feedforward_torque(&self, pos: &[f64], acc: &[f64], out: &mut [f64]) {
1265        let t = self.legs.inverse([pos[0], pos[1]]).unwrap_or([f64::NAN; 2]);
1266        let (mass, _) = self.load(t, [0.0; 2]);
1267        let (_, j) = self.pose(t);
1268        let arm_acc = inverse(&j).map_or([f64::NAN; 2], |inv| mul(&inv, [acc[0], acc[1]]));
1269        let at_arm = mul(&mass, arm_acc);
1270        for k in 0..2 {
1271            let joint = &self.joints[k];
1272            out[k] = at_arm[k] / joint.ratio() + joint.rotor_inertia * joint.ratio() * arm_acc[k];
1273        }
1274        for (e, x) in self.extras.iter().enumerate() {
1275            out[2 + e] = x.feedforward(acc[2 + e], self.payload_attached);
1276        }
1277    }
1278
1279    /// With the speed: θ̇ = J⁻¹ ṗ, θ̈ = J⁻¹ (p̈ − J_x⁻¹ w), and at the arm I_b θ̈ + m_nt Jᵀ p̈, over the ratio,
1280    /// plus the rotor's own J_rotor i θ̈.
1281    fn feedforward_torque_moving(&self, pos: &[f64], vel: &[f64], acc: &[f64], out: &mut [f64]) {
1282        let p = [pos[0], pos[1]];
1283        let t = self.legs.inverse(p).unwrap_or([f64::NAN; 2]);
1284        let (_, j) = self.pose(t);
1285        let inv = inverse(&j).unwrap_or([[f64::NAN; 2]; 2]);
1286        let (pv, pa) = ([vel[0], vel[1]], [acc[0], acc[1]]);
1287        let w = mul(&inv, pv);
1288        let bend = self.legs.velocity_term(t, p, w, pv).unwrap_or([f64::NAN; 2]);
1289        let arm_acc = mul(&inv, [pa[0] - bend[0], pa[1] - bend[1]]);
1290        let force = transpose(&j).map(|column| self.m_nt() * dot(column, pa));
1291        for k in 0..2 {
1292            let joint = &self.joints[k];
1293            out[k] = (self.arm_inertia * arm_acc[k] + force[k]) / joint.ratio()
1294                + joint.rotor_inertia * joint.ratio() * arm_acc[k];
1295        }
1296        // The stroke and the turn are linear: nothing for the speed.
1297        for (e, x) in self.extras.iter().enumerate() {
1298            out[2 + e] = x.feedforward(acc[2 + e], self.payload_attached);
1299        }
1300    }
1301
1302    /// The rigid model at theta'' = 0: each arm at theta' = J^-1 p', the stroke and the turn at their own speeds; per
1303    /// joint the motor shaft's friction (with the gearbox's drag) at i q' and the joint's own friction (bearings, the
1304    /// Z guides and the nut's preload) through the gearbox as `rigid_solve` and `Extra::solve` take it: f(q') / (i loss).
1305    fn steady_friction(&self, pos: &[f64], vel: &[f64], out: &mut [f64]) {
1306        let t = self.legs.inverse([pos[0], pos[1]]).unwrap_or([f64::NAN; 2]);
1307        let (_, j) = self.pose(t);
1308        let w = inverse(&j).map_or([f64::NAN; 2], |inv| mul(&inv, [vel[0], vel[1]]));
1309        let joints =
1310            self.joints.iter().zip(w).chain(self.extras.iter().map(|x| &x.joint).zip(vel[2..].iter().copied()));
1311        for (k, (joint, v)) in joints.enumerate() {
1312            let (i, friction) = (joint.ratio(), joint.friction.torque(v));
1313            out[k] = joint.shaft.torque(i * v) + friction / (i * joint.gearbox.loss_factor(friction, v));
1314        }
1315    }
1316
1317    fn energy(&self, s: &[f64]) -> f64 {
1318        self.energy_parts(s).iter().sum()
1319    }
1320
1321    fn set_payload_attached(&mut self, attached: bool) {
1322        self.payload_attached = attached;
1323    }
1324    fn set_brake_engaged(&mut self, engaged: bool) {
1325        self.brake_engaged = engaged;
1326    }
1327    /// A stop met within the step (`HardStop::substeps`, `RotaryJoint::stop_substeps`).
1328    fn substeps_wanted(&self, s: &[f64], _torque: &[f64], dt: f64, _substeps: u32) -> u32 {
1329        let (t, w) = self.arms(s);
1330        let extras = self.extras.iter().enumerate().map(|(e, x)| {
1331            let state = self.extra_state(s, e);
1332            x.joint.stop_substeps(state[0], state[1], dt)
1333        });
1334        (0..2).map(|k| self.joints[k].stop_substeps(t[k], w[k], dt)).chain(extras).max().unwrap_or(1)
1335    }
1336    /// The push acts on the arms beyond their gearboxes (`pushed`) and on each extra axis's load, in either model; its
1337    /// power is the budget's crash row.
1338    fn set_tool_force(&mut self, force: &[f64]) -> bool {
1339        self.push = [force[0], force[1]];
1340        self.extras.iter_mut().zip(&force[2..]).for_each(|(x, f)| x.push = *f);
1341        true
1342    }
1343
1344    /// The arms' gearboxes' hysteresis states move on to where the step ended (`Gearbox::commit`).
1345    fn after_step(&mut self, s: &mut [f64], _dt: f64) {
1346        if self.elastic {
1347            for k in 0..2 {
1348                self.joints[k].gearbox.commit(s[4 + k], s[k]);
1349            }
1350            let (at, n) = (self.planar_len(), self.extra_len());
1351            for (e, x) in self.extras.iter_mut().enumerate() {
1352                x.joint.gearbox.commit(s[at + n * e + 3], s[at + n * e]);
1353            }
1354        }
1355    }
1356
1357    /// The gearboxes, in the order of `thermal_parts`.
1358    fn set_part_temperatures(&mut self, rises: &[f64]) {
1359        let Some(law) = &self.thermal else { return };
1360        let mut rises = rises.iter();
1361        if !self.joints[0].gearbox.is_coupling() {
1362            for (joint, rise) in self.joints.iter_mut().zip(rises.by_ref()) {
1363                joint.gearbox.efficiency = law.gearbox_efficiency(*rise);
1364            }
1365        }
1366        for x in self.extras.iter_mut().filter(|x| !x.joint.coupled) {
1367            if let (Some(law), Some(rise)) = (&x.thermal, rises.next()) {
1368                x.joint.gearbox.efficiency = law.gearbox_efficiency(*rise) * x.joint.extra_efficiency;
1369            }
1370        }
1371    }
1372
1373    /// With elastic gearboxes, the motors held (`modes_at`), lowest first.
1374    fn modes(&self, tool_pose: &[f64]) -> Vec<sim_core::Mode> {
1375        self.modes_at(tool_pose, false)
1376    }
1377    /// `modes` with the gearboxes' hysteresis stiffness added (K1 + sigma): the frequencies of a small ringing.
1378    fn modes_small_amplitude(&self, tool_pose: &[f64]) -> Vec<sim_core::Mode> {
1379        self.modes_at(tool_pose, true)
1380    }
1381    /// With effects.joint_elasticity: per arm its gearbox's spring between the rotor and the rest of the motor's rigid
1382    /// inertia at the pose (`RotaryJoint::train`); the stroke's and the turn's trains are left out.
1383    fn trains(&self, tool_pose: &[f64]) -> Vec<Option<sim_core::Train>> {
1384        if !self.elastic {
1385            return Vec::new();
1386        }
1387        let whole = sim_components::control::rigid_inertias(self, tool_pose);
1388        let mut out: Vec<_> = self.joints.iter().zip(whole).map(|(j, whole)| j.train(whole)).collect();
1389        out.resize(self.motors().len(), None);
1390        out
1391    }
1392
1393    /// The plane's lowest mode, which an input shaper on the path is for; the stroke's and the turn's are in `modes`.
1394    fn resonance_hz(&self, tool_pose: &[f64]) -> Option<f64> {
1395        self.plane_modes(tool_pose, false).first().map(|m| m.hz)
1396    }
1397
1398    /// The mode of `resonance_hz` and its shape: the arms' angles along its eigenvector v of (K - lambda M) v = 0
1399    /// (`plane_modes`), the rotors held (their angles 0 in it), the stroke and the turn still; scaled so that the plate
1400    /// moves 1 m along x (J v), or, where the mode moves it across x alone, 1 m along y.
1401    fn mode_shape(&self, tool_pose: &[f64]) -> Option<(f64, Vec<f64>)> {
1402        let hz = self.resonance_hz(tool_pose)?;
1403        let t = self.legs.inverse([tool_pose[0], tool_pose[1]])?;
1404        let (m, _) = self.load(t, [0.0; 2]);
1405        let k: V2 = std::array::from_fn(|i| spring(&self.joints[i].gearbox, false));
1406        let lambda = (std::f64::consts::TAU * hz).powi(2);
1407        let v = mode_vector(k, &m, lambda);
1408        let (_, j) = self.pose(t);
1409        let moved = mul(&j, v);
1410        let along = if moved[0].abs() > 1e-9 * norm(moved) { moved[0] } else { moved[1] };
1411        let mut shape = vec![0.0; self.state_len()];
1412        (shape[0], shape[1]) = (v[0] / along, v[1] / along);
1413        Some((hz, shape))
1414    }
1415
1416    /// What the gearboxes can sag at rest anywhere in the working range (`rest_sag`).
1417    fn setpoint_slack(&self) -> f64 {
1418        self.rest_slack
1419    }
1420
1421    fn unreachable(&self, tool: &[f64], slack: f64) -> Option<&'static str> {
1422        if tool.len() != self.axes.len() {
1423            return Some("error-target-out-of-range");
1424        }
1425        let p = [tool[0], tool[1]];
1426        if !self.in_envelope(&p, slack) {
1427            return Some("error-delta-outside-envelope");
1428        }
1429        let Some(t) = self.legs.inverse(p) else { return Some("error-delta-out-of-reach") };
1430        let (min, max) = self.joints[0].range;
1431        if t.iter().any(|a| *a < min || *a > max) {
1432            return Some("error-delta-joint-stop");
1433        }
1434        match self.legs.jacobian(t, p) {
1435            Some(j) if condition_number(&j) <= self.max_condition => None,
1436            _ => Some("error-delta-singularity"),
1437        }
1438    }
1439
1440    fn signal_infos(&self) -> Vec<SignalInfo> {
1441        let mut out = Vec::new();
1442        for (k, motor) in self.motors[..2].iter().enumerate() {
1443            let arm = ["arm-1", "arm-2"][k];
1444            out.push(SignalInfo::new(format!("arm.{}.angle", motor.id), arm, "quantity-arm-angle", "rad"));
1445            out.push(SignalInfo::new(
1446                format!("gearbox.{}.output_torque", motor.id),
1447                motor.key,
1448                "quantity-gearbox-torque",
1449                "N m",
1450            ));
1451        }
1452        out.push(SignalInfo::new("kinematics.condition", "group-kinematics", "quantity-condition-number", ""));
1453        // The stroke's force on its nut and its screw's speed, d n and life; the turn's gearbox torque.
1454        for (e, x) in self.extras.iter().enumerate() {
1455            let (axis, motor) = (&self.axes[2 + e], &self.motors[2 + e]);
1456            match &x.screw {
1457                Some(screw) => {
1458                    let force = format!("joint.{}.force", axis.id);
1459                    out.push(SignalInfo::new(force, axis.key, "quantity-joint-force", "N"));
1460                    out.extend(screw.signal_infos(axis.id, axis.key));
1461                }
1462                None => out.push(SignalInfo::new(
1463                    format!("gearbox.{}.output_torque", motor.id),
1464                    motor.key,
1465                    "quantity-gearbox-torque",
1466                    "N m",
1467                )),
1468            }
1469        }
1470        self.effect_infos(&mut out);
1471        out
1472    }
1473
1474    /// The stroke's ball screw: its speed, d n, buckling, static load and life.
1475    fn rating_checks(&self) -> Vec<RatingCheck> {
1476        let screws = self.extras.iter().enumerate().filter_map(|(e, x)| Some((e, x.screw.as_ref()?)));
1477        screws.flat_map(|(e, screw)| screw.rating_checks(self.axes[2 + e].id, 2 + e, self.required_life)).collect()
1478    }
1479
1480    fn base_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1481        let (t, _) = self.arms(s);
1482        let gear = self.gear_output(s, torque);
1483        for k in 0..2 {
1484            out.extend([t[k], gear[k]]);
1485        }
1486        let (_, j) = self.pose(t);
1487        out.push(condition_number(&j));
1488        for (e, x) in self.extras.iter().enumerate() {
1489            let state = self.extra_state(s, e);
1490            let (.., force) = x.solve(state, torque[2 + e], self.brake_engaged, self.payload_attached);
1491            out.push(force);
1492            if let Some(screw) = &x.screw {
1493                screw.signals(state[1], force, out);
1494            }
1495        }
1496    }
1497    fn effect_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1498        self.view_signals(s, torque, out);
1499    }
1500    fn loss_powers(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1501        out.extend(self.losses(s, torque).powers);
1502        self.extra_losses(s, torque, out);
1503    }
1504
1505    /// The two arms' bearing friction, rotary contacts (N m over rad/s at the arm).
1506    fn friction_contacts(&self) -> Vec<sim_core::FrictionContact> {
1507        (0..2).map(|k| sim_core::FrictionContact { id: JOINT_CONTACTS[k], owner_key: ARMS[k] }).collect()
1508    }
1509    fn friction_rotary(&self, _i: usize) -> bool {
1510        true
1511    }
1512    fn friction_curve(&self, i: usize, speed: f64, _load_scale: f64) -> [f64; 3] {
1513        self.joints.get(i).filter(|_| i < 2).map_or([0.0; 3], |j| j.friction_split(speed))
1514    }
1515    /// The arm turns at its motor's highest speed over the gearbox's ratio.
1516    fn friction_speed_limit(&self, i: usize, motor_speed: &[f64]) -> Option<f64> {
1517        if i < 2 { Some(motor_speed.get(i)? / self.joints[i].ratio()) } else { None }
1518    }
1519
1520    /// The two gearboxes, where there are gearboxes (not on a direct drive); then the extra axes' (not behind a
1521    /// coupling), drawn after the arms'.
1522    fn thermal_parts(&self) -> Vec<ThermalPart> {
1523        let planar = if self.joints[0].gearbox.is_coupling() {
1524            &[][..]
1525        } else {
1526            &[("gearbox_1", "motor-arm-1"), ("gearbox_2", "motor-arm-2")][..]
1527        };
1528        let extras = self.extras.iter().zip(&self.motors[2..]).filter(|(x, _)| !x.joint.coupled);
1529        let extras = extras.map(|(_, m)| (if m.id == "3" { "gearbox_3" } else { "gearbox_4" }, m.key));
1530        planar
1531            .iter()
1532            .copied()
1533            .zip(0..)
1534            .chain(extras.zip(2..))
1535            .map(|((id, owner_key), scene_index)| ThermalPart {
1536                id,
1537                kind: "gearbox",
1538                owner_key,
1539                scene_part: "gearbox",
1540                scene_index,
1541            })
1542            .collect()
1543    }
1544
1545    /// The machine in the plane z = 0 of the scene: base beam, per arm a motor and a gearbox box above its shoulder with
1546    /// a bar turned by the rotor angle, the arm, the forearm pair's two rods (apart along z, the joints' axis), the
1547    /// plate; at the plate the quill down to the tool's flange, the payload under it, a bar across the flange turned
1548    /// with the tool, and on top the Z and C motors.
1549    fn scene(&self, s: &[f64], out: &mut Scene) {
1550        let (t, _) = self.arms(s);
1551        let (rotor, rotor_speed) = self.rotors(s);
1552        let tool = self.tool_pose(s);
1553        let p = [tool[0], tool[1]];
1554        out.parts.clear();
1555        out.labels.clear();
1556        let grey = [0.62, 0.64, 0.68];
1557        out.parts.push(Part::new(
1558            "base",
1559            Shape::Box { size: [2.0 * self.base_radius + 0.2, 0.2, 0.04] },
1560            [0.0, 0.0, 0.1],
1561            grey,
1562        ));
1563        for k in 0..2 {
1564            let side = SIDE[k];
1565            let shoulder = [side * self.base_radius, 0.0, 0.0];
1566            // The elbow drawn where the arm ends: the legs' elbow is at e, the arm's end at the base radius.
1567            let [elbow, ..] = self.legs.elbow(k, t[k]);
1568            let arm_end = [elbow[0] + side * self.platform_radius, elbow[1], 0.0];
1569            let at = |z: f64| [side * self.base_radius, 0.0, z];
1570            out.parts.push(Part::new(
1571                sim_core::scene::MOTOR_PART,
1572                Shape::Box { size: [0.09, 0.09, 0.12] },
1573                at(0.16),
1574                [0.9, 0.45, 0.1],
1575            ));
1576            out.parts.push(Part::new("gearbox", Shape::Box { size: [0.09, 0.09, 0.06] }, at(0.05), [0.25, 0.25, 0.28]));
1577            out.parts.push(
1578                Part::new("rotor-bar", Shape::Box { size: [0.07, 0.004, 0.012] }, at(0.225), [0.1, 0.1, 0.1])
1579                    .turned(rotor[k]),
1580            );
1581            out.parts.push(Part::new("arm", Shape::Segment { to: arm_end, width: 0.04 }, shoulder, [0.2, 0.22, 0.26]));
1582            for half in [-0.5 * self.rod_spacing, 0.5 * self.rod_spacing] {
1583                let (from, to) = ([arm_end[0], arm_end[1], half], [p[0] + side * self.platform_radius, p[1], half]);
1584                out.parts.push(Part::new("forearm", Shape::Segment { to, width: 0.012 }, from, [0.15, 0.15, 0.15]));
1585            }
1586            out.labels.push(Label {
1587                pos: at(0.3),
1588                owner_key: self.motors[k].key,
1589                value: rotor_speed[k] * 60.0 / std::f64::consts::TAU,
1590                unit_key: "unit-rpm",
1591                decimals: 0,
1592            });
1593        }
1594        out.parts.extend(self.on_platform(&tool));
1595        let below = [p[0], p[1], self.flange_z(&tool) - 0.17];
1596        out.labels.push(Label {
1597            pos: below,
1598            owner_key: self.axes[1].key,
1599            value: p[1],
1600            unit_key: "unit-m",
1601            decimals: 3,
1602        });
1603        // The Z motor behind the plate and the C motor in front of it, on top, each with its gearbox where
1604        // it has one; the bar across the flange shows the tool's turn.
1605        for (e, x) in self.extras.iter().enumerate() {
1606            let k = 2 + e;
1607            let state = self.extra_state(s, e);
1608            let at = |z: f64| [p[0], p[1] + if x.screw.is_some() { 0.08 } else { -0.08 }, z];
1609            out.parts.push(Part::new(
1610                sim_core::scene::MOTOR_PART,
1611                Shape::Box { size: [0.05, 0.05, 0.08] },
1612                at(0.13),
1613                [0.9, 0.45, 0.1],
1614            ));
1615            if !x.joint.coupled {
1616                out.parts.push(Part::new("gearbox", Shape::Box { size: [0.05, 0.05, 0.04] }, at(0.07), [0.25; 3]));
1617            }
1618            out.parts.push(
1619                Part::new("rotor-bar", Shape::Box { size: [0.04, 0.004, 0.01] }, at(0.18), [0.1; 3])
1620                    .turned(x.rotor(state).0),
1621            );
1622            out.labels.push(Label {
1623                pos: at(0.23),
1624                owner_key: self.motors[k].key,
1625                value: x.rotor(state).1 * 60.0 / std::f64::consts::TAU,
1626                unit_key: "unit-rpm",
1627                decimals: 0,
1628            });
1629            if x.screw.is_none() {
1630                let (c, flange) = (state[0], self.flange_z(&tool) - 0.025);
1631                let (dx, dy) = (0.05 * c.cos(), 0.05 * c.sin());
1632                let to = [p[0] + dx, p[1] + dy, flange];
1633                out.parts.push(Part::new(
1634                    "tool-bar",
1635                    Shape::Segment { to, width: 0.01 },
1636                    [p[0] - dx, p[1] - dy, flange],
1637                    [0.9, 0.8, 0.1],
1638                ));
1639            }
1640        }
1641    }
1642
1643    /// The underside of the tool's flange.
1644    fn scene_point(&self, tool_pose: &[f64]) -> Option<[f64; 3]> {
1645        Some([tool_pose[0], tool_pose[1], self.flange_z(tool_pose) - 0.02])
1646    }
1647
1648    /// The plate, the quill, the tool's flange and the payload under it, where `scene` draws them. The forearms are left
1649    /// out.
1650    fn collision_bodies(&self, s: &[f64]) -> Vec<sim_core::Aabb> {
1651        sim_core::scene::scene_boxes(&self.on_platform(&self.tool_pose(s)), &["platform", "quill", "tool", "payload"])
1652    }
1653}
1654
1655#[cfg(test)]
1656mod tests;