Skip to main content

sim_netlist/
spatial.rs

1//! Delta picker D3 (Clavel): three motor-driven arms at 120 degrees on a base, each carrying a parallelogram of two
2//! forearms down to a platform that stays level. The tool is the platform's centre, x, y, z.
3//!
4//! Kinematics per leg i at azimuth phi_i, with e = base radius - platform radius (the platform's offset folded into the
5//! base, as the platform never turns), the arm angle theta_i (0 horizontal, positive down), upper arm L_a, forearm L_b:
6//!
7//! ```text
8//! elbow     c_i = R_z(phi_i) (e + L_a cos theta, 0, -L_a sin theta)
9//! constraint |p - c_i|^2 = L_b^2
10//! inverse   A cos theta + B sin theta + C = 0, A = -2 L_a (x' - e), B = 2 L_a z, C = (x' - e)^2 + y'^2 + z^2 + L_a^2 - L_b^2
11//!           theta = 2 atan((-B - sqrt(A^2 + B^2 - C^2)) / (C - A))     (elbow out; (x', y', z) = R_z(-phi_i) p)
12//! forward   p = the lower of the two points at L_b from all three elbows (trilateration)
13//! 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
14//!           J_x p'' = J_q theta'' + w, w_i = theta_i'^2 (u_i . c_i'') - |p' - c_i' theta_i'|^2
15//! ```
16//!
17//! Dynamics (Codourey 1998 as used by Olsson 2009): the forearms' rotational inertia is left out and each forearm pair's
18//! mass m_fb split, a share r at the elbow (it turns with the arm) and 1 - r at the platform. Then the machine is three
19//! arms about their joints plus a point mass at the platform, m_nt = platform + payload + 3 (1 - r) m_fb, and by virtual
20//! work
21//!
22//! ```text
23//! 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
24//! I_b = I_arm + L_a^2 (m_elbow + r m_fb),   Q_g,i = g m_LG cos theta_i - m_nt g J_zi,   m_LG = m_arm l_cg + L_a (m_elbow + r m_fb)
25//! ```
26//!
27//! exact for that model: the platform's kinetic energy m_nt |J theta'|^2 / 2 is what M holds, and the velocity term is the
28//! platform's m_nt J'theta' through J^T.
29//!
30//! With effects.forearm_inertia each forearm pair is a rigid slender rod instead (the two rods of a pair move alike, the
31//! platform never turning): its kinetic energy (m/6)(|c'|^2 + c'.p' + |p'|^2) is exactly that of m/6 at each end and
32//! 2m/3 at its middle, so the rod is m_fb/6 at the elbow, m_fb/6 at the platform and 2 m_fb/3 at its middle
33//! (c_i + p)/2, whose Jacobian J_m,i = (J + dc_i/dtheta e_i^T)/2 adds m_mid J_m^T J_m to M, its acceleration at no
34//! arm acceleration (J_x^-1 w + c_i'' theta_i'^2)/2 the velocity term and its weight to Q_g. The spin of a rod about its
35//! own axis is left out.
36//!
37//! With effects.link_elasticity each upper arm bends (in the plane it turns in): the elbow turns by delta_i against the
38//! arm's root, on a spring k_b = 3 E I / L_a (a cantilever's tip deflection as a turn about the shoulder) with a damper.
39//! The arm's tube stays with the root (I_arm, m_arm l_cg), the elbow and all beyond move with the elbow angle
40//! theta + delta: I_arm theta'' = tau_gear + g m_arm l_cg cos theta + k_b delta + c_b delta' + tau_joint, and the rest of
41//! the machine as above at the elbow angles with the spring's -k_b delta - c_b delta' in place of the gearbox.
42//! With effects.arm_tube_inertia as well the tube bends in the static shape of a cantilever under a tip load,
43//! psi = (3 xi^2 - xi^3) / 2 (psi(L_a) = 1), the mode consistent with k_b (Rayleigh; `beam::STATIC_SHAPE_MASS`): the tube is as
44//! much of the arm's mass as its inertia allows a uniform tube, m = min(m_arm, 3 I_arm / L_a^2), the rest a hub on the
45//! shoulder's axis. Its kinetic energy, its sections at s theta' + psi(s) L_a delta', is
46//! m L_a^2 (theta'^2 / 3 + 2 int(xi psi) theta' delta' + int(psi^2) delta'^2) / 2, int(xi psi) = 11/40,
47//! int(psi^2) = 33/140: in theta and e = theta + delta, I_r theta'^2 / 2 + B theta' e' + 33/280 m L_a^2 e'^2 with
48//! B = (11/40 - 33/140) m L_a^2 and I_r = I_arm - 33/140 m L_a^2 - 2 B; 3/8 m L_a of its first moment (int psi) moves to
49//! the elbow. The joints' equation takes the elbows' solved, (I_r - B^2 (M_d^-1)_ee) theta'' = f_r - B (M_d^-1 f_d)_e
50//! (`joint_load`), then M_d q'' = f_d - B theta'' on the elbows' rows (`bend_rates`). Out of its plane 33/140 of the
51//! tube's mass moves with the elbow's move y, and the elbow block turns with the tube's tip slope 3/2 y / L_a.
52//! Each joint is a `RotaryJoint` (gearbox with stiffness, backlash and
53//! efficiency, motor with friction, ripple and brake, joint friction, stops). Elastic (effects.joint_elasticity) the
54//! rotors are states of their own behind the gearboxes' springs; rigid, each rotor turns with its arm times the ratio and
55//! its inertia counts at the arm times the ratio squared, the gearbox losing its efficiency on what passes through it.
56
57use crate::linkage::{Arms, LinkageNode, Numbers};
58use crate::netlist::Netlist;
59use sim_components::joint::RotaryJoint;
60use sim_components::mech::{ShaftFriction, ThermalFeedback};
61use sim_core::{
62    AxisInfo, Config, ConfigError, ENERGY_PARTS, LOSS_PREFIX, Label, Machine, Mode, MotorInfo, Part, Scene, Shape,
63    SignalInfo, TORQUE_PARTS, ThermalPart,
64};
65
66const G: f64 = 9.80665;
67
68pub type V3 = [f64; 3];
69pub type M3 = [[f64; 3]; 3];
70/// Mass matrix, velocity term and gravity in N coordinates.
71type Load<const N: usize> = ([[f64; N]; N], [f64; N], [f64; N]);
72
73/// A point mass m into `load`: its Jacobian jm (3 x N), its acceleration am at no acceleration of the coordinates, its
74/// weight down z at g.
75fn add_point<const N: usize>(load: &mut Load<N>, m: f64, jm: &[[f64; N]; 3], am: V3, g: f64) {
76    for r in 0..N {
77        for c in 0..N {
78            load.0[r][c] += m * (0..3).map(|k| jm[k][r] * jm[k][c]).sum::<f64>();
79        }
80        load.1[r] += m * (0..3).map(|k| jm[k][r] * am[k]).sum::<f64>();
81        load.2[r] -= m * g * jm[2][r];
82    }
83}
84
85pub fn dot(a: V3, b: V3) -> f64 {
86    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
87}
88
89pub fn sub(a: V3, b: V3) -> V3 {
90    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
91}
92
93pub fn cross(a: V3, b: V3) -> V3 {
94    [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
95}
96
97pub fn norm(a: V3) -> f64 {
98    dot(a, a).sqrt()
99}
100
101pub fn mul(m: &M3, v: V3) -> V3 {
102    [dot(m[0], v), dot(m[1], v), dot(m[2], v)]
103}
104
105pub fn transpose(m: &M3) -> M3 {
106    std::array::from_fn(|i| std::array::from_fn(|j| m[j][i]))
107}
108
109/// The inverse of a 3 x 3 matrix by its adjugate; `None` where it is singular.
110pub fn inverse(m: &M3) -> Option<M3> {
111    let det = dot(m[0], cross(m[1], m[2]));
112    if !(det.abs() > 1e-300) || !det.is_finite() {
113        return None;
114    }
115    // The columns of the inverse are the cross products of the rows over the determinant.
116    let (c0, c1, c2) = (cross(m[1], m[2]), cross(m[2], m[0]), cross(m[0], m[1]));
117    Some(std::array::from_fn(|i| [c0[i] / det, c1[i] / det, c2[i] / det]))
118}
119
120/// The 2-norm condition number of a 3 x 3 matrix: the square root of the largest over the smallest eigenvalue of
121/// J^T J, by the closed form for a symmetric 3 x 3 (trigonometric solution of the characteristic cubic).
122pub fn condition_number(j: &M3) -> f64 {
123    let jt = transpose(j);
124    let a: M3 = std::array::from_fn(|r| std::array::from_fn(|c| dot(jt[r], jt[c])));
125    let q = (a[0][0] + a[1][1] + a[2][2]) / 3.0;
126    let p1 = a[0][1] * a[0][1] + a[0][2] * a[0][2] + a[1][2] * a[1][2];
127    let p2 = (0..3).map(|i| (a[i][i] - q).powi(2)).sum::<f64>() + 2.0 * p1;
128    let p = (p2 / 6.0).sqrt();
129    if p < 1e-15 * q.abs() {
130        return 1.0;
131    }
132    let b: M3 = std::array::from_fn(|r| std::array::from_fn(|c| (a[r][c] - if r == c { q } else { 0.0 }) / p));
133    let half_det = (dot(b[0], cross(b[1], b[2])) / 2.0).clamp(-1.0, 1.0);
134    let phi = half_det.acos() / 3.0;
135    let (largest, smallest) = (q + 2.0 * p * phi.cos(), q + 2.0 * p * (phi + 2.0 * std::f64::consts::PI / 3.0).cos());
136    if smallest <= 0.0 { f64::INFINITY } else { (largest / smallest).sqrt() }
137}
138
139/// The leg geometry and the kinematics, apart from masses and drives.
140#[derive(Debug, Clone)]
141pub struct Legs {
142    /// Base radius less platform radius, upper arm, forearm.
143    pub e: f64,
144    pub la: f64,
145    pub lb: f64,
146    /// cos and sin of the legs' azimuths, 0, 120 and 240 degrees.
147    pub azimuth: [(f64, f64); 3],
148}
149
150impl Legs {
151    pub fn new(e: f64, la: f64, lb: f64) -> Self {
152        let azimuth = [0.0f64, 120.0, 240.0].map(|deg| (deg.to_radians().cos(), deg.to_radians().sin()));
153        Self { e, la, lb, azimuth }
154    }
155
156    /// A vector in leg i's frame turned into the base frame (R_z(phi_i) v), and back.
157    fn to_base(&self, i: usize, v: V3) -> V3 {
158        let (c, s) = self.azimuth[i];
159        [c * v[0] - s * v[1], s * v[0] + c * v[1], v[2]]
160    }
161    fn to_leg(&self, i: usize, v: V3) -> V3 {
162        let (c, s) = self.azimuth[i];
163        [c * v[0] + s * v[1], -s * v[0] + c * v[1], v[2]]
164    }
165
166    /// The elbow of leg i at arm angle t, and its first and second derivative by t.
167    pub fn elbow(&self, i: usize, t: f64) -> [V3; 3] {
168        let (s, c) = t.sin_cos();
169        let la = self.la;
170        [
171            self.to_base(i, [self.e + la * c, 0.0, -la * s]),
172            self.to_base(i, [-la * s, 0.0, -la * c]),
173            self.to_base(i, [-la * c, 0.0, la * s]),
174        ]
175    }
176
177    /// The direction of leg i's elbow axis: the rods of a pair are apart along it, and the upper arm bends out of the
178    /// plane it turns in along it.
179    pub fn tangent(&self, i: usize) -> V3 {
180        self.to_base(i, [0.0, 1.0, 0.0])
181    }
182
183    /// The elbows at arm angles t, each moved by y_i along its tangent (the arms bent out of their planes).
184    pub fn elbows_moved(&self, t: V3, y: V3) -> [V3; 3] {
185        std::array::from_fn(|i| {
186            let (c, tg) = (self.elbow(i, t[i])[0], self.tangent(i));
187            std::array::from_fn(|k| c[k] + y[i] * tg[k])
188        })
189    }
190
191    /// Arm angles for a platform position, elbows out; `None` out of reach.
192    pub fn inverse(&self, p: V3) -> Option<V3> {
193        self.inverse_moved(p, [0.0; 3])
194    }
195
196    /// `inverse` with the elbows moved by y along their tangents: in the leg's frame the platform is y_i nearer.
197    pub fn inverse_moved(&self, p: V3, moved: V3) -> Option<V3> {
198        let mut out = [0.0; 3];
199        for (i, t) in out.iter_mut().enumerate() {
200            let [x, y, z] = self.to_leg(i, p);
201            let y = y - moved[i];
202            let (a, b, c) = (
203                -2.0 * self.la * (x - self.e),
204                2.0 * self.la * z,
205                (x - self.e).powi(2) + y * y + z * z + self.la * self.la - self.lb * self.lb,
206            );
207            let d = a * a + b * b - c * c;
208            if !(d >= 0.0) {
209                return None;
210            }
211            // a cos t + b sin t + c = 0 by the half angle u = tan(t / 2): (c - a) u^2 + 2 b u + (a + c) = 0, the root
212            // (-b - sqrt d) / (c - a) = (a + c) / (sqrt d - b). Below the base (b = 2 L_a z < 0) the second form stays
213            // finite where c = a, at which the first divided by zero (motor 2 at 0 rad at (-0.15, -0.0866, -0.9)).
214            let s = d.sqrt();
215            *t = if b <= 0.0 { 2.0 * (a + c).atan2(s - b) } else { 2.0 * ((-b - s) / (c - a)).atan() };
216        }
217        Some(out)
218    }
219
220    /// The platform position for arm angles: the lower point at a forearm's length from all three elbows. `None` where
221    /// the legs cannot be assembled.
222    pub fn forward(&self, t: V3) -> Option<V3> {
223        self.forward_moved(t, [0.0; 3])
224    }
225
226    /// `forward` with the elbows moved by y along their tangents.
227    pub fn forward_moved(&self, t: V3, y: V3) -> Option<V3> {
228        let c = self.elbows_moved(t, y);
229        let ex = sub(c[1], c[0]);
230        let d = norm(ex);
231        let ex = ex.map(|v| v / d);
232        let to3 = sub(c[2], c[0]);
233        let i = dot(ex, to3);
234        let ey = sub(to3, ex.map(|v| v * i));
235        let ey_len = norm(ey);
236        if !(d > 1e-12 && ey_len > 1e-12) {
237            return None;
238        }
239        let ey = ey.map(|v| v / ey_len);
240        let ez = cross(ex, ey);
241        let j = dot(ey, to3);
242        let x = d / 2.0;
243        let y = (i * i + j * j - 2.0 * i * x) / (2.0 * j);
244        let z2 = self.lb * self.lb - x * x - y * y;
245        if !(z2 >= 0.0) {
246            return None;
247        }
248        let base: V3 = std::array::from_fn(|k| c[0][k] + x * ex[k] + y * ey[k]);
249        let (up, down): (V3, V3) = (
250            std::array::from_fn(|k| base[k] + z2.sqrt() * ez[k]),
251            std::array::from_fn(|k| base[k] - z2.sqrt() * ez[k]),
252        );
253        Some(if up[2] < down[2] { up } else { down })
254    }
255
256    /// J_x (rows: the forearm vectors u_i = p - c_i), the diagonal of J_q (u_i . dc_i/dt) and that of the elbows'
257    /// moves (u_i . tangent_i), with the elbows moved by y.
258    fn constraint(&self, t: V3, y: V3, p: V3) -> (M3, V3, V3) {
259        let jx = self.elbows_moved(t, y).map(|c| sub(p, c));
260        (jx, [0, 1, 2].map(|i| dot(jx[i], self.elbow(i, t[i])[1])), [0, 1, 2].map(|i| dot(jx[i], self.tangent(i))))
261    }
262
263    /// The Jacobian J[i][j] = dp_i / dtheta_j at arm angles t and platform position p; `None` at a direct singularity.
264    pub fn jacobian(&self, t: V3, p: V3) -> Option<M3> {
265        self.jacobians(t, [0.0; 3], p).map(|(j, _)| j)
266    }
267
268    /// The platform's Jacobians by the arm angles and by the elbows' moves y along their tangents, with the elbows
269    /// moved by y: J_x^-1 J_q and J_x^-1 diag(u_i . tangent_i).
270    pub fn jacobians(&self, t: V3, y: V3, p: V3) -> Option<(M3, M3)> {
271        let (jx, jq, jy) = self.constraint(t, y, p);
272        let inv = inverse(&jx)?;
273        let scaled = |d: V3| -> M3 { std::array::from_fn(|i| std::array::from_fn(|j| inv[i][j] * d[j])) };
274        Some((scaled(jq), scaled(jy)))
275    }
276
277    /// J' theta' = J_x^-1 w: the platform's acceleration at arm speeds `w_t` and no arm acceleration.
278    pub fn velocity_term(&self, t: V3, p: V3, wt: V3, pv: V3) -> Option<V3> {
279        self.velocity_term_moved(t, [0.0; 3], p, wt, [0.0; 3], pv)
280    }
281
282    /// `velocity_term` with the elbows moved by y and moving at yv along their tangents, which stay as they are:
283    /// w_i = theta_i'^2 (u_i . c_i'') - |p' - c_i'|^2 with c_i' = dc_i/dtheta theta_i' + tangent_i y_i'.
284    pub fn velocity_term_moved(&self, t: V3, y: V3, p: V3, wt: V3, yv: V3, pv: V3) -> Option<V3> {
285        let (jx, ..) = self.constraint(t, y, p);
286        let inv = inverse(&jx)?;
287        let w: V3 = std::array::from_fn(|i| {
288            let ([_, d1, d2], tg) = (self.elbow(i, t[i]), self.tangent(i));
289            let rel: V3 = std::array::from_fn(|k| pv[k] - d1[k] * wt[i] - tg[k] * yv[i]);
290            wt[i] * wt[i] * dot(jx[i], d2) - dot(rel, rel)
291        });
292        Some(mul(&inv, w))
293    }
294
295    /// The two rods of leg i's forearm pair, elbow end to platform end, at elbow angle t and platform position p, as
296    /// drawn: `spacing` apart along the elbow's axis, their ends at the base radius (the legs' elbow is at e, `r` the
297    /// platform radius added back) and at the platform's rim; the elbow moved by y along its axis (the arm bent out of
298    /// its plane).
299    pub fn rods(&self, i: usize, t: f64, y: f64, p: V3, r: f64, spacing: f64) -> [(V3, V3); 2] {
300        let (c, sn) = self.azimuth[i];
301        let (at, tg) = (self.elbow(i, t)[0], self.tangent(i));
302        let elbow: V3 = std::array::from_fn(|k| at[k] + y * tg[k]);
303        let half = [-0.5 * spacing * sn, 0.5 * spacing * c, 0.0];
304        let (arm_end, platform_end) =
305            ([elbow[0] + r * c, elbow[1] + r * sn, elbow[2]], [p[0] + r * c, p[1] + r * sn, p[2]]);
306        [-1.0, 1.0].map(|side| {
307            (
308                std::array::from_fn(|k| arm_end[k] + side * half[k]),
309                std::array::from_fn(|k| platform_end[k] + side * half[k]),
310            )
311        })
312    }
313}
314
315/// The arms' modes with the motors held (by their position loops): per arm the gearbox's spring k_g from the motor to
316/// the arm's root (inertia `root`, joined to its elbow by the tube's `coupling` B; `k_gear` one per arm, each arm's own
317/// gearbox), the bending spring k_b from the root to the elbow, and the rest of the machine as
318/// the mass matrix `distal` in the elbow angles and, where it is 6 x 6, the elbows' moves out of the arms' planes, each
319/// on its lateral spring k_l. `None` for a rigid spring (infinite stiffness: the two ends one body). The coordinates
320/// are (roots, elbow angles, elbow moves), the flexibility per arm K^-1 = [[1/k_g, 1/k_g], [1/k_g, 1/k_g + 1/k_b]]
321/// (root, elbow) and 1/k_l; with M = L L^T (Cholesky) the eigenvalues mu = 1/w^2 of the symmetric L^T K^-1 L, by
322/// Jacobi rotations, the shape v = K^-1 L z / mu. A rigid connection has mu = 0 and is no mode. Gravity's stiffness
323/// (some N m/rad against 1e4) and the stops are left out. Returns w^2 and the shape per mode, lowest first.
324pub fn arm_modes(
325    (root, coupling): (f64, f64),
326    distal: &[Vec<f64>],
327    k_gear: Option<[f64; 3]>,
328    k_bend: Option<f64>,
329    k_lateral: Option<f64>,
330) -> Vec<(f64, Vec<f64>)> {
331    let flex = |k: Option<f64>| k.map_or(0.0, |k| 1.0 / k);
332    let (fb, fl) = (flex(k_bend), flex(k_lateral));
333    let n = 3 + distal.len();
334    let (mut m, mut f) = (vec![vec![0.0; n]; n], vec![vec![0.0; n]; n]);
335    for i in 0..3 {
336        m[i][i] = root;
337        if n > 3 {
338            (m[i][3 + i], m[3 + i][i]) = (coupling, coupling);
339        }
340        let fg = k_gear.map_or(0.0, |k| 1.0 / k[i]);
341        (f[i][i], f[i][3 + i], f[3 + i][i], f[3 + i][3 + i]) = (fg, fg, fg, fg + fb);
342        if n == 9 {
343            f[6 + i][6 + i] = fl;
344        }
345    }
346    for (r, row) in distal.iter().enumerate() {
347        m[3 + r][3..].copy_from_slice(row);
348    }
349    let mut l = vec![vec![0.0; n]; n];
350    for i in 0..n {
351        for j in 0..=i {
352            let s = m[i][j] - (0..j).map(|k| l[i][k] * l[j][k]).sum::<f64>();
353            l[i][j] = if i == j { s.max(0.0).sqrt() } else { s / l[j][j] };
354        }
355    }
356    let times = |a: &[Vec<f64>], b: &[Vec<f64>]| -> Vec<Vec<f64>> {
357        (0..n).map(|r| (0..n).map(|c| (0..n).map(|k| a[r][k] * b[k][c]).sum()).collect()).collect()
358    };
359    let lt: Vec<Vec<f64>> = (0..n).map(|r| (0..n).map(|c| l[c][r]).collect()).collect();
360    let fl_ = times(&f, &l);
361    let (mu, z) = symmetric_eigen(times(&lt, &fl_));
362    let largest = mu.iter().fold(0f64, |a, b| a.max(*b));
363    let mut out: Vec<(f64, Vec<f64>)> = (0..n)
364        .filter(|&k| mu[k] > 1e-9 * largest)
365        .map(|k| (1.0 / mu[k], (0..n).map(|r| (0..n).map(|c| fl_[r][c] * z[c][k]).sum::<f64>() / mu[k]).collect()))
366        .collect();
367    out.sort_by(|a, b| a.0.total_cmp(&b.0));
368    out
369}
370
371/// The eigenvalues and eigenvectors (columns) of a symmetric matrix, by cyclic Jacobi rotations.
372fn symmetric_eigen(mut a: Vec<Vec<f64>>) -> (Vec<f64>, Vec<Vec<f64>>) {
373    let n = a.len();
374    let mut v: Vec<Vec<f64>> = (0..n).map(|i| (0..n).map(|j| if i == j { 1.0 } else { 0.0 }).collect()).collect();
375    for _ in 0..50 {
376        let off: f64 = (0..n).flat_map(|p| (p + 1..n).map(move |q| (p, q))).map(|(p, q)| a[p][q] * a[p][q]).sum();
377        let diagonal: f64 = (0..n).map(|i| a[i][i] * a[i][i]).sum();
378        if !(off > 1e-30 * diagonal) {
379            break;
380        }
381        for p in 0..n {
382            for q in p + 1..n {
383                if a[p][q] == 0.0 {
384                    continue;
385                }
386                let theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q]);
387                let t = theta.signum() / (theta.abs() + (theta * theta + 1.0).sqrt());
388                let c = 1.0 / (t * t + 1.0).sqrt();
389                let s = t * c;
390                for k in 0..n {
391                    (a[k][p], a[k][q]) = (c * a[k][p] - s * a[k][q], s * a[k][p] + c * a[k][q]);
392                }
393                for k in 0..n {
394                    (a[p][k], a[q][k]) = (c * a[p][k] - s * a[q][k], s * a[p][k] + c * a[q][k]);
395                    (v[k][p], v[k][q]) = (c * v[k][p] - s * v[k][q], s * v[k][p] + c * v[k][q]);
396                }
397            }
398        }
399    }
400    ((0..n).map(|i| a[i][i]).collect(), v)
401}
402
403/// A force on the platform against its motion along the line from a fixed point to a point on the platform: the
404/// sliding friction of a telescopic shaft hung from `pivot` and joined to the platform at `offset` from its centre (the
405/// fourth axis of a four-axis delta built on this crate). The D3 itself has none.
406#[derive(Debug, Clone)]
407pub struct PlatformDrag {
408    pub pivot: [f64; 3],
409    pub offset: [f64; 3],
410    /// Along the line, N, against the rate at which the line lengthens.
411    pub friction: ShaftFriction,
412}
413
414impl PlatformDrag {
415    /// The unit vector from the pivot to the platform's joint, with the platform's centre at p.
416    pub fn direction(&self, p: [f64; 3]) -> [f64; 3] {
417        let d: V3 = std::array::from_fn(|k| p[k] + self.offset[k] - self.pivot[k]);
418        let l = norm(d);
419        d.map(|v| v / l)
420    }
421
422    /// The force on the platform at p moving at v: -f(L') u, with u the line's direction and L' = u . v its rate.
423    pub fn force(&self, p: [f64; 3], v: [f64; 3]) -> [f64; 3] {
424        let u = self.direction(p);
425        let f = self.friction.torque(dot(u, v));
426        u.map(|c| -f * c)
427    }
428}
429
430/// The upper arms' bending (effects.link_elasticity): in the plane an arm turns in, a turn of the elbow against the
431/// root, N m/rad and N m s/rad; out of it, a move of the elbow along its axis, N/m and N s/m.
432#[derive(Debug, Clone, Copy)]
433struct Bending {
434    k: f64,
435    c: f64,
436    k_lateral: f64,
437    c_lateral: f64,
438}
439
440pub struct Delta {
441    legs: Legs,
442    /// `PlatformDrag`, set by a machine built on this one; `None` on the D3.
443    drag: Option<PlatformDrag>,
444    /// The geometry as configured, for the scene: base and platform radius, the rods' spacing.
445    base_radius: f64,
446    platform_radius: f64,
447    rod_spacing: f64,
448    elastic: bool,
449    g: f64,
450    /// I_b without the rotor and m_LG, each split into the arm's tube (root, about the joint) and what sits at the
451    /// elbow (tip); the mass at each forearm's middle (effects.forearm_inertia, else 0); platform mass without and with
452    /// payload (forearm share included).
453    root_inertia: f64,
454    root_moment: f64,
455    tip_inertia: f64,
456    tip_moment: f64,
457    m_rod_middle: f64,
458    /// Per leg, the forearm weight that the lumped inertia split puts at the elbow beyond the half a rod's weight has
459    /// there ((share - 1/2) m_fb; 0 with the rods): the weight takes it from the elbow to the platform (`load_n`).
460    weight_shift: f64,
461    /// Each forearm pair's mass and the share of it the inertia puts at the elbow (a sixth with the rods), for the
462    /// frame momentum (the rods' own, `frame_momentum`).
463    m_forearms: f64,
464    forearm_share: f64,
465    /// The mass at each elbow (elbow block and the forearms' share), which moves with an arm's bend out of its plane.
466    /// What moves with an arm's bend out of its plane, at the elbow: the elbow block and the forearms' share, with
467    /// effects.arm_tube_inertia the tube's own share and the elbow block's twist too.
468    m_lateral: f64,
469    /// What sits at the elbow as a point (the elbow block and the forearms' share), and with effects.arm_tube_inertia the
470    /// tube's mass and the elbow block's twist inertia (both 0 without it): the frame momentum takes them apart.
471    m_elbow: f64,
472    tube_mass: f64,
473    twist_inertia: f64,
474    /// B, the tube's inertia that joins each root to its elbow (effects.arm_tube_inertia, else 0), kg m^2.
475    tube_coupling: f64,
476    /// The spin inertia of a forearm pair, both rods about their own axes (effects.forearm_inertia, else 0), kg m^2.
477    rod_spin: f64,
478    /// effects.link_elasticity: the upper arms' bending.
479    bending: Option<Bending>,
480    m_platform: f64,
481    m_payload: f64,
482    payload_attached: bool,
483    brake_engaged: bool,
484    /// An obstacle's push on the platform (`Machine::set_tool_force`), along x, y and z, N; held until changed.
485    tool_push: V3,
486    joints: [RotaryJoint; 3],
487    thermal: Option<ThermalFeedback>,
488    /// The working range: radius, top, bottom sphere's centre height and radius; the condition number refused above.
489    radius: f64,
490    top: f64,
491    sphere: (f64, f64),
492    max_condition: f64,
493    axes: [AxisInfo; 3],
494    motors: [MotorInfo; 3],
495    /// The gearbox nodes' ids, for their warmth.
496    gearbox_ids: [&'static str; 3],
497    /// `Machine::setpoint_slack`, worked out once (`rest_sag`).
498    rest_slack: f64,
499}
500
501// Elastic state: [theta 1..3, omega 1..3, rotor angle 1..3, rotor speed 1..3, brake 1..3].
502const N_ELASTIC: usize = 15;
503// Rigid state: [theta 1..3, omega 1..3, brake 1..3].
504const N_RIGID: usize = 9;
505
506/// The losses of one moment: per joint its friction, its motor's friction with the brake, its gearbox; the stops and
507/// what the ripple gives off; the arms' bending damping (effects.link_elasticity); and per joint the gearbox loss as a
508/// torque at the rotor.
509struct Losses {
510    powers: [f64; 12],
511    gear_at_rotor: V3,
512}
513
514impl Delta {
515    /// The platform at `p` and the payload under it, as `scene` draws them.
516    fn on_platform(&self, p: [f64; 3]) -> Vec<Part> {
517        let size = 2.4 * self.platform_radius.max(0.03);
518        let mut parts = vec![Part::new("platform", Shape::Box { size: [size, size, 0.03] }, p, [0.55, 0.55, 0.6])];
519        if self.payload_attached && self.m_payload > 0.0 {
520            parts.push(Part::new(
521                "payload",
522                Shape::Box { size: [0.1, 0.1, 0.08] },
523                [p[0], p[1], p[2] - 0.06],
524                [0.2, 0.7, 0.3],
525            ));
526        }
527        parts
528    }
529
530    /// Upper arm k from its shoulder to its end, as `scene` draws it: the legs' elbow is at e, the arm's end at the base
531    /// radius (the platform's radius added back), moved by y out of the arm's plane.
532    pub fn arm(&self, k: usize, t: V3, y: V3) -> (V3, V3) {
533        let (c, sn) = self.legs.azimuth[k];
534        let elbow = self.legs.elbows_moved(t, y)[k];
535        (
536            [self.base_radius * c, self.base_radius * sn, 0.0],
537            [elbow[0] + self.platform_radius * c, elbow[1] + self.platform_radius * sn, elbow[2]],
538        )
539    }
540
541    /// The spatial delta of a crate's tables: `[geometry]`, `[mass]`, `[upper_arm]`, `[workspace]`, one `[joint]` for
542    /// all three arms, the axes `x`, `y` and `z`.
543    pub fn new(cfg: &Config) -> Result<Self, ConfigError> {
544        Self::build(cfg, cfg, Arms::shared(cfg, [("x", "axis-x"), ("y", "axis-y"), ("z", "axis-z")])?)
545    }
546
547    /// The spatial delta of a machine file's linkage node with three arms.
548    pub fn from_node(cfg: &Config, net: &Netlist, node: &LinkageNode) -> Result<Self, ConfigError> {
549        Self::build(cfg, node, Arms::of_file(cfg, net)?)
550    }
551
552    /// The machine from its numbers (`n`, by their paths in a crate's tables) and its drives; the effects from `cfg`.
553    pub fn build(cfg: &Config, n: &dyn Numbers, arms: Arms<3>) -> Result<Self, ConfigError> {
554        let base_radius = n.positive("geometry.base_radius_m")?;
555        let platform_radius = n.non_negative("geometry.platform_radius_m")?;
556        let (la, lb) = (n.positive("geometry.upper_arm_m")?, n.positive("geometry.forearm_m")?);
557        if lb <= la {
558            return Err(n.invalid("geometry.forearm_m"));
559        }
560        let share = n.non_negative("mass.forearm_elbow_share")?;
561        if share > 1.0 {
562            return Err(n.invalid("mass.forearm_elbow_share"));
563        }
564        let (m_arm, cg, i_arm) = (
565            n.positive("mass.upper_arm_kg")?,
566            n.non_negative("mass.upper_arm_cg_m")?,
567            n.positive("mass.upper_arm_inertia_kgm2")?,
568        );
569        let (m_elbow, m_fb) = (n.non_negative("mass.elbow_kg")?, n.non_negative("mass.forearm_pair_kg")?);
570        // A rigid rod: a sixth at each end, two thirds at its middle (see the crate's doc).
571        let rods = cfg.bool("effects.forearm_inertia")?;
572        let (share, middle) = if rods { (1.0 / 6.0, 2.0 / 3.0) } else { (share, 0.0) };
573        let elbow = m_elbow + share * m_fb;
574        let bending = Bending {
575            k: n.positive("upper_arm.bending_stiffness_nm_rad")?,
576            c: n.non_negative("upper_arm.bending_damping_nm_s_rad")?,
577            k_lateral: n.positive("upper_arm.lateral_stiffness_n_m")?,
578            c_lateral: n.non_negative("upper_arm.lateral_damping_n_s_m")?,
579        };
580        let spin = n.non_negative("mass.forearm_rod_spin_inertia_kgm2")?;
581        let (radius, top) = (n.positive("workspace.radius_m")?, n.number("workspace.top_z_m")?);
582        let (edge, centre) = (n.positive("workspace.height_edge_m")?, n.positive("workspace.height_centre_m")?);
583        if centre < edge {
584            return Err(n.invalid("workspace.height_centre_m"));
585        }
586        // The bottom: a sphere through the centre's depth and the edge's ring; flat where both heights are the same.
587        let sag = centre - edge;
588        let sphere = if sag > 0.0 {
589            let r = (radius * radius + sag * sag) / (2.0 * sag);
590            (top - centre + r, r)
591        } else {
592            (f64::INFINITY, f64::INFINITY)
593        };
594        // effects.arm_tube_inertia (with the bending arms, see the module comment): the tube is as much of the arm's mass
595        // as its inertia allows a uniform tube (m L^2 / 3), the rest a hub on the shoulder's axis; it bends in the
596        // cantilever's static shape (`beam::STATIC_SHAPE_MASS`). A config without the switch reads it as off.
597        let rod_spacing = n.non_negative("geometry.forearm_spacing_m")?;
598        let (mut root_inertia, mut root_moment, mut tip_inertia, mut tip_moment, mut m_lateral) =
599            (i_arm, m_arm * cg, la * la * elbow, la * elbow, elbow);
600        let (mut tube_mass, mut twist_inertia, mut tube_coupling) = (0.0, 0.0, 0.0);
601        let tube = cfg.get("effects.arm_tube_inertia").is_ok() && cfg.bool("effects.arm_tube_inertia")?;
602        if tube && cfg.bool("effects.link_elasticity")? {
603            use sim_components::beam::{STATIC_SHAPE_MASS, STATIC_SHAPE_PARTICIPATION, STATIC_SHAPE_TIP_SLOPE};
604            // The root keeps I_arm - 33/140 m_t L^2 - 2 B >= (1/3 + 33/140 - 2 * 11/40) m_t L^2 = 0.0190 m_t L^2.
605            let m_tube = m_arm.min(3.0 * i_arm / (la * la));
606            let (inertia, moment) = (STATIC_SHAPE_MASS * m_tube * la * la, STATIC_SHAPE_PARTICIPATION * m_tube * la);
607            tube_coupling = (TUBE_MOMENT - STATIC_SHAPE_MASS) * m_tube * la * la;
608            if moment > root_moment {
609                return Err(n.invalid("mass.upper_arm_inertia_kgm2"));
610            }
611            (root_inertia, root_moment, tip_inertia, tip_moment) = (
612                root_inertia - inertia - 2.0 * tube_coupling,
613                root_moment - moment,
614                tip_inertia + inertia,
615                tip_moment + moment,
616            );
617            twist_inertia =
618                n.non_negative("mass.elbow_twist_inertia_kgm2")? + share * m_fb * rod_spacing * rod_spacing / 4.0;
619            m_lateral += STATIC_SHAPE_MASS * m_tube + twist_inertia * (STATIC_SHAPE_TIP_SLOPE / la).powi(2);
620            tube_mass = m_tube;
621        }
622        let mut delta = Self {
623            legs: Legs::new(base_radius - platform_radius, la, lb),
624            drag: None,
625            base_radius,
626            platform_radius,
627            rod_spacing,
628            elastic: cfg.bool("effects.joint_elasticity")?,
629            g: if cfg.bool("effects.gravity")? { G } else { 0.0 },
630            root_inertia,
631            root_moment,
632            tip_inertia,
633            tip_moment,
634            m_rod_middle: middle * m_fb,
635            weight_shift: if rods { 0.0 } else { (share - 0.5) * m_fb },
636            m_forearms: m_fb,
637            forearm_share: share,
638            m_lateral,
639            m_elbow: elbow,
640            tube_mass,
641            twist_inertia,
642            tube_coupling,
643            rod_spin: if rods { 2.0 * spin } else { 0.0 },
644            bending: cfg.bool("effects.link_elasticity")?.then_some(bending),
645            m_platform: n.positive("mass.platform_kg")? + 3.0 * (1.0 - share - middle) * m_fb,
646            m_payload: if cfg.bool("effects.payload")? { n.non_negative("mass.payload_kg")? } else { 0.0 },
647            payload_attached: true,
648            brake_engaged: false,
649            tool_push: [0.0; 3],
650            joints: arms.joints.clone(),
651            thermal: ThermalFeedback::from_config(cfg)?,
652            radius,
653            top,
654            sphere,
655            max_condition: n.positive("workspace.max_condition_number")?,
656            axes: [
657                arms.axis(cfg, 0, -radius, radius)?,
658                arms.axis(cfg, 1, -radius, radius)?,
659                arms.axis(cfg, 2, top - centre, top)?,
660            ],
661            motors: arms.motors,
662            gearbox_ids: arms.gearboxes,
663            rest_slack: 0.0,
664        };
665        delta.rest_slack = delta.rest_sag();
666        Ok(delta)
667    }
668
669    /// How far the motors' pose can be from the tool's at rest anywhere in the working range, payload on or off: each
670    /// gearbox twisted by the torque it holds against gravity over its stiffness, plus half its backlash either way (an
671    /// arm that holds little can rest anywhere in it, so all eight combinations are tried), through the forward
672    /// kinematics. Over a grid of the range: 5 radii, 24 directions, 9 heights and the bottom; plus a tenth for what the
673    /// grid steps over and the joints' friction. At least the default 0.1 mm; that alone in the rigid model, whose
674    /// gearboxes do not twist.
675    fn rest_sag(&self) -> f64 {
676        let mut most = 0f64;
677        if !self.elastic && self.bending.is_none() {
678            return 1e-4;
679        }
680        let (bottom, top) = (self.axes[2].min, self.top);
681        for ring in 0..=4 {
682            let rho = self.radius * ring as f64 / 4.0;
683            for turn in 0..24 {
684                let (sin, cos) = (turn as f64 * std::f64::consts::TAU / 24.0).sin_cos();
685                let (x, y) = (rho * cos, rho * sin);
686                let (centre, r) = self.sphere;
687                let lowest = if centre.is_finite() { centre - (r * r - rho * rho).max(0.0).sqrt() } else { bottom };
688                let heights = (0..=8).map(|k| lowest + (top - lowest) * k as f64 / 8.0);
689                for p in heights.map(|z| [x, y, z]).filter(|p| self.in_envelope(p, 1e-9)) {
690                    if self.legs.inverse(p).is_none() {
691                        continue;
692                    }
693                    for m in [self.m_platform, self.m_platform + self.m_payload] {
694                        // The joints' angles at rest, the arms' bend taken off the elbows'.
695                        let (t, gravity, ..) = self.rest_at(p, m);
696                        let twist: V3 = std::array::from_fn(|k| {
697                            let held = -gravity[k] - self.joints[k].output_torque(t[k], 0.0);
698                            if self.elastic { self.joints[k].gearbox.spring_twist_signed(held) } else { 0.0 }
699                        });
700                        for signs in 0..8 {
701                            // No backlash in the rigid joint model.
702                            let backlash =
703                                |k: usize| if self.elastic { self.joints[k].gearbox.half_backlash } else { 0.0 };
704                            let half = |k: usize| if signs >> k & 1 == 1 { 1.0 } else { -1.0 } * backlash(k);
705                            if let Some(q) = self.legs.forward(std::array::from_fn(|k| t[k] + twist[k] + half(k))) {
706                                most = most.max(norm(sub(q, p)));
707                            }
708                        }
709                    }
710                }
711            }
712        }
713        (1.1 * most).max(1e-4)
714    }
715
716    pub fn legs(&self) -> &Legs {
717        &self.legs
718    }
719
720    /// Puts a force on the platform against its motion (`PlatformDrag`), or takes it off. It enters the dynamics as a
721    /// generalised force J^T F at the elbows (in `load_at`'s velocity term); the feedforward, the rigid loss-free model,
722    /// leaves it out as it leaves out the joints' friction.
723    pub fn set_platform_drag(&mut self, drag: Option<PlatformDrag>) {
724        self.drag = drag;
725    }
726
727    /// The drag's generalised force J^T F at elbow angles t and speeds w; zero without a drag.
728    fn drag_torque(&self, t: V3, w: V3) -> V3 {
729        let Some(drag) = &self.drag else { return [0.0; 3] };
730        let (p, j) = self.pose(t);
731        mul(&transpose(&j), drag.force(p, mul(&j, w)))
732    }
733
734    /// Each arm's gearbox ratio.
735    fn ratios(&self) -> V3 {
736        std::array::from_fn(|k| self.joints[k].ratio())
737    }
738
739    /// The arms whose gearbox is one (not a coupling), in the order of `thermal_parts`.
740    fn geared(&self) -> impl Iterator<Item = usize> + '_ {
741        (0..3).filter(|&k| !self.joints[k].gearbox.is_coupling())
742    }
743
744    /// The point mass at the platform.
745    pub fn m_nt(&self) -> f64 {
746        self.m_platform + if self.payload_attached { self.m_payload } else { 0.0 }
747    }
748
749    /// The arm's inertia about its joint, elbow share of the forearms included, rotor not (the arm turned whole: root,
750    /// tip and twice the tube's coupling).
751    pub fn arm_inertia(&self) -> f64 {
752        self.root_inertia + self.tip_inertia + 2.0 * self.tube_coupling
753    }
754
755    /// m_LG: the arm's gravity torque is g m_LG cos(theta).
756    pub fn arm_moment(&self) -> f64 {
757        self.root_moment + self.tip_moment
758    }
759
760    /// The arm split for its bend (effects.link_elasticity): inertia and first moment at the root and at the elbow,
761    /// and the mass that moves with the elbow out of the arm's plane, as [root_inertia, root_moment, tip_inertia,
762    /// tip_moment, m_lateral], and the tube's coupling B of root and elbow.
763    pub fn bend_split(&self) -> ([f64; 5], f64) {
764        ([self.root_inertia, self.root_moment, self.tip_inertia, self.tip_moment, self.m_lateral], self.tube_coupling)
765    }
766
767    /// Arm angles and speeds of a state: at the joints, the gearboxes' output side.
768    fn arms(&self, s: &[f64]) -> (V3, V3) {
769        ([s[0], s[1], s[2]], [s[3], s[4], s[5]])
770    }
771
772    /// Where the arms' bend sits in the state, after the brakes.
773    fn bend_at(&self) -> usize {
774        if self.elastic { N_ELASTIC } else { N_RIGID }
775    }
776
777    /// The arms' bend (the elbow's turn against the arm's root) and its rate; zero with rigid links.
778    fn bend(&self, s: &[f64]) -> (V3, V3) {
779        if self.bending.is_none() {
780            return ([0.0; 3], [0.0; 3]);
781        }
782        let at = self.bend_at();
783        ([s[at], s[at + 1], s[at + 2]], [s[at + 3], s[at + 4], s[at + 5]])
784    }
785
786    /// The elbows' moves out of the arms' planes, along their axes, and their rates; zero with rigid links.
787    fn lateral(&self, s: &[f64]) -> (V3, V3) {
788        if self.bending.is_none() {
789            return ([0.0; 3], [0.0; 3]);
790        }
791        let at = self.bend_at() + 6;
792        ([s[at], s[at + 1], s[at + 2]], [s[at + 3], s[at + 4], s[at + 5]])
793    }
794
795    /// The elbow angles and speeds, which the kinematics take: the arms' plus their bend.
796    fn elbows(&self, s: &[f64]) -> (V3, V3) {
797        let ((t, w), (b, r)) = (self.arms(s), self.bend(s));
798        (std::array::from_fn(|k| t[k] + b[k]), std::array::from_fn(|k| w[k] + r[k]))
799    }
800
801    /// Rotor angles and speeds of a state.
802    fn rotors(&self, s: &[f64]) -> (V3, V3) {
803        if self.elastic {
804            ([s[6], s[7], s[8]], [s[9], s[10], s[11]])
805        } else {
806            let i = self.ratios();
807            ([s[0] * i[0], s[1] * i[1], s[2] * i[2]], [s[3] * i[0], s[4] * i[1], s[5] * i[2]])
808        }
809    }
810
811    fn brakes(&self, s: &[f64]) -> V3 {
812        let at = if self.elastic { 12 } else { 6 };
813        [s[at], s[at + 1], s[at + 2]]
814    }
815
816    /// Where the platform is and the Jacobian there, for arm angles; NaN where the legs cannot be assembled.
817    pub fn pose(&self, t: V3) -> (V3, M3) {
818        let (p, j, _) = self.pose_moved(t, [0.0; 3]);
819        (p, j)
820    }
821
822    /// `pose` with the elbows moved by y out of the arms' planes, and the Jacobian by those moves.
823    fn pose_moved(&self, t: V3, y: V3) -> (V3, M3, M3) {
824        self.legs
825            .forward_moved(t, y)
826            .and_then(|p| {
827                let (j, jy) = self.legs.jacobians(t, y, p)?;
828                Some((p, j, jy))
829            })
830            .unwrap_or(([f64::NAN; 3], [[f64::NAN; 3]; 3], [[f64::NAN; 3]; 3]))
831    }
832
833    /// The platform's position and velocity at state s.
834    fn platform(&self, s: &[f64]) -> (V3, V3) {
835        let ((t, w), (y, yv)) = (self.elbows(s), self.lateral(s));
836        let (p, j, jy) = self.pose_moved(t, y);
837        let (a, b) = (mul(&j, w), mul(&jy, yv));
838        (p, std::array::from_fn(|k| a[k] + b[k]))
839    }
840
841    /// The load's mass matrix M, the velocity term m_nt J^T J' theta' (and the forearms' middles'), and the generalised
842    /// gravity Q_g at arm angles t and speeds w, the links rigid.
843    fn load(&self, t: V3, w: V3) -> (M3, V3, V3) {
844        self.load_at(t, w, self.m_nt(), true)
845    }
846
847    /// `load` at elbow angles t and speeds w with the platform's mass m: of everything beyond the gearboxes (`root`), or
848    /// only of what lies beyond the arms' tubes (what the bending springs carry).
849    pub fn load_at(&self, t: V3, w: V3, m: f64, root: bool) -> (M3, V3, V3) {
850        self.load_n::<3>(t, [0.0; 3], w, [0.0; 3], m, root)
851    }
852
853    /// `load_at` in N coordinates: the elbow angles t (speeds w) and, with N = 6, the elbows' moves y out of the arms'
854    /// planes along their axes (rates yv). Each point mass (platform, the rods' middles, on the moves the elbows) counts
855    /// with its Jacobian P (3 x N): m P^T P in the mass matrix, m P^T a0 in the velocity term (a0 its acceleration at
856    /// no acceleration of the coordinates), -m g P_z in the gravity; the elbows' on the angles are `tip_inertia` and
857    /// `tip_moment`. With the rods also their spin about their own axes (`add_spin`).
858    fn load_n<const N: usize>(&self, t: V3, y: V3, w: V3, yv: V3, m: f64, root: bool) -> Load<N> {
859        let (p, j, jy) = self.pose_moved(t, y);
860        let jp: [[f64; N]; 3] =
861            std::array::from_fn(|r| std::array::from_fn(|c| if c < 3 { j[r][c] } else { jy[r][c - 3] }));
862        let qv: [f64; N] = std::array::from_fn(|c| if c < 3 { w[c] } else { yv[c - 3] });
863        let pv: V3 = std::array::from_fn(|r| (0..N).map(|c| jp[r][c] * qv[c]).sum());
864        let a0 = self.legs.velocity_term_moved(t, y, p, w, yv, pv).unwrap_or([f64::NAN; 3]);
865        let mut load = ([[0.0; N]; N], [0.0; N], [0.0; N]);
866        add_point(&mut load, m, &jp, a0, self.g);
867        // The weight of the lumped forearms is half at the elbow, half at the platform whatever share the inertia has.
868        for r in 0..N {
869            load.2[r] -= 3.0 * self.weight_shift * self.g * jp[2][r];
870        }
871        let (inertia, moment) =
872            if root { (self.arm_inertia(), self.arm_moment()) } else { (self.tip_inertia, self.tip_moment) };
873        if let Some(drag) = &self.drag {
874            let f = drag.force(p, pv);
875            for r in 0..N {
876                load.1[r] -= (0..3).map(|k| jp[k][r] * f[k]).sum::<f64>();
877            }
878        }
879        let elbows = self.legs.elbows_moved(t, y);
880        for i in 0..3 {
881            load.0[i][i] += inertia;
882            load.2[i] += self.g * (moment - self.legs.la * self.weight_shift) * t[i].cos();
883            // The elbow's Jacobian: dc/dtheta on its angle, its axis on its move; c'' = d2 w^2 at no acceleration.
884            let ([_, d1, d2], axis) = (self.legs.elbow(i, t[i]), self.legs.tangent(i));
885            let je: [[f64; N]; 3] = std::array::from_fn(|r| {
886                std::array::from_fn(|c| {
887                    if c == i {
888                        d1[r]
889                    } else if c == 3 + i {
890                        axis[r]
891                    } else {
892                        0.0
893                    }
894                })
895            });
896            let ae = d2.map(|v| v * w[i] * w[i]);
897            if N == 6 {
898                // Along its axis the elbow mass has no acceleration at none of the coordinates', and no weight.
899                load.0[3 + i][3 + i] += self.m_lateral;
900            }
901            if self.m_rod_middle > 0.0 {
902                let jm = std::array::from_fn(|r| std::array::from_fn(|c| 0.5 * (jp[r][c] + je[r][c])));
903                add_point(&mut load, self.m_rod_middle, &jm, std::array::from_fn(|k| 0.5 * (a0[k] + ae[k])), self.g);
904            }
905            if self.rod_spin > 0.0 {
906                let ju = std::array::from_fn(|r| std::array::from_fn(|c| jp[r][c] - je[r][c]));
907                let accel = std::array::from_fn(|k| a0[k] - ae[k]);
908                self.add_spin(&mut load, axis, sub(p, elbows[i]), &ju, &qv, accel);
909            }
910        }
911        load
912    }
913
914    /// The spin of a forearm pair's rods about their own axis into `load`, both rods alike: the parallelogram keeps the
915    /// pair's plane through the elbow's axis a (fixed) and the forearm u = p - c, so a rod turns about u as that plane
916    /// does. With sigma = a . u, n = a . (u' x u) and L = |u|, the spin is s = -sigma n / (L (L^2 - sigma^2)), linear in
917    /// the speeds: s = g . q', g = -sigma / (L (L^2 - sigma^2)) J_u^T (u x a), J_u the forearm's Jacobian. The rod's
918    /// angular momentum about its axis I s e (e = u / L) gives, by Kane's equations with the rod's angular velocity
919    /// e x e' + s e, I g g^T in the mass matrix and I (s0' g + s J_u^T (u' x u) / L^3) in the velocity term, s0' the
920    /// spin's rate at no acceleration of the coordinates (u'' = `accel`); its kinetic energy is I s^2 / 2.
921    fn add_spin<const N: usize>(&self, load: &mut Load<N>, a: V3, u: V3, ju: &[[f64; N]; 3], qv: &[f64; N], accel: V3) {
922        let l = self.legs.lb;
923        let du: V3 = std::array::from_fn(|r| (0..N).map(|c| ju[r][c] * qv[c]).sum());
924        let (sigma, n) = (dot(a, u), dot(a, cross(du, u)));
925        let d = l * l - sigma * sigma;
926        let s = -sigma * n / (l * d);
927        let axis = cross(u, a);
928        let g: [f64; N] = std::array::from_fn(|c| -sigma / (l * d) * (0..3).map(|k| ju[k][c] * axis[k]).sum::<f64>());
929        let (dsigma, dn) = (dot(a, du), dot(a, cross(accel, u)));
930        let ds = -(dsigma * n + sigma * dn) / (l * d) - 2.0 * sigma * sigma * dsigma * n / (l * d * d);
931        let turn = cross(du, u).map(|v| v / l.powi(3));
932        for r in 0..N {
933            for c in 0..N {
934                load.0[r][c] += self.rod_spin * g[r] * g[c];
935            }
936            load.1[r] += self.rod_spin * (ds * g[r] + s * (0..3).map(|k| ju[k][r] * turn[k]).sum::<f64>());
937        }
938    }
939
940    /// The spin of leg i's rods about their own axis (see `add_spin`), rad/s, at elbow angles t and moves y, speeds w
941    /// and yv.
942    pub fn rod_spin(&self, i: usize, t: V3, y: V3, w: V3, yv: V3) -> f64 {
943        let (p, j, jy) = self.pose_moved(t, y);
944        let (a, b) = (mul(&j, w), mul(&jy, yv));
945        let ([_, d1, _], axis) = (self.legs.elbow(i, t[i]), self.legs.tangent(i));
946        let du: V3 = std::array::from_fn(|k| a[k] + b[k] - d1[k] * w[i] - axis[k] * yv[i]);
947        let u = sub(p, self.legs.elbows_moved(t, y)[i]);
948        let (l, sigma) = (self.legs.lb, dot(axis, u));
949        -sigma * dot(axis, cross(du, u)) / (l * (l * l - sigma * sigma))
950    }
951
952    /// At rest with the platform at p and its mass m: the joints' angles, the torque gravity puts on each joint (all of
953    /// it: with bending arms the tube's own and, through the spring, the rest), the arms' bend, Q_d / k_b, and the
954    /// elbows' moves out of the arms' planes, Q_y / k_l (from none, until they settle).
955    fn rest_at(&self, p: V3, m: f64) -> (V3, V3, V3, V3) {
956        let Some(b) = self.bending else {
957            let elbows = self.legs.inverse(p).unwrap_or([f64::NAN; 3]);
958            return (elbows, self.load_at(elbows, [0.0; 3], m, true).2, [0.0; 3], [0.0; 3]);
959        };
960        let tip_at = |y: V3| {
961            let elbows = self.legs.inverse_moved(p, y).unwrap_or([f64::NAN; 3]);
962            (elbows, self.load_n::<6>(elbows, y, [0.0; 3], [0.0; 3], m, false).2)
963        };
964        // Q_y hardly changes with y: each round takes some 1e-4 of what is left.
965        let mut y = [0.0; 3];
966        for _ in 0..20 {
967            let (_, tip) = tip_at(y);
968            let next: V3 = std::array::from_fn(|i| tip[3 + i] / b.k_lateral);
969            let settled = (0..3).all(|i| (next[i] - y[i]).abs() <= 1e-15);
970            y = next;
971            if settled {
972                break;
973            }
974        }
975        let (elbows, tip) = tip_at(y);
976        let bend: V3 = std::array::from_fn(|i| tip[i] / b.k);
977        let t: V3 = std::array::from_fn(|i| elbows[i] - bend[i]);
978        (t, std::array::from_fn(|i| self.g * self.root_moment * t[i].cos() + tip[i]), bend, y)
979    }
980
981    /// What the joints carry at state s, as `load` has it: mass matrix, velocity term, gravity. With bending arms only
982    /// the tubes are on the joints, and the springs' torque stands in for the rest: its weight Q_d in the gravity, the
983    /// remainder in the velocity term (so that the torque breakdown shows the weight as gravity).
984    /// An obstacle's push on the platform (`set_tool_force`) is in these equations of motion only, not in the
985    /// feedforward or the state at rest (`push`): with rigid arms in the gravity, with bending ones beyond the tubes.
986    fn joint_load(&self, s: &[f64]) -> (M3, V3, V3) {
987        let (t, w) = self.arms(s);
988        let Some(b) = self.bending else {
989            let (mass, velocity, gravity) = self.load(t, w);
990            let push = self.push::<3>(t, [0.0; 3]);
991            return (mass, velocity, std::array::from_fn(|i| gravity[i] + push[i]));
992        };
993        let ((elbows, _), (bend, rate), (y, _)) = (self.elbows(s), self.bend(s), self.lateral(s));
994        let (_, _, tip) = self.load_n::<6>(elbows, y, [0.0; 3], [0.0; 3], self.m_nt(), false);
995        let mut mass: M3 =
996            std::array::from_fn(|r| std::array::from_fn(|col| if r == col { self.root_inertia } else { 0.0 }));
997        let gravity = std::array::from_fn(|i| self.g * self.root_moment * t[i].cos() + tip[i]);
998        let mut velocity: V3 = std::array::from_fn(|i| tip[i] - b.k * bend[i] - b.c * rate[i]);
999        if self.tube_coupling > 0.0 {
1000            // The elbows' equation solved for them: (I_r - B^2 (M_d^-1)_ee) theta'' = f_r - B (M_d^-1 f_d)_e.
1001            let (m, f) = self.distal(s, b);
1002            let inv = sim_components::chain::Lu::new(&m).and_then(|lu| lu.inverse()).unwrap_or([[f64::NAN; 6]; 6]);
1003            let bb = self.tube_coupling;
1004            for r in 0..3 {
1005                for c in 0..3 {
1006                    mass[r][c] -= bb * bb * inv[r][c];
1007                }
1008                velocity[r] += bb * (0..6).map(|c| inv[r][c] * f[c]).sum::<f64>();
1009            }
1010        }
1011        (mass, velocity, gravity)
1012    }
1013
1014    /// Beyond the tubes (bending arms): the mass matrix M_d in the elbows' angles and moves, and what drives them,
1015    /// f_d = Q_d - v_d - (k_b delta + c_b delta', k_l y + c_l y').
1016    fn distal(&self, s: &[f64], b: Bending) -> ([[f64; 6]; 6], [f64; 6]) {
1017        let ((elbows, speeds), (bend, rate), (y, yv)) = (self.elbows(s), self.bend(s), self.lateral(s));
1018        let (mass, velocity, gravity) = self.load_n::<6>(elbows, y, speeds, yv, self.m_nt(), false);
1019        let push = self.push::<6>(elbows, y);
1020        let rhs = std::array::from_fn(|i| {
1021            let spring =
1022                if i < 3 { b.k * bend[i] + b.c * rate[i] } else { b.k_lateral * y[i - 3] + b.c_lateral * yv[i - 3] };
1023            gravity[i] + push[i] - velocity[i] - spring
1024        });
1025        (mass, rhs)
1026    }
1027
1028    /// An obstacle's push F on the platform (`set_tool_force`) at elbow angles t and moves y: P^T F on the angles and,
1029    /// after them, on the moves (P = [J, J_y], the platform's Jacobian).
1030    fn push<const N: usize>(&self, t: V3, y: V3) -> [f64; N] {
1031        let (_, j, jy) = self.pose_moved(t, y);
1032        std::array::from_fn(|c| {
1033            (0..3).map(|k| if c < 3 { j[k][c] } else { jy[k][c - 3] } * self.tool_push[k]).sum::<f64>()
1034        })
1035    }
1036
1037    /// With bending arms, the rates of the bend states into `out`, from the joints' acceleration `acc`: the elbows'
1038    /// accelerations, of their angles and their moves, from M_d q'' = Q_d - v_d - (k_b delta + c_b delta', k_l y + c_l y')
1039    /// (`load_n` beyond the tubes), less the tube's coupling B theta'' on the elbows' rows.
1040    fn bend_rates(&self, s: &[f64], acc: V3, out: &mut [f64]) {
1041        let Some(b) = self.bending else { return };
1042        let ((_, rate), (_, yv)) = (self.bend(s), self.lateral(s));
1043        let (mass, mut rhs) = self.distal(s, b);
1044        for i in 0..3 {
1045            rhs[i] -= self.tube_coupling * acc[i];
1046        }
1047        let q = sim_components::chain::solve(mass.as_flattened(), &rhs).unwrap_or_else(|| vec![f64::NAN; 6]);
1048        let at = self.bend_at();
1049        out[at..at + 3].copy_from_slice(&rate);
1050        for i in 0..3 {
1051            out[at + 3 + i] = q[i] - acc[i];
1052        }
1053        out[at + 6..at + 9].copy_from_slice(&yv);
1054        out[at + 9..at + 12].copy_from_slice(&q[3..]);
1055    }
1056
1057    /// The modes at a tool pose with the motors held (`arm_modes`), lowest first: frequency in Hz, damping ratio and
1058    /// shape (the joints' turns, the elbows' turns, with bending arms the elbows' moves). The damping of a shape v is
1059    /// v'Cv / (2 w v'Mv) with C the gearboxes', the bending's and the lateral dampers (the cross terms of a damping that
1060    /// is not proportional left out). None with rigid gearboxes and rigid arms, or out of reach.
1061    fn modes_at(&self, tool: &[f64], small: bool) -> Vec<(f64, f64, Vec<f64>)> {
1062        // Each arm's own gearbox (`arm_modes` takes one spring per arm).
1063        // K1, the stiffness of the moves that excite the mode; with hysteresis a small vibration (`small`) sees K1 + sigma
1064        // (2 K1 as shipped, about 41 % higher, docs/model-reference.md, Resonance).
1065        let k_gear = self.elastic.then(|| {
1066            std::array::from_fn(|i| {
1067                let g = &self.joints[i].gearbox;
1068                g.stiffness + if small && g.hysteresis > 0.0 { g.dahl_stiffness } else { 0.0 }
1069            })
1070        });
1071        let elbows = if tool.len() == 3 { self.legs.inverse([tool[0], tool[1], tool[2]]) } else { None };
1072        let (Some(elbows), true) = (elbows, k_gear.is_some() || self.bending.is_some()) else { return Vec::new() };
1073        let distal: Vec<Vec<f64>> = match self.bending {
1074            Some(_) => {
1075                self.load_n::<6>(elbows, [0.0; 3], [0.0; 3], [0.0; 3], self.m_nt(), false).0.map(Vec::from).into()
1076            }
1077            None => self.load_at(elbows, [0.0; 3], self.m_nt(), false).0.map(Vec::from).into(),
1078        };
1079        let c_gear: V3 = std::array::from_fn(|i| if self.elastic { self.joints[i].gearbox.damping } else { 0.0 });
1080        let b = self.bending;
1081        let modes =
1082            arm_modes((self.root_inertia, self.tube_coupling), &distal, k_gear, b.map(|b| b.k), b.map(|b| b.k_lateral));
1083        modes
1084            .into_iter()
1085            .map(|(w2, v)| {
1086                let n = v.len() - 3;
1087                let distal_kinetic: f64 =
1088                    (0..n).map(|r| v[3 + r] * (0..n).map(|c| distal[r][c] * v[3 + c]).sum::<f64>()).sum();
1089                let kinetic = (0..3)
1090                    .map(|i| self.root_inertia * v[i] * v[i] + 2.0 * self.tube_coupling * v[i] * v[3 + i])
1091                    .sum::<f64>()
1092                    + distal_kinetic;
1093                let damped: f64 = (0..3)
1094                    .map(|i| {
1095                        c_gear[i] * v[i] * v[i]
1096                            + b.map_or(0.0, |b| b.c * (v[3 + i] - v[i]).powi(2) + b.c_lateral * v[6 + i] * v[6 + i])
1097                    })
1098                    .sum();
1099                let w = w2.sqrt();
1100                (w / std::f64::consts::TAU, damped / (2.0 * w * kinetic), v)
1101            })
1102            .collect()
1103    }
1104
1105    /// Rigid model: the arms' acceleration, and per joint the torque into its gearbox (after the rotor's own
1106    /// acceleration) and out of it, at the arm.
1107    fn rigid_solve(&self, s: &[f64], torque: &[f64]) -> (V3, V3, V3) {
1108        let (t, w) = self.arms(s);
1109        let (rotor, rotor_speed) = self.rotors(s);
1110        let brakes = self.brakes(s);
1111        let (mass, velocity, gravity) = self.joint_load(s);
1112        let drive: V3 = std::array::from_fn(|k| {
1113            self.joints[k].rigid_drive(torque[k], rotor[k], rotor_speed[k], brakes[k], self.brake_engaged).0
1114        });
1115        let rest: V3 = std::array::from_fn(|k| gravity[k] - velocity[k] + self.joints[k].output_torque(t[k], w[k]));
1116        let solve = |loss: V3| -> V3 {
1117            let m: M3 = std::array::from_fn(|r| {
1118                std::array::from_fn(|c| {
1119                    mass[r][c] + if r == c { loss[r] * self.joints[r].reflected_inertia() } else { 0.0 }
1120                })
1121            });
1122            let rhs: V3 = std::array::from_fn(|k| loss[k] * drive[k] + rest[k]);
1123            inverse(&m).map_or([f64::NAN; 3], |inv| mul(&inv, rhs))
1124        };
1125        // The loss factors of the torques going in, at their fixed point (`mech::settled_loss`).
1126        let loss = sim_components::mech::settled_loss([1.0; 3], |loss| {
1127            let acc = solve(*loss);
1128            std::array::from_fn(|k| {
1129                self.joints[k].gearbox.loss_factor(drive[k] - self.joints[k].reflected_inertia() * acc[k], w[k])
1130            })
1131        });
1132        let acc = solve(loss);
1133        let into: V3 = std::array::from_fn(|k| drive[k] - self.joints[k].reflected_inertia() * acc[k]);
1134        (acc, into, std::array::from_fn(|k| loss[k] * into[k]))
1135    }
1136
1137    /// The arms' acceleration in either model.
1138    fn arm_acceleration(&self, s: &[f64], torque: &[f64]) -> V3 {
1139        if self.elastic {
1140            let mut d = vec![0.0; self.state_len()];
1141            self.derivatives(s, torque, &mut d);
1142            [d[3], d[4], d[5]]
1143        } else {
1144            self.rigid_solve(s, torque).0
1145        }
1146    }
1147
1148    /// The torque each gearbox passes to its arm.
1149    fn gear_output(&self, s: &[f64], torque: &[f64]) -> V3 {
1150        if self.elastic {
1151            std::array::from_fn(|k| self.joints[k].gearbox.torque(s[6 + k], s[9 + k], s[k], s[3 + k]).output)
1152        } else {
1153            self.rigid_solve(s, torque).2
1154        }
1155    }
1156
1157    pub fn energy_parts(&self, s: &[f64]) -> [f64; 3] {
1158        let (t, w) = self.arms(s);
1159        let ((elbows, speeds), (y, yv)) = (self.elbows(s), self.lateral(s));
1160        // Beyond the tubes at the elbows' speeds and moves, the tubes at the joints' (all of it at once with rigid
1161        // links).
1162        let mut kinetic = if self.bending.is_some() {
1163            let (mass, ..) = self.load_n::<6>(elbows, y, speeds, yv, self.m_nt(), false);
1164            let q: [f64; 6] = std::array::from_fn(|i| if i < 3 { speeds[i] } else { yv[i - 3] });
1165            let moving: f64 = (0..6).map(|r| q[r] * (0..6).map(|c| mass[r][c] * q[c]).sum::<f64>()).sum();
1166            0.5 * moving + 0.5 * self.root_inertia * dot(w, w) + self.tube_coupling * dot(w, speeds)
1167        } else {
1168            0.5 * dot(speeds, mul(&self.load_at(elbows, speeds, self.m_nt(), true).0, speeds))
1169        };
1170        let (p, ..) = self.pose_moved(elbows, y);
1171        let middles: f64 = (0..3).map(|i| 0.5 * (self.legs.elbow(i, elbows[i])[0][2] + p[2])).sum();
1172        let sines = |a: V3| a[0].sin() + a[1].sin() + a[2].sin();
1173        let potential = self.g
1174            * ((self.m_nt() + 3.0 * self.weight_shift) * p[2] + self.m_rod_middle * middles
1175                - self.root_moment * sines(t)
1176                - (self.tip_moment - self.legs.la * self.weight_shift) * sines(elbows));
1177        let mut elastic: f64 = (0..3).map(|k| self.joints[k].stop_energy(t[k])).sum();
1178        if let Some(b) = self.bending {
1179            let (bend, _) = self.bend(s);
1180            elastic += 0.5 * b.k * dot(bend, bend) + 0.5 * b.k_lateral * dot(y, y);
1181        }
1182        if self.elastic {
1183            for k in 0..3 {
1184                kinetic += 0.5 * self.joints[k].rotor_inertia * s[9 + k] * s[9 + k];
1185                elastic += self.joints[k].gearbox.energy(s[6 + k], s[k]);
1186            }
1187        } else {
1188            kinetic += 0.5 * (0..3).map(|k| self.joints[k].reflected_inertia() * w[k] * w[k]).sum::<f64>();
1189        }
1190        [kinetic, potential, elastic]
1191    }
1192
1193    fn losses(&self, s: &[f64], torque: &[f64]) -> Losses {
1194        let (t, w) = self.arms(s);
1195        let (rotor, rotor_speed) = self.rotors(s);
1196        let brakes = self.brakes(s);
1197        let mut powers = [0.0; 12];
1198        let mut gear_at_rotor = [0.0; 3];
1199        let rigid = (!self.elastic).then(|| self.rigid_solve(s, torque));
1200        let mut stops = 0.0;
1201        let mut other = 0.0;
1202        for k in 0..3 {
1203            let joint = &self.joints[k];
1204            let [friction, stop, shaft, drag] = joint.losses(t[k], w[k], rotor_speed[k], brakes[k], self.brake_engaged);
1205            let gear = match &rigid {
1206                Some((_, into, out)) => {
1207                    gear_at_rotor[k] = (into[k] - out[k]) / joint.ratio();
1208                    (into[k] - out[k]) * w[k]
1209                }
1210                None => {
1211                    let g = joint.gearbox.torque(s[6 + k], s[9 + k], s[k], s[3 + k]);
1212                    gear_at_rotor[k] = g.rotor - g.output / joint.ratio();
1213                    joint.gearbox.loss_power(s[6 + k], s[9 + k], s[k], s[3 + k])
1214                }
1215            };
1216            powers[3 * k..3 * k + 3].copy_from_slice(&[friction, shaft, gear + drag]);
1217            stops += stop;
1218            other += (torque[k] - joint.ripple.apply(torque[k], rotor[k])) * rotor_speed[k];
1219        }
1220        powers[9] = stops;
1221        powers[10] = other;
1222        if let Some(b) = self.bending {
1223            let ((_, rate), (_, moving)) = (self.bend(s), self.lateral(s));
1224            powers[11] = b.c * dot(rate, rate) + b.c_lateral * dot(moving, moving);
1225        }
1226        Losses { powers, gear_at_rotor }
1227    }
1228
1229    /// How many of `Losses::powers` are signals: the arms' bending damping only with effects.link_elasticity.
1230    fn loss_count(&self) -> usize {
1231        if self.bending.is_some() { 12 } else { 11 }
1232    }
1233
1234    /// Whether a pose is within the working range (cylinder, top, spherical bottom), widened by `slack`.
1235    fn in_envelope(&self, p: &[f64], slack: f64) -> bool {
1236        let (centre, r) = self.sphere;
1237        let below = if centre.is_finite() {
1238            (p[0] * p[0] + p[1] * p[1] + (p[2] - centre).powi(2)).sqrt() <= r + slack
1239        } else {
1240            p[2] >= self.axes[2].min - slack
1241        };
1242        p[0].hypot(p[1]) <= self.radius + slack && p[2] <= self.top + slack && below
1243    }
1244
1245    /// The torque breakdown, loss powers, energies, friction signals of the effect views.
1246    fn view_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1247        let (_, w) = self.arms(s);
1248        let (_, rotor_speed) = self.rotors(s);
1249        let brakes = self.brakes(s);
1250        let (mass, velocity, gravity) = self.joint_load(s);
1251        let acc = self.arm_acceleration(s, torque);
1252        let moving = mul(&mass, acc);
1253        let losses = self.losses(s, torque);
1254        // A drag on the platform is friction: with rigid links it is in the joints' velocity term (`load_at`), and is
1255        // moved over to the friction here. With bending arms it reaches the joints through the springs.
1256        let drag = if self.bending.is_none() { self.drag_torque(self.arms(s).0, w) } else { [0.0; 3] };
1257        for k in 0..3 {
1258            let joint = &self.joints[k];
1259            let i = joint.ratio();
1260            let held = joint.brake.torque(self.brake_engaged, rotor_speed[k], brakes[k]).0;
1261            let parts = [
1262                (moving[k] + velocity[k] + drag[k] + joint.reflected_inertia() * acc[k]) / i,
1263                -gravity[k] / i,
1264                joint.shaft.torque(rotor_speed[k])
1265                    + held
1266                    + losses.gear_at_rotor[k]
1267                    + (joint.friction.torque(w[k]) - drag[k]) / i,
1268            ];
1269            out.extend(parts);
1270            out.push(torque[k] - parts.iter().sum::<f64>());
1271        }
1272        out.extend(&losses.powers[..self.loss_count()]);
1273        out.extend(self.energy_parts(s));
1274        for k in 0..3 {
1275            out.extend(self.joints[k].friction_signals(w[k]));
1276        }
1277    }
1278
1279    fn effect_infos(&self, out: &mut Vec<SignalInfo>) {
1280        for motor in &self.motors {
1281            out.extend(TORQUE_PARTS.map(|part| {
1282                SignalInfo::new(
1283                    format!("motor.{}.torque_{part}", motor.id),
1284                    motor.key,
1285                    &format!("quantity-torque-{part}"),
1286                    "N m",
1287                )
1288            }));
1289        }
1290        for (k, motor) in self.motors.iter().enumerate() {
1291            let arm = ["arm-1", "arm-2", "arm-3"][k];
1292            let gear = if self.joints[k].gearbox.is_coupling() {
1293                "quantity-coupling-loss-power"
1294            } else {
1295                "quantity-gearbox-loss-power"
1296            };
1297            out.push(SignalInfo::new(format!("{LOSS_PREFIX}joint_{}", motor.id), arm, "quantity-friction-power", "W"));
1298            out.push(SignalInfo::new(
1299                format!("{LOSS_PREFIX}shaft_{}", motor.id),
1300                motor.key,
1301                "quantity-shaft-friction-power",
1302                "W",
1303            ));
1304            out.push(SignalInfo::new(format!("{LOSS_PREFIX}gearbox_{}", motor.id), motor.key, gear, "W"));
1305        }
1306        out.push(SignalInfo::new(format!("{LOSS_PREFIX}hard_stops"), "group-joint", "quantity-damping-power", "W"));
1307        out.push(SignalInfo::new(format!("{LOSS_PREFIX}other"), "loss-other", "quantity-power-given-off", "W"));
1308        if self.bending.is_some() {
1309            out.push(SignalInfo::new(
1310                format!("{LOSS_PREFIX}arm_bending"),
1311                "group-upper-arms",
1312                "quantity-damping-power",
1313                "W",
1314            ));
1315        }
1316        out.extend(ENERGY_PARTS.map(|part| {
1317            SignalInfo::new(format!("energy.{part}"), "group-energy", &format!("quantity-energy-{part}"), "J")
1318        }));
1319        for k in 0..3 {
1320            out.extend(RotaryJoint::friction_infos(JOINT_CONTACTS[k], ["arm-1", "arm-2", "arm-3"][k]));
1321        }
1322    }
1323}
1324
1325/// The ids of the arms' friction contacts (`<id>.friction_<part>`), in the motors' order.
1326const JOINT_CONTACTS: [&str; 3] = ["joint.1", "joint.2", "joint.3"];
1327
1328impl Machine for Delta {
1329    /// The platform (with the payload and the forearms' share), each arm's tube turning with its joint and what sits at
1330    /// its elbow turning with the elbow (the bend added), the elbow's move out of the arm's plane, the forearms' middles,
1331    /// and the rotors spinning about the joints' axes. The joints are where they are, at the base radius; the platform's
1332    /// centre is the tool. With effects.forearm_inertia each forearm pair's spin about its own axis e = u / L (u the
1333    /// forearm, from the elbow to the platform joint): the angular momentum I s e of `add_spin` (`rod_spin` is s). What
1334    /// does not move is left out (see `FrameMomentum`).
1335    fn frame_momentum(&self, s: &[f64]) -> Option<sim_core::FrameMomentum> {
1336        use sim_components::base::{add_point, add_spin, add_turning};
1337        let mut f = sim_core::FrameMomentum { gravity: [0.0, 0.0, -self.g], ..Default::default() };
1338        let ((t, w), (e, ew), (y, yv)) = (self.arms(s), self.elbows(s), self.lateral(s));
1339        let (p, pv) = self.platform(s);
1340        // The forearms as the rods they are, whatever share of their inertia the lumped dynamics put at the elbow: a
1341        // sixth at each end, two thirds at the middle (as with effects.forearm_inertia), so that their weight sits
1342        // where the potential has it. What the split puts at the elbow and at the platform beyond those sixths:
1343        let m_fb = self.m_forearms;
1344        let at_elbow = (self.forearm_share - 1.0 / 6.0) * m_fb;
1345        let at_platform = (5.0 / 6.0 - self.forearm_share) * m_fb - self.m_rod_middle;
1346        add_point(&mut f, self.m_nt() - 3.0 * at_platform, p, pv);
1347        let rotor_speed = self.rotors(s).1;
1348        for i in 0..3 {
1349            let joint = self.legs.to_base(i, [self.base_radius, 0.0, 0.0]);
1350            let turn = |angle: f64| {
1351                let (sin, cos) = angle.sin_cos();
1352                (self.legs.to_base(i, [cos, 0.0, -sin]), self.legs.to_base(i, [-sin, 0.0, -cos]))
1353            };
1354            let (dir, ddir) = turn(t[i]);
1355            add_turning(&mut f, joint, dir, ddir, w[i], self.root_inertia, self.root_moment);
1356            let (tip, dtip) = turn(e[i]);
1357            let (tangent, la) = (self.legs.tangent(i), self.legs.la);
1358            // What turns with the elbow beyond the point at it (the tube's bent share), and the point itself at its
1359            // moved place with its whole speed. The coupling B theta' e' adds B (theta' + e') about the arm's axis.
1360            let point = la * la * self.m_elbow;
1361            add_turning(&mut f, joint, tip, dtip, ew[i], self.tip_inertia - point, self.tip_moment - la * self.m_elbow);
1362            add_spin(&mut f, cross(dir, ddir), self.tube_coupling, w[i] + ew[i]);
1363            let elbow: [f64; 3] = std::array::from_fn(|k| joint[k] + la * tip[k] + y[i] * tangent[k]);
1364            let elbow_speed: [f64; 3] = std::array::from_fn(|k| la * ew[i] * dtip[k] + yv[i] * tangent[k]);
1365            add_point(&mut f, self.m_elbow - at_elbow, elbow, elbow_speed);
1366            if self.tube_mass > 0.0 {
1367                // Out of the plane the tube's sections move by psi(s) y: momentum int(psi) m y' = 3/8 m y' at
1368                // 11/15 L_a along the arm (int(xi psi) / int(psi)); the moved sections carry the in-plane momentum
1369                // m L_a (11/40 theta' + 33/140 delta') along the turn, y off the plane. The elbow block twists about the
1370                // arm's normal with the tube's tip slope.
1371                use sim_components::beam::{STATIC_SHAPE_MASS, STATIC_SHAPE_PARTICIPATION, STATIC_SHAPE_TIP_SLOPE};
1372                let m = STATIC_SHAPE_PARTICIPATION * self.tube_mass;
1373                let at: V3 = std::array::from_fn(|k| joint[k] + TUBE_CENTROID * la * tip[k]);
1374                add_point(&mut f, m, std::array::from_fn(|k| at[k] + y[i] * tangent[k]), tangent.map(|v| v * yv[i]));
1375                add_point(&mut f, -m, at, [0.0; 3]);
1376                let along = self.tube_mass * la * (TUBE_MOMENT * w[i] + STATIC_SHAPE_MASS * (ew[i] - w[i]));
1377                let off = cross(tangent.map(|v| v * y[i]), dtip.map(|v| v * along));
1378                (0..3).for_each(|k| f.angular[k] += off[k]);
1379                add_spin(&mut f, cross(tip, tangent), self.twist_inertia, STATIC_SHAPE_TIP_SLOPE * yv[i] / la);
1380            }
1381            let at_platform = self.legs.to_base(i, [self.platform_radius, 0.0, 0.0]);
1382            let middle: [f64; 3] = std::array::from_fn(|k| 0.5 * (elbow[k] + p[k] + at_platform[k]));
1383            add_point(&mut f, 2.0 / 3.0 * m_fb, middle, std::array::from_fn(|k| 0.5 * (elbow_speed[k] + pv[k])));
1384            add_spin(&mut f, tangent, self.joints[i].rotor_inertia, rotor_speed[i]);
1385            if self.rod_spin > 0.0 {
1386                let u = sub(p, self.legs.elbows_moved(e, y)[i]);
1387                let rod = u.map(|v| v / self.legs.lb);
1388                add_spin(&mut f, rod, self.rod_spin, self.rod_spin(i, e, y, ew, yv));
1389            }
1390        }
1391        // An obstacle's push on the platform is not in the outside force: a compliant base takes it through the tool's
1392        // shift (`base::Based`), and here it pushed the base a second time.
1393        f.external_at = p;
1394        Some(f)
1395    }
1396    fn axes(&self) -> &[AxisInfo] {
1397        &self.axes
1398    }
1399    fn motors(&self) -> &[MotorInfo] {
1400        &self.motors
1401    }
1402
1403    /// NaN where the pose is out of reach: the controller never asks for one (see `unreachable`).
1404    fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
1405        let t = self.legs.inverse([tool[0], tool[1], tool[2]]).unwrap_or([f64::NAN; 3]);
1406        for k in 0..3 {
1407            motors[k] = self.joints[k].ratio() * t[k];
1408        }
1409    }
1410    fn forward(&self, motors: &[f64], tool: &mut [f64]) {
1411        let i = self.ratios();
1412        let p = self.legs.forward([motors[0] / i[0], motors[1] / i[1], motors[2] / i[2]]).unwrap_or([f64::NAN; 3]);
1413        tool[..3].copy_from_slice(&p);
1414    }
1415
1416    fn state_len(&self) -> usize {
1417        self.bend_at() + if self.bending.is_some() { 12 } else { 0 }
1418    }
1419
1420    fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
1421        // The elbows at the pose; the joints short of them by the arms' bend under the weight.
1422        let (t, gravity, bend, lateral) = self.rest_at([tool[0], tool[1], tool[2]], self.m_nt());
1423        state.clear();
1424        state.extend(t);
1425        state.extend([0.0; 3]);
1426        for k in 0..3 {
1427            let joint = &self.joints[k];
1428            // At rest the gearbox holds the arm against gravity and the stops.
1429            let out = -gravity[k] - joint.output_torque(t[k], 0.0);
1430            let rotor = joint.ratio() * (t[k] + if self.elastic { joint.gearbox.static_twist(out) } else { 0.0 });
1431            if self.elastic {
1432                state.push(rotor);
1433            }
1434            torque[k] = joint.ripple.invert(out / joint.ratio(), rotor);
1435        }
1436        // Rotor speeds and brakes at rest; the bend still.
1437        state.resize(self.bend_at(), 0.0);
1438        if self.bending.is_some() {
1439            state.extend(bend);
1440            state.extend([0.0; 3]);
1441            state.extend(lateral);
1442        }
1443        state.resize(self.state_len(), 0.0);
1444    }
1445
1446    fn derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
1447        if !self.elastic {
1448            let (acc, ..) = self.rigid_solve(s, torque);
1449            let (_, rotor_speed) = self.rotors(s);
1450            let brakes = self.brakes(s);
1451            out[..3].copy_from_slice(&s[3..6]);
1452            out[3..6].copy_from_slice(&acc);
1453            for k in 0..3 {
1454                out[6 + k] = self.joints[k].brake.torque(self.brake_engaged, rotor_speed[k], brakes[k]).1;
1455            }
1456            self.bend_rates(s, acc, out);
1457            return;
1458        }
1459        let (t, w) = self.arms(s);
1460        let (mass, velocity, gravity) = self.joint_load(s);
1461        let mut rhs = [0.0; 3];
1462        for k in 0..3 {
1463            let joint = &self.joints[k];
1464            let (gear, rotor_acc, brake_rate) =
1465                joint.rotor(torque[k], s[6 + k], s[9 + k], t[k], w[k], s[12 + k], self.brake_engaged);
1466            rhs[k] = gear.output + gravity[k] - velocity[k] + joint.output_torque(t[k], w[k]);
1467            out[6 + k] = s[9 + k];
1468            out[9 + k] = rotor_acc;
1469            out[12 + k] = brake_rate;
1470        }
1471        let acc = inverse(&mass).map_or([f64::NAN; 3], |inv| mul(&inv, rhs));
1472        out[..3].copy_from_slice(&s[3..6]);
1473        out[3..6].copy_from_slice(&acc);
1474        self.bend_rates(s, acc, out);
1475    }
1476
1477    fn tool_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1478        let (p, v) = self.platform(s);
1479        pos[..3].copy_from_slice(&p);
1480        vel[..3].copy_from_slice(&v);
1481    }
1482    /// The arms turn at the speed, their bend (in and out of their planes) standing still.
1483    fn set_tool_velocity(&self, s: &mut [f64], vel: &[f64]) {
1484        let ((t, _), (y, _)) = (self.elbows(s), self.lateral(s));
1485        let (_, j, _) = self.pose_moved(t, y);
1486        let w = inverse(&j).map_or([f64::NAN; 3], |inv| mul(&inv, [vel[0], vel[1], vel[2]]));
1487        s[3..6].copy_from_slice(&w);
1488        if self.bending.is_some() {
1489            let at = self.bend_at();
1490            s[at + 3..at + 6].fill(0.0);
1491            s[at + 9..at + 12].fill(0.0);
1492        }
1493        if self.elastic {
1494            for k in 0..3 {
1495                s[9 + k] = self.joints[k].ratio() * w[k];
1496            }
1497        }
1498    }
1499    fn motor_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1500        let (rotor, speed) = self.rotors(s);
1501        pos[..3].copy_from_slice(&rotor);
1502        vel[..3].copy_from_slice(&speed);
1503    }
1504
1505    /// Rigid, loss-free, at rest: M theta'' - Q_g at the arm over the ratio, plus the rotor's own J_rotor i theta''.
1506    fn feedforward_torque(&self, pos: &[f64], acc: &[f64], out: &mut [f64]) {
1507        let t = self.legs.inverse([pos[0], pos[1], pos[2]]).unwrap_or([f64::NAN; 3]);
1508        let (mass, _, gravity) = self.load(t, [0.0; 3]);
1509        let (_, j) = self.pose(t);
1510        let arm_acc = inverse(&j).map_or([f64::NAN; 3], |inv| mul(&inv, [acc[0], acc[1], acc[2]]));
1511        let at_arm = mul(&mass, arm_acc);
1512        for k in 0..3 {
1513            let joint = &self.joints[k];
1514            out[k] = (at_arm[k] - gravity[k]) / joint.ratio() + joint.rotor_inertia * joint.ratio() * arm_acc[k];
1515        }
1516    }
1517
1518    /// With the speed: θ̇ = J⁻¹ ṗ, θ̈ = J⁻¹ (p̈ − J_x⁻¹ w), and at the arm M θ̈ + v − Q_g (`load`: with the lumped
1519    /// forearms that is I_b θ̈ + m_nt Jᵀ p̈ − Q_g; with rods their middles' too), over the ratio, plus the rotor's own
1520    /// J_rotor i θ̈. The links rigid.
1521    fn feedforward_torque_moving(&self, pos: &[f64], vel: &[f64], acc: &[f64], out: &mut [f64]) {
1522        let p = [pos[0], pos[1], pos[2]];
1523        let t = self.legs.inverse(p).unwrap_or([f64::NAN; 3]);
1524        let (_, j) = self.pose(t);
1525        let inv = inverse(&j).unwrap_or([[f64::NAN; 3]; 3]);
1526        let (pv, pa) = ([vel[0], vel[1], vel[2]], [acc[0], acc[1], acc[2]]);
1527        let w = mul(&inv, pv);
1528        let bend = self.legs.velocity_term(t, p, w, pv).unwrap_or([f64::NAN; 3]);
1529        let arm_acc = mul(&inv, std::array::from_fn(|i| pa[i] - bend[i]));
1530        let (mass, velocity, gravity) = self.load(t, w);
1531        // The rigid model is loss-free: a platform drag is friction, which `load` puts in the velocity term for the
1532        // dynamics, and is taken out again here. What stays is quadratic in the speed, as the time-optimal planner reads
1533        // it: a sliding friction of 5 N read as d v^2 from its value at speed 1 grew ninefold at speed 3, and held the
1534        // tool's turn on a path to 15 rad/s where its motor allows 39.
1535        let drag = self.drag_torque(t, w);
1536        let at_arm = mul(&mass, arm_acc);
1537        for k in 0..3 {
1538            let joint = &self.joints[k];
1539            out[k] = (at_arm[k] + velocity[k] + drag[k] - gravity[k]) / joint.ratio()
1540                + joint.rotor_inertia * joint.ratio() * arm_acc[k];
1541        }
1542    }
1543
1544    /// The rigid model at a steady speed, θ̇ = J⁻¹ ṗ: per arm the joint's friction f(θ̇) and the platform drag's
1545    /// −Jᵀ F through the gearbox as `rigid_solve` takes them, (f − drag) / (i loss), plus the motor shaft's friction (with
1546    /// the gearbox's drag) at i θ̇. The gearbox's loss factor is the one of what it passes at rest, the weight's −Q_g
1547    /// with the friction, as in `rigid_solve` (of the torque going in: `linkage::steady_loss`), and on all of it: the
1548    /// weight's lossless torque is the rigid feedforward's, so what the loss adds to it is part of what this returns
1549    /// (as the linkage's, the trait's rule: the load goes through the efficiencies where the motor drives). The same holds
1550    /// for the speed's own torque at the arm, M θ̈ + v at p̈ = 0 (the feedforward's, loss-free): the loss is taken of it
1551    /// with the rest, and what it adds is returned here. The brake is released and the stops are not touched in a move.
1552    fn steady_friction(&self, pos: &[f64], vel: &[f64], out: &mut [f64]) {
1553        let p = [pos[0], pos[1], pos[2]];
1554        let t = self.legs.inverse(p).unwrap_or([f64::NAN; 3]);
1555        let (_, j) = self.pose(t);
1556        let inv = inverse(&j).unwrap_or([[f64::NAN; 3]; 3]);
1557        let pv = [vel[0], vel[1], vel[2]];
1558        let w = mul(&inv, pv);
1559        let bend = self.legs.velocity_term(t, p, w, pv).unwrap_or([f64::NAN; 3]);
1560        let arm_acc = mul(&inv, bend.map(|b| -b));
1561        let (mass, velocity, gravity) = self.load(t, w);
1562        let drag = self.drag_torque(t, w);
1563        let at_mass = mul(&mass, arm_acc);
1564        for k in 0..3 {
1565            let joint = &self.joints[k];
1566            let moving = at_mass[k] + velocity[k] + drag[k];
1567            let at_arm = joint.friction.torque(w[k]) - drag[k];
1568            let passed = moving + at_arm - gravity[k];
1569            let loss = crate::linkage::steady_loss(&joint.gearbox, passed, w[k]);
1570            out[k] = joint.shaft.torque(joint.ratio() * w[k]) + (passed / loss - moving + gravity[k]) / joint.ratio();
1571        }
1572    }
1573
1574    fn energy(&self, s: &[f64]) -> f64 {
1575        self.energy_parts(s).iter().sum()
1576    }
1577
1578    fn set_payload_attached(&mut self, attached: bool) {
1579        self.payload_attached = attached;
1580    }
1581    /// The push acts on the platform, the tool (`push`, in `joint_load` and `distal`): its generalised forces P^T F on the coordinates its place
1582    /// moves with, whose power F . v is the platform's speed times it.
1583    fn set_tool_force(&mut self, force: &[f64]) -> bool {
1584        self.tool_push = [force[0], force[1], force[2]];
1585        true
1586    }
1587    fn set_brake_engaged(&mut self, engaged: bool) {
1588        self.brake_engaged = engaged;
1589    }
1590    /// A stop met within the step (`HardStop::substeps`, `RotaryJoint::stop_substeps`).
1591    fn substeps_wanted(&self, s: &[f64], _torque: &[f64], dt: f64, _substeps: u32) -> u32 {
1592        let (t, w) = self.arms(s);
1593        (0..t.len()).map(|k| self.joints[k].stop_substeps(t[k], w[k], dt)).max().unwrap_or(1)
1594    }
1595
1596    /// The gearboxes, in the order of `thermal_parts`.
1597    /// The gearboxes' hysteresis states move on to where the step ended (`Gearbox::commit`).
1598    fn after_step(&mut self, s: &mut [f64], _dt: f64) {
1599        if self.elastic {
1600            for k in 0..3 {
1601                self.joints[k].gearbox.commit(s[6 + k], s[k]);
1602            }
1603        }
1604    }
1605    fn memory(&self) -> Vec<f64> {
1606        sim_components::mech::Gearbox::anchors(self.joints.iter().map(|j| &j.gearbox))
1607    }
1608    fn set_memory(&mut self, memory: &[f64]) {
1609        sim_components::mech::Gearbox::set_anchors(self.joints.iter_mut().map(|j| &mut j.gearbox), memory)
1610    }
1611
1612    fn set_part_temperatures(&mut self, rises: &[f64]) {
1613        let Some(law) = &self.thermal else { return };
1614        let geared: Vec<usize> = self.geared().collect();
1615        for (k, rise) in geared.into_iter().zip(rises) {
1616            self.joints[k].gearbox.efficiency = law.gearbox_efficiency(*rise);
1617            self.joints[k].shaft.set_oil(law.viscosity_factor(*rise));
1618        }
1619    }
1620
1621    /// What the gearboxes can sag at rest anywhere in the working range (`rest_sag`): 0.73 mm with the SP+ 100 and its
1622    /// typical 2.25 arcmin (the simulation at rest puts the motors' pose up to 0.66 mm off the tool's at the rim's lower
1623    /// edge between two arms); 2.30 mm with the NRB080's 9 arcmin before 14 November 2026, and until 13 November a
1624    /// fixed 1.5 mm, which 9 arcmin outgrew. Its arms rest at one side of their backlash; the bound takes either.
1625    fn setpoint_slack(&self) -> f64 {
1626        self.rest_slack
1627    }
1628
1629    fn unreachable(&self, tool: &[f64], slack: f64) -> Option<&'static str> {
1630        if tool.len() != 3 {
1631            return Some("error-target-out-of-range");
1632        }
1633        let p = [tool[0], tool[1], tool[2]];
1634        if !self.in_envelope(&p, slack) {
1635            return Some("error-delta-outside-envelope");
1636        }
1637        let Some(t) = self.legs.inverse(p) else { return Some("error-delta-out-of-reach") };
1638        if (0..3).any(|k| t[k] < self.joints[k].range.0 || t[k] > self.joints[k].range.1) {
1639            return Some("error-delta-joint-stop");
1640        }
1641        match self.legs.jacobian(t, p) {
1642            Some(j) if condition_number(&j) <= self.max_condition => None,
1643            _ => Some("error-delta-singularity"),
1644        }
1645    }
1646
1647    /// Of the arm angles, elbows out, as the signal `kinematics.condition` and the check against
1648    /// `workspace.max_condition_number`.
1649    fn condition(&self, tool: &[f64]) -> Option<f64> {
1650        let p = [tool[0], tool[1], tool[2]];
1651        let j = self.legs.inverse(p).and_then(|t| self.legs.jacobian(t, p));
1652        Some(j.map_or(f64::INFINITY, |j| condition_number(&j)))
1653    }
1654
1655    fn signal_infos(&self) -> Vec<SignalInfo> {
1656        let mut out = Vec::new();
1657        for (k, motor) in self.motors.iter().enumerate() {
1658            let arm = ["arm-1", "arm-2", "arm-3"][k];
1659            out.push(SignalInfo::new(format!("arm.{}.angle", motor.id), arm, "quantity-arm-angle", "rad"));
1660            out.push(SignalInfo::new(
1661                format!("gearbox.{}.output_torque", motor.id),
1662                motor.key,
1663                "quantity-gearbox-torque",
1664                "N m",
1665            ));
1666        }
1667        out.push(SignalInfo::new("kinematics.condition", "group-kinematics", "quantity-condition-number", ""));
1668        self.effect_infos(&mut out);
1669        out
1670    }
1671
1672    fn base_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1673        let (t, _) = self.arms(s);
1674        let gear = self.gear_output(s, torque);
1675        for k in 0..3 {
1676            out.extend([t[k], gear[k]]);
1677        }
1678        let (_, j) = self.pose(self.elbows(s).0);
1679        out.push(condition_number(&j));
1680    }
1681    fn effect_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1682        self.view_signals(s, torque, out);
1683    }
1684    fn loss_powers(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1685        out.extend(&self.losses(s, torque).powers[..self.loss_count()]);
1686    }
1687
1688    /// The three arms' bearing friction, rotary contacts (N m over rad/s at the arm).
1689    fn friction_contacts(&self) -> Vec<sim_core::FrictionContact> {
1690        (0..3)
1691            .map(|k| sim_core::FrictionContact { id: JOINT_CONTACTS[k], owner_key: ["arm-1", "arm-2", "arm-3"][k] })
1692            .collect()
1693    }
1694    fn friction_rotary(&self, _i: usize) -> bool {
1695        true
1696    }
1697    fn friction_curve(&self, i: usize, speed: f64, _load_scale: f64) -> [f64; 3] {
1698        self.joints.get(i).map_or([0.0; 3], |j| j.friction_split(speed))
1699    }
1700    /// The arm turns at its motor's highest speed over the gearbox's ratio.
1701    fn friction_speed_limit(&self, i: usize, motor_speed: &[f64]) -> Option<f64> {
1702        Some(motor_speed.get(i)? / self.joints.get(i)?.ratio())
1703    }
1704
1705    /// The gearboxes that are not couplings, by their nodes' ids.
1706    fn thermal_parts(&self) -> Vec<ThermalPart> {
1707        self.geared()
1708            .map(|k| ThermalPart {
1709                id: self.gearbox_ids[k],
1710                kind: "gearbox",
1711                owner_key: self.motors[k].key,
1712                scene_part: "gearbox",
1713                scene_index: k,
1714            })
1715            .collect()
1716    }
1717
1718    fn scene(&self, s: &[f64], out: &mut Scene) {
1719        // The arms drawn straight to their elbows, bent or not.
1720        let ((t, _), (y, _)) = (self.elbows(s), self.lateral(s));
1721        let (rotor, rotor_speed) = self.rotors(s);
1722        let (p, ..) = self.pose_moved(t, y);
1723        out.parts.clear();
1724        out.labels.clear();
1725        let grey = [0.62, 0.64, 0.68];
1726        out.parts.push(Part::new(
1727            "base",
1728            Shape::Box { size: [2.4 * self.base_radius, 2.4 * self.base_radius, 0.04] },
1729            [0.0, 0.0, 0.1],
1730            grey,
1731        ));
1732        for k in 0..3 {
1733            let (c, sn) = self.legs.azimuth[k];
1734            let (shoulder, arm_end) = self.arm(k, t, y);
1735            let at = |r: f64, z: f64| [r * c, r * sn, z];
1736            out.parts.push(Part::new(
1737                sim_core::scene::MOTOR_PART,
1738                Shape::Box { size: [0.09, 0.09, 0.12] },
1739                at(self.base_radius, 0.16),
1740                [0.9, 0.45, 0.1],
1741            ));
1742            out.parts.push(Part::new(
1743                "gearbox",
1744                Shape::Box { size: [0.09, 0.09, 0.06] },
1745                at(self.base_radius, 0.05),
1746                [0.25, 0.25, 0.28],
1747            ));
1748            out.parts.push(
1749                Part::new(
1750                    "rotor-bar",
1751                    Shape::Box { size: [0.07, 0.004, 0.012] },
1752                    at(self.base_radius, 0.225),
1753                    [0.1, 0.1, 0.1],
1754                )
1755                .turned(rotor[k]),
1756            );
1757            out.parts.push(Part::new(
1758                "arm",
1759                Shape::Segment { to: arm_end, width: ARM_WIDTH },
1760                shoulder,
1761                [0.2, 0.22, 0.26],
1762            ));
1763            // The two rods of the forearm pair, apart along the elbow's axis (tangential to the base).
1764            for (from, to) in self.legs.rods(k, t[k], y[k], p, self.platform_radius, self.rod_spacing) {
1765                out.parts.push(Part::new("forearm", Shape::Segment { to, width: ROD_WIDTH }, from, [0.15, 0.15, 0.15]));
1766            }
1767            out.labels.push(Label {
1768                pos: at(self.base_radius, 0.3),
1769                owner_key: self.motors[k].key,
1770                value: rotor_speed[k] * 60.0 / std::f64::consts::TAU,
1771                unit_key: "unit-rpm",
1772                decimals: 0,
1773            });
1774        }
1775        out.parts.extend(self.on_platform(p));
1776        out.labels.push(Label {
1777            pos: [p[0], p[1], p[2] - 0.15],
1778            owner_key: self.axes[2].key,
1779            value: p[2],
1780            unit_key: "unit-m",
1781            decimals: 3,
1782        });
1783    }
1784
1785    /// The platform's centre: the machine's frame is the scene's.
1786    fn scene_point(&self, tool_pose: &[f64]) -> Option<[f64; 3]> {
1787        Some([tool_pose[0], tool_pose[1], tool_pose[2]])
1788    }
1789
1790    /// The platform and the payload under it, where `scene` draws them, without drawing the rest: the live check asks
1791    /// for them every base step. The rods and arms are `collision_capsules`.
1792    fn collision_bodies(&self, s: &[f64]) -> Vec<sim_core::Aabb> {
1793        let ((t, _), (y, _)) = (self.elbows(s), self.lateral(s));
1794        let p = self.pose_moved(t, y).0;
1795        sim_core::scene::scene_boxes(&self.on_platform(p), &["platform", "payload"])
1796    }
1797
1798    /// The six forearm rods and the three upper arms, each the capsule along the segment `scene` draws, of half its
1799    /// width: exact for a round rod of that width, and no wider than the drawn strip anywhere along it.
1800    fn collision_capsules(&self, s: &[f64]) -> Vec<sim_core::Capsule> {
1801        let ((t, _), (y, _)) = (self.elbows(s), self.lateral(s));
1802        let p = self.pose_moved(t, y).0;
1803        let mut out = Vec::new();
1804        for k in 0..3 {
1805            for (from, to) in self.legs.rods(k, t[k], y[k], p, self.platform_radius, self.rod_spacing) {
1806                out.push(sim_core::Capsule { from, to, radius: ROD_WIDTH / 2.0 });
1807            }
1808        }
1809        for k in 0..3 {
1810            let (from, to) = self.arm(k, t, y);
1811            out.push(sim_core::Capsule { from, to, radius: ARM_WIDTH / 2.0 });
1812        }
1813        out
1814    }
1815
1816    /// With effects.joint_elasticity: per arm its gearbox's spring (K1) between the rotor and the rest of the motor's
1817    /// rigid inertia at the pose, over the ratio squared. The arms' bending (effects.link_elasticity) is left out.
1818    fn trains(&self, tool_pose: &[f64]) -> Vec<Option<sim_core::Train>> {
1819        if !self.elastic {
1820            return Vec::new();
1821        }
1822        let whole = sim_components::control::rigid_inertias(self, tool_pose);
1823        self.joints.iter().zip(whole).map(|(j, whole)| j.train(whole)).collect()
1824    }
1825
1826    /// The lowest of `modes`: the gearboxes' springs (effects.joint_elasticity) and the arms' bending in and out of
1827    /// their planes (effects.link_elasticity), in series where both are on. At the centre the lowest is sideways
1828    /// (twice).
1829    fn resonance_hz(&self, tool_pose: &[f64]) -> Option<f64> {
1830        self.modes_at(tool_pose, false).first().map(|mode| mode.0)
1831    }
1832
1833    /// The mode of `resonance_hz`: the joints' turns in the arm angles, the bend (elbow less joint) in the bend states,
1834    /// the elbows' moves out of the arms' planes in theirs, rotors still; scaled so that the platform's largest travel
1835    /// along an axis is 1 m.
1836    fn mode_shape(&self, tool_pose: &[f64]) -> Option<(f64, Vec<f64>)> {
1837        let (hz, _, v) = self.modes_at(tool_pose, false).into_iter().next()?;
1838        let p = [tool_pose[0], tool_pose[1], tool_pose[2]];
1839        let (j, jy) = self.legs.jacobians(self.legs.inverse(p)?, [0.0; 3], p)?;
1840        let (root, tip) = ([v[0], v[1], v[2]], [v[3], v[4], v[5]]);
1841        let moves = if v.len() == 9 { [v[6], v[7], v[8]] } else { [0.0; 3] };
1842        let (a, b) = (mul(&j, tip), mul(&jy, moves));
1843        let largest = (0..3).fold(0f64, |m, k| m.max((a[k] + b[k]).abs()));
1844        let mut shape = vec![0.0; self.state_len()];
1845        shape[..3].copy_from_slice(&root.map(|v| v / largest));
1846        if self.bending.is_some() {
1847            let at = self.bend_at();
1848            for k in 0..3 {
1849                shape[at + k] = (tip[k] - root[k]) / largest;
1850                shape[at + 6 + k] = moves[k] / largest;
1851            }
1852        }
1853        Some((hz, shape))
1854    }
1855
1856    /// Every mode of `modes_at` with its damping ratio: 3 with the gearboxes' springs alone (one per arm), 6 with the
1857    /// arms' bending alone (in and out of their planes), 9 with both.
1858    fn modes(&self, tool_pose: &[f64]) -> Vec<Mode> {
1859        self.modes_at(tool_pose, false).into_iter().map(|(hz, damping, _)| Mode { hz, damping }).collect()
1860    }
1861
1862    /// `modes` with the gearboxes' hysteresis stiffness added (K1 + sigma): the frequencies of a small ringing.
1863    fn modes_small_amplitude(&self, tool_pose: &[f64]) -> Vec<Mode> {
1864        self.modes_at(tool_pose, true).into_iter().map(|(hz, damping, _)| Mode { hz, damping }).collect()
1865    }
1866}
1867
1868/// The tube's mode, the static shape psi = (3 xi^2 - xi^3) / 2 along the arm (xi = s / L_a, consistent with
1869/// k_b = 3 E I / L_a, `beam::STATIC_SHAPE_MASS`): int(xi psi) = 11/40 over int(psi) = 3/8, 11/15, where its momentum out
1870/// of the plane acts; int(xi psi) itself, the tube's in-plane momentum that moves with its turn.
1871const TUBE_CENTROID: f64 = sim_components::beam::STATIC_SHAPE_MOMENT / sim_components::beam::STATIC_SHAPE_PARTICIPATION;
1872const TUBE_MOMENT: f64 = sim_components::beam::STATIC_SHAPE_MOMENT;
1873
1874/// The forearm rods' width and the upper arms', as drawn and as collision capsules (twice their radius), m.
1875const ROD_WIDTH: f64 = 0.012;
1876const ARM_WIDTH: f64 = 0.04;
1877
1878#[cfg(test)]
1879mod tests {
1880    use super::arm_modes;
1881
1882    /// Each arm on its own gearbox: with rigid arms the root (inertia I = 0.5) and the elbow's share of the rest
1883    /// (D = 1 kg m^2, uncoupled between the arms) ride the gearbox's spring together, w^2 = k / (I + D) per arm. For
1884    /// k = 900, 1500, 2400 N m/rad: 600, 1000, 1600 1/s^2, lowest first, where one stiffness for all three would have
1885    /// given three equal modes.
1886    #[test]
1887    fn each_arm_has_its_own_gearbox_stiffness_in_the_modes() {
1888        let distal: Vec<Vec<f64>> = (0..3).map(|r| (0..3).map(|c| if r == c { 1.0 } else { 0.0 }).collect()).collect();
1889        let modes = arm_modes((0.5, 0.0), &distal, Some([1500.0, 900.0, 2400.0]), None, None);
1890        let w2: Vec<f64> = modes.iter().map(|m| m.0).collect();
1891        assert_eq!(w2.len(), 3, "{w2:?}");
1892        for (found, by_hand) in w2.iter().zip([600.0, 1000.0, 1600.0]) {
1893            assert!((found - by_hand).abs() < 1e-6 * by_hand, "{w2:?}");
1894        }
1895    }
1896    /// The tube's coupling B of root and elbow (effects.arm_tube_inertia) in the modes: per arm the root J_r = 0.002 and
1897    /// the elbow's share D = 0.05 kg m^2 joined by B = 0.005, the gearbox k_g = 1000 and the bend k_b = 3000 N m/rad:
1898    /// K = [[k_g + k_b, -k_b], [-k_b, k_b]] against M = [[J_r, B], [B, D]], so
1899    /// (J_r D - B^2) w^4 - ((k_g + k_b) D + k_b J_r + 2 k_b B) w^2 + k_g k_b = 0, each root three times (three alike
1900    /// arms, uncoupled).
1901    #[test]
1902    fn the_tubes_coupling_joins_root_and_elbow_in_the_modes() {
1903        let (jr, d, b, kg, kb) = (0.002, 0.05, 0.005, 1000.0, 3000.0);
1904        let distal: Vec<Vec<f64>> = (0..3).map(|r| (0..3).map(|c| if r == c { d } else { 0.0 }).collect()).collect();
1905        let modes = arm_modes((jr, b), &distal, Some([kg; 3]), Some(kb), None);
1906        let (qa, qb, qc) = (jr * d - b * b, (kg + kb) * d + kb * jr + 2.0 * kb * b, kg * kb);
1907        let root = (qb * qb - 4.0 * qa * qc).sqrt();
1908        let (low, high) = ((qb - root) / (2.0 * qa), (qb + root) / (2.0 * qa));
1909        let w2: Vec<f64> = modes.iter().map(|m| m.0).collect();
1910        assert_eq!(w2.len(), 6, "{w2:?}");
1911        for (k, found) in w2.iter().enumerate() {
1912            let by_hand = if k < 3 { low } else { high };
1913            assert!((found - by_hand).abs() < 1e-9 * by_hand, "{w2:?} against {low}, {high}");
1914        }
1915    }
1916}