Skip to main content

machine_cable_robot/
lib.rs

1//! Cable-driven parallel robots: a platform hung in cables, each cable wound on a winch driven by a servo motor through
2//! a gearbox. Two machines of the one model here:
3//!
4//! - `cable-planar`: a point-mass carriage in a vertical plane on 4 cables from the frame's corners; tool x, z (m).
5//! - `cable-spatial`: a platform with 6 degrees of freedom on 8 cables from the corners of a box frame; tool x, y, z (m)
6//!   and the orientation as a rotation vector rx, ry, rz (rad, in the base frame).
7//!
8//! Kinematics. Each cable leaves its winch along the axis `e_z` of a swivelling pulley of radius r at the point A
9//! (`frame.exits_m`, `frame.winch_directions`), wraps it by the angle beta and runs straight from its exit point B to
10//! the platform's anchor P = p + R a (`platform.anchors_m`). The pulley swivels about `e_z` into the plane of P:
11//!
12//! ```text
13//! d = P - A, gamma = atan2(d . e_y, d . e_x), e_u = cos gamma e_x + sin gamma e_y   (e_x towards the frame's centre)
14//! in the pulley's plane (u along e_u, w along e_z): centre M = (r, 0), P = (d . e_u, d . e_z)
15//! m = |P - M|, l_f = sqrt(m^2 - r^2), theta_B = atan2(P_w, P_u - r) - acos(r / m), beta = (theta_B - pi) mod 2 pi
16//! L = r beta + l_f, u = (B - P) / l_f (the unit vector from the anchor to the exit point); dL/dP = -u
17//! ```
18//!
19//! Statics. A cable pulls the platform with t u at its anchor: the structure matrix A (n x m) has the columns
20//! (u, b x u) restricted to the platform's degrees of freedom, b = R a, and the cables hold a wrench w when A t = w with
21//! every tension between `cable.min_tension_n` and the rating `cable.breaking_load_n` / `cable.safety_factor`. Cables
22//! can only pull, so the tensions are distributed by a small QP (`distribute`): those nearest `cable.reference_tension_n`
23//! that hold the wrench within the band, which is the closed form t = t_ref + A^+ (w - A t_ref) wherever no cable sits
24//! at a bound, and changes continuously with the pose where one does. A pose whose platform weight (with payload) no
25//! tensions in the band hold is outside the wrench-feasible workspace and refused.
26//! The workspace of the poses is the static one (the weight at rest); the wrench of a cycle's accelerations is held to
27//! the band by the time-optimal plan: `Machine::rigid_tensions_moving` gives each cable's tension at a pose, speed and
28//! acceleration (the distribution for the wrench M xi' + c + g), and `Machine::tension_band` gives the plan the band
29//! itself (`cable.min_tension_n` to the rating above, the one source; `ratings.belt_*_tension_n` are not read here), which
30//! it keeps them within with the share `profile.tension_reserve` of the room.
31//!
32//! Dynamics. The platform (mass, inertia R I R^T about its centre, payload a point mass there) moves by its twist
33//! xi = (v, w): M xi' + c + g = A t, c = (0, w x I_w w), g = (0, 0, m g, 0, 0, 0). Each winch is a `joint::RotaryJoint`
34//! in metres of cable: motor, gearbox with the drum's radius as a lever (ratio i / r rad per m), the drum's inertia as
35//! a mass J / r^2 at the cable, friction in its bearings and stops at its capacity. Elastic (effects.cable_stretch),
36//! the cable of free length l is a spring of potential V = EA (L - l)^2 / (2 l) while taut (none while slack): it pulls
37//! the platform with t = EA (L - l) / l, of stiffness EA / l, so that the stiffness changes over the workspace, and the
38//! drum with t (1 + (L - l) / (2 l)); with effects.cable_damping a damper of c / l (`cable.specific_damping_n_s`).
39//! Drum and rotor are bodies of their own behind the gearbox's spring, as on every joint. Rigid, the cables do not
40//! stretch: l = L(pose), the rotors turn with the drums, and the winches' inertia joins the platform's through
41//! G = dL/dxi = -A^T: (M + G^T diag(J_k) G) xi' = G^T (drive + friction) - c - g - G^T diag(J_k) (G' xi).
42//!
43//! The cables' own mass (`cable.mass_per_m_kg` rho, 0 where the key is left out) acts in two ways. Its weight: the
44//! cable between the pulley's swivel point E and the anchor P (length L) hangs from both ends, so its potential is
45//! V = rho g L (z_P - z_E) / 2 (the mass of the free span at the height of its middle, the cable paid out counted from
46//! the pulley's height: the run from the drum to the pulley keeps its length, and lifting cable from the drum's height
47//! to the pulley's is the winch's, rho g h l with h the drum's drop (with effects.cable_inertia, from `frame.run_lengths_m`): a force rho g h at the
48//! cable, 0.05 N for 0.5 m at 10 g/m), and the platform's equation has the wrench dV/dxi: at the anchor the force
49//! rho g / 2 (L e_z - (z_P - z_E) u), half the weight of the span along gravity and the share of its along-cable pull
50//! (dL/dP = -u), with the moment b x f; V joins the potential energy, so the budget closes. And the sag (parabolic,
51//! shallow): a cable of weight w = rho g per metre hanging over its straight part l_f, whose horizontal part is l_h, at
52//! the chord tension T sags by d = w l_h l_f / (8 T) and is longer than its chord by (w l_h)^2 l_f / (24 T^2). The cable
53//! of free length l, stretched to l (1 + T / EA), spans that, so with t0 = EA (L - l) / l (the straight cable's tension)
54//! t0 = T - c / (2 T^2), c = (w l_h)^2 EA l_f / (12 L): the cable pulls with the one positive root T of
55//! T^3 - t0 T^2 - c / 2 = 0 (`sagged`), taut at any t0 (a slack cable hangs: T = sqrt(c / (2 |t0|)) far below zero),
56//! and its stiffness dT/dt0 = 1 / (1 + c / T^3) is Ernst's equivalent modulus E / (1 + (w l_h)^2 E A / (12 T^3)) (times
57//! l_f / L). Its energy, the stretch's and the sag's weight together, is (l / EA) W with W = T^2 / 2 - c / T, the integral
58//! of T over t0 (`pull_work`), so that the platform takes T along the chord and the drum T L / l - W / EA, and W's
59//! change with c over the pose too (the sag's weight moving with l_h, about (w l_h)^2 l / (12 T l_h), 5e-5 N at 10 g/m
60//! and 20 N: `sag_pull`). With effects.cable_inertia the cable runs along itself at the drum's speed, the whole of the
61//! drum's capacity a mass rho capacity at the cable beside J / r^2. And each straight span swings across
62//! itself with its anchor, rho l_f / 3 (1 - u u^T) at the anchor with its velocity terms (`swing_bias`; 42 g on the
63//! spatial platform's 8 kg with the payload, 0.5 %). Rigid cables do not stretch and have no sag.
64//!
65//! The motor angles of a pose (`inverse`) are those of the free lengths that hold the platform at rest there with the
66//! tensions of the distribution, l = L / (1 + t / EA) (rigid: l = L), so that position setpoints and the torque
67//! feedforward ask the same pretension of the cables. `forward` finds the pose by Gauss-Newton on the cable lengths
68//! (rigid), or where the platform hangs at rest on cables of the motors' free lengths (elastic).
69
70use sim_components::chain::{solve, solve_in_place};
71use sim_components::joint::RotaryJoint;
72use sim_components::mech::{HardStop, ShaftFriction, ThermalFeedback};
73use sim_components::rigid::{M3, V3, about, add, cross, dot, matmul, mul};
74use sim_components::transmission::Converter;
75use sim_core::{
76    AxisInfo, Config, ConfigError, ENERGY_PARTS, FRICTION_SIGNALS, FrictionContact, LOSS_PREFIX, Label, Machine,
77    MachineEntry, Mode, MotorInfo, Part, RatingCheck, Scene, Shape, SignalInfo, TORQUE_PARTS, ThermalPart,
78};
79use std::f64::consts::{PI, TAU};
80
81const I18N: &[(&str, &str)] = &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))];
82
83pub static PLANAR: MachineEntry = MachineEntry {
84    id: "cable-planar",
85    key: "machine-cable-planar",
86    default_config: concat!(include_str!("../config/common.toml"), "\n", include_str!("../config/planar.toml")),
87    i18n: I18N,
88    build,
89    suite_configs: || suite_configs(&PLANAR),
90};
91
92pub static SPATIAL: MachineEntry = MachineEntry {
93    id: "cable-spatial",
94    key: "machine-cable-spatial",
95    default_config: concat!(include_str!("../config/common.toml"), "\n", include_str!("../config/spatial.toml")),
96    i18n: I18N,
97    build,
98    suite_configs: || suite_configs(&SPATIAL),
99};
100
101const G: f64 = 9.80665;
102
103/// Effects that take energy out or put it in; the standard suite runs with them off.
104pub const LOSSY_EFFECTS: [&str; 8] = [
105    "winch_friction",
106    "motor_friction",
107    "gearbox_drag",
108    "gearbox_lost_motion",
109    "gearbox_efficiency",
110    "torque_ripple",
111    "holding_brake",
112    "cable_damping",
113];
114
115/// The default config with every loss switched off.
116pub fn lossless_config(entry: &MachineEntry) -> Config {
117    let mut cfg = entry.config();
118    for effect in LOSSY_EFFECTS {
119        cfg.set_text(&format!("effects.{effect} = false")).unwrap();
120    }
121    cfg.set_text("gearbox.damping_nm_s_rad = 0.0").unwrap();
122    cfg.set_text("winch.stop_damping_n_s_m = 0.0").unwrap();
123    cfg
124}
125
126/// Loss-free rigid and elastic models, with and without the payload. Held by constant tensions the platform is stable
127/// (pulled cables stiffen it), so gravity stays on.
128fn suite_configs(entry: &MachineEntry) -> Vec<Config> {
129    [(false, true), (false, false), (true, true), (true, false)]
130        .into_iter()
131        .map(|(elastic, payload)| {
132            let mut cfg = lossless_config(entry);
133            cfg.set_text(&format!("effects.cable_stretch = {elastic}")).unwrap();
134            cfg.set_text(&format!("effects.payload = {payload}")).unwrap();
135            cfg
136        })
137        .collect()
138}
139
140fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
141    sim_components::base::mount(cfg, Box::new(CableRobot::new(cfg)?))
142}
143
144const MOTOR_IDS: [&str; 8] = ["1", "2", "3", "4", "5", "6", "7", "8"];
145const MOTOR_KEYS: [&str; 8] = [
146    "motor-winch-1",
147    "motor-winch-2",
148    "motor-winch-3",
149    "motor-winch-4",
150    "motor-winch-5",
151    "motor-winch-6",
152    "motor-winch-7",
153    "motor-winch-8",
154];
155const WINCH_KEYS: [&str; 8] = ["winch-1", "winch-2", "winch-3", "winch-4", "winch-5", "winch-6", "winch-7", "winch-8"];
156const WINCH_CONTACTS: [&str; 8] =
157    ["winch.1", "winch.2", "winch.3", "winch.4", "winch.5", "winch.6", "winch.7", "winch.8"];
158const CABLE_KEYS: [&str; 8] = ["cable-1", "cable-2", "cable-3", "cable-4", "cable-5", "cable-6", "cable-7", "cable-8"];
159const GEARBOX_IDS: [&str; 8] =
160    ["gearbox_1", "gearbox_2", "gearbox_3", "gearbox_4", "gearbox_5", "gearbox_6", "gearbox_7", "gearbox_8"];
161const AXIS_IDS: [&str; 6] = ["x", "y", "z", "rx", "ry", "rz"];
162const AXIS_KEYS: [&str; 6] = ["axis-x", "axis-y", "axis-z", "axis-rx", "axis-ry", "axis-rz"];
163
164fn sub(a: V3, b: V3) -> V3 {
165    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
166}
167
168fn scale(a: V3, s: f64) -> V3 {
169    a.map(|v| v * s)
170}
171
172fn norm(a: V3) -> f64 {
173    dot(a, a).sqrt()
174}
175
176/// The chord tension T of a cable with sag constant `c` at the straight cable's tension `t0 = EA strain`: the positive
177/// root of T^3 - t0 T^2 - c / 2 = 0 (t0 = T - c / (2 T^2)), by Newton from max(t0, 0) + (c / 2)^(1/3), which is above
178/// the root, where the cubic is convex and rising, so that the steps come down monotonically. Without sag max(t0, 0).
179fn sagged(t0: f64, c: f64) -> f64 {
180    if c == 0.0 {
181        return t0.max(0.0);
182    }
183    let mut t = t0.max(0.0) + (0.5 * c).cbrt();
184    for _ in 0..100 {
185        let step = (t * t * (t - t0) - 0.5 * c) / (t * (3.0 * t - 2.0 * t0));
186        t -= step;
187        if step <= 1e-15 * t {
188            break;
189        }
190    }
191    t
192}
193
194/// `sagged`'s inverse: the straight cable's tension t0 = T - c / (2 T^2) for the chord tension T.
195fn unsagged(t: f64, c: f64) -> f64 {
196    if t <= 0.0 || c == 0.0 { t } else { t - 0.5 * c / (t * t) }
197}
198
199/// W(t0), the integral of `sagged` over t0, so that (l / EA) W is the cable's energy: without sag max(t0, 0)^2 / 2;
200/// with it, by dt0 = (1 + c / T^3) dT, T^2 / 2 - c / T (the stretch's energy and the sag's weight), which goes to the
201/// former as c goes to 0.
202fn pull_work(t0: f64, c: f64) -> f64 {
203    if c == 0.0 {
204        return 0.5 * t0.max(0.0).powi(2);
205    }
206    let t = sagged(t0, c);
207    0.5 * t * t - c / t
208}
209
210fn transpose(m: &M3) -> M3 {
211    std::array::from_fn(|i| std::array::from_fn(|j| m[j][i]))
212}
213
214/// The rotation of a rotation vector.
215fn exp(r: V3) -> M3 {
216    let angle = norm(r);
217    if angle == 0.0 { about([0.0, 0.0, 1.0], 0.0) } else { about(scale(r, 1.0 / angle), angle) }
218}
219
220/// The rotation vector (axis times angle, angle up to pi) of a rotation matrix.
221fn log(r: &M3) -> V3 {
222    let vee = [r[2][1] - r[1][2], r[0][2] - r[2][0], r[1][0] - r[0][1]];
223    let cos = ((r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0).clamp(-1.0, 1.0);
224    let sin = 0.5 * norm(vee);
225    let angle = sin.atan2(cos);
226    if angle < 1e-6 {
227        return vee.map(|v| 0.5 * v * (1.0 + angle * angle / 6.0));
228    }
229    if angle < PI - 1e-6 {
230        return vee.map(|v| v * angle / (2.0 * sin));
231    }
232    let i = (0..3).max_by(|&a, &b| r[a][a].total_cmp(&r[b][b])).unwrap_or(0);
233    let col: V3 = std::array::from_fn(|k| r[k][i] + if k == i { 1.0 } else { 0.0 });
234    let n = norm(col);
235    let sign = if dot(col, vee) < 0.0 { -1.0 } else { 1.0 };
236    col.map(|v| sign * v / n * angle)
237}
238
239/// The skew matrix [r]x and its square, and the angle.
240fn skew(r: V3) -> (M3, M3, f64) {
241    let k = [[0.0, -r[2], r[1]], [r[2], 0.0, -r[0]], [-r[1], r[0], 0.0]];
242    (k, matmul(&k, &k), norm(r))
243}
244
245/// The left Jacobian of the rotation vector: w = J_l(r) r'. J_l = 1 + (1 - cos a) / a^2 [r]x + (a - sin a) / a^3 [r]x^2.
246fn left_jacobian(r: V3) -> M3 {
247    let (k, k2, a) = skew(r);
248    let (c1, c2) = if a < 1e-4 {
249        (0.5 - a * a / 24.0, 1.0 / 6.0 - a * a / 120.0)
250    } else {
251        ((1.0 - a.cos()) / (a * a), (a - a.sin()) / (a * a * a))
252    };
253    std::array::from_fn(|i| std::array::from_fn(|j| if i == j { 1.0 } else { 0.0 } + c1 * k[i][j] + c2 * k2[i][j]))
254}
255
256/// Its inverse: r' = J_l^-1 w, J_l^-1 = 1 - [r]x / 2 + (1 / a^2 - (1 + cos a) / (2 a sin a)) [r]x^2.
257fn left_jacobian_inverse(r: V3) -> M3 {
258    let (k, k2, a) = skew(r);
259    let c2 = if a < 1e-4 { 1.0 / 12.0 + a * a / 720.0 } else { 1.0 / (a * a) - (1.0 + a.cos()) / (2.0 * a * a.sin()) };
260    std::array::from_fn(|i| std::array::from_fn(|j| if i == j { 1.0 } else { 0.0 } - 0.5 * k[i][j] + c2 * k2[i][j]))
261}
262
263/// The eigenvalues of the symmetric n x n matrix `a` (row by row), by Jacobi rotations.
264fn eigenvalues(mut a: Vec<f64>, n: usize) -> Vec<f64> {
265    for _ in 0..100 {
266        let off: f64 = (0..n * n).filter(|k| k / n != k % n).map(|k| a[k].powi(2)).sum();
267        let diag: f64 = (0..n).map(|k| a[k * n + k].powi(2)).sum();
268        if !(off > 1e-30 * diag) {
269            break;
270        }
271        for p in 0..n {
272            for q in p + 1..n {
273                if a[p * n + q] == 0.0 {
274                    continue;
275                }
276                let theta = 0.5 * (a[q * n + q] - a[p * n + p]) / a[p * n + q];
277                let t = if theta == 0.0 { 1.0 } else { theta.signum() / (theta.abs() + (theta * theta + 1.0).sqrt()) };
278                let (c, s) = (1.0 / (t * t + 1.0).sqrt(), t / (t * t + 1.0).sqrt());
279                for k in 0..n {
280                    let (akp, akq) = (a[k * n + p], a[k * n + q]);
281                    a[k * n + p] = c * akp - s * akq;
282                    a[k * n + q] = s * akp + c * akq;
283                }
284                for k in 0..n {
285                    let (apk, aqk) = (a[p * n + k], a[q * n + k]);
286                    a[p * n + k] = c * apk - s * aqk;
287                    a[q * n + k] = s * apk + c * aqk;
288                }
289            }
290        }
291    }
292    let mut eig: Vec<f64> = (0..n).map(|k| a[k * n + k]).collect();
293    eig.sort_by(f64::total_cmp);
294    eig
295}
296
297/// min 1/2 t^T H t - c^T t over l <= t <= u (H symmetric positive definite, m x m, row by row): the primal
298/// active-set method from t = clamp(start), finite for a strictly convex problem. Each round solves the free
299/// coordinates' Newton step with the fixed ones held; a step that would cross a bound stops there and fixes it; with no
300/// step left, a fixed coordinate whose gradient pulls it back inside is freed; none: done.
301fn box_qp(h: &[f64], c: &[f64], l: f64, u: f64, start: &[f64]) -> Option<Vec<f64>> {
302    let m = c.len();
303    let mut t: Vec<f64> = start.iter().map(|v| v.clamp(l, u)).collect();
304    let mut fixed: Vec<bool> = t.iter().map(|v| *v == l || *v == u).collect();
305    let scale = c.iter().fold(1.0f64, |s, v| s.max(v.abs()));
306    for _ in 0..20 * m + 20 {
307        let grad = |t: &[f64]| -> Vec<f64> {
308            (0..m).map(|i| (0..m).map(|j| h[i * m + j] * t[j]).sum::<f64>() - c[i]).collect()
309        };
310        let g = grad(&t);
311        let free: Vec<usize> = (0..m).filter(|k| !fixed[*k]).collect();
312        let f = free.len();
313        let mut stationary = f == 0;
314        if !stationary {
315            // The free coordinates' exact minimum with the fixed ones held (a quadratic: one Newton step), as far as
316            // the first bound it meets.
317            let hff: Vec<f64> = (0..f * f).map(|rc| h[free[rc / f] * m + free[rc % f]]).collect();
318            let step = solve(&hff, &free.iter().map(|k| -g[*k]).collect::<Vec<_>>())?;
319            let (mut alpha, mut block) = (1.0f64, None);
320            for (i, k) in free.iter().enumerate() {
321                let limit = match step[i] {
322                    s if s < 0.0 => (l - t[*k]) / s,
323                    s if s > 0.0 => (u - t[*k]) / s,
324                    _ => f64::INFINITY,
325                };
326                if limit < alpha {
327                    (alpha, block) = (limit.max(0.0), Some((*k, step[i] < 0.0)));
328                }
329            }
330            for (i, k) in free.iter().enumerate() {
331                t[*k] += alpha * step[i];
332            }
333            match block {
334                Some((k, low)) => {
335                    t[k] = if low { l } else { u };
336                    fixed[k] = true;
337                }
338                None => stationary = true,
339            }
340        }
341        if stationary {
342            // A fixed coordinate whose gradient points inside: at l it wants to grow (gradient < 0), at u to shrink.
343            let g = grad(&t);
344            let wrong = (0..m)
345                .filter(|k| fixed[*k])
346                .map(|k| (k, if t[k] == l { -g[k] } else { g[k] }))
347                .filter(|(_, pull)| *pull > 1e-12 * scale)
348                .max_by(|a, b| a.1.total_cmp(&b.1));
349            match wrong {
350                Some((k, _)) => fixed[k] = false,
351                None => return Some(t),
352            }
353        }
354    }
355    None
356}
357
358/// The penalised distribution: min |t - t_ref|^2 / 2 + RHO |A t - w|^2 / 2 within [t_min, t_max], defined for every
359/// wrench and continuous in it (a strictly convex problem over a box). Inside the wrench-feasible workspace it misses
360/// the wrench by about |t - t_ref| / RHO, 1e-4 N; what the motors' setpoints are taken from, so that `forward` finds
361/// a pose from any motor angles.
362fn penalised(a: &[f64], w: &[f64], t_min: f64, t_max: f64, t_ref: f64) -> Option<Vec<f64>> {
363    const RHO: f64 = 1e6;
364    let n = w.len();
365    let m = a.len() / n;
366    let h: Vec<f64> = (0..m * m)
367        .map(|rc| if rc / m == rc % m { 1.0 } else { 0.0 } + RHO * (0..n).map(|r| a[r * m + rc / m] * a[r * m + rc % m]).sum::<f64>())
368        .collect();
369    let c: Vec<f64> = (0..m).map(|k| t_ref + RHO * (0..n).map(|r| a[r * m + k] * w[r]).sum::<f64>()).collect();
370    box_qp(&h, &c, t_min, t_max, &vec![t_ref; m])
371}
372
373/// The tension distribution: the tensions t (m) nearest t_ref that hold the wrench, A t = w for the structure matrix
374/// `a` (n x m, row by row), each within [t_min, t_max]; `None` where there are none (outside the wrench-feasible
375/// workspace). A small QP, min |t - t_ref|^2 subject to A t = w and the band: the penalised problem (`penalised`) finds
376/// which cables sit at a bound, and the free ones are then solved exactly, t_F = t_ref + A_F^T (A_F A_F^T)^-1 (w - A_B
377/// t_B - A_F t_ref). Where no cable is at a bound that is the closed form t_ref + A^+ (w - A t_ref); unlike the improved
378/// closed-form method, which fixes one cable at a time and never frees it, the QP's tensions change continuously with
379/// the pose wherever they exist.
380pub fn distribute(a: &[f64], w: &[f64], t_min: f64, t_max: f64, t_ref: f64) -> Option<Vec<f64>> {
381    let n = w.len();
382    let m = a.len() / n;
383    let mut t = penalised(a, w, t_min, t_max, t_ref)?;
384    let band = 1e-9 * t_max.abs().clamp(1.0, 1e12);
385    let mut free: Vec<usize> = (0..m).filter(|k| t[*k] > t_min && t[*k] < t_max).collect();
386    // A cable the penalised problem leaves just inside the band (20.04 N against 20 N) can land just outside it in the
387    // exact solve (19.97 N): it goes to its bound and the others are solved again, until none crosses.
388    while free.len() >= n {
389        let f = free.len();
390        let rest: Vec<f64> = (0..n)
391            .map(|r| w[r] - (0..m).filter(|k| !free.contains(k)).map(|k| a[r * m + k] * t[k]).sum::<f64>())
392            .collect();
393        let af = |r: usize, k: usize| a[r * m + free[k]];
394        let aat: Vec<f64> = (0..n * n).map(|rc| (0..f).map(|k| af(rc / n, k) * af(rc % n, k)).sum()).collect();
395        let miss: Vec<f64> = (0..n).map(|r| rest[r] - (0..f).map(|k| af(r, k) * t_ref).sum::<f64>()).collect();
396        let y = solve(&aat, &miss)?;
397        for k in 0..f {
398            t[free[k]] = t_ref + (0..n).map(|r| af(r, k) * y[r]).sum::<f64>();
399        }
400        let crossed = |v: f64| v < t_min - band || v > t_max + band;
401        if !free.iter().any(|k| crossed(t[*k])) {
402            break;
403        }
404        free.retain(|k| !crossed(t[*k]));
405        for v in &mut t {
406            *v = v.clamp(t_min, t_max);
407        }
408    }
409    let off = (0..n).map(|r| ((0..m).map(|k| a[r * m + k] * t[k]).sum::<f64>() - w[r]).abs()).fold(0.0, f64::max);
410    let scale = w.iter().fold(t_max.abs().clamp(1.0, 1e12), |s, v| s.max(v.abs()));
411    let inside = t.iter().all(|v| *v >= t_min - band && *v <= t_max + band);
412    (inside && off <= 1e-9 * scale && t.iter().all(|v| v.is_finite())).then_some(t)
413}
414
415/// One cable's pulley and anchor.
416#[derive(Debug, Clone)]
417struct Cable {
418    /// Where the cable leaves the winch's line onto the pulley, the pulley's swivel axis (towards the winch), and the
419    /// pulley's direction at rest (towards the frame's centre, square to the axis).
420    exit: V3,
421    axis: V3,
422    ref_x: V3,
423    /// axis x ref_x, the pulley's third direction.
424    ref_y: V3,
425    /// On the platform, in its frame.
426    anchor: V3,
427}
428
429/// A list of at most `N` entries on the stack (the per-cable and per-degree-of-freedom vectors of one derivative, which
430/// would each cost a heap allocation; the cable count is at most 8 and the degrees of freedom 6, checked in `new`),
431/// read as a slice.
432#[derive(Debug, Clone, Copy)]
433pub struct Short<T, const N: usize> {
434    items: [T; N],
435    len: usize,
436}
437
438impl<T: Copy + Default, const N: usize> Short<T, N> {
439    fn filled(len: usize, value: T) -> Self {
440        assert!(len <= N, "a list of {len} entries on the stack of {N}");
441        Self { items: [value; N], len }
442    }
443}
444
445impl<const N: usize> Short<f64, N> {
446    fn zeros(len: usize) -> Self {
447        Self::filled(len, 0.0)
448    }
449}
450
451impl<T: Copy + Default, const N: usize> Default for Short<T, N> {
452    fn default() -> Self {
453        Self::filled(0, T::default())
454    }
455}
456
457impl<T: Copy + Default, const N: usize> FromIterator<T> for Short<T, N> {
458    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
459        let mut out = Self::default();
460        for v in iter {
461            assert!(out.len < N, "a list of more than {N} entries on the stack");
462            out.items[out.len] = v;
463            out.len += 1;
464        }
465        out
466    }
467}
468
469impl<T, const N: usize> IntoIterator for Short<T, N> {
470    type Item = T;
471    type IntoIter = std::iter::Take<std::array::IntoIter<T, N>>;
472    fn into_iter(self) -> Self::IntoIter {
473        self.items.into_iter().take(self.len)
474    }
475}
476
477impl<'a, T, const N: usize> IntoIterator for &'a Short<T, N> {
478    type Item = &'a T;
479    type IntoIter = std::slice::Iter<'a, T>;
480    fn into_iter(self) -> Self::IntoIter {
481        self.iter()
482    }
483}
484
485impl<T, const N: usize> std::ops::Deref for Short<T, N> {
486    type Target = [T];
487    fn deref(&self) -> &[T] {
488        &self.items[..self.len]
489    }
490}
491
492impl<T, const N: usize> std::ops::DerefMut for Short<T, N> {
493    fn deref_mut(&mut self) -> &mut [T] {
494        &mut self.items[..self.len]
495    }
496}
497
498/// One value per cable (at most 8), per degree of freedom (at most 6), the structure matrix (n x m) and the mass matrix
499/// (n x n).
500type PerCable = Short<f64, 8>;
501type PerDof = Short<f64, 6>;
502type Structure = Short<f64, 48>;
503type MassMatrix = Short<f64, 36>;
504
505/// One cable at a pose: its length from the pulley's swivel point to the anchor (arc and straight part), the straight
506/// part, the unit vector from the anchor to the exit point, the exit point, and the anchor's offset b = R a.
507#[derive(Debug, Clone, Copy, Default)]
508pub struct Span {
509    pub length: f64,
510    pub straight: f64,
511    pub u: V3,
512    pub exit: V3,
513    pub b: V3,
514    /// The anchor's height over the pulley's swivel point, z_P - z_E.
515    pub dz: f64,
516}
517
518/// The pulley's plane for an anchor at `p` (world): its direction e_u, the anchor in it (P_u, P_w), and its distance m
519/// from the pulley's centre; `None` where the cable cannot be drawn (the anchor at its pulley).
520fn pulley_plane(c: &Cable, r: f64, p: V3) -> Option<(V3, f64, f64, f64)> {
521    let d = sub(p, c.exit);
522    let ey = c.ref_y;
523    let gamma = dot(d, ey).atan2(dot(d, c.ref_x));
524    let eu = add(scale(c.ref_x, gamma.cos()), scale(ey, gamma.sin()));
525    let (pu, pw) = (dot(d, eu), dot(d, c.axis));
526    let m = (pu - r).hypot(pw);
527    (m > r * (1.0 + 1e-9) && m > 1e-9).then_some((eu, pu, pw, m))
528}
529
530/// The pulley's geometry for an anchor at `p` (world).
531fn span(c: &Cable, r: f64, p: V3) -> Option<(f64, f64, V3, V3)> {
532    let (eu, pu, pw, m) = pulley_plane(c, r, p)?;
533    let straight = (m * m - r * r).sqrt();
534    let theta = pw.atan2(pu - r) - (r / m).acos();
535    let beta = (theta - PI).rem_euclid(TAU);
536    let exit = add(c.exit, add(scale(eu, r + r * theta.cos()), scale(c.axis, r * theta.sin())));
537    Some((r * beta + straight, straight, scale(sub(exit, p), 1.0 / straight), exit))
538}
539
540#[derive(Clone)]
541pub struct CableRobot {
542    spatial: bool,
543    /// The platform's degrees of freedom among (x, y, z, wx, wy, wz).
544    dofs: Vec<usize>,
545    cables: Vec<Cable>,
546    pulley: f64,
547    ea: f64,
548    /// The cable's mass per metre, kg/m (0: its weight and sag are left out).
549    rope: f64,
550    /// effects.cable_inertia: the cable's mass that runs along itself at the drum's speed l', rho times
551    /// `winch.capacity_m` (in `drum_mass`), kg; 0 without it.
552    cable_moving: f64,
553    /// effects.cable_inertia: each cable's run from its drum D to its pulley's swivel point E along the winch's direction,
554    /// D = E + r axis (`frame.run_lengths_m`), m; 0 without it. Its mass rho r runs at the drum's speed (in `drum_mass`),
555    /// and the cable paid out is lifted from the drum's height to the pulley's, h = z_E - z_D (`drop`).
556    runs: Vec<f64>,
557    /// Each winch's spin axis (unit), about which the drum and the rotor turn.
558    spin: Vec<V3>,
559    damping: f64,
560    t_min: f64,
561    t_max: f64,
562    t_ref: f64,
563    mass: f64,
564    payload: f64,
565    attached: bool,
566    inertia: M3,
567    /// The anchors' largest distance from the centre: the length that weighs turns against travels.
568    size: f64,
569    g: f64,
570    elastic: bool,
571    winches: Vec<RotaryJoint>,
572    /// Per winch the mass at its cable: the drum's J / r^2, with effects.cable_inertia and the cable's mass the cable
573    /// running at the drum's speed too, rho (capacity + run).
574    drum_mass: Vec<f64>,
575    drum_radius: f64,
576    thermal: Option<ThermalFeedback>,
577    brake_engaged: bool,
578    /// An obstacle's push on the platform, per axis (`Machine::set_tool_force`), held until changed; empty for none.
579    push: Vec<f64>,
580    axes: Vec<AxisInfo>,
581    motors: Vec<MotorInfo>,
582    /// The pose Gauss-Newton starts from: the centre of the tool's box.
583    home: Vec<f64>,
584    frame: Vec<V3>,
585    /// `rest_sag`, once asked for.
586    rest_slack: std::sync::OnceLock<f64>,
587    /// The elastic `forward` at the last grid point of free lengths (`ANCHOR_STEP`) and its Jacobian there: Newton
588    /// starts there.
589    last_forward: LastForward,
590    /// The motor torques of the last `base_signals`, for the scene's tension labels (`scene` has no torque argument).
591    last_torque: LastTorque,
592}
593
594/// The grid of free lengths the elastic `forward`'s Newton starts from, m: from the nearest point, so the pose is a
595/// function of the motor angles alone, whatever was called before (a run, its replay and a perturbed run give the same
596/// numbers). The controller asks for the setpoint's and the actual pose every position cycle, micrometres apart.
597const ANCHOR_STEP: f64 = 1e-3;
598
599/// The elastic `forward` at a grid point: its index (free lengths over `ANCHOR_STEP`), the pose it found, and the
600/// Jacobian of its residual it took the last step with (n x n); behind a lock (`Machine` is `Send`, `forward` takes
601/// `&self`).
602#[derive(Debug, Clone)]
603struct Forwarded {
604    key: Short<i64, 8>,
605    pose: PerDof,
606    jacobian: MassMatrix,
607}
608
609#[derive(Debug, Default)]
610struct LastForward(std::sync::Mutex<Option<Forwarded>>);
611
612impl LastForward {
613    fn get(&self) -> Option<Forwarded> {
614        self.0.lock().ok().and_then(|f| f.clone())
615    }
616    fn set(&self, last: Option<Forwarded>) {
617        if let Ok(mut f) = self.0.lock() {
618            *f = last;
619        }
620    }
621}
622
623impl Clone for LastForward {
624    fn clone(&self) -> Self {
625        Self(std::sync::Mutex::new(self.get()))
626    }
627}
628
629/// The torques the signals were last computed with, behind a lock like `LastForward`.
630#[derive(Debug, Default)]
631struct LastTorque(std::sync::Mutex<Vec<f64>>);
632
633impl Clone for LastTorque {
634    fn clone(&self) -> Self {
635        Self(std::sync::Mutex::new(self.0.lock().map(|t| t.clone()).unwrap_or_default()))
636    }
637}
638
639/// Per cable of one moment: tension on the platform, on the drum, and the damper's share of it.
640struct Tensions {
641    platform: PerCable,
642    drum: PerCable,
643    damper: PerCable,
644}
645
646impl CableRobot {
647    pub fn new(cfg: &Config) -> Result<Self, ConfigError> {
648        let spatial = cfg.bool("platform.spatial")?;
649        let dofs: Vec<usize> = if spatial { (0..6).collect() } else { vec![0, 2] };
650        let n = dofs.len();
651        let rows = |key: &str| -> Result<Vec<V3>, ConfigError> {
652            let invalid = || ConfigError::Invalid(key.into());
653            cfg.array(key)?
654                .iter()
655                .map(|v| {
656                    let row: Vec<f64> = v.as_array().ok_or_else(invalid)?.iter().filter_map(|x| x.as_float()).collect();
657                    (row.len() == 3).then(|| [row[0], row[1], row[2]]).ok_or_else(invalid)
658                })
659                .collect()
660        };
661        let exits = rows("frame.exits_m")?;
662        let directions = rows("frame.winch_directions")?;
663        let m = exits.len();
664        if !(n + 1..=8).contains(&m) || directions.len() != m {
665            return Err(ConfigError::Invalid("frame.exits_m".into()));
666        }
667        let anchors = if spatial { rows("platform.anchors_m")? } else { vec![[0.0; 3]; m] };
668        if anchors.len() != m {
669            return Err(ConfigError::Invalid("platform.anchors_m".into()));
670        }
671        let centre = scale(exits.iter().fold([0.0; 3], |s, e| add(s, *e)), 1.0 / m as f64);
672        let mut cables = Vec::new();
673        for k in 0..m {
674            let axis = scale(directions[k], 1.0 / norm(directions[k]));
675            let inward = sub(centre, exits[k]);
676            let flat = sub(inward, scale(axis, dot(inward, axis)));
677            if !(norm(flat) > 1e-9) || !axis.iter().all(|v| v.is_finite()) {
678                return Err(ConfigError::Invalid("frame.winch_directions".into()));
679            }
680            let ref_x = scale(flat, 1.0 / norm(flat));
681            cables.push(Cable { exit: exits[k], axis, ref_x, ref_y: cross(axis, ref_x), anchor: anchors[k] });
682        }
683        let t_min = cfg.non_negative("cable.min_tension_n")?;
684        let t_max = cfg.positive("cable.breaking_load_n")? / cfg.positive("cable.safety_factor")?;
685        let t_ref = cfg.positive("cable.reference_tension_n")?;
686        if !(t_min < t_ref && t_ref < t_max) {
687            return Err(ConfigError::Invalid("cable.reference_tension_n".into()));
688        }
689        let diag = if spatial { cfg.f64s("platform.inertia_kgm2")? } else { vec![1.0; 3] };
690        if diag.len() != 3 || diag.iter().any(|v| !(*v > 0.0)) {
691            return Err(ConfigError::Invalid("platform.inertia_kgm2".into()));
692        }
693        let inertia = std::array::from_fn(|i| std::array::from_fn(|j| if i == j { diag[i] } else { 0.0 }));
694        // Each winch: the drum's radius as the lever behind the gearbox, no give of its own (the cable's is apart).
695        let drum_radius = cfg.positive("winch.drum_radius_m")?;
696        let on = cfg.bool("effects.winch_friction")?;
697        let friction = ShaftFriction {
698            coulomb: if on { cfg.non_negative("winch.friction_coulomb_n")? } else { 0.0 },
699            viscous: if on { cfg.non_negative("winch.friction_viscous_n_s_m")? } else { 0.0 },
700            smoothing: cfg.positive("winch.friction_smoothing_m_s")?,
701            ..ShaftFriction::NONE
702        };
703        let stops = if cfg.bool("effects.hard_stops")? {
704            HardStop {
705                stiffness: cfg.positive("winch.stop_stiffness_n_m")?,
706                damping: cfg.non_negative("winch.stop_damping_n_s_m")?,
707            }
708        } else {
709            HardStop { stiffness: 0.0, damping: 0.0 }
710        };
711        let mut winch = RotaryJoint::with(cfg, friction, stops, (0.0, cfg.positive("winch.capacity_m")?))?;
712        let drum_mass = cfg.positive("winch.drum_inertia_kgm2")? / (drum_radius * drum_radius);
713        // The cap on the gear's mesh-friction bristle takes the lighter of the rotor (seen at the cable) and the drum.
714        Converter {
715            lever: drum_radius,
716            stiffness: f64::INFINITY,
717            backlash: 0.0,
718            efficiency: 1.0,
719            inertia: 0.0,
720            damping_ratio: 0.0,
721        }
722        .apply_to(cfg, &mut winch, drum_mass)?;
723        let (min, max) = (cfg.f64s("workspace.tool_min")?, cfg.f64s("workspace.tool_max")?);
724        if min.len() != n || max.len() != n || (0..n).any(|k| !(min[k] < max[k])) {
725            return Err(ConfigError::Invalid("workspace.tool_max".into()));
726        }
727        let axes = (0..n)
728            .map(|k| {
729                let id = AXIS_IDS[dofs[k]];
730                let unit = if dofs[k] < 3 { "m" } else { "rad" };
731                let get = |what: &str, rate: &str| cfg.positive(&format!("axis.{id}.max_{what}_{unit}_{rate}"));
732                Ok(AxisInfo {
733                    id,
734                    key: AXIS_KEYS[dofs[k]],
735                    unit,
736                    min: min[k],
737                    max: max[k],
738                    max_vel: get("velocity", "s")?,
739                    max_acc: get("acceleration", "s2")?,
740                    max_jerk: get("jerk", "s3")?,
741                })
742            })
743            .collect::<Result<Vec<_>, ConfigError>>()?;
744        let mass = cfg.positive("platform.mass_kg")?;
745        let payload = if cfg.bool("effects.payload")? { cfg.non_negative("platform.payload_kg")? } else { 0.0 };
746        let rope = if cfg.get("cable.mass_per_m_kg").is_ok() { cfg.non_negative("cable.mass_per_m_kg")? } else { 0.0 };
747        // effects.cable_inertia: the cable runs along itself at the drum's speed l', the turns on the drum with it at its
748        // radius and the paid-out cable along its run and span: all of it, the drum's `winch.capacity_m` (from its end
749        // on the drum to the anchor; the fixed run from the drum to the pulley left out), is a constant mass at the
750        // cable as the drum's J / r^2 is. A config without the switch reads it as off.
751        let cable_moving = if cfg.get("effects.cable_inertia").is_ok() && cfg.bool("effects.cable_inertia")? {
752            rope * cfg.positive("winch.capacity_m")?
753        } else {
754            0.0
755        };
756        // effects.cable_inertia: the runs from the drums to the pulleys ([estimate] lengths, one per cable).
757        let runs = if cable_moving > 0.0 {
758            let runs = cfg.f64s("frame.run_lengths_m")?;
759            if runs.len() != m || runs.iter().any(|r| !(*r >= 0.0)) {
760                return Err(ConfigError::Invalid("frame.run_lengths_m".into()));
761            }
762            runs
763        } else {
764            vec![0.0; m]
765        };
766        // The winches' spin axes: `frame.winch_spin_axes` (one row per cable), or where it is empty or left out the
767        // horizontal axis square to the cable's direction at the winch, axis x e_z (for a vertical cable the pulley's
768        // own square direction, which is the plane's normal on the planar robot).
769        let given = if cfg.get("frame.winch_spin_axes").is_ok() { rows("frame.winch_spin_axes")? } else { Vec::new() };
770        if !given.is_empty() && (given.len() != m || given.iter().any(|a| !(norm(*a) > 1e-9))) {
771            return Err(ConfigError::Invalid("frame.winch_spin_axes".into()));
772        }
773        let spin: Vec<V3> = if given.is_empty() {
774            cables
775                .iter()
776                .map(|c| {
777                    let h = cross(c.axis, [0.0, 0.0, 1.0]);
778                    let h = if norm(h) > 1e-9 { h } else { c.ref_y };
779                    scale(h, 1.0 / norm(h))
780                })
781                .collect()
782        } else {
783            given.iter().map(|a| scale(*a, 1.0 / norm(*a))).collect()
784        };
785        let robot = Self {
786            rope,
787            cable_moving,
788            runs: runs.clone(),
789            spin,
790            spatial,
791            size: anchors.iter().map(|a| norm(*a)).fold(0.0, f64::max).max(0.1),
792            dofs,
793            cables,
794            pulley: cfg.positive("pulley.radius_m")?,
795            ea: cfg.positive("cable.ea_n")?,
796            damping: if cfg.bool("effects.cable_damping")? {
797                cfg.non_negative("cable.specific_damping_n_s")?
798            } else {
799                0.0
800            },
801            t_min,
802            t_max,
803            t_ref,
804            mass,
805            payload,
806            attached: true,
807            inertia,
808            g: if cfg.bool("effects.gravity")? { G } else { 0.0 },
809            elastic: cfg.bool("effects.cable_stretch")?,
810            winches: vec![winch; m],
811            drum_mass: runs.iter().map(|r| drum_mass + cable_moving + rope * r).collect(),
812            drum_radius,
813            thermal: ThermalFeedback::from_config(cfg)?,
814            brake_engaged: false,
815            push: Vec::new(),
816            axes,
817            motors: (0..m).map(|k| MotorInfo { id: MOTOR_IDS[k], key: MOTOR_KEYS[k] }).collect(),
818            home: (0..n).map(|k| 0.5 * (min[k] + max[k])).collect(),
819            frame: exits,
820            rest_slack: std::sync::OnceLock::new(),
821            last_forward: LastForward::default(),
822            last_torque: LastTorque::default(),
823        };
824        let mut torque = vec![0.0; m];
825        robot.equilibrium(&robot.home, &mut Vec::new(), &mut torque);
826        if !torque.iter().all(|t| t.is_finite()) {
827            return Err(ConfigError::Invalid("workspace.tool_min".into()));
828        }
829        Ok(robot)
830    }
831
832    /// How far the tool can be from where the motors' angles put it at rest anywhere in the tool's box, payload on or
833    /// off: the gearboxes twisted (with half their backlash) under the cables' tensions, as `equilibrium` sets them up,
834    /// through the forward kinematics; over the box's corners, edges, faces and centre (each axis at its two ends and
835    /// its middle). The cables hold the platform's turns weakly near the box's edges, and the twist of a few um of
836    /// cable turns it there by up to 0.42 mrad (at the end of x, turned 0.05 rad about z; 0.46 mrad on a grid of five
837    /// a side). Plus a tenth for what the grid steps over; at least the default 0.1 mm.
838    fn rest_sag(&mut self) -> f64 {
839        let (n, m) = (self.n(), self.m());
840        let mut most = 0f64;
841        for attached in [true, false] {
842            self.attached = attached;
843            for k in 0..3usize.pow(n as u32) {
844                let pose: Vec<f64> = (0..n)
845                    .map(|i| {
846                        let a = &self.axes[i];
847                        a.min + (a.max - a.min) * ((k / 3usize.pow(i as u32)) % 3) as f64 / 2.0
848                    })
849                    .collect();
850                if self.unreachable(&pose, 0.0).is_some() {
851                    continue;
852                }
853                let (mut state, mut torque) = (Vec::new(), vec![0.0; m]);
854                let (mut motors, mut speed, mut tool) = (vec![0.0; m], vec![0.0; m], vec![0.0; n]);
855                self.equilibrium(&pose, &mut state, &mut torque);
856                self.motor_state(&state, &mut motors, &mut speed);
857                self.forward(&motors, &mut tool);
858                most = (0..n).map(|i| (tool[i] - pose[i]).abs()).fold(most, f64::max);
859            }
860        }
861        self.attached = true;
862        (1.1 * most).max(1e-4)
863    }
864
865    fn n(&self) -> usize {
866        self.dofs.len()
867    }
868    fn m(&self) -> usize {
869        self.cables.len()
870    }
871    fn moving(&self) -> f64 {
872        self.mass + if self.attached { self.payload } else { 0.0 }
873    }
874
875    /// Position and rotation of a pose.
876    fn place(&self, pose: &[f64]) -> (V3, M3) {
877        let mut full = [0.0; 6];
878        for (k, d) in self.dofs.iter().enumerate() {
879            full[*d] = pose[k];
880        }
881        ([full[0], full[1], full[2]], exp([full[3], full[4], full[5]]))
882    }
883
884    /// The pose moved by a twist step `step` (in the degrees of freedom): p + v, exp(w) R.
885    fn moved(&self, pose: &[f64], step: &[f64]) -> PerDof {
886        if !self.spatial {
887            return pose.iter().zip(step).map(|(a, b)| a + b).collect();
888        }
889        let r = log(&matmul(&exp([step[3], step[4], step[5]]), &exp([pose[3], pose[4], pose[5]])));
890        PerDof::from_iter([pose[0] + step[0], pose[1] + step[1], pose[2] + step[2], r[0], r[1], r[2]])
891    }
892
893    /// The full twist (v, w) of one in the degrees of freedom.
894    fn full(&self, xi: &[f64]) -> (V3, V3) {
895        let mut f = [0.0; 6];
896        for (k, d) in self.dofs.iter().enumerate() {
897            f[*d] = xi[k];
898        }
899        ([f[0], f[1], f[2]], [f[3], f[4], f[5]])
900    }
901
902    /// The cables at a pose; `None` where one cannot be drawn (the anchor at its pulley).
903    pub fn spans(&self, pose: &[f64]) -> Option<Short<Span, 8>> {
904        let (p, r) = self.place(pose);
905        self.spans_at(p, &r)
906    }
907
908    /// `spans` with the pose placed (`place`).
909    fn spans_at(&self, p: V3, r: &M3) -> Option<Short<Span, 8>> {
910        let mut out = Short::<Span, 8>::filled(self.m(), Span::default());
911        for (c, o) in self.cables.iter().zip(out.iter_mut()) {
912            let b = mul(r, c.anchor);
913            let anchor = add(p, b);
914            let (length, straight, u, exit) = span(c, self.pulley, anchor)?;
915            *o = Span { length, straight, u, exit, b, dz: anchor[2] - c.exit[2] };
916        }
917        Some(out)
918    }
919
920    /// The structure matrix A (n x m, row by row): column k is cable k's wrench per newton, (u, b x u) in the degrees
921    /// of freedom.
922    pub fn structure(&self, spans: &[Span]) -> Short<f64, 48> {
923        let (n, m) = (self.n(), self.m());
924        let mut a = Structure::zeros(n * m);
925        for (k, s) in spans.iter().enumerate() {
926            let moment = cross(s.b, s.u);
927            let full = [s.u[0], s.u[1], s.u[2], moment[0], moment[1], moment[2]];
928            for (r, d) in self.dofs.iter().enumerate() {
929                a[r * m + k] = full[*d];
930            }
931        }
932        a
933    }
934
935    /// The platform's mass matrix over its twist, in the degrees of freedom (n x n), with the cables' swing
936    /// (`swing_mass`).
937    fn platform_mass(&self, pose: &[f64]) -> MassMatrix {
938        let (p, r) = self.place(pose);
939        let spans = if self.cable_moving > 0.0 { self.spans_at(p, &r).unwrap_or_default() } else { Default::default() };
940        self.platform_mass_at(&r, &spans)
941    }
942
943    /// `platform_mass` at the pose's rotation `r` and the cables' `spans` there (not read without effects.cable_inertia).
944    fn platform_mass_at(&self, r: &M3, spans: &[Span]) -> MassMatrix {
945        let iw = matmul(&matmul(r, &self.inertia), &transpose(r));
946        let n = self.n();
947        let mut out = MassMatrix::zeros(n * n);
948        for (i, di) in self.dofs.iter().enumerate() {
949            for (j, dj) in self.dofs.iter().enumerate() {
950                out[i * n + j] = match (*di < 3, *dj < 3) {
951                    (true, true) if di == dj => self.moving(),
952                    (false, false) => iw[di - 3][dj - 3],
953                    _ => 0.0,
954                };
955            }
956        }
957        if self.cable_moving > 0.0 {
958            for s in spans {
959                let mu = self.rope * s.straight / 3.0;
960                // The anchor's velocity per twist component: e_i for v, e_i x b for w.
961                let column = |d: usize| -> V3 {
962                    let mut e = [0.0; 3];
963                    e[d % 3] = 1.0;
964                    if d < 3 { e } else { cross(e, s.b) }
965                };
966                for (i, di) in self.dofs.iter().enumerate() {
967                    let ci = column(*di);
968                    for (j, dj) in self.dofs.iter().enumerate() {
969                        let cj = column(*dj);
970                        out[i * n + j] += mu * (dot(ci, cj) - dot(ci, s.u) * dot(cj, s.u));
971                    }
972                }
973            }
974        }
975        out
976    }
977
978    /// With effects.cable_inertia, the cables' swing across themselves: each straight span pivots at its exit point, its
979    /// sections at s / l_f of the anchor's speed across the cable, v_P - u (u . v_P), so it carries
980    /// T = mu |v_perp|^2 / 2 with mu = rho l_f / 3: a mass M = mu (1 - u u^T) at the anchor that changes with its place
981    /// (`swing_mass` in `platform_mass_at`). Its velocity terms by Lagrange on the anchor P as a particle,
982    /// F = M a + M' v - grad_P (v^T M v) / 2 with a = J xi' + w x (w x b): M' v = mu' v_perp - mu (u' (u . v) + u (u' . v)),
983    /// mu' = rho / 3 grad l_f . v, u' = grad u v, and grad_P (v^T M v) / 2 = rho / 6 grad l_f |v_perp|^2 - mu (u . v)
984    /// grad u^T v (`span_gradients`); the wrench (F, b x F) without M J xi' in the degrees of freedom.
985    fn swing_bias(&self, spans: &[Span], xi: &[f64]) -> PerDof {
986        let mut full = [0.0; 6];
987        let (v, w) = self.full(xi);
988        for (k, s) in spans.iter().enumerate() {
989            let Some((grad_lf, grad_u)) = self.span_gradients(k, s) else { continue };
990            let vp = add(v, cross(w, s.b));
991            let mu = self.rope * s.straight / 3.0;
992            let along = dot(s.u, vp);
993            let across = sub(vp, scale(s.u, along));
994            let turn: V3 = std::array::from_fn(|i| dot(grad_u[i], vp));
995            let back: V3 = std::array::from_fn(|j| (0..3).map(|i| grad_u[i][j] * vp[i]).sum());
996            let mu_rate = self.rope / 3.0 * dot(grad_lf, vp);
997            let centripetal = cross(w, cross(w, s.b));
998            let at_rest = sub(centripetal, scale(s.u, dot(s.u, centripetal)));
999            let f: V3 = std::array::from_fn(|i| {
1000                mu * at_rest[i] + mu_rate * across[i]
1001                    - mu * (turn[i] * along + s.u[i] * dot(turn, vp))
1002                    - self.rope / 6.0 * grad_lf[i] * dot(across, across)
1003                    + mu * along * back[i]
1004            });
1005            let moment = cross(s.b, f);
1006            (0..3).for_each(|i| (full[i], full[3 + i]) = (full[i] + f[i], full[3 + i] + moment[i]));
1007        }
1008        self.dofs.iter().map(|d| full[*d]).collect()
1009    }
1010
1011    /// What the cables have to give the platform besides its acceleration: c + g = (0, 0, m g, w x I_w w), and the
1012    /// cables' weight of the rigid model (`cable_weight`).
1013    fn platform_bias(&self, pose: &[f64], xi: &[f64]) -> PerDof {
1014        let (p, r) = self.place(pose);
1015        // The cables' weight needs the spans; without it (rope 0) they are not looked at.
1016        match if self.rope > 0.0 { self.spans_at(p, &r) } else { Some(Default::default()) } {
1017            Some(spans) => self.platform_bias_at(&r, &spans, None, xi),
1018            None => PerDof::filled(self.n(), f64::NAN),
1019        }
1020    }
1021
1022    /// `platform_bias` at the pose's rotation `r`, with the cables `spans` there (not read where the cables have no
1023    /// mass) and, elastic, their free lengths `free` (`cable_weight`).
1024    fn platform_bias_at(&self, r: &M3, spans: &[Span], free: Option<&[f64]>, xi: &[f64]) -> PerDof {
1025        let (_, w) = self.full(xi);
1026        let iw = matmul(&matmul(r, &self.inertia), &transpose(r));
1027        let gyro = cross(w, mul(&iw, w));
1028        let full = [0.0, 0.0, self.moving() * self.g, gyro[0], gyro[1], gyro[2]];
1029        let mut bias: PerDof = self.dofs.iter().map(|d| full[*d]).collect();
1030        bias.iter_mut().zip(self.cable_weight(spans, free).0).for_each(|(b, c)| *b += c);
1031        if self.cable_moving > 0.0 {
1032            bias.iter_mut().zip(self.swing_bias(spans, xi)).for_each(|(b, c)| *b += c);
1033        }
1034        bias
1035    }
1036
1037    /// How far cable `k`'s drum sits below its pulley's swivel point, z_E - z_D (`runs`; negative for a drum above it).
1038    fn drop(&self, k: usize) -> f64 {
1039        -self.runs[k] * self.cables[k].axis[2]
1040    }
1041
1042    /// The cables' own weight (`rope` > 0): the wrench in the degrees of freedom that the platform's equation takes, and
1043    /// the potential V. A span's mass hangs at the height of its middle, V = rho g l (z_P - z_E) / 2 with l the cable in
1044    /// it: elastic, its free length, a state of its own, so the anchor takes the force rho g l / 2 e_z (half the span's
1045    /// weight; the exact elastic catenary agrees to 7e-5 N, see the tests) and the drum -dV/dl = -rho g (z_P - z_E) / 2
1046    /// (`tensions`); rigid, l = L(pose) and the tension t is the one at the drum, so dL/dP = -u brings that share to the
1047    /// anchor: the force rho g / 2 (L e_z - (z_P - z_E) u). Each with its moment b x f.
1048    fn cable_weight(&self, spans: &[Span], free: Option<&[f64]>) -> (PerDof, f64) {
1049        let mut full = [0.0; 6];
1050        let mut potential = 0.0;
1051        if self.rope > 0.0 {
1052            let half = 0.5 * self.rope * self.g;
1053            for (k, s) in spans.iter().enumerate() {
1054                // The cable paid out has come up from the drum to the pulley, `drop` higher: rho g h l.
1055                let (dz, lift) = (s.dz, self.rope * self.g * self.drop(k));
1056                let f = match free {
1057                    Some(l) => {
1058                        potential += (half * dz + lift) * l[k];
1059                        [0.0, 0.0, half * l[k]]
1060                    }
1061                    None => {
1062                        potential += (half * dz + lift) * s.length;
1063                        let along = half * dz + lift;
1064                        [-along * s.u[0], -along * s.u[1], half * s.length - along * s.u[2]]
1065                    }
1066                };
1067                let moment = cross(s.b, f);
1068                (0..3).for_each(|i| {
1069                    full[i] += f[i];
1070                    full[3 + i] += moment[i];
1071                });
1072            }
1073        }
1074        (self.dofs.iter().map(|d| full[*d]).collect(), potential)
1075    }
1076
1077    /// The sag constant c = (w l_h)^2 EA l_f / (12 L) of a cable (`sagged`): w its weight per metre, l_f its straight
1078    /// span, l_h that span's horizontal part, L its whole length.
1079    fn sag(&self, s: &Span) -> f64 {
1080        let w = self.rope * self.g;
1081        (w * s.straight * s.u[0].hypot(s.u[1])).powi(2) * self.ea * s.straight / (12.0 * s.length)
1082    }
1083
1084    /// The sagging cables' pull beyond their chords, as the wrench in the degrees of freedom the platform's equation
1085    /// takes (elastic, `rope` > 0; zero otherwise): the cable's energy (l / EA) W(t0, c) changes with the sag constant c
1086    /// over the anchor's place too (the span's horizontal part and its length), and dW/dc = -1 / (2 T) at a fixed t0
1087    /// (T^3 - t0 T^2 - c / 2 = 0 gives dT/dc = T / (2 (T^3 + c))), so the anchor takes F = l / (2 EA T) grad_P c, with
1088    /// its moment b x F (`sag_gradient`). About (w l_h)^2 l / (12 T l_h): 5e-5 N at 10 g/m and 20 N, where the at-rest
1089    /// tensions settle to 1e-11 N.
1090    fn sag_pull(&self, spans: &[Span], free: &[f64], tension: &[f64]) -> PerDof {
1091        let mut full = [0.0; 6];
1092        if !(self.elastic && self.rope > 0.0) {
1093            return PerDof::zeros(self.n());
1094        }
1095        for (k, s) in spans.iter().enumerate() {
1096            if !(tension[k] > 0.0) {
1097                continue;
1098            }
1099            let Some(gradient) = self.sag_gradient(k, s) else { continue };
1100            let f = scale(gradient, free[k] / (2.0 * self.ea * tension[k]));
1101            let moment = cross(s.b, f);
1102            (0..3).for_each(|i| (full[i], full[3 + i]) = (full[i] + f[i], full[3 + i] + moment[i]));
1103        }
1104        self.dofs.iter().map(|d| full[*d]).collect()
1105    }
1106
1107    /// The gradient over the anchor's place of cable `k`'s sag constant c = (w l_h)^2 EA l_f / (12 L) at its span `s`,
1108    /// c (2 grad l_h / l_h + grad l_f / l_f - grad L / L); `None` where c is 0. grad L = -u. The straight part
1109    /// l_f = sqrt(m^2 - r^2), m the anchor's distance q from the pulley's centre M; the pulley swivels so that its plane
1110    /// holds the anchor and M moves across that plane only, so grad m = q / m and grad l_f = q / l_f. The cable's
1111    /// direction u turns by -n (dP . n) / l_f for a step dP along the plane's normal n to it (the tangent point slides
1112    /// along u), and with the swivel, d gamma = dP . e_v / P_u (e_v = e_z x e_u, P_u the anchor's distance from the
1113    /// swivel's axis), about the axis: grad u = -n n^T / l_f + (e_z x u) e_v^T / P_u. l_h = l_f |u_h| (u_h u's
1114    /// horizontal part) has grad l_h = |u_h| grad l_f + l_f (u_x grad u_x + u_y grad u_y) / |u_h|.
1115    fn sag_gradient(&self, k: usize, s: &Span) -> Option<V3> {
1116        let (c, horizontal) = (self.sag(s), s.u[0].hypot(s.u[1]));
1117        if !(c > 0.0 && horizontal > 0.0) {
1118            return None;
1119        }
1120        let (straight, [dx, dy, _]) = self.span_gradients(k, s)?;
1121        let level: V3 = std::array::from_fn(|j| {
1122            horizontal * straight[j] + s.straight * (s.u[0] * dx[j] + s.u[1] * dy[j]) / horizontal
1123        });
1124        let level_h = s.straight * horizontal;
1125        Some(std::array::from_fn(|j| c * (2.0 * level[j] / level_h + straight[j] / s.straight + s.u[j] / s.length)))
1126    }
1127
1128    /// The gradients over the anchor's place of cable `k`'s straight part l_f and of its direction u (the rows d u_i / dP)
1129    /// at its span `s` (`sag_gradient`): grad l_f = q / l_f, grad u = -n n^T / l_f + (e_z x u) e_v^T / P_u.
1130    fn span_gradients(&self, k: usize, s: &Span) -> Option<(V3, [V3; 3])> {
1131        let cable = &self.cables[k];
1132        let anchor = sub(s.exit, scale(s.u, s.straight));
1133        let (eu, pu, ..) = pulley_plane(cable, self.pulley, anchor)?;
1134        let straight = scale(sub(anchor, add(cable.exit, scale(eu, self.pulley))), 1.0 / s.straight);
1135        let ev = cross(cable.axis, eu);
1136        let (n, turn) = (cross(ev, s.u), cross(cable.axis, s.u));
1137        let du = |i: usize| -> V3 { std::array::from_fn(|j| -n[i] * n[j] / s.straight + turn[i] * ev[j] / pu) };
1138        Some((straight, [du(0), du(1), du(2)]))
1139    }
1140
1141    /// The free length of a cable that holds the tension `t` at the length L of `s`: l = L / (1 + t0 / EA), t0 the straight
1142    /// cable's tension of the same strain (`unsagged`).
1143    fn free_for(&self, s: &Span, t: f64) -> f64 {
1144        s.length / (1.0 + unsagged(t, self.sag(s)) / self.ea)
1145    }
1146
1147    /// What the spring of tension `spring` (straight-cable tension `t0`, sag constant `c`, stretch `e` = L - l of the
1148    /// free length `l`) pulls the drum with: minus the derivative of its energy over l, t L / l - W / EA; where there is
1149    /// no sag t (1 + e / (2 l)).
1150    fn drum_share(&self, spring: f64, t0: f64, c: f64, e: f64, l: f64) -> f64 {
1151        if c == 0.0 { spring * (1.0 + e / (2.0 * l)) } else { spring * (1.0 + e / l) - pull_work(t0, c) / self.ea }
1152    }
1153
1154    /// The energy in a cable's spring at the free length `l`: EA e^2 / (2 l) for e = L - l > 0, none slack; with sag
1155    /// (l / EA) W(t0), slack too.
1156    fn spring_energy(&self, s: &Span, l: f64) -> f64 {
1157        let c = self.sag(s);
1158        if c == 0.0 {
1159            let e = (s.length - l).max(0.0);
1160            0.5 * self.ea * e * e / l
1161        } else {
1162            l / self.ea * pull_work(self.ea * (s.length - l) / l, c)
1163        }
1164    }
1165
1166    /// The static wrench at a pose with the payload on, for the workspace: (0, 0, (m + payload) g), and the cables' own
1167    /// weight at that pose (the rigid model's).
1168    fn weight(&self, spans: &[Span]) -> Vec<f64> {
1169        let full = [0.0, 0.0, (self.mass + self.payload) * self.g, 0.0, 0.0, 0.0];
1170        let mut w: Vec<f64> = self.dofs.iter().map(|d| full[*d]).collect();
1171        w.iter_mut().zip(self.cable_weight(spans, None).0).for_each(|(b, c)| *b += c);
1172        w
1173    }
1174
1175    /// The tensions `solve` gives for the wrench of the platform at rest at a pose. Elastic with heavy cables that wrench
1176    /// holds the cables' free lengths, which the tensions set (`free_for`): from those of the reference tension, two
1177    /// rounds more take it to about 1e-11 N (each one by a factor of rho g L / (2 EA), 2e-7).
1178    fn at_rest(&self, spans: &[Span], pose: &[f64], solve: impl Fn(&[f64]) -> Option<Vec<f64>>) -> Option<Vec<f64>> {
1179        if !(self.elastic && self.rope > 0.0) {
1180            return solve(&self.platform_bias(pose, &vec![0.0; self.n()]));
1181        }
1182        let rot = self.place(pose).1;
1183        let mut t = vec![self.t_ref; self.m()];
1184        for _ in 0..3 {
1185            let free: Vec<f64> = spans.iter().zip(&t).map(|(s, t)| self.free_for(s, *t)).collect();
1186            let mut w = self.platform_bias_at(&rot, spans, Some(&free), &vec![0.0; self.n()]);
1187            w.iter_mut().zip(self.sag_pull(spans, &free, &t)).for_each(|(w, f)| *w -= f);
1188            t = solve(&w)?;
1189        }
1190        Some(t)
1191    }
1192
1193    /// The tensions that hold the platform at rest at a pose, by the distribution; `None` outside the wrench-feasible
1194    /// workspace.
1195    pub fn static_tensions(&self, pose: &[f64]) -> Option<Vec<f64>> {
1196        let spans = self.spans(pose)?;
1197        let a = self.structure(&spans);
1198        self.at_rest(&spans, pose, |w| distribute(&a, w, self.t_min, self.t_max, self.t_ref))
1199    }
1200
1201    /// The tensions the motors' angles count on at rest at a pose: the distribution's (`static_tensions`), which the
1202    /// feedforward and `equilibrium` ask too, so that the platform hangs at the pose on cables stretched by them
1203    /// (`forward`); the closed form t_ref + A^+ (w - A t_ref) without the band beyond the wrench-feasible workspace.
1204    /// The closed form alone, smoother in the pose, asked -8.7 N of cable 5 at (0.3, -0.2, 1.3) m turned (0.05, -0.03,
1205    /// 0.08): a slack cable, and the platform 1.5 mrad off. Where a cable reaches a bound the distribution has a kink
1206    /// in the pose, and the cables' speed setpoints one of L / EA times the jump in the tension's slope.
1207    fn rest_tensions(&self, spans: &[Span], pose: &[f64]) -> Option<Vec<f64>> {
1208        let a = self.structure(spans);
1209        let (n, m) = (self.n(), self.m());
1210        self.at_rest(spans, pose, |w| {
1211            if let Some(t) = distribute(&a, w, self.t_min, self.t_max, self.t_ref) {
1212                return Some(t);
1213            }
1214            let aat: Vec<f64> =
1215                (0..n * n).map(|rc| (0..m).map(|k| a[rc / n * m + k] * a[rc % n * m + k]).sum()).collect();
1216            let miss: Vec<f64> =
1217                (0..n).map(|r| w[r] - (0..m).map(|k| a[r * m + k] * self.t_ref).sum::<f64>()).collect();
1218            let y = solve(&aat, &miss)?;
1219            Some((0..m).map(|k| self.t_ref + (0..n).map(|r| a[r * m + k] * y[r]).sum::<f64>()).collect())
1220        })
1221    }
1222
1223    /// The cables' free lengths that the motors' angles stand for at a pose, l = L / (1 + t / EA) at `rest_tensions`
1224    /// where the cables stretch, l = L where they do not.
1225    fn rest_lengths(&self, pose: &[f64]) -> Option<Vec<f64>> {
1226        let spans = self.spans(pose)?;
1227        if !self.elastic {
1228            return Some(spans.iter().map(|s| s.length).collect());
1229        }
1230        let t = self.rest_tensions(&spans, pose)?;
1231        Some(spans.iter().zip(&t).map(|(s, t)| self.free_for(s, *t)).collect())
1232    }
1233
1234    /// `rest_lengths` inside the wrench-feasible workspace, `None` outside it.
1235    fn free_lengths(&self, pose: &[f64]) -> Option<Vec<f64>> {
1236        self.static_tensions(pose)?;
1237        self.rest_lengths(pose)
1238    }
1239
1240    /// `forward` from `warm`'s pose with its Jacobian (from the pose of the lengths without it): the Jacobian of the
1241    /// last step, `None` where it does not settle (the tool NaN).
1242    fn settle(&self, motors: &[f64], tool: &mut [f64], warm: Option<Forwarded>) -> Option<MassMatrix> {
1243        let (n, m) = (self.n(), self.m());
1244        let free: PerCable = (0..m).map(|k| motors[k] / self.winches[k].ratio()).collect();
1245        let stretch = if self.elastic { 1.0 + self.t_ref / self.ea } else { 1.0 };
1246        let stretched: PerCable = free.iter().map(|l| l * stretch).collect();
1247        let (start, mut chord) = match warm {
1248            Some(last) => (Some(last.pose), Some(last.jacobian)),
1249            None => (self.pose_of_lengths(&stretched, &self.home), None),
1250        };
1251        let Some(mut pose) = start else {
1252            tool[..n].fill(f64::NAN);
1253            return None;
1254        };
1255        if !self.elastic {
1256            tool[..n].copy_from_slice(&pose);
1257            return Some(MassMatrix::default());
1258        }
1259        let at_rest = PerCable::zeros(m);
1260        let residual = |pose: &[f64]| -> Option<PerDof> {
1261            let (p, rot) = self.place(pose);
1262            let spans = self.spans_at(p, &rot)?;
1263            let t = self.tensions(&spans, &at_rest, &free, &at_rest).platform;
1264            let (a, w) = (self.structure(&spans), self.platform_bias_at(&rot, &spans, Some(&free), &at_rest[..n]));
1265            let pull = self.sag_pull(&spans, &free, &t);
1266            Some((0..n).map(|r| (0..m).map(|k| a[r * m + k] * t[k]).sum::<f64>() + pull[r] - w[r]).collect())
1267        };
1268        // The potential the equilibrium is the least of: the platform's and the cables' weight and the taut cables'
1269        // springs.
1270        let energy = |pose: &[f64]| -> Option<f64> {
1271            let (p, rot) = self.place(pose);
1272            let spans = self.spans_at(p, &rot)?;
1273            let springs = spans.iter().zip(&free).map(|(s, l)| self.spring_energy(s, *l));
1274            Some(springs.sum::<f64>() + self.moving() * self.g * p[2] + self.cable_weight(&spans, Some(&free)).1)
1275        };
1276        let size = |v: &[f64]| v.iter().map(|x| x * x).sum::<f64>().sqrt();
1277        for _ in 0..50 {
1278            let Some(miss) = residual(&pose) else { break };
1279            let (jacobian, cached) = match chord.take() {
1280                Some(jacobian) => (jacobian, true),
1281                None => {
1282                    let mut jacobian = MassMatrix::zeros(n * n);
1283                    for c in 0..n {
1284                        let mut step = PerDof::zeros(n);
1285                        step[c] = 1e-7;
1286                        let up = residual(&self.moved(&pose, &step));
1287                        step[c] = -1e-7;
1288                        let down = residual(&self.moved(&pose, &step));
1289                        let (Some(up), Some(down)) = (up, down) else { break };
1290                        (0..n).for_each(|r| jacobian[r * n + c] = (up[r] - down[r]) / 2e-7);
1291                    }
1292                    (jacobian, false)
1293                }
1294            };
1295            // The residual is the potential's slope taken back, so a step downhill has a positive product with it. Where
1296            // Newton's is not (every cable slack, the Jacobian zero), the longest step along the residual, halved below.
1297            let downhill = |step: &PerDof| (0..n).map(|r| step[r] * miss[r]).sum::<f64>() > 0.0;
1298            // `solve` on copies, which are the stack's here.
1299            let newton = {
1300                let (mut a, mut x) = (jacobian, miss.iter().map(|v| -v).collect::<PerDof>());
1301                solve_in_place(&mut a, &mut x).then_some(x)
1302            }
1303            .filter(downhill);
1304            // The last call's Jacobian whose step is not downhill: this pose's own, in the next round.
1305            if cached && newton.is_none() {
1306                continue;
1307            }
1308            let mut step = newton.unwrap_or_else(|| {
1309                let most = miss.iter().fold(0.0f64, |s, v| s.max(v.abs()));
1310                miss.iter().map(|v| v * 0.05 / most).collect()
1311            });
1312            let longest = step.iter().fold(0.0f64, |s, v| s.max(v.abs()));
1313            if longest > 0.05 {
1314                step.iter_mut().for_each(|v| *v *= 0.05 / longest);
1315            }
1316            if longest < 1e-12 {
1317                tool[..n].copy_from_slice(&self.moved(&pose, &step));
1318                return Some(jacobian);
1319            }
1320            // A step is taken where it lowers the potential, or, near the equilibrium where the potential changes by
1321            // less than its rounding, where it shrinks the residual and does not raise the potential beyond that.
1322            let Some(here) = energy(&pose) else { break };
1323            let mut next = None;
1324            for _ in 0..30 {
1325                let trial = self.moved(&pose, &step);
1326                let (lower, smaller) = (
1327                    energy(&trial).map(|e| (e < here, e <= here + 1e-12 * (1.0 + here.abs()))),
1328                    residual(&trial).is_some_and(|r| size(&r) < size(&miss)),
1329                );
1330                if lower.is_some_and(|(lower, level)| lower || level && smaller) {
1331                    next = Some(trial);
1332                    break;
1333                }
1334                step.iter_mut().for_each(|v| *v *= 0.5);
1335            }
1336            match next {
1337                Some(next) => {
1338                    pose = next;
1339                    chord = cached.then_some(jacobian);
1340                }
1341                // The last call's Jacobian whose step helps nothing: this pose's own, in the next round.
1342                None if cached => {}
1343                // The residual at its rounding floor: no step helps any more.
1344                None => {
1345                    tool[..n].copy_from_slice(&pose);
1346                    return Some(jacobian);
1347                }
1348            }
1349        }
1350        tool[..n].fill(f64::NAN);
1351        None
1352    }
1353
1354    /// The pose whose cables are `lengths` long (pulley to anchor): Gauss-Newton through G = -A^T from `start`, no step
1355    /// longer than 50 mm or 50 mrad, until a step is below 1e-14, or the steps still to come add up to less than 1e-14;
1356    /// `None` where it does not settle within 100 steps. Lengths that no pose fits exactly give the pose that fits them
1357    /// best: there the misfit r = L - l leaves a residual, and Gauss-Newton, which leaves out the misfit's curvature
1358    /// sum r_k d2L_k, slows down (by 0.97 a step at 12 mm off, the motors of a weak drive's run 2.5 rad behind); once a
1359    /// step shrinks by less than half, Newton steps on the misfit's gradient -A r take over, its Hessian by central
1360    /// differences of the gradient (0.1 um, 0.1 urad), as long as they go downhill.
1361    fn pose_of_lengths(&self, lengths: &[f64], start: &[f64]) -> Option<PerDof> {
1362        let (n, m) = (self.n(), self.m());
1363        // A A^T and A r at a pose: Gauss-Newton solves (A A^T) step = A r, Newton H step = A r with H = -d(A r)/d xi.
1364        // A A^T only where asked for: the Newton steps' differences need A r alone.
1365        let at = |pose: &[f64], gauss: bool| -> Option<(Vec<f64>, Vec<f64>)> {
1366            let spans = self.spans(pose)?;
1367            let a = self.structure(&spans);
1368            let aat = if gauss {
1369                (0..n * n).map(|rc| (0..m).map(|k| a[rc / n * m + k] * a[rc % n * m + k]).sum()).collect()
1370            } else {
1371                Vec::new()
1372            };
1373            let rhs = (0..n).map(|r| (0..m).map(|k| a[r * m + k] * (spans[k].length - lengths[k])).sum()).collect();
1374            Some((aat, rhs))
1375        };
1376        let (mut pose, mut last, mut slow) = (start.iter().copied().collect::<PerDof>(), f64::INFINITY, false);
1377        for _ in 0..100 {
1378            let (aat, rhs) = at(&pose, true)?;
1379            let newton = || -> Option<Vec<f64>> {
1380                let mut h = vec![0.0; n * n];
1381                for c in 0..n {
1382                    let mut e = vec![0.0; n];
1383                    e[c] = 1e-7;
1384                    let up = at(&self.moved(&pose, &e), false)?.1;
1385                    e[c] = -1e-7;
1386                    let down = at(&self.moved(&pose, &e), false)?.1;
1387                    (0..n).for_each(|r| h[r * n + c] = -(up[r] - down[r]) / 2e-7);
1388                }
1389                let sym: Vec<f64> = (0..n * n).map(|rc| 0.5 * (h[rc] + h[rc % n * n + rc / n])).collect();
1390                solve(&sym, &rhs).filter(|step| (0..n).map(|r| step[r] * rhs[r]).sum::<f64>() > 0.0)
1391            };
1392            let mut step = match slow.then(newton).flatten() {
1393                Some(step) => step,
1394                None => solve(&aat, &rhs)?,
1395            };
1396            let longest = step.iter().fold(0.0f64, |s, v| s.max(v.abs()));
1397            if longest > 0.05 {
1398                step.iter_mut().for_each(|v| *v *= 0.05 / longest);
1399            }
1400            pose = self.moved(&pose, &step);
1401            // At a ratio r the steps still to come add up to longest r / (1 - r).
1402            let r = longest / last;
1403            if longest < 1e-14 || last.is_finite() && r < 0.95 && longest * r / (1.0 - r) < 1e-14 {
1404                return Some(pose);
1405            }
1406            slow |= last.is_finite() && r > 0.5;
1407            last = longest;
1408        }
1409        None
1410    }
1411
1412    /// G' xi: the cables' length acceleration at the twist `xi` with no platform acceleration, per cable:
1413    /// -u . (w x (w x b)) + w_P^T H w_P, w_P = v + w x b the anchor's speed and H = -du/dP the Hessian of the length
1414    /// over the anchor's place (by central differences of u, 1 um).
1415    fn length_curvature(&self, spans: &[Span], pose: &[f64], xi: &[f64]) -> Vec<f64> {
1416        let (p, _) = self.place(pose);
1417        let (v, w) = self.full(xi);
1418        spans
1419            .iter()
1420            .zip(&self.cables)
1421            .map(|(s, c)| {
1422                let wp = add(v, cross(w, s.b));
1423                let anchor = add(p, s.b);
1424                let h = 1e-6;
1425                let mut hw = [0.0; 3];
1426                for i in 0..3 {
1427                    let mut e = [0.0; 3];
1428                    e[i] = h;
1429                    let up = span(c, self.pulley, add(anchor, e)).map_or([f64::NAN; 3], |s| s.2);
1430                    let down = span(c, self.pulley, sub(anchor, e)).map_or([f64::NAN; 3], |s| s.2);
1431                    for (j, out) in hw.iter_mut().enumerate() {
1432                        *out -= (up[j] - down[j]) / (2.0 * h) * wp[i];
1433                    }
1434                }
1435                -dot(s.u, cross(w, cross(w, s.b))) + dot(wp, hw)
1436            })
1437            .collect()
1438    }
1439
1440    /// The push at the tool on the platform, taken off its bias (M xi' = A t - bias): the wrench of its virtual power per
1441    /// unit of each component of the twist (`sim_core::tool_force_on_rates`, through `pose_rate`).
1442    fn pushed(&self, s: &[f64], bias: &mut [f64]) {
1443        let n = self.n();
1444        if let Some(push) = sim_core::tool_force_on_rates(self, s, &self.push, n..2 * n) {
1445            bias.iter_mut().zip(push).for_each(|(b, p)| *b -= p);
1446        }
1447    }
1448
1449    /// Pose and twist of a state.
1450    fn platform<'a>(&self, s: &'a [f64]) -> (&'a [f64], &'a [f64]) {
1451        let n = self.n();
1452        (&s[..n], &s[n..2 * n])
1453    }
1454
1455    /// Free lengths and their rates, rotor angles and speeds of a state.
1456    fn winch_state(&self, s: &[f64], spans: &[Span]) -> (Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>) {
1457        let (n, m) = (self.n(), self.m());
1458        if self.elastic {
1459            let at = |k: usize| s[2 * n + k * m..2 * n + (k + 1) * m].to_vec();
1460            return (at(0), at(1), at(2), at(3));
1461        }
1462        let (_, xi) = self.platform(s);
1463        let rates = self.length_rates(spans, xi);
1464        let lengths: Vec<f64> = spans.iter().map(|s| s.length).collect();
1465        let ratio = |k: usize| self.winches[k].ratio();
1466        let rotor = (0..m).map(|k| ratio(k) * lengths[k]).collect();
1467        let speed = (0..m).map(|k| ratio(k) * rates[k]).collect();
1468        (lengths, rates.to_vec(), rotor, speed)
1469    }
1470
1471    fn brakes<'a>(&self, s: &'a [f64]) -> &'a [f64] {
1472        let (n, m) = (self.n(), self.m());
1473        let at = if self.elastic { 2 * n + 4 * m } else { 2 * n };
1474        &s[at..at + m]
1475    }
1476
1477    /// L' = G xi = -A^T xi.
1478    fn length_rates(&self, spans: &[Span], xi: &[f64]) -> PerCable {
1479        self.length_rates_with(&self.structure(spans), xi)
1480    }
1481
1482    /// `length_rates` with the structure matrix `a` known.
1483    fn length_rates_with(&self, a: &[f64], xi: &[f64]) -> PerCable {
1484        let (n, m) = (self.n(), self.m());
1485        (0..m).map(|k| -(0..n).map(|r| a[r * m + k] * xi[r]).sum::<f64>()).collect()
1486    }
1487
1488    /// The elastic cables' tensions at lengths L (rates L') and free lengths l (rates l').
1489    fn tensions(&self, spans: &[Span], rates: &[f64], free: &[f64], free_rates: &[f64]) -> Tensions {
1490        let m = self.m();
1491        let mut out = Tensions { platform: PerCable::zeros(m), drum: PerCable::zeros(m), damper: PerCable::zeros(m) };
1492        for k in 0..m {
1493            let e = spans[k].length - free[k];
1494            let (t0, c) = (self.ea * e / free[k], self.sag(&spans[k]));
1495            // A sagging cable pulls slack too; the damping is the stretch's, taut.
1496            let spring = sagged(t0, c);
1497            if spring > 0.0 {
1498                let damping = if e > 0.0 { self.damping / free[k] * (rates[k] - free_rates[k]) } else { 0.0 };
1499                let total = (spring + damping).max(0.0);
1500                out.damper[k] = total - spring;
1501                out.platform[k] = total;
1502                out.drum[k] = self.drum_share(spring, t0, c, e, free[k]) + out.damper[k];
1503            }
1504            // The span's weight on its free length and the lift from the drum to the pulley (`cable_weight`): -dV/dl.
1505            out.drum[k] -= self.rope * self.g * (0.5 * spans[k].dz + self.drop(k));
1506        }
1507        out
1508    }
1509
1510    /// Rigid model: the platform's acceleration (twist rate), the cables' length accelerations, and per winch the
1511    /// force into its gearbox (after the rotor's acceleration) and out of it, at the cable (N).
1512    fn rigid_solve(&self, s: &[f64], torque: &[f64]) -> (Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>) {
1513        let (n, m) = (self.n(), self.m());
1514        let (pose, xi) = self.platform(s);
1515        let nan = || (vec![f64::NAN; n], vec![f64::NAN; m], vec![f64::NAN; m], vec![f64::NAN; m]);
1516        let Some(spans) = self.spans(pose) else { return nan() };
1517        let (lengths, rates, rotor, speed) = self.winch_state(s, &spans);
1518        let brakes = self.brakes(s);
1519        let a = self.structure(&spans);
1520        let curve = self.length_curvature(&spans, pose, xi);
1521        let mass = self.platform_mass(pose);
1522        let mut bias = self.platform_bias(pose, xi);
1523        self.pushed(s, &mut bias);
1524        let drive: Vec<f64> = (0..m)
1525            .map(|k| self.winches[k].rigid_drive(torque[k], rotor[k], speed[k], brakes[k], self.brake_engaged).0)
1526            .collect();
1527        let out: Vec<f64> = (0..m).map(|k| self.winches[k].output_torque(lengths[k], rates[k])).collect();
1528        // G = -A^T: G^T x = -A x.
1529        let solve_with = |loss: &[f64]| -> Vec<f64> {
1530            let inertia: Vec<f64> =
1531                (0..m).map(|k| loss[k] * self.winches[k].reflected_inertia() + self.drum_mass[k]).collect();
1532            let mut mm = mass;
1533            for i in 0..n {
1534                for j in 0..n {
1535                    mm[i * n + j] += (0..m).map(|k| a[i * m + k] * inertia[k] * a[j * m + k]).sum::<f64>();
1536                }
1537            }
1538            let rhs: Vec<f64> = (0..n)
1539                .map(|i| {
1540                    -(0..m).map(|k| a[i * m + k] * (loss[k] * drive[k] + out[k] - inertia[k] * curve[k])).sum::<f64>()
1541                        - bias[i]
1542                })
1543                .collect();
1544            solve(&mm, &rhs).unwrap_or_else(|| vec![f64::NAN; n])
1545        };
1546        let length_acc = |acc: &[f64]| -> Vec<f64> {
1547            (0..m).map(|k| curve[k] - (0..n).map(|r| a[r * m + k] * acc[r]).sum::<f64>()).collect()
1548        };
1549        // The loss factors of the torques going in, at their fixed point (`mech::settled_loss`).
1550        let loss = sim_components::mech::settled_loss(vec![1.0; m], |loss| {
1551            let lacc = length_acc(&solve_with(loss));
1552            (0..m)
1553                .map(|k| {
1554                    let w = &self.winches[k];
1555                    w.gearbox.loss_factor(drive[k] - w.reflected_inertia() * lacc[k], rates[k])
1556                })
1557                .collect()
1558        });
1559        let acc = solve_with(&loss);
1560        let lacc = length_acc(&acc);
1561        let into: Vec<f64> = (0..m).map(|k| drive[k] - self.winches[k].reflected_inertia() * lacc[k]).collect();
1562        let outs = (0..m).map(|k| loss[k] * into[k]).collect();
1563        (acc, lacc, into, outs)
1564    }
1565
1566    /// The tensions of either model at a state: the springs' where the cables stretch; where they do not, what the drums
1567    /// hold against the gearboxes and friction.
1568    fn state_tensions(&self, s: &[f64], torque: &[f64]) -> Vec<f64> {
1569        let (pose, xi) = self.platform(s);
1570        let Some(spans) = self.spans(pose) else { return vec![f64::NAN; self.m()] };
1571        if self.elastic {
1572            let (free, free_rates, ..) = self.winch_state(s, &spans);
1573            return self.tensions(&spans, &self.length_rates(&spans, xi), &free, &free_rates).platform.to_vec();
1574        }
1575        let (lengths, rates, ..) = self.winch_state(s, &spans);
1576        let (_, lacc, _, out) = self.rigid_solve(s, torque);
1577        (0..self.m())
1578            .map(|k| self.drum_mass[k] * lacc[k] - out[k] - self.winches[k].output_torque(lengths[k], rates[k]))
1579            .collect()
1580    }
1581
1582    /// The platform's twist rate, in either model.
1583    fn twist_acceleration(&self, s: &[f64], torque: &[f64]) -> Vec<f64> {
1584        let n = self.n();
1585        if self.elastic {
1586            let mut d = vec![0.0; self.state_len()];
1587            self.derivatives(s, torque, &mut d);
1588            d[n..2 * n].to_vec()
1589        } else {
1590            self.rigid_solve(s, torque).0
1591        }
1592    }
1593
1594    /// Pose rate from twist: p' = v, r' = J_l(r)^-1 w.
1595    fn pose_rate(&self, pose: &[f64], xi: &[f64]) -> PerDof {
1596        if !self.spatial {
1597            return xi.iter().copied().collect();
1598        }
1599        let r = mul(&left_jacobian_inverse([pose[3], pose[4], pose[5]]), [xi[3], xi[4], xi[5]]);
1600        PerDof::from_iter([xi[0], xi[1], xi[2], r[0], r[1], r[2]])
1601    }
1602
1603    /// Twist from pose rate: w = J_l(r) r'.
1604    fn twist(&self, pose: &[f64], rate: &[f64]) -> Vec<f64> {
1605        if !self.spatial {
1606            return rate.to_vec();
1607        }
1608        let w = mul(&left_jacobian([pose[3], pose[4], pose[5]]), [rate[3], rate[4], rate[5]]);
1609        vec![rate[0], rate[1], rate[2], w[0], w[1], w[2]]
1610    }
1611
1612    /// The cables' stiffness EA / l alone, summed over the cables as K = sum EA / l_k a_k a_k^T (n x n, in the degrees
1613    /// of freedom), at the free lengths of the platform held at rest at `pose`.
1614    pub fn cable_stiffness(&self, pose: &[f64]) -> Option<Vec<f64>> {
1615        let spans = self.spans(pose)?;
1616        let t = self.static_tensions(pose)?;
1617        let (n, m) = (self.n(), self.m());
1618        let a = self.structure(&spans);
1619        // EA / l = (EA + t0) / L of the straight cable, times the sag's slope dT / dt0 = T^3 / (T^3 + c) (Ernst's).
1620        let k: Vec<f64> = (0..m)
1621            .map(|k| {
1622                let (c, t0) = (self.sag(&spans[k]), unsagged(t[k], self.sag(&spans[k])));
1623                let slope = t[k].powi(3) / (t[k].powi(3) + c);
1624                slope * (self.ea + t0) / spans[k].length
1625            })
1626            .collect();
1627        Some((0..n * n).map(|rc| (0..m).map(|c| a[rc / n * m + c] * k[c] * a[rc % n * m + c]).sum()).collect())
1628    }
1629
1630    /// The cables' dampers on the platform held at rest at `pose`, the drums held: a taut cable's c / l on its stretch's
1631    /// rate L' = -a^T xi (`tensions`), summed as C = sum c / l_k a_k a_k^T (n x n, in the degrees of freedom), l_k the
1632    /// free length of rest. Zero without effects.cable_damping.
1633    pub fn cable_damping(&self, pose: &[f64]) -> Option<Vec<f64>> {
1634        let spans = self.spans(pose)?;
1635        let t = self.static_tensions(pose)?;
1636        let (n, m) = (self.n(), self.m());
1637        let a = self.structure(&spans);
1638        let c: Vec<f64> = (0..m)
1639            .map(|k| {
1640                let free = self.free_for(&spans[k], t[k]);
1641                if spans[k].length > free { self.damping / free } else { 0.0 }
1642            })
1643            .collect();
1644        Some((0..n * n).map(|rc| (0..m).map(|k| a[rc / n * m + k] * c[k] * a[rc % n * m + k]).sum()).collect())
1645    }
1646
1647    /// The whole stiffness of the platform with the drums held at the free lengths of rest at `pose`: minus the
1648    /// derivative of the cables' wrench on it over a small twist (central differences of 1 um and 1 urad), so with
1649    /// the stiffness of the tensions turning with the cables (the geometric part) and the pulleys.
1650    pub fn stiffness(&self, pose: &[f64]) -> Option<Vec<f64>> {
1651        let (n, m) = (self.n(), self.m());
1652        let spans = self.spans(pose)?;
1653        let t = self.static_tensions(pose)?;
1654        let free: Vec<f64> = (0..m).map(|k| self.free_for(&spans[k], t[k])).collect();
1655        let wrench = |p: &[f64]| -> Option<Vec<f64>> {
1656            let spans = self.spans(p)?;
1657            let a = self.structure(&spans);
1658            let tension = self.tensions(&spans, &vec![0.0; m], &free, &vec![0.0; m]).platform;
1659            Some((0..n).map(|r| (0..m).map(|k| a[r * m + k] * tension[k]).sum()).collect())
1660        };
1661        let mut k = vec![0.0; n * n];
1662        for c in 0..n {
1663            let mut step = vec![0.0; n];
1664            step[c] = 1e-6;
1665            let up = wrench(&self.moved(pose, &step))?;
1666            step[c] = -1e-6;
1667            let down = wrench(&self.moved(pose, &step))?;
1668            for r in 0..n {
1669                k[r * n + c] = -(up[r] - down[r]) / 2e-6;
1670            }
1671        }
1672        // Symmetric up to the differences' error and the non-conservative part of a turning moment.
1673        Some((0..n * n).map(|rc| 0.5 * (k[rc] + k[rc % n * n + rc / n])).collect())
1674    }
1675
1676    /// The platform's natural frequencies on its cables at a pose, Hz, lowest first: the eigenvalues of
1677    /// L^-1 K L^-T with M = L L^T (Cholesky), the drums held.
1678    pub fn natural_frequencies(&self, pose: &[f64]) -> Option<Vec<f64>> {
1679        let n = self.n();
1680        let k = self.stiffness(pose)?;
1681        let mm = self.platform_mass(pose);
1682        let mut l = vec![0.0; n * n];
1683        for i in 0..n {
1684            for j in 0..=i {
1685                let s: f64 = mm[i * n + j] - (0..j).map(|c| l[i * n + c] * l[j * n + c]).sum::<f64>();
1686                l[i * n + j] = if i == j { s.sqrt() } else { s / l[j * n + j] };
1687            }
1688        }
1689        // C = L^-1 K L^-T, column by column through forward substitution.
1690        let lower = |b: &[f64]| -> Vec<f64> {
1691            let mut x = vec![0.0; n];
1692            for i in 0..n {
1693                x[i] = (b[i] - (0..i).map(|c| l[i * n + c] * x[c]).sum::<f64>()) / l[i * n + i];
1694            }
1695            x
1696        };
1697        let mut y = vec![0.0; n * n];
1698        for c in 0..n {
1699            let col = lower(&(0..n).map(|r| k[r * n + c]).collect::<Vec<_>>());
1700            for r in 0..n {
1701                y[r * n + c] = col[r];
1702            }
1703        }
1704        let mut cmat = vec![0.0; n * n];
1705        for r in 0..n {
1706            let row = lower(&y[r * n..r * n + n]);
1707            for c in 0..n {
1708                cmat[c * n + r] = row[c];
1709            }
1710        }
1711        let eig = eigenvalues(cmat, n);
1712        Some(eig.iter().map(|e| e.max(0.0).sqrt() / TAU).collect())
1713    }
1714
1715    /// The twist and its rate from the pose's speed and acceleration (w' = J_l r'' + (d/dt J_l) r', the latter by
1716    /// central differences along r').
1717    fn twist_and_rate(&self, pos: &[f64], vel: &[f64], acc: &[f64]) -> (Vec<f64>, Vec<f64>) {
1718        let n = self.n();
1719        let xi = self.twist(pos, &vel[..n]);
1720        let mut rate = self.twist(pos, &acc[..n]);
1721        if self.spatial {
1722            let rv = [vel[3], vel[4], vel[5]];
1723            let speed = norm(rv);
1724            if speed > 0.0 {
1725                let h = 1e-4 / speed;
1726                let at = |s: f64| left_jacobian([pos[3] + s * rv[0], pos[4] + s * rv[1], pos[5] + s * rv[2]]);
1727                let (up, down) = (mul(&at(h), rv), mul(&at(-h), rv));
1728                // (d/dt J_l) r' = (J_l(r + h r') - J_l(r - h r')) r' / (2 h).
1729                for i in 0..3 {
1730                    rate[3 + i] += (up[i] - down[i]) / (2.0 * h);
1731                }
1732            }
1733        }
1734        (xi, rate)
1735    }
1736
1737    /// The motor torques of the rigid, loss-free model for a pose, twist and twist rate: the tensions of the
1738    /// distribution for the platform's wrench, and the winches' own inertia on the cables' length accelerations.
1739    fn torques_for(&self, pose: &[f64], xi: &[f64], xi_rate: &[f64], out: &mut [f64]) {
1740        let (n, m) = (self.n(), self.m());
1741        let Some(spans) = self.spans(pose) else {
1742            out.fill(f64::NAN);
1743            return;
1744        };
1745        let a = self.structure(&spans);
1746        let mass = self.platform_mass(pose);
1747        let bias = self.platform_bias(pose, xi);
1748        let w: Vec<f64> = (0..n).map(|r| (0..n).map(|c| mass[r * n + c] * xi_rate[c]).sum::<f64>() + bias[r]).collect();
1749        // Beyond the cables' band the feedforward still asks for the distribution's nearest: unbounded tensions.
1750        let t = distribute(&a, &w, self.t_min, self.t_max, self.t_ref)
1751            .or_else(|| distribute(&a, &w, -1e12, 1e12, self.t_ref))
1752            .unwrap_or_else(|| vec![f64::NAN; m]);
1753        let curve = self.length_curvature(&spans, pose, xi);
1754        for k in 0..m {
1755            let j = &self.winches[k];
1756            let lacc = curve[k] - (0..n).map(|r| a[r * m + k] * xi_rate[r]).sum::<f64>();
1757            out[k] = (self.drum_mass[k] * lacc - t[k]) / j.ratio() + j.rotor_inertia * j.ratio() * lacc;
1758        }
1759    }
1760
1761    /// The losses of one moment: per winch its bearings' friction, its motor's friction with the brake, its gearbox;
1762    /// per cable its damper; then the stops and what the ripple gives off. And per winch the gearbox's loss as a torque
1763    /// at the rotor.
1764    fn losses(&self, s: &[f64], torque: &[f64]) -> (Vec<f64>, Vec<f64>) {
1765        let m = self.m();
1766        let (pose, xi) = self.platform(s);
1767        let mut powers = vec![0.0; 4 * m + 2];
1768        let mut at_rotor = vec![0.0; m];
1769        let Some(spans) = self.spans(pose) else { return (vec![f64::NAN; 4 * m + 2], at_rotor) };
1770        let (free, free_rates, rotor, speed) = self.winch_state(s, &spans);
1771        let brakes = self.brakes(s);
1772        let rigid = (!self.elastic).then(|| self.rigid_solve(s, torque));
1773        let damper = self.elastic.then(|| {
1774            let rates = self.length_rates(&spans, xi);
1775            let t = self.tensions(&spans, &rates, &free, &free_rates);
1776            (0..m).map(|k| t.damper[k] * (rates[k] - free_rates[k])).collect::<Vec<_>>()
1777        });
1778        for k in 0..m {
1779            let j = &self.winches[k];
1780            let [friction, stop, shaft, drag] =
1781                j.losses(free[k], free_rates[k], speed[k], brakes[k], self.brake_engaged);
1782            let gear = match &rigid {
1783                Some((_, _, into, out)) => {
1784                    at_rotor[k] = (into[k] - out[k]) / j.ratio();
1785                    (into[k] - out[k]) * free_rates[k]
1786                }
1787                None => {
1788                    let g = j.gearbox.torque(rotor[k], speed[k], free[k], free_rates[k]);
1789                    at_rotor[k] = g.rotor - g.output / j.ratio();
1790                    j.gearbox.loss_power(rotor[k], speed[k], free[k], free_rates[k])
1791                }
1792            };
1793            powers[3 * k..3 * k + 3].copy_from_slice(&[friction, shaft, gear + drag]);
1794            powers[3 * m + k] = damper.as_ref().map_or(0.0, |d| d[k]);
1795            powers[4 * m] += stop;
1796            powers[4 * m + 1] += (torque[k] - j.ripple.apply(torque[k], rotor[k])) * speed[k];
1797        }
1798        (powers, at_rotor)
1799    }
1800
1801    fn energy_parts(&self, s: &[f64]) -> [f64; 3] {
1802        let (n, m) = (self.n(), self.m());
1803        let (pose, xi) = self.platform(s);
1804        let Some(spans) = self.spans(pose) else { return [f64::NAN; 3] };
1805        let mass = self.platform_mass(pose);
1806        let mut kinetic = 0.5 * (0..n * n).map(|rc| xi[rc / n] * mass[rc] * xi[rc % n]).sum::<f64>();
1807        let (p, _) = self.place(pose);
1808        let (free, free_rates, rotor, speed) = self.winch_state(s, &spans);
1809        let potential = self.moving() * self.g * p[2] + self.cable_weight(&spans, self.elastic.then_some(&free[..])).1;
1810        let mut elastic = 0.0;
1811        for k in 0..m {
1812            let j = &self.winches[k];
1813            elastic += j.stop_energy(free[k]);
1814            if self.elastic {
1815                kinetic += 0.5 * self.drum_mass[k] * free_rates[k].powi(2) + 0.5 * j.rotor_inertia * speed[k].powi(2);
1816                elastic += j.gearbox.energy(rotor[k], free[k]);
1817                elastic += self.spring_energy(&spans[k], free[k]);
1818            } else {
1819                kinetic += 0.5 * (self.drum_mass[k] + j.reflected_inertia()) * free_rates[k].powi(2);
1820            }
1821        }
1822        [kinetic, potential, elastic]
1823    }
1824
1825    /// The least-norm share of the platform's wrench `w` per cable, A^+ w: what the parts of the torque breakdown count
1826    /// for inertia and gravity (the pretension the motors also hold shows in the rest).
1827    fn least_norm(a: &[f64], w: &[f64]) -> Vec<f64> {
1828        let n = w.len();
1829        let m = a.len() / n;
1830        let aat: Vec<f64> = (0..n * n).map(|rc| (0..m).map(|k| a[rc / n * m + k] * a[rc % n * m + k]).sum()).collect();
1831        let y = solve(&aat, w).unwrap_or_else(|| vec![f64::NAN; n]);
1832        (0..m).map(|k| (0..n).map(|r| a[r * m + k] * y[r]).sum()).collect()
1833    }
1834}
1835
1836impl CableRobot {
1837    /// Cable `k`'s mass in the frame's (effects.cable_inertia), all rho (capacity + run) of it: the cable wound on the
1838    /// drum, rho (capacity - l), at the drum's centre D = E + run axis; the run, rho run, from D to the pulley's swivel
1839    /// point E, moving along it at the drum's speed l'; the free length l between E and the anchor P (the pulley's wrap
1840    /// taken as the straight E to P), a point at the share f of the way moving at (1 - f) a + f P', a = l' (P - E) / l,
1841    /// the cable entering at E (l' u rigid; stretched, faster by L / l) and leaving with the anchor (as the kinetic
1842    /// energy has it: rho l l'^2 / 2 along, rho l / 6 |P'_perp|^2 across). So the first moment rho ((capacity - l) D +
1843    /// run (D + E) / 2 + l (E + P) / 2), the momentum rho (l' (E - D) + l (a + P') / 2), its rate; the angular momentum
1844    /// rho (l' D x E + l (E x (a + P') / 2 + (P - E) x (a / 6 + P' / 3))).
1845    fn cable_momentum(&self, f: &mut sim_core::FrameMomentum, k: usize, anchor: V3, speed: V3, l: f64, rate: f64) {
1846        let (rho, run, e) = (self.rope, self.runs[k], self.cables[k].exit);
1847        let capacity = self.cable_moving / rho;
1848        let drum = add(e, scale(self.cables[k].axis, run));
1849        let d = sub(anchor, e);
1850        let a = scale(d, rate / l);
1851        f.mass += rho * (capacity + run);
1852        for i in 0..3 {
1853            f.first_moment[i] +=
1854                rho * ((capacity - l) * drum[i] + run * 0.5 * (drum[i] + e[i]) + l * 0.5 * (e[i] + anchor[i]));
1855            f.linear[i] += rho * (rate * (e[i] - drum[i]) + 0.5 * l * (a[i] + speed[i]));
1856        }
1857        let along = cross(drum, e);
1858        let (mid, tip) = (cross(e, add(a, speed)), cross(d, add(scale(a, 1.0 / 6.0), scale(speed, 1.0 / 3.0))));
1859        for i in 0..3 {
1860            f.angular[i] += rho * (rate * along[i] + l * (0.5 * mid[i] + tip[i]));
1861        }
1862    }
1863}
1864
1865impl Machine for CableRobot {
1866    /// The platform (payload at its centre p) at its twist (v, w): m v, p x m v + R I R^T w. And each winch's spin on
1867    /// the frame, about its axis `h` (`frame.winch_spin_axes`; by default horizontal and square to the cable's direction
1868    /// at the winch): the drum, which pays the cable out at the speed l' with the radius r, turns at l' / r about h
1869    /// (J_drum l' / r = m_drum r l'), and the rotor at the motor's speed; h (m_drum r l' + J_rotor w_rotor). With
1870    /// effects.cable_inertia the cable on the drum, rho (capacity - l), turns with it, and the cable is in the frame's mass,
1871    /// first moment and momentum (`cable_momentum`); without it the cable's mass is not (its weight, the potential's, is).
1872    fn frame_momentum(&self, s: &[f64]) -> Option<sim_core::FrameMomentum> {
1873        let (pose, xi) = self.platform(s);
1874        let (p, r) = self.place(pose);
1875        let (v, w) = self.full(xi);
1876        let mut f = sim_core::FrameMomentum { gravity: [0.0, 0.0, -self.g], ..Default::default() };
1877        sim_components::base::add_point(&mut f, self.moving(), p, v);
1878        let turning = mul(&matmul(&matmul(&r, &self.inertia), &transpose(&r)), w);
1879        (0..3).for_each(|k| f.angular[k] += turning[k]);
1880        if let Some(spans) = self.spans(pose) {
1881            let (free, rates, _, speed) = self.winch_state(s, &spans);
1882            for k in 0..self.m() {
1883                // With effects.cable_inertia the cable still on the drum, rho (capacity - l), turns with it. The l paid out runs
1884                // along its span: like its weight (the potential's), its mass is not in the frame's, nor its momentum.
1885                let paid = if self.cable_moving > 0.0 { self.rope * (free[k] + self.runs[k]) } else { 0.0 };
1886                let turning = self.drum_mass[k] - paid;
1887                let spin = turning * self.drum_radius * rates[k] + self.winches[k].rotor_inertia * speed[k];
1888                (0..3).for_each(|i| f.angular[i] += self.spin[k][i] * spin);
1889                if self.cable_moving > 0.0 {
1890                    let anchor = add(p, mul(&r, self.cables[k].anchor));
1891                    let speed = add(v, cross(w, mul(&r, self.cables[k].anchor)));
1892                    self.cable_momentum(&mut f, k, anchor, speed, free[k], rates[k]);
1893                }
1894            }
1895        }
1896        Some(f)
1897    }
1898    fn axes(&self) -> &[AxisInfo] {
1899        &self.axes
1900    }
1901    fn motors(&self) -> &[MotorInfo] {
1902        &self.motors
1903    }
1904
1905    /// Per cable its highest tension against the rating (breaking load over the safety factor) and how far it fell
1906    /// below the least tension that keeps it taut (0 allowed).
1907    fn rating_checks(&self) -> Vec<RatingCheck> {
1908        (0..self.m())
1909            .flat_map(|k| {
1910                [
1911                    RatingCheck {
1912                        check: "cable-max-tension",
1913                        signal: format!("cable.{}.tension", MOTOR_IDS[k]),
1914                        motor: Some(k),
1915                        limit: self.t_max,
1916                        life: false,
1917                    },
1918                    RatingCheck {
1919                        check: "cable-min-tension",
1920                        signal: format!("cable.{}.shortfall", MOTOR_IDS[k]),
1921                        motor: Some(k),
1922                        limit: 0.0,
1923                        life: false,
1924                    },
1925                ]
1926            })
1927            .collect()
1928    }
1929
1930    /// NaN where the pose cannot be held (see `unreachable`).
1931    fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
1932        match self.free_lengths(tool) {
1933            Some(l) => (0..self.m()).for_each(|k| motors[k] = self.winches[k].ratio() * l[k]),
1934            None => motors.fill(f64::NAN),
1935        }
1936    }
1937
1938    /// The motors' cable to the pose. Rigid: the pose of those lengths (`pose_of_lengths`). Elastic: where the platform
1939    /// hangs at rest on cables of those free lengths l, its static equilibrium A t = w with t = EA (L - l) / l on each
1940    /// taut cable (none on a slack one): eight cables fix six degrees of freedom and their pretension, so any free
1941    /// lengths have one pose, whatever tensions they were set up for (the closed form's of `inverse`, the
1942    /// distribution's of `equilibrium`, or neither, as the motors of a run with a following error stand). Newton on
1943    /// the residual A t - w from the pose of the lengths stretched at the reference tension, its Jacobian by central
1944    /// differences (0.1 um, 0.1 urad), each step halved until it lowers the potential (weight and cable springs) whose
1945    /// least the equilibrium is; where Newton's step is not downhill (every cable slack), one along the residual. No
1946    /// step longer than 50 mm or 50 mrad. Settled at a step below 1e-12 m (rad), or where no step helps any more (at
1947    /// the rounding floor). NaN where it does not settle within 50 steps. Newton starts from the pose at the nearest point
1948    /// of the `ANCHOR_STEP` grid of free lengths instead (found as above, and kept until the lengths leave its cell),
1949    /// with the Jacobian it took its last step with, as long as that one's steps go downhill (a chord method: the
1950    /// Jacobian of a pose at most half a millimetre of cable away; recomputed at the pose where a step fails); as above
1951    /// where that does not settle. That saves the pose of the lengths, which took about 16 Gauss-Newton steps from the
1952    /// box's centre, and the 2 n residuals of each Jacobian; the pose then differs by Newton's tolerance, not more, and
1953    /// depends on the motor angles alone. The controller asks for it every position cycle, for the tool's following
1954    /// error.
1955    fn forward(&self, motors: &[f64], tool: &mut [f64]) {
1956        if !self.elastic {
1957            self.settle(motors, tool, None);
1958            return;
1959        }
1960        let m = self.m();
1961        let key: Short<i64, 8> =
1962            (0..m).map(|k| (motors[k] / self.winches[k].ratio() / ANCHOR_STEP).round() as i64).collect();
1963        let anchor = self.last_forward.get().filter(|a| a.key[..] == key[..]).or_else(|| {
1964            let grid: PerCable = (0..m).map(|k| key[k] as f64 * ANCHOR_STEP * self.winches[k].ratio()).collect();
1965            let mut pose = PerDof::zeros(self.n());
1966            let jacobian = self.settle(&grid, &mut pose, None)?;
1967            let anchor = Forwarded { key, pose, jacobian };
1968            self.last_forward.set(Some(anchor.clone()));
1969            Some(anchor)
1970        });
1971        if anchor.and_then(|a| self.settle(motors, tool, Some(a))).is_none() {
1972            self.settle(motors, tool, None);
1973        }
1974    }
1975
1976    fn state_len(&self) -> usize {
1977        2 * self.n() + self.m() * if self.elastic { 5 } else { 1 }
1978    }
1979
1980    fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
1981        let (n, m) = (self.n(), self.m());
1982        state.clear();
1983        state.extend_from_slice(&tool[..n]);
1984        state.extend(vec![0.0; n]);
1985        let (Some(spans), Some(t)) = (self.spans(tool), self.static_tensions(tool)) else {
1986            state.iter_mut().for_each(|v| *v = f64::NAN);
1987            state.resize(self.state_len(), f64::NAN);
1988            torque.fill(f64::NAN);
1989            return;
1990        };
1991        let (mut free, mut rotors) = (vec![0.0; m], vec![0.0; m]);
1992        for k in 0..m {
1993            let j = &self.winches[k];
1994            let (l, drum) = if self.elastic {
1995                let l = self.free_for(&spans[k], t[k]);
1996                let (e, c) = (spans[k].length - l, self.sag(&spans[k]));
1997                let weight = 0.5 * self.rope * self.g * spans[k].dz;
1998                (l, self.drum_share(t[k], self.ea * e / l, c, e, l) - weight)
1999            } else {
2000                (spans[k].length, t[k])
2001            };
2002            // At rest the gearbox holds the drum against its cable and the stops.
2003            let out = -drum - j.output_torque(l, 0.0);
2004            let rotor = j.ratio() * (l + if self.elastic { j.gearbox.static_twist(out) } else { 0.0 });
2005            free[k] = l;
2006            rotors[k] = rotor;
2007            torque[k] = j.ripple.invert(out / j.ratio(), rotor);
2008        }
2009        if self.elastic {
2010            state.extend(&free);
2011            state.extend(vec![0.0; m]);
2012            state.extend(&rotors);
2013            state.extend(vec![0.0; m]);
2014        }
2015        state.resize(self.state_len(), 0.0);
2016    }
2017
2018    fn derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
2019        let (n, m) = (self.n(), self.m());
2020        let (pose, xi) = self.platform(s);
2021        out[..n].copy_from_slice(&self.pose_rate(pose, xi));
2022        if !self.elastic {
2023            let (acc, ..) = self.rigid_solve(s, torque);
2024            out[n..2 * n].copy_from_slice(&acc);
2025            let Some(spans) = self.spans(pose) else {
2026                out.fill(f64::NAN);
2027                return;
2028            };
2029            let (_, _, _, speed) = self.winch_state(s, &spans);
2030            let brakes = self.brakes(s);
2031            for k in 0..m {
2032                out[2 * n + k] = self.winches[k].brake.torque(self.brake_engaged, speed[k], brakes[k]).1;
2033            }
2034            return;
2035        }
2036        // The pose placed and the structure matrix once, for the spans, the rates and the platform.
2037        let (p, rot) = self.place(pose);
2038        let Some(spans) = self.spans_at(p, &rot) else {
2039            out.fill(f64::NAN);
2040            return;
2041        };
2042        let state = |k: usize| &s[2 * n + k * m..2 * n + (k + 1) * m];
2043        let (free, free_rates, rotor, speed) = (state(0), state(1), state(2), state(3));
2044        let brakes = self.brakes(s);
2045        let a = self.structure(&spans);
2046        let rates = self.length_rates_with(&a, xi);
2047        let t = self.tensions(&spans, &rates, free, free_rates);
2048        let mut bias = self.platform_bias_at(&rot, &spans, Some(free), xi);
2049        let springs: PerCable = (0..m).map(|k| t.platform[k] - t.damper[k]).collect();
2050        bias.iter_mut().zip(self.sag_pull(&spans, free, &springs)).for_each(|(b, f)| *b -= f);
2051        self.pushed(s, &mut bias);
2052        let mut acc: PerDof =
2053            (0..n).map(|r| (0..m).map(|k| a[r * m + k] * t.platform[k]).sum::<f64>() - bias[r]).collect();
2054        if !solve_in_place(&mut self.platform_mass_at(&rot, &spans), &mut acc) {
2055            acc.fill(f64::NAN);
2056        }
2057        out[n..2 * n].copy_from_slice(&acc);
2058        for k in 0..m {
2059            let j = &self.winches[k];
2060            let (gear, rotor_acc, brake_rate) =
2061                j.rotor(torque[k], rotor[k], speed[k], free[k], free_rates[k], brakes[k], self.brake_engaged);
2062            out[2 * n + k] = free_rates[k];
2063            out[2 * n + m + k] =
2064                (gear.output + j.output_torque(free[k], free_rates[k]) + t.drum[k]) / self.drum_mass[k];
2065            out[2 * n + 2 * m + k] = speed[k];
2066            out[2 * n + 3 * m + k] = rotor_acc;
2067            out[2 * n + 4 * m + k] = brake_rate;
2068        }
2069    }
2070
2071    fn tool_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
2072        let n = self.n();
2073        let (pose, xi) = self.platform(s);
2074        pos[..n].copy_from_slice(pose);
2075        vel[..n].copy_from_slice(&self.pose_rate(pose, xi));
2076    }
2077
2078    fn set_tool_velocity(&self, s: &mut [f64], vel: &[f64]) {
2079        let (n, m) = (self.n(), self.m());
2080        let pose = s[..n].to_vec();
2081        let xi = self.twist(&pose, &vel[..n]);
2082        s[n..2 * n].copy_from_slice(&xi);
2083        if self.elastic {
2084            let Some(spans) = self.spans(&pose) else { return };
2085            let rates = self.length_rates(&spans, &xi);
2086            for k in 0..m {
2087                s[2 * n + m + k] = rates[k];
2088                s[2 * n + 3 * m + k] = self.winches[k].ratio() * rates[k];
2089            }
2090        }
2091    }
2092
2093    fn motor_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
2094        let (n, m) = (self.n(), self.m());
2095        let (pose, _) = self.platform(s);
2096        if self.elastic {
2097            // The rotors are states of their own: the spans only tell whether the pose can be drawn.
2098            let (p, r) = self.place(pose);
2099            if self.cables.iter().all(|c| pulley_plane(c, self.pulley, add(p, mul(&r, c.anchor))).is_some()) {
2100                pos[..m].copy_from_slice(&s[2 * n + 2 * m..2 * n + 3 * m]);
2101                vel[..m].copy_from_slice(&s[2 * n + 3 * m..2 * n + 4 * m]);
2102            } else {
2103                pos[..m].fill(f64::NAN);
2104                vel[..m].fill(f64::NAN);
2105            }
2106            return;
2107        }
2108        let Some(spans) = self.spans(pose) else {
2109            pos[..m].fill(f64::NAN);
2110            vel[..m].fill(f64::NAN);
2111            return;
2112        };
2113        let (_, _, rotor, speed) = self.winch_state(s, &spans);
2114        pos[..m].copy_from_slice(&rotor);
2115        vel[..m].copy_from_slice(&speed);
2116    }
2117
2118    fn feedforward_torque(&self, pos: &[f64], acc: &[f64], out: &mut [f64]) {
2119        let n = self.n();
2120        self.feedforward_torque_moving(pos, &vec![0.0; n], acc, out);
2121    }
2122
2123    /// The rigid model at a steady twist: per winch, at the cable's speed L' = -A^T xi, the motor shaft's friction (with
2124    /// the gearbox's drag) at i L' and the drum's bearings f(L') through the gearbox as `rigid_solve` takes it,
2125    /// f / (i loss). The loss factor at the power of the whole load on the gearbox (the cable's steady tension of
2126    /// `torques_for` and f), as there: a cable paying out drives its gearbox back, which then takes eta off f, not on.
2127    /// With effects.gearbox_mesh_friction also the mesh's friction on the tension at rest there, (1 - eta) of its torque
2128    /// at the rotor, along the motion.
2129    fn steady_friction(&self, pos: &[f64], vel: &[f64], out: &mut [f64]) {
2130        let n = self.n();
2131        let xi = self.twist(pos, &vel[..n]);
2132        let Some(spans) = self.spans(&pos[..n]) else { return out.fill(0.0) };
2133        let rates = self.length_rates(&spans, &xi);
2134        let mut held = vec![0.0; self.m()];
2135        self.torques_for(pos, &xi, &vec![0.0; n], &mut held);
2136        // The tension at rest there, which the mesh friction is in proportion to (no speed terms).
2137        let mut resting = vec![0.0; self.m()];
2138        self.torques_for(pos, &vec![0.0; n], &vec![0.0; n], &mut resting);
2139        for (k, w) in self.winches.iter().enumerate() {
2140            let (i, v) = (w.ratio(), rates[k]);
2141            let friction = w.friction.torque(v);
2142            out[k] = w.shaft.torque(i * v) + friction / (i * w.gearbox.loss_factor(i * held[k] + friction, v));
2143            // The mesh friction on the torque the gear holds, the cable's tension (`Gearbox::mesh_friction`), against the
2144            // motion: (1 - eta) of it, which the integrator carried and took past the target when the motion stopped.
2145            if w.gearbox.mesh_stiffness > 0.0 && v != 0.0 {
2146                out[k] += (1.0 - w.gearbox.efficiency) * resting[k].abs() * v.signum();
2147            }
2148        }
2149    }
2150
2151    /// The twist and its rate from the pose's speed and acceleration (w' = J_l r'' + (d/dt J_l) r', the latter by
2152    /// central differences along r'), then `torques_for`.
2153    fn feedforward_torque_moving(&self, pos: &[f64], vel: &[f64], acc: &[f64], out: &mut [f64]) {
2154        let (xi, rate) = self.twist_and_rate(pos, vel, acc);
2155        self.torques_for(pos, &xi, &rate, out);
2156    }
2157
2158    /// Each cable's tension in the rigid loss-free model at a pose, speed and acceleration of the tool (the distribution
2159    /// for the wrench M xi' + c + g, the unbounded one where the band holds none, as the feedforward's): what the
2160    /// time-optimal plan keeps within the cables' band (`tension_band`).
2161    /// Linear in the acceleration wherever no cable sits at a bound, as the plan fits it.
2162    /// The cables' band: `cable.min_tension_n` to the breaking load over the safety factor, as the rating checks.
2163    fn tension_band(&self) -> Option<[f64; 2]> {
2164        Some([self.t_min, self.t_max])
2165    }
2166    fn rigid_tensions(&self, pos: &[f64], acc: &[f64], out: &mut Vec<f64>) {
2167        self.rigid_tensions_moving(pos, &vec![0.0; self.n()], acc, out);
2168    }
2169    fn rigid_tensions_moving(&self, pos: &[f64], vel: &[f64], acc: &[f64], out: &mut Vec<f64>) {
2170        let (n, m) = (self.n(), self.m());
2171        let (xi, rate) = self.twist_and_rate(pos, vel, acc);
2172        let Some(spans) = self.spans(&pos[..n]) else { return out.extend(vec![f64::NAN; m]) };
2173        let a = self.structure(&spans);
2174        let mass = self.platform_mass(pos);
2175        let bias = self.platform_bias(pos, &xi);
2176        let w: Vec<f64> = (0..n).map(|r| (0..n).map(|c| mass[r * n + c] * rate[c]).sum::<f64>() + bias[r]).collect();
2177        let t = distribute(&a, &w, self.t_min, self.t_max, self.t_ref)
2178            .or_else(|| distribute(&a, &w, -1e12, 1e12, self.t_ref))
2179            .unwrap_or_else(|| vec![f64::NAN; m]);
2180        out.extend(t);
2181    }
2182
2183    fn energy(&self, s: &[f64]) -> f64 {
2184        self.energy_parts(s).iter().sum()
2185    }
2186
2187    fn set_payload_attached(&mut self, attached: bool) {
2188        self.attached = attached;
2189    }
2190    /// Elastic: the winches' gearboxes commit where the step ended (their mesh friction's and hysteresis's anchors).
2191    fn after_step(&mut self, s: &mut [f64], _dt: f64) {
2192        let (n, m) = (self.n(), self.m());
2193        if self.elastic {
2194            for k in 0..m {
2195                self.winches[k].gearbox.commit(s[2 * n + 2 * m + k], s[2 * n + k]);
2196            }
2197        }
2198    }
2199    fn memory(&self) -> Vec<f64> {
2200        sim_components::mech::Gearbox::anchors(self.winches.iter().map(|j| &j.gearbox))
2201    }
2202    fn set_memory(&mut self, memory: &[f64]) {
2203        sim_components::mech::Gearbox::set_anchors(self.winches.iter_mut().map(|j| &mut j.gearbox), memory)
2204    }
2205
2206    fn set_brake_engaged(&mut self, engaged: bool) {
2207        self.brake_engaged = engaged;
2208    }
2209    /// A stop met within the step (`HardStop::substeps`, `RotaryJoint::stop_substeps`).
2210    fn substeps_wanted(&self, s: &[f64], _torque: &[f64], dt: f64, _substeps: u32) -> u32 {
2211        let Some(spans) = self.spans(self.platform(s).0) else { return 1 };
2212        let (lengths, rates, ..) = self.winch_state(s, &spans);
2213        (0..self.m()).map(|k| self.winches[k].stop_substeps(lengths[k], rates[k], dt)).max().unwrap_or(1)
2214    }
2215    /// The push acts on the platform, beyond the cables, in either model (`pushed`); its power is the budget's crash
2216    /// row.
2217    fn set_tool_force(&mut self, force: &[f64]) -> bool {
2218        self.push.clear();
2219        self.push.extend_from_slice(force);
2220        true
2221    }
2222
2223    /// The gearboxes, in the order of `thermal_parts`.
2224    fn set_part_temperatures(&mut self, rises: &[f64]) {
2225        let Some(law) = &self.thermal else { return };
2226        for (winch, rise) in self.winches.iter_mut().filter(|w| !w.coupled).zip(rises) {
2227            winch.gearbox.efficiency = law.gearbox_efficiency(*rise) * winch.extra_efficiency;
2228            winch.shaft.set_oil(law.viscosity_factor(*rise));
2229        }
2230    }
2231
2232    fn resonance_hz(&self, tool_pose: &[f64]) -> Option<f64> {
2233        self.natural_frequencies(tool_pose)?.first().copied()
2234    }
2235    /// `natural_frequencies` with each mode's damping ratio from the cables' dampers (`cable_damping`).
2236    fn modes(&self, tool_pose: &[f64]) -> Vec<Mode> {
2237        let (Some(k), Some(c)) = (self.stiffness(tool_pose), self.cable_damping(tool_pose)) else { return Vec::new() };
2238        let mut modes = sim_components::chain::matrix_modes(&self.platform_mass(tool_pose), &k, &c, self.n());
2239        modes.sort_by(|a, b| a.hz.total_cmp(&b.hz));
2240        modes
2241    }
2242
2243    /// Out of the cables' reach (an anchor at its pulley), outside the wrench-feasible workspace (no tensions within
2244    /// the band hold the platform with its payload at rest), or a winch beyond its capacity.
2245    fn unreachable(&self, tool: &[f64], slack: f64) -> Option<&'static str> {
2246        let Some(spans) = self.spans(tool) else { return Some("error-target-out-of-range") };
2247        let a = self.structure(&spans);
2248        if distribute(&a, &self.weight(&spans), self.t_min, self.t_max, self.t_ref).is_none() {
2249            return Some("error-cable-wrench-infeasible");
2250        }
2251        let (min, max) = self.winches[0].range;
2252        let free = self.free_lengths(tool)?;
2253        free.iter().any(|l| *l < min - slack || *l > max + slack).then_some("error-joint-beyond-stop")
2254    }
2255
2256    /// The structure matrix's condition number, the turns weighed by the platform's size.
2257    /// What the gearboxes twist at rest anywhere in the tool's box (`rest_sag`).
2258    fn setpoint_slack(&self) -> f64 {
2259        // On a copy: `rest_sag` switches the payload, and nothing else it reads changes after `new`.
2260        *self.rest_slack.get_or_init(|| self.clone().rest_sag())
2261    }
2262
2263    fn condition(&self, tool: &[f64]) -> Option<f64> {
2264        let Some(spans) = self.spans(tool) else { return Some(f64::INFINITY) };
2265        let (n, m) = (self.n(), self.m());
2266        let mut a = self.structure(&spans);
2267        for (r, d) in self.dofs.iter().enumerate() {
2268            if *d >= 3 {
2269                (0..m).for_each(|k| a[r * m + k] /= self.size);
2270            }
2271        }
2272        let aat: Vec<f64> = (0..n * n).map(|rc| (0..m).map(|k| a[rc / n * m + k] * a[rc % n * m + k]).sum()).collect();
2273        let eig = eigenvalues(aat, n);
2274        let (least, most) = (eig[0], eig[n - 1]);
2275        Some(if least > 1e-24 * most { (most / least).sqrt() } else { f64::INFINITY })
2276    }
2277
2278    fn signal_infos(&self) -> Vec<SignalInfo> {
2279        let m = self.m();
2280        let mut out = Vec::new();
2281        for k in 0..m {
2282            out.push(SignalInfo::new(
2283                format!("cable.{}.tension", MOTOR_IDS[k]),
2284                CABLE_KEYS[k],
2285                "quantity-cable-tension",
2286                "N",
2287            ));
2288            out.push(SignalInfo::new(
2289                format!("cable.{}.shortfall", MOTOR_IDS[k]),
2290                CABLE_KEYS[k],
2291                "quantity-cable-shortfall",
2292                "N",
2293            ));
2294            out.push(SignalInfo::new(
2295                format!("cable.{}.length", MOTOR_IDS[k]),
2296                CABLE_KEYS[k],
2297                "quantity-cable-length",
2298                "m",
2299            ));
2300        }
2301        out.push(SignalInfo::new("platform.condition", "group-platform", "quantity-condition-number", ""));
2302        for motor in &self.motors {
2303            out.extend(TORQUE_PARTS.map(|part| {
2304                SignalInfo::new(
2305                    format!("motor.{}.torque_{part}", motor.id),
2306                    motor.key,
2307                    &format!("quantity-torque-{part}"),
2308                    "N m",
2309                )
2310            }));
2311        }
2312        for k in 0..m {
2313            out.push(SignalInfo::new(
2314                format!("{LOSS_PREFIX}winch_{}", MOTOR_IDS[k]),
2315                WINCH_KEYS[k],
2316                "quantity-friction-power",
2317                "W",
2318            ));
2319            out.push(SignalInfo::new(
2320                format!("{LOSS_PREFIX}shaft_{}", MOTOR_IDS[k]),
2321                MOTOR_KEYS[k],
2322                "quantity-shaft-friction-power",
2323                "W",
2324            ));
2325            // A winch on a coupling (ratio 1) has no gearbox: its loss is the coupling's, as no gearbox warms.
2326            let quantity =
2327                if self.winches[k].coupled { "quantity-coupling-loss-power" } else { "quantity-gearbox-loss-power" };
2328            out.push(SignalInfo::new(format!("{LOSS_PREFIX}gearbox_{}", MOTOR_IDS[k]), MOTOR_KEYS[k], quantity, "W"));
2329        }
2330        for k in 0..m {
2331            out.push(SignalInfo::new(
2332                format!("{LOSS_PREFIX}cable_{}", MOTOR_IDS[k]),
2333                CABLE_KEYS[k],
2334                "quantity-damping-power",
2335                "W",
2336            ));
2337        }
2338        out.push(SignalInfo::new(format!("{LOSS_PREFIX}hard_stops"), "group-winch", "quantity-damping-power", "W"));
2339        out.push(SignalInfo::new(format!("{LOSS_PREFIX}other"), "loss-other", "quantity-power-given-off", "W"));
2340        out.extend(ENERGY_PARTS.map(|part| {
2341            SignalInfo::new(format!("energy.{part}"), "group-energy", &format!("quantity-energy-{part}"), "J")
2342        }));
2343        for contact in self.friction_contacts() {
2344            for part in FRICTION_SIGNALS {
2345                let unit = match part {
2346                    "speed" => "m/s",
2347                    "load_scale" => "",
2348                    _ => "N",
2349                };
2350                out.push(SignalInfo::new(
2351                    format!("{}.friction_{part}", contact.id),
2352                    contact.owner_key,
2353                    &format!("quantity-friction-{}", part.replace('_', "-")),
2354                    unit,
2355                ));
2356            }
2357        }
2358        out
2359    }
2360
2361    fn base_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
2362        let (pose, _) = self.platform(s);
2363        if let Ok(mut last) = self.last_torque.0.lock() {
2364            *last = torque.to_vec();
2365        }
2366        let tension = self.state_tensions(s, torque);
2367        let lengths: Vec<f64> =
2368            self.spans(pose).map_or(vec![f64::NAN; self.m()], |sp| sp.iter().map(|s| s.length).collect());
2369        for k in 0..self.m() {
2370            out.extend([tension[k], (self.t_min - tension[k]).max(0.0), lengths[k]]);
2371        }
2372        out.push(self.condition(pose).unwrap_or(f64::INFINITY));
2373    }
2374
2375    /// Torque breakdown (inertia and gravity as the least-norm shares of the platform's wrench, plus the winches' own
2376    /// inertia; friction; the rest with the pretension), loss powers, energies, winch friction.
2377    fn effect_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
2378        let (n, m) = (self.n(), self.m());
2379        let (pose, xi) = self.platform(s);
2380        let Some(spans) = self.spans(pose) else {
2381            out.extend(vec![f64::NAN; 4 * m + 4 * m + 2 + 3 + 5 * m]);
2382            return;
2383        };
2384        let a = self.structure(&spans);
2385        let acc = self.twist_acceleration(s, torque);
2386        let mass = self.platform_mass(pose);
2387        let bias = self.platform_bias(pose, xi);
2388        let gravity_w = self.platform_bias(pose, &vec![0.0; n]);
2389        let inertia_w: Vec<f64> =
2390            (0..n).map(|r| (0..n).map(|c| mass[r * n + c] * acc[c]).sum::<f64>() + bias[r] - gravity_w[r]).collect();
2391        let (inertia_t, gravity_t) = (Self::least_norm(&a, &inertia_w), Self::least_norm(&a, &gravity_w));
2392        let curve = self.length_curvature(&spans, pose, xi);
2393        let (_, free_rates, _, speed) = self.winch_state(s, &spans);
2394        let brakes = self.brakes(s);
2395        let (powers, at_rotor) = self.losses(s, torque);
2396        for k in 0..m {
2397            let j = &self.winches[k];
2398            let lacc = curve[k] - (0..n).map(|r| a[r * m + k] * acc[r]).sum::<f64>();
2399            let held = j.brake.torque(self.brake_engaged, speed[k], brakes[k]).0;
2400            let parts = [
2401                (self.drum_mass[k] * lacc - inertia_t[k]) / j.ratio() + j.rotor_inertia * j.ratio() * lacc,
2402                -gravity_t[k] / j.ratio(),
2403                j.shaft.torque(speed[k]) + held + at_rotor[k] + j.friction.torque(free_rates[k]) / j.ratio(),
2404            ];
2405            out.extend(parts);
2406            out.push(torque[k] - parts.iter().sum::<f64>());
2407        }
2408        out.extend(&powers);
2409        out.extend(self.energy_parts(s));
2410        for k in 0..m {
2411            let f = &self.winches[k].friction;
2412            out.extend([
2413                free_rates[k],
2414                f.coulomb * (free_rates[k] / f.smoothing).tanh(),
2415                f.viscous * free_rates[k],
2416                0.0,
2417                1.0,
2418            ]);
2419        }
2420    }
2421    fn loss_powers(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
2422        out.extend(self.losses(s, torque).0);
2423    }
2424
2425    fn friction_contacts(&self) -> Vec<FrictionContact> {
2426        (0..self.m()).map(|k| FrictionContact { id: WINCH_CONTACTS[k], owner_key: WINCH_KEYS[k] }).collect()
2427    }
2428    /// The winch's bearings and pulley at the cable (`winch.friction_coulomb_n`, `friction_viscous_n_s_m`): N against the
2429    /// cable's speed in m/s, as the winch is a joint in metres of cable, so the contact is a sliding one (`friction_rotary`
2430    /// false, the default).
2431    fn friction_curve(&self, i: usize, speed: f64, _load_scale: f64) -> [f64; 3] {
2432        let Some(w) = self.winches.get(i) else { return [0.0; 3] };
2433        [w.friction.coulomb * (speed / w.friction.smoothing).tanh(), w.friction.viscous * speed, 0.0]
2434    }
2435    /// The cable runs at most at its motor's highest speed through the gearbox and the drum (`ratio`: rad per m).
2436    fn friction_speed_limit(&self, i: usize, motor_speed: &[f64]) -> Option<f64> {
2437        Some(motor_speed.get(i)? / self.winches.get(i)?.ratio())
2438    }
2439
2440    fn thermal_parts(&self) -> Vec<ThermalPart> {
2441        (0..self.m())
2442            .filter(|k| !self.winches[*k].coupled)
2443            .enumerate()
2444            .map(|(i, k)| ThermalPart {
2445                id: GEARBOX_IDS[k],
2446                kind: "gearbox",
2447                owner_key: MOTOR_KEYS[k],
2448                scene_part: "gearbox",
2449                scene_index: i,
2450            })
2451            .collect()
2452    }
2453
2454    /// The frame's posts, each winch (motor and gearbox) behind its pulley, the cables coloured by their tension against
2455    /// the reference, the platform.
2456    fn scene(&self, s: &[f64], out: &mut Scene) {
2457        out.parts.clear();
2458        out.labels.clear();
2459        let (pose, _) = self.platform(s);
2460        let Some(spans) = self.spans(pose) else { return };
2461        let (p, _) = self.place(pose);
2462        // The torques of the last signals (zero before any): the rigid model's tensions depend on them.
2463        let mut torque = self.last_torque.0.lock().map(|t| t.clone()).unwrap_or_default();
2464        torque.resize(self.m(), 0.0);
2465        let tension = self.state_tensions(s, &torque);
2466        let (_, _, rotor, speed) = self.winch_state(s, &spans);
2467        let grey = [0.55, 0.57, 0.6];
2468        let floor = self.frame.iter().map(|e| e[2]).fold(f64::INFINITY, f64::min) - 0.1;
2469        for (k, c) in self.cables.iter().enumerate() {
2470            let post = [c.exit[0], c.exit[1], floor];
2471            if !self.frame[..k].iter().any(|e| (e[0] - c.exit[0]).abs() < 1e-6 && (e[1] - c.exit[1]).abs() < 1e-6) {
2472                let top =
2473                    self.frame.iter().filter(|e| (e[0] - c.exit[0]).abs() < 1e-6 && (e[1] - c.exit[1]).abs() < 1e-6);
2474                let height = top.map(|e| e[2]).fold(f64::NEG_INFINITY, f64::max) + 0.1;
2475                out.parts.push(Part::new(
2476                    "frame",
2477                    Shape::Segment { to: [c.exit[0], c.exit[1], height], width: 0.05 },
2478                    post,
2479                    grey,
2480                ));
2481            }
2482            let back = add(c.exit, scale(c.axis, 0.12));
2483            out.parts.push(Part::new(
2484                "pulley",
2485                Shape::Cylinder { radius: self.pulley, length: 0.02 },
2486                c.exit,
2487                [0.3, 0.3, 0.32],
2488            ));
2489            out.parts.push(Part::new(
2490                sim_core::scene::MOTOR_PART,
2491                Shape::Box { size: [0.08, 0.08, 0.08] },
2492                add(back, scale(c.ref_x, -0.1)),
2493                [0.9, 0.45, 0.1],
2494            ));
2495            // The shaft's bar behind the motor turns with the rotor, as on every machine.
2496            out.parts.push(
2497                Part::new(
2498                    "rotor-bar",
2499                    Shape::Box { size: [0.07, 0.004, 0.012] },
2500                    add(back, scale(c.ref_x, -0.15)),
2501                    [0.1; 3],
2502                )
2503                .turned(rotor[k]),
2504            );
2505            out.parts.push(Part::new(
2506                "gearbox",
2507                Shape::Box { size: [0.06, 0.06, 0.06] },
2508                add(back, scale(c.ref_x, -0.03)),
2509                [0.25, 0.25, 0.28],
2510            ));
2511            out.parts.push(Part::new(
2512                "drum",
2513                Shape::Cylinder { radius: self.drum_radius, length: 0.05 },
2514                add(back, scale(c.ref_x, 0.04)),
2515                [0.75, 0.75, 0.78],
2516            ));
2517            let level = ((tension[k] - self.t_ref) / self.t_ref).clamp(-1.0, 1.0) as f32;
2518            out.parts.push(
2519                Part::new(
2520                    "cable",
2521                    Shape::Segment { to: add(p, spans[k].b), width: 0.006 },
2522                    spans[k].exit,
2523                    sim_core::scene::BELT_COLOR,
2524                )
2525                .highlighted(level),
2526            );
2527            if self.spatial {
2528                out.parts.push(Part::new(
2529                    "platform",
2530                    Shape::Segment { to: add(p, spans[k].b), width: 0.02 },
2531                    p,
2532                    [0.3, 0.45, 0.7],
2533                ));
2534            }
2535            out.labels.push(Label {
2536                pos: add(back, [0.0, 0.0, 0.1]),
2537                owner_key: MOTOR_KEYS[k],
2538                value: speed[k] * 60.0 / TAU,
2539                unit_key: "unit-rpm",
2540                decimals: 0,
2541            });
2542            out.labels.push(Label {
2543                pos: scale(add(spans[k].exit, add(p, spans[k].b)), 0.5),
2544                owner_key: CABLE_KEYS[k],
2545                value: tension[k],
2546                unit_key: "unit-n",
2547                decimals: 0,
2548            });
2549        }
2550        let size = if self.spatial { 0.08 } else { 0.1 };
2551        out.parts.push(Part::new("tool", Shape::Box { size: [size, size, size] }, p, [0.2, 0.22, 0.26]));
2552        if self.attached && self.payload > 0.0 {
2553            out.parts.push(Part::new(
2554                "payload",
2555                Shape::Box { size: [0.08, 0.08, 0.06] },
2556                add(p, [0.0, 0.0, -0.08]),
2557                [0.2, 0.7, 0.3],
2558            ));
2559        }
2560    }
2561    fn scene_point(&self, tool: &[f64]) -> Option<[f64; 3]> {
2562        Some(self.place(tool).0)
2563    }
2564    fn collision_bodies(&self, s: &[f64]) -> Vec<sim_core::Aabb> {
2565        let mut scene = Scene::default();
2566        self.scene(s, &mut scene);
2567        sim_core::scene::scene_boxes(&scene.parts, &["tool", "payload"])
2568    }
2569}
2570
2571#[cfg(test)]
2572mod tests;