Skip to main content

machine_hexapod_rotary/
lib.rs

1//! A six-axis platform on six cranks (6-RSS): six servo motors with gearboxes on the base, each turning a crank in its
2//! own plane (R), each crank's tip joined to the platform by a rod with a ball joint at both ends (S, S). The build of
3//! motion simulators and fast six-axis positioners. Six degrees of freedom: the tool pose is the centre of the platform
4//! joints' plane x, y, z (m, z above the plane of the crank axes) and the platform's orientation as a rotation vector
5//! rx, ry, rz (rad, axis times angle, in the base frame). Each joint coordinate is a crank angle theta_i (rad).
6//!
7//! Geometry (`[platform]`, `[crank]`, `[rod]`): the crank axes' centres B_i on a circle of `base_radius_m` in pairs at
8//! 120 k -+ `base_half_angle_deg`, the platform joints a_i (platform frame) on a circle of `platform_radius_m` at
9//! 120 k -+ (60 - `platform_half_angle_deg`), so that each leg runs from a base pair to the neighbouring platform pair.
10//! Each crank axis k_i is horizontal: the base radius through B_i turned about z by -+ `crank.axis_turn_deg` (mirrored
11//! in a pair). The crank turns in the vertical plane across it, spanned by d_i = k_i x z... written the other way round:
12//! d_i is the horizontal direction in the crank's plane that points away from the pair's partner, and k_i = d_i x z, so
13//! that a positive theta lifts the tip:
14//!
15//! ```text
16//! tip      C_i = B_i + r (cos theta d_i + sin theta z),  t_i = dC/dtheta = r (-sin theta d_i + cos theta z),
17//!          t2_i = d^2C/dtheta^2 = -r (cos theta d_i + sin theta z)
18//! joint    P_i = p + b_i,  b_i = R a_i;  the rod  |P_i - C_i| = L,  u_i = (P_i - C_i) / L
19//! inverse  e = P_i - B_i:  a cos theta + b sin theta = c,  a = e . d_i,  b = e . z,  c = (|e|^2 + r^2 - L^2) / (2 r),
20//!          theta = atan2(b, a) -+ acos(c / sqrt(a^2 + b^2)): "out" takes -, "in" takes + (`crank.branch`, once for all
21//!          legs); no solution where |c| > sqrt(a^2 + b^2) (the rod cannot reach)
22//! rates    A xi = diag(m) theta',  A row i = (u_i, b_i x u_i),  m_i = u_i . t_i (the crank's torque arm, m),
23//!          xi = (v, w) the platform's twist: xi = K theta', K = A^-1 diag(m)
24//!          A xi' = diag(m) theta'' + s,  s_i = u_i . t2_i theta_i'^2 - |v_i - t_i theta_i'|^2 / L - u_i . (w x (w x b_i)),
25//!          v_i = v + w x b_i
26//! forward  Newton on the twist: xi = A^-1 (L - |P_i - C_i|), p += v, R = exp(w) R, from the home pose, until the rods'
27//!          lengths are within 1e-12 m, and one step more; refused (NaN) where it does not converge within 40 steps
28//! ```
29//!
30//! The dead centre: the rod in the plane of the crank and its axis, u_i . t_i = 0, where the motor's torque arm m_i
31//! vanishes; the angle between the rod and the crank's tangent, acos(|u_i . t_i| / r), is 90 degrees there.
32//!
33//! Dynamics by virtual work in the crank angles (M theta'' + h = tau at the cranks):
34//!
35//! - the platform with the payload, one rigid body of mass m, first moment S = R s and inertia I = R I_p R^T about p:
36//!   M_xi = [m 1, -[S]x; [S]x, I], its required wrench W = M_xi xi' + (w x (w x S), w x I w) - (m g, S x g), through K:
37//!   K^T M_xi K and K^T (M_xi xi0' + c - G), xi0' = A^-1 s the twist's acceleration at theta'' = 0;
38//! - each rod a slender rigid rod (ball joints at both ends, its spin about its axis left out): a sixth of its mass at
39//!   each end, two thirds at its middle, which is exact for a uniform rod's mass, centre and inertia across; each a point
40//!   with its Jacobian P (3 x 6) in theta: m P^T P and m P^T (a0 - g);
41//! - each crank its inertia about its axis and its weight at `crank.cg_m` from the axis.
42//!
43//! The motor, its rotor through the ratio, the gearbox (stiffness, backlash, efficiency, drag) and the crank bearings'
44//! friction are each a `joint::RotaryJoint` (`chain::JointMachine`), as on the arms and the delta pickers.
45//!
46//! The force along each rod (`rod_forces`, compression positive) follows from the platform: A^T f = W plus the rods'
47//! upper ends, the rod's own mass carried by its nodes (its upper sixth and half its middle at the platform joint).
48//! The rods' spin about their own axes is free between two ball joints and nothing excites it, so it is not a state;
49//! the ball joints' friction has no published data and is left out.
50//!
51//! Parts that cross are checked among the rods (`workspace.min_rod_clearance_m`, axis to axis) and each rod against the
52//! platform's and the base's hexagon edges, the edges at its own two joints apart (`workspace.min_body_clearance_m`,
53//! axis to edge line; the rod's radius and the plate's half thickness make it).
54
55use sim_components::chain::{
56    JOINT_KEYS, JointMachine, JointSpec, MOTOR_IDS, MOTOR_KEYS, Mechanism, condition_number, solve,
57};
58use sim_components::joint::RotaryJoint;
59use sim_components::mech::ThermalFeedback;
60use sim_components::rigid::{M3, V3, add, cross, dot, exp, log, matmul, mul, transpose};
61use sim_core::{
62    AxisInfo, Config, ConfigError, Label, Machine, MachineEntry, MotorInfo, Part, RatingCheck, Scene, Shape, SignalInfo,
63};
64use std::f64::consts::{FRAC_PI_2, PI, TAU};
65
66pub static ENTRY: MachineEntry = MachineEntry {
67    id: "hexapod-rotary",
68    key: "machine-hexapod-rotary",
69    default_config: include_str!("../default.toml"),
70    i18n: &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))],
71    build,
72    suite_configs,
73};
74
75const G: f64 = 9.80665;
76
77/// Effects that take energy out or put it in; the standard suite runs with them off.
78pub const LOSSY_EFFECTS: [&str; 7] = [
79    "joint_friction",
80    "motor_friction",
81    "gearbox_drag",
82    "gearbox_lost_motion",
83    "gearbox_efficiency",
84    "torque_ripple",
85    "holding_brake",
86];
87
88const AXIS_IDS: [&str; 6] = ["x", "y", "z", "rx", "ry", "rz"];
89const AXIS_KEYS: [&str; 6] = ["axis-x", "axis-y", "axis-z", "axis-rx", "axis-ry", "axis-rz"];
90const Z: V3 = [0.0, 0.0, 1.0];
91
92/// The default config with every loss switched off.
93pub fn lossless_config() -> Config {
94    let mut cfg = ENTRY.config();
95    for effect in LOSSY_EFFECTS {
96        cfg.set_text(&format!("effects.{effect} = false")).unwrap();
97    }
98    cfg.set_text("gearbox.damping_nm_s_rad = 0.0").unwrap();
99    cfg.set_text("joint.stop_damping_nm_s_rad = 0.0").unwrap();
100    cfg
101}
102
103/// Loss-free rigid and elastic models, with and without the payload, all without gravity: held by constant crank
104/// torques, as the suite holds it after its pulse, the platform under its weight is not held in place (the cranks'
105/// torques at rest keep the rods' forces, not the pose), so it runs away from the pose, a real property that the
106/// position loops hold and not a numerical one (tried: the rigid loss-free config with gravity leaves the pose within the
107/// suite's 10 s, its invariant off by 80 times the pulse's energy). Gravity's part is checked on the default config
108/// (static hold, loss budget) and by the hand-calculated holding torques. Without gravity nothing holds the gearboxes against a flank
109/// either: the suite's pulse sends them across their backlash, and each crossing's impact (whether it falls before or
110/// after a step's end) changed the travel after a second by 1.2 % when the step was halved. So the backlash is off
111/// here too; the default config, which runs the suite's static hold and loss budget, keeps it.
112fn suite_configs() -> Vec<Config> {
113    [(false, true), (false, false), (true, true), (true, false)]
114        .into_iter()
115        .map(|(elastic, payload)| {
116            let mut cfg = lossless_config();
117            cfg.set_text(&format!("effects.joint_elasticity = {elastic}")).unwrap();
118            cfg.set_text(&format!("effects.payload = {payload}")).unwrap();
119            cfg.set_text("effects.gravity = false").unwrap();
120            cfg.set_text("effects.gearbox_backlash = false").unwrap();
121            cfg
122        })
123        .collect()
124}
125
126fn sub(a: V3, b: V3) -> V3 {
127    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
128}
129
130fn scale(a: V3, k: f64) -> V3 {
131    a.map(|v| v * k)
132}
133
134fn norm(a: V3) -> f64 {
135    dot(a, a).sqrt()
136}
137
138/// A 6 x 6 matrix factored by Gaussian elimination with partial pivoting (P A = L U), to solve with it more than once.
139struct Lu {
140    a: [f64; 36],
141    pivot: [usize; 6],
142}
143
144impl Lu {
145    /// The factors of `m` (row by row); `None` where it is singular.
146    fn of(m: &[f64]) -> Option<Lu> {
147        let mut a: [f64; 36] = std::array::from_fn(|k| m[k]);
148        let mut pivot = [0; 6];
149        for c in 0..6 {
150            let p = (c..6).max_by(|&i, &j| a[i * 6 + c].abs().total_cmp(&a[j * 6 + c].abs()))?;
151            if !(a[p * 6 + c].abs() > 1e-300) {
152                return None;
153            }
154            pivot[c] = p;
155            if p != c {
156                for k in 0..6 {
157                    a.swap(p * 6 + k, c * 6 + k);
158                }
159            }
160            for r in c + 1..6 {
161                let f = a[r * 6 + c] / a[c * 6 + c];
162                a[r * 6 + c] = f;
163                for k in c + 1..6 {
164                    a[r * 6 + k] -= f * a[c * 6 + k];
165                }
166            }
167        }
168        Some(Lu { a, pivot })
169    }
170
171    /// x with A x = b.
172    fn solve(&self, mut b: [f64; 6]) -> [f64; 6] {
173        // The rows' interchanges first, in their order: the multipliers moved with every later interchange.
174        for c in 0..6 {
175            b.swap(c, self.pivot[c]);
176        }
177        for c in 0..6 {
178            for r in c + 1..6 {
179                b[r] -= self.a[r * 6 + c] * b[c];
180            }
181        }
182        for c in (0..6).rev() {
183            let s: f64 = (c + 1..6).map(|k| self.a[c * 6 + k] * b[k]).sum();
184            b[c] = (b[c] - s) / self.a[c * 6 + c];
185        }
186        b
187    }
188}
189
190/// The least distance between the segments p0-p1 and q0-q1.
191pub fn segment_distance(p0: V3, p1: V3, q0: V3, q1: V3) -> f64 {
192    let (d1, d2, r) = (sub(p1, p0), sub(q1, q0), sub(p0, q0));
193    let (a, e, f) = (dot(d1, d1), dot(d2, d2), dot(d2, r));
194    let (c, b) = (dot(d1, r), dot(d1, d2));
195    let denom = a * e - b * b;
196    let mut s = if denom > 1e-18 { ((b * f - c * e) / denom).clamp(0.0, 1.0) } else { 0.0 };
197    let mut t = (b * s + f) / e;
198    if t < 0.0 {
199        t = 0.0;
200        s = (-c / a).clamp(0.0, 1.0);
201    } else if t > 1.0 {
202        t = 1.0;
203        s = ((b - c) / a).clamp(0.0, 1.0);
204    }
205    norm(sub(add(p0, scale(d1, s)), add(q0, scale(d2, t))))
206}
207
208/// One leg at a pose: the crank's tip C, its tangent t and second derivative t2 by the crank angle, the platform joint
209/// P and its offset b = R a from the platform centre, the rod's unit vector u from C to P and its length |P - C|, the
210/// torque arm u . t, and the cosine of the crank angle.
211#[derive(Debug, Clone, Copy, Default)]
212pub struct Leg {
213    pub tip: V3,
214    pub t: V3,
215    pub t2: V3,
216    pub joint: V3,
217    pub b: V3,
218    pub u: V3,
219    pub length: f64,
220    pub arm: f64,
221    pub cos: f64,
222}
223
224/// A crank at its angle, which depends on the angle alone (not on the platform's pose): the tip, the tangent, the second
225/// derivative and the cosine of the angle.
226#[derive(Debug, Clone, Copy)]
227pub struct Crank {
228    pub tip: V3,
229    pub t: V3,
230    pub t2: V3,
231    pub cos: f64,
232}
233
234/// The kinematics, apart from masses and drives.
235#[derive(Debug, Clone)]
236pub struct Geometry {
237    /// Crank axes' centres (base frame), the cranks' zero directions d_i, their axes k_i, and the platform joints
238    /// (platform frame).
239    pub base: [V3; 6],
240    pub dir: [V3; 6],
241    pub axis: [V3; 6],
242    pub anchors: [V3; 6],
243    pub platform_radius: f64,
244    pub crank: f64,
245    pub rod: f64,
246    /// -1 for the branch "out", +1 for "in".
247    pub branch: f64,
248    /// Working range: the least angle from the dead centre (rad), the steepest rod at the crank's ball joint (out of the
249    /// crank's plane) and at the platform's (against the platform's normal), rad, the least distance between two rods
250    /// (m), the highest condition number.
251    pub min_margin: f64,
252    pub max_crank_joint: f64,
253    pub max_platform_joint: f64,
254    pub min_clearance: f64,
255    /// The least distance of a rod's axis from the platform's and the base's hexagon edges (m).
256    pub min_body_clearance: f64,
257    pub max_condition: f64,
258    /// The pose Newton's forward kinematics starts from: the centre of the tool's box.
259    pub home: [f64; 6],
260    /// The cranks' angles at `home` and the twist per crank angle there (K, 6 x 6): Newton starts from home moved by
261    /// K (q - q_home), a guess that depends on q alone (`set_home`); it saves about two of its steps.
262    home_q: [f64; 6],
263    home_k: [f64; 36],
264}
265
266impl Geometry {
267    /// Joints at the azimuths 120 k -+ the base half angle and 120 k -+ (60 - the platform half angle), degrees; each
268    /// crank axis the base radius turned by -+ `axis_turn` degrees; cranks of length `crank`, rods of `rod`.
269    pub fn new(
270        base_radius: f64,
271        base_half: f64,
272        platform_radius: f64,
273        platform_half: f64,
274        axis_turn: f64,
275        crank: f64,
276        rod: f64,
277        out: bool,
278    ) -> Self {
279        let at = |radius: f64, deg: f64| [radius * deg.to_radians().cos(), radius * deg.to_radians().sin(), 0.0];
280        let side = |i: usize| if i.is_multiple_of(2) { -1.0 } else { 1.0 };
281        let base = std::array::from_fn(|i| at(base_radius, 120.0 * (i / 2) as f64 + side(i) * base_half));
282        let anchors =
283            std::array::from_fn(|i| at(platform_radius, 120.0 * (i / 2) as f64 + side(i) * (60.0 - platform_half)));
284        let dir: [V3; 6] = std::array::from_fn(|i| {
285            let n = at(1.0, 120.0 * (i / 2) as f64 + side(i) * (base_half + axis_turn));
286            // z x n, the tangent turning counter-clockwise, towards the partner for the first of a pair.
287            scale([-n[1], n[0], 0.0], side(i))
288        });
289        let axis = std::array::from_fn(|i| cross(dir[i], Z));
290        Self {
291            base,
292            dir,
293            axis,
294            anchors,
295            platform_radius,
296            crank,
297            rod,
298            branch: if out { -1.0 } else { 1.0 },
299            min_margin: 0.0,
300            max_crank_joint: FRAC_PI_2,
301            max_platform_joint: PI,
302            min_clearance: 0.0,
303            min_body_clearance: 0.0,
304            max_condition: f64::INFINITY,
305            home: [0.0; 6],
306            home_q: [0.0; 6],
307            home_k: [0.0; 36],
308        }
309    }
310
311    /// Sets the pose the forward kinematics starts from, and its first-order guess there (none where home is out of
312    /// reach or singular).
313    pub fn set_home(&mut self, home: [f64; 6]) {
314        (self.home, self.home_q, self.home_k) = (home, [0.0; 6], [0.0; 36]);
315        let mut q = [0.0; 6];
316        if !self.inverse(&home, &mut q) {
317            return;
318        }
319        let legs = self.legs_at(&q, [home[0], home[1], home[2]], &Self::rotation(&home));
320        let Some(lu) = Lu::of(&Self::constraint(&legs)) else { return };
321        for c in 0..6 {
322            let col = lu.solve(std::array::from_fn(|i| if i == c { legs[c].arm } else { 0.0 }));
323            (0..6).for_each(|r| self.home_k[r * 6 + c] = col[r]);
324        }
325        self.home_q = q;
326    }
327
328    pub fn rotation(tool: &[f64]) -> M3 {
329        exp([tool[3], tool[4], tool[5]])
330    }
331
332    /// Crank i's tip, tangent and second derivative at the angle theta.
333    pub fn tip(&self, i: usize, theta: f64) -> Crank {
334        let (s, c) = theta.sin_cos();
335        let (r, d) = (self.crank, self.dir[i]);
336        Crank {
337            tip: add(self.base[i], scale(add(scale(d, c), scale(Z, s)), r)),
338            t: scale(add(scale(d, -s), scale(Z, c)), r),
339            t2: scale(add(scale(d, c), scale(Z, s)), -r),
340            cos: c,
341        }
342    }
343
344    /// The six cranks at the angles `q`: what a Newton iteration over the platform's pose keeps, since the cranks do not
345    /// move with it.
346    pub fn cranks(&self, q: &[f64]) -> [Crank; 6] {
347        std::array::from_fn(|i| self.tip(i, q[i]))
348    }
349
350    /// The crank angle that puts crank i's rod onto the platform joint at `joint` (closed form); `None` out of reach.
351    pub fn crank_angle(&self, i: usize, joint: V3) -> Option<f64> {
352        let e = sub(joint, self.base[i]);
353        let (a, b) = (dot(e, self.dir[i]), e[2]);
354        let c = (dot(e, e) + self.crank * self.crank - self.rod * self.rod) / (2.0 * self.crank);
355        let rho = a.hypot(b);
356        if !(c.abs() <= rho) {
357            return None;
358        }
359        Some(b.atan2(a) + self.branch * (c / rho).acos())
360    }
361
362    /// The legs at crank angles `q` with the platform at `p` turned by `r`.
363    pub fn legs_at(&self, q: &[f64], p: V3, r: &M3) -> [Leg; 6] {
364        self.legs_on(&self.cranks(q), p, r)
365    }
366
367    /// `legs_at` with the cranks (`cranks`) known.
368    fn legs_on(&self, cranks: &[Crank; 6], p: V3, r: &M3) -> [Leg; 6] {
369        std::array::from_fn(|i| {
370            let Crank { tip, t, t2, cos } = cranks[i];
371            let b = mul(r, self.anchors[i]);
372            let joint = add(p, b);
373            let d = sub(joint, tip);
374            let length = norm(d);
375            let u = scale(d, 1.0 / length);
376            Leg { tip, t, t2, joint, b, u, length, arm: dot(u, t), cos }
377        })
378    }
379
380    /// Crank angles for a tool pose (closed form); `false` where a rod cannot reach.
381    pub fn inverse(&self, tool: &[f64], q: &mut [f64]) -> bool {
382        let (p, r) = ([tool[0], tool[1], tool[2]], Self::rotation(tool));
383        for i in 0..6 {
384            match self.crank_angle(i, add(p, mul(&r, self.anchors[i]))) {
385                Some(theta) => q[i] = theta,
386                None => return false,
387            }
388        }
389        true
390    }
391
392    /// The legs at a tool pose, by the inverse; `None` out of reach.
393    pub fn legs(&self, tool: &[f64]) -> Option<[Leg; 6]> {
394        let mut q = [0.0; 6];
395        self.inverse(tool, &mut q).then(|| self.legs_at(&q, [tool[0], tool[1], tool[2]], &Self::rotation(tool)))
396    }
397
398    /// A (6 x 6, row by row): row i (u_i, b_i x u_i), the rate of rod i's length over the platform's twist.
399    pub fn constraint(legs: &[Leg; 6]) -> [f64; 36] {
400        let mut a = [0.0; 36];
401        for (i, leg) in legs.iter().enumerate() {
402            let m = cross(leg.b, leg.u);
403            a[i * 6..i * 6 + 6].copy_from_slice(&[leg.u[0], leg.u[1], leg.u[2], m[0], m[1], m[2]]);
404        }
405        a
406    }
407
408    /// The inverse Jacobian (6 x 6, row by row): the crank rates per platform twist, theta' = diag(m)^-1 A xi.
409    pub fn inverse_jacobian(legs: &[Leg; 6]) -> Vec<f64> {
410        let mut j = Self::constraint(legs);
411        for (i, leg) in legs.iter().enumerate() {
412            j[i * 6..i * 6 + 6].iter_mut().for_each(|v| *v /= leg.arm);
413        }
414        j.to_vec()
415    }
416
417    /// The platform's centre and rotation for crank angles, by Newton's method from `home`; `None` where it does not
418    /// converge.
419    pub fn pose(&self, q: &[f64]) -> Option<(V3, M3)> {
420        self.pose_on(&self.cranks(q), q)
421    }
422
423    /// `pose` with the cranks at `q` known.
424    fn pose_on(&self, cranks: &[Crank; 6], q: &[f64]) -> Option<(V3, M3)> {
425        let dq: [f64; 6] = std::array::from_fn(|c| q[c] - self.home_q[c]);
426        let guess: [f64; 6] = std::array::from_fn(|r| (0..6).map(|c| self.home_k[r * 6 + c] * dq[c]).sum());
427        // Far from home (or out of reach of the guess) Newton starts from home itself.
428        let ok = guess.iter().all(|v| v.is_finite() && v.abs() < 0.5);
429        let guess = if ok { guess } else { [0.0; 6] };
430        let p = add([self.home[0], self.home[1], self.home[2]], [guess[0], guess[1], guess[2]]);
431        let r = matmul(&exp([guess[3], guess[4], guess[5]]), &Self::rotation(&self.home));
432        self.pose_from(cranks, p, r)
433    }
434
435    /// `pose`'s Newton from the platform at `p` turned by `r`, for the cranks at the angles asked for.
436    fn pose_from(&self, cranks: &[Crank; 6], mut p: V3, mut r: M3) -> Option<(V3, M3)> {
437        for _ in 0..40 {
438            let legs = self.legs_on(cranks, p, &r);
439            let miss: [f64; 6] = std::array::from_fn(|i| self.rod - legs[i].length);
440            let worst = miss.iter().fold(0.0f64, |m, v| m.max(v.abs()));
441            if !worst.is_finite() {
442                return None;
443            }
444            let step = Lu::of(&Self::constraint(&legs))?.solve(miss);
445            p = add(p, [step[0], step[1], step[2]]);
446            r = matmul(&exp([step[3], step[4], step[5]]), &r);
447            // Within 1e-12 m one more step: Newton's square takes the rest to the rounding (stopping at 1e-13 left some
448            // poses unconverged by their rounding, stopping at 1e-12 left 1e-13 of noise in the pose, which the
449            // controller's differences of the forward kinematics amplify).
450            if worst < 1e-12 {
451                return Some((p, r));
452            }
453        }
454        None
455    }
456
457    /// The tool pose for crank angles (`pose`); NaN where it does not converge.
458    pub fn forward(&self, q: &[f64], tool: &mut [f64]) {
459        match self.pose(q) {
460            Some((p, r)) => {
461                let rv = log(&r);
462                tool[..6].copy_from_slice(&[p[0], p[1], p[2], rv[0], rv[1], rv[2]]);
463            }
464            None => tool.iter_mut().for_each(|v| *v = f64::NAN),
465        }
466    }
467
468    /// The condition number of the inverse Jacobian with the turns weighed by the platform radius (the platform
469    /// joints' speed for w); infinite out of reach and where one crank is at its dead centre (all six at once scale the
470    /// rows alike, which the dead centre's margin in `unreachable` catches).
471    pub fn condition(&self, tool: &[f64]) -> f64 {
472        let Some(legs) = self.legs(tool) else { return f64::INFINITY };
473        let mut j = Self::inverse_jacobian(&legs);
474        for i in 0..6 {
475            for c in 3..6 {
476                j[i * 6 + c] /= self.platform_radius;
477            }
478        }
479        if !j.iter().all(|v| v.is_finite()) {
480            return f64::INFINITY;
481        }
482        condition_number(&j, 6, 6)
483    }
484
485    /// Per leg: the rod's angle from the crank's tangent (90 degrees at the dead centre), its angle out of the crank's
486    /// plane at the crank's ball joint, and its angle against the platform's normal at the platform's, rad.
487    pub fn angles(&self, legs: &[Leg; 6], r: &M3) -> [[f64; 3]; 6] {
488        let normal = mul(r, Z);
489        std::array::from_fn(|i| {
490            let leg = &legs[i];
491            [
492                (leg.arm.abs() / self.crank).clamp(0.0, 1.0).acos(),
493                dot(leg.u, self.axis[i]).abs().clamp(0.0, 1.0).asin(),
494                dot(leg.u, normal).clamp(-1.0, 1.0).acos(),
495            ]
496        })
497    }
498
499    /// The least distance between the axes of two rods, m.
500    pub fn clearance(legs: &[Leg; 6]) -> f64 {
501        let mut least = f64::INFINITY;
502        for i in 0..6 {
503            for j in i + 1..6 {
504                least = least.min(segment_distance(legs[i].tip, legs[i].joint, legs[j].tip, legs[j].joint));
505            }
506        }
507        least
508    }
509
510    /// The least distance of a rod's axis from the platform's hexagon (its joints in order) and the base's (the crank
511    /// axes' centres in order): the edges that end at the rod's own platform joint, and at its own crank axis, apart.
512    pub fn body_clearance(&self, legs: &[Leg; 6]) -> f64 {
513        let mut least = f64::INFINITY;
514        for i in 0..6 {
515            for j in 0..6 {
516                let k = (j + 1) % 6;
517                if i != j && i != k {
518                    least = least.min(segment_distance(legs[i].tip, legs[i].joint, legs[j].joint, legs[k].joint));
519                    least = least.min(segment_distance(legs[i].tip, legs[i].joint, self.base[j], self.base[k]));
520                }
521            }
522        }
523        least
524    }
525}
526
527/// The platform with what it carries, as one rigid body in the platform frame: mass, first moment (kg m) and inertia
528/// about the platform centre.
529#[derive(Debug, Clone, Copy)]
530struct Body {
531    mass: f64,
532    moment: V3,
533    inertia: M3,
534}
535
536/// A body's inertia about a point `c` from its centre of mass: I_cg + m (|c|^2 1 - c c^T).
537fn shifted(diag: V3, m: f64, c: V3) -> M3 {
538    std::array::from_fn(|i| {
539        std::array::from_fn(|j| if i == j { diag[i] + m * dot(c, c) } else { 0.0 } - m * c[i] * c[j])
540    })
541}
542
543impl Body {
544    fn plus(&self, other: &Body) -> Body {
545        Body {
546            mass: self.mass + other.mass,
547            moment: add(self.moment, other.moment),
548            inertia: std::array::from_fn(|i| std::array::from_fn(|j| self.inertia[i][j] + other.inertia[i][j])),
549        }
550    }
551}
552
553/// The mechanism: geometry, platform, payload, cranks and rods.
554#[derive(Clone)]
555pub struct RotaryPlatform {
556    pub geo: Geometry,
557    platform: Body,
558    payload: Body,
559    attached: bool,
560    /// The rods' shares the dynamics counts with the platform: a third of each rod's mass at its platform joint for the
561    /// inertia (the m/3 H^T H of its upper end and middle), a half for the weight (m/6 and m/3).
562    rods_inertia: Body,
563    rods_weight: Body,
564    pub crank_mass: f64,
565    pub crank_cg: f64,
566    pub crank_inertia: f64,
567    pub rod_mass: f64,
568    g: f64,
569    /// Rating limits: the rod's angle from the crank's tangent (rad), the rods' buckling load over the safety factor
570    /// (N); the ball joints' from the working range.
571    dead_centre_limit: f64,
572    buckling_limit: f64,
573    /// The grid point's pose the dynamics' Newton starts from (`warm_motion`).
574    last: LastFound,
575}
576
577/// What the platform's motion is at crank angles and rates: the pose, the legs, A^-1, K = A^-1 diag(m), the twist and
578/// its acceleration at theta'' = 0.
579struct Motion {
580    tool: [f64; 6],
581    r: M3,
582    legs: [Leg; 6],
583    k: [f64; 36],
584    xi: [f64; 6],
585    xi0: [f64; 6],
586}
587
588/// The pose at a point of the crank angles' grid (`ANCHOR_STEP`) the dynamics' Newton starts from: the grid point's
589/// index, its crank angles, the platform's centre and rotation, and K there.
590#[derive(Debug, Clone, Copy)]
591struct Found {
592    key: [i64; 6],
593    q: [f64; 6],
594    p: V3,
595    r: M3,
596    k: [f64; 36],
597}
598
599/// The grid of crank angles the dynamics' Newton starts from, rad: from the nearest point, so the pose is a function of
600/// the angles alone, whatever was called before (a run, its replay and a perturbed run give the same numbers).
601const ANCHOR_STEP: f64 = 1e-3;
602
603/// The last grid point's pose behind a lock (`Mechanism` is `Send`, and the integrator calls `dynamics` through `&self`).
604#[derive(Debug, Default)]
605struct LastFound(std::sync::Mutex<Option<Found>>);
606
607impl LastFound {
608    fn get(&self) -> Option<Found> {
609        self.0.lock().ok().and_then(|f| *f)
610    }
611    fn set(&self, found: Option<Found>) {
612        if let Ok(mut f) = self.0.lock() {
613            *f = found;
614        }
615    }
616}
617
618impl Clone for LastFound {
619    fn clone(&self) -> Self {
620        Self(std::sync::Mutex::new(self.get()))
621    }
622}
623
624fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
625    let (machine, _) = RotaryPlatform::from_config(cfg)?;
626    sim_components::base::mount(cfg, machine)
627}
628
629fn vec3(cfg: &Config, key: &str, positive: bool) -> Result<V3, ConfigError> {
630    let v = cfg.f64s(key)?;
631    if v.len() != 3 || v.iter().any(|x| !x.is_finite() || (positive && !(*x > 0.0))) {
632        return Err(ConfigError::Invalid(key.into()));
633    }
634    Ok([v[0], v[1], v[2]])
635}
636
637impl RotaryPlatform {
638    /// The machine, and its mechanism alone for the tests.
639    pub fn from_config(cfg: &Config) -> Result<(Box<dyn Machine>, RotaryPlatform), ConfigError> {
640        let out = match cfg.get("crank.branch")?.as_str() {
641            Some("out") => true,
642            Some("in") => false,
643            _ => return Err(ConfigError::Invalid("crank.branch".into())),
644        };
645        let (crank, rod) = (cfg.positive("crank.length_m")?, cfg.positive("rod.length_m")?);
646        let mut geo = Geometry::new(
647            cfg.positive("platform.base_radius_m")?,
648            cfg.non_negative("platform.base_half_angle_deg")?,
649            cfg.positive("platform.platform_radius_m")?,
650            cfg.non_negative("platform.platform_half_angle_deg")?,
651            cfg.f64("crank.axis_turn_deg")?,
652            crank,
653            rod,
654            out,
655        );
656        geo.min_margin = cfg.non_negative("workspace.min_dead_centre_margin_deg")?.to_radians();
657        geo.max_crank_joint = cfg.positive("workspace.crank_joint_max_angle_deg")?.to_radians();
658        geo.max_platform_joint = cfg.positive("workspace.platform_joint_max_angle_deg")?.to_radians();
659        geo.min_clearance = cfg.non_negative("workspace.min_rod_clearance_m")?;
660        geo.min_body_clearance = cfg.non_negative("workspace.min_body_clearance_m")?;
661        geo.max_condition = cfg.positive("workspace.max_condition_number")?;
662        let (min, max) = (cfg.f64s("workspace.tool_min")?, cfg.f64s("workspace.tool_max")?);
663        if min.len() != 6 || max.len() != 6 {
664            return Err(ConfigError::Invalid("workspace.tool_min".into()));
665        }
666        if (0..6).any(|k| !(min[k] < max[k])) {
667            return Err(ConfigError::Invalid("workspace.tool_max".into()));
668        }
669        geo.set_home(std::array::from_fn(|k| 0.5 * (min[k] + max[k])));
670        let body =
671            |mass: f64, cg: V3, diag: V3| Body { mass, moment: scale(cg, mass), inertia: shifted(diag, mass, cg) };
672        let platform = body(
673            cfg.positive("mass.platform_kg")?,
674            vec3(cfg, "mass.platform_cg_m", false)?,
675            vec3(cfg, "mass.platform_inertia_kgm2", true)?,
676        );
677        let payload = if cfg.bool("effects.payload")? {
678            body(
679                cfg.non_negative("mass.payload_kg")?,
680                vec3(cfg, "mass.payload_cg_m", false)?,
681                vec3(cfg, "mass.payload_inertia_kgm2", false)?,
682            )
683        } else {
684            body(0.0, [0.0; 3], [0.0; 3])
685        };
686        // Euler's case 2 (both ends free to turn): F = pi^2 E I / L^2 of the tube's section.
687        let (d_out, wall) = (cfg.positive("rod.outer_diameter_m")?, cfg.positive("rod.wall_m")?);
688        if 2.0 * wall > d_out {
689            return Err(ConfigError::Invalid("rod.wall_m".into()));
690        }
691        let second_moment = PI / 64.0 * (d_out.powi(4) - (d_out - 2.0 * wall).powi(4));
692        let euler = PI * PI * cfg.positive("rod.youngs_modulus_pa")? * second_moment / (rod * rod);
693        let rod_mass = cfg.non_negative("rod.mass_kg")?;
694        let at_joints =
695            |m: f64| geo.anchors.iter().fold(body(0.0, [0.0; 3], [0.0; 3]), |sum, a| sum.plus(&body(m, *a, [0.0; 3])));
696        let (rods_inertia, rods_weight) = (at_joints(rod_mass / 3.0), at_joints(rod_mass / 2.0));
697        let mech = RotaryPlatform {
698            geo,
699            platform,
700            payload,
701            attached: true,
702            rods_inertia,
703            rods_weight,
704            crank_mass: cfg.non_negative("crank.mass_kg")?,
705            crank_cg: cfg.non_negative("crank.cg_m")?,
706            crank_inertia: cfg.positive("crank.inertia_kgm2")?,
707            rod_mass,
708            g: if cfg.bool("effects.gravity")? { G } else { 0.0 },
709            dead_centre_limit: FRAC_PI_2 - cfg.non_negative("ratings.crank_dead_centre_margin_deg")?.to_radians(),
710            buckling_limit: euler / cfg.positive("ratings.rod_buckling_safety_factor")?,
711            last: LastFound::default(),
712        };
713        let joint = RotaryJoint::from_config(cfg)?;
714        let axes = (0..6)
715            .map(|k| {
716                let unit = if k < 3 { "m" } else { "rad" };
717                let get =
718                    |what: &str, rate: &str| cfg.positive(&format!("axis.{}.max_{what}_{unit}_{rate}", AXIS_IDS[k]));
719                Ok(AxisInfo {
720                    id: AXIS_IDS[k],
721                    key: AXIS_KEYS[k],
722                    unit,
723                    min: min[k],
724                    max: max[k],
725                    max_vel: get("velocity", "s")?,
726                    max_acc: get("acceleration", "s2")?,
727                    max_jerk: get("jerk", "s3")?,
728                })
729            })
730            .collect::<Result<Vec<_>, ConfigError>>()?;
731        let specs = (0..6)
732            .map(|k| JointSpec {
733                drive: joint.clone(),
734                id: MOTOR_IDS[k],
735                key: JOINT_KEYS[k],
736                gear_lever: None,
737                unit: "rad",
738            })
739            .collect();
740        let motors = (0..6).map(|k| MotorInfo { id: MOTOR_IDS[k], key: MOTOR_KEYS[k] }).collect();
741        let machine = JointMachine::new(
742            mech.clone(),
743            specs,
744            cfg.bool("effects.joint_elasticity")?,
745            ThermalFeedback::from_config(cfg)?,
746            axes,
747            motors,
748        );
749        Ok((Box::new(machine), mech))
750    }
751
752    /// The platform with the payload as it is attached.
753    fn body(&self) -> Body {
754        if self.attached { self.platform.plus(&self.payload) } else { self.platform }
755    }
756
757    /// The Euler buckling load of a rod over its safety factor, N.
758    pub fn buckling_limit(&self) -> f64 {
759        self.buckling_limit
760    }
761
762    /// The platform's motion at crank angles q and rates qd; `None` where the forward kinematics fails or A is
763    /// singular.
764    fn motion(&self, q: &[f64], qd: &[f64]) -> Option<Motion> {
765        let cranks = self.geo.cranks(q);
766        self.motion_at(&cranks, qd, self.geo.pose_on(&cranks, q)?)
767    }
768
769    /// `motion` for the dynamics, which runs four times a sub-step: Newton starts from the pose at the nearest point of
770    /// the `ANCHOR_STEP` grid moved by K (q - q_grid), which takes it two steps instead of about four from `forward`'s
771    /// guess; as `motion` where that does not converge. The grid point's pose (by `motion`) is kept until the cranks
772    /// leave its cell. The pose differs from `forward`'s by Newton's tolerance (1e-12 m on the rods, and one step more).
773    fn warm_motion(&self, q: &[f64], qd: &[f64]) -> Option<Motion> {
774        let key: [i64; 6] = std::array::from_fn(|i| (q[i] / ANCHOR_STEP).round() as i64);
775        let cranks = self.geo.cranks(q);
776        let anchor = self.last.get().filter(|f| f.key == key).or_else(|| {
777            let g: [f64; 6] = std::array::from_fn(|i| key[i] as f64 * ANCHOR_STEP);
778            let at_grid = self.geo.cranks(&g);
779            let (p, r) = self.geo.pose_on(&at_grid, &g)?;
780            let found = Found { key, q: g, p, r, k: self.motion_at(&at_grid, &[0.0; 6], (p, r))?.k };
781            self.last.set(Some(found));
782            Some(found)
783        });
784        let warm = anchor.and_then(|f| {
785            let xi: [f64; 6] = std::array::from_fn(|r| (0..6).map(|c| f.k[r * 6 + c] * (q[c] - f.q[c])).sum());
786            self.geo.pose_from(&cranks, add(f.p, [xi[0], xi[1], xi[2]]), matmul(&exp([xi[3], xi[4], xi[5]]), &f.r))
787        });
788        let pose = match warm {
789            Some(pose) => pose,
790            None => self.geo.pose_on(&cranks, q)?,
791        };
792        self.motion_at(&cranks, qd, pose)
793    }
794
795    /// `motion` with the platform's centre and rotation known.
796    fn motion_at(&self, cranks: &[Crank; 6], qd: &[f64], (p, r): (V3, M3)) -> Option<Motion> {
797        let rv = log(&r);
798        let tool = [p[0], p[1], p[2], rv[0], rv[1], rv[2]];
799        let legs = self.geo.legs_on(cranks, p, &r);
800        let lu = Lu::of(&Geometry::constraint(&legs))?;
801        let mut k = [0.0; 36];
802        for c in 0..6 {
803            let col = lu.solve(std::array::from_fn(|i| if i == c { legs[c].arm } else { 0.0 }));
804            (0..6).for_each(|r| k[r * 6 + c] = col[r]);
805        }
806        let xi = lu.solve(std::array::from_fn(|i| legs[i].arm * qd[i]));
807        let (v, w) = ([xi[0], xi[1], xi[2]], [xi[3], xi[4], xi[5]]);
808        let s: [f64; 6] = std::array::from_fn(|i| {
809            let leg = &legs[i];
810            let slip = sub(add(v, cross(w, leg.b)), scale(leg.t, qd[i]));
811            dot(leg.u, leg.t2) * qd[i] * qd[i] - dot(slip, slip) / self.geo.rod - dot(leg.u, cross(w, cross(w, leg.b)))
812        });
813        let xi0 = lu.solve(s);
814        Some(Motion { tool, r, legs, k, xi, xi0 })
815    }
816
817    /// The platform joint's velocity per crank rate (3 x 6, row by row): K_v + K_w x b.
818    fn joint_jacobian(m: &Motion, b: V3) -> [[f64; 6]; 3] {
819        let mut out = [[0.0; 6]; 3];
820        for c in 0..6 {
821            let v = [m.k[c], m.k[6 + c], m.k[12 + c]];
822            let w = [m.k[18 + c], m.k[24 + c], m.k[30 + c]];
823            let col = add(v, cross(w, b));
824            (0..3).for_each(|r| out[r][c] = col[r]);
825        }
826        out
827    }
828
829    /// The body's mass matrix over the twist (6 x 6), its speed terms c and its weight G, in the base frame.
830    /// `body` moves, `weight` weighs (the same but where the rods' shares differ).
831    fn twist_terms(&self, m: &Motion, body: &Body, weight: &Body) -> ([f64; 36], [f64; 6], [f64; 6]) {
832        let s = mul(&m.r, body.moment);
833        let inertia = matmul(&matmul(&m.r, &body.inertia), &transpose(&m.r));
834        let mut mx = [0.0; 36];
835        for i in 0..3 {
836            mx[i * 6 + i] = body.mass;
837            for j in 0..3 {
838                mx[(3 + i) * 6 + 3 + j] = inertia[i][j];
839            }
840        }
841        // [S]x in the lower left, -[S]x in the upper right.
842        let sx = [[0.0, -s[2], s[1]], [s[2], 0.0, -s[0]], [-s[1], s[0], 0.0]];
843        for i in 0..3 {
844            for j in 0..3 {
845                mx[(3 + i) * 6 + j] = sx[i][j];
846                mx[i * 6 + 3 + j] = -sx[i][j];
847            }
848        }
849        let w = [m.xi[3], m.xi[4], m.xi[5]];
850        let (f, t) = (cross(w, cross(w, s)), cross(w, mul(&inertia, w)));
851        let gw = cross(mul(&m.r, weight.moment), [0.0, 0.0, -self.g]);
852        (mx, [f[0], f[1], f[2], t[0], t[1], t[2]], [0.0, 0.0, -weight.mass * self.g, gw[0], gw[1], gw[2]])
853    }
854
855    /// The force along each rod (compression positive, N) at crank angles, rates and accelerations: A^T f = W, the
856    /// platform's required wrench with the rods' upper sixth and half their middle carried at the platform joints.
857    pub fn rod_forces(&self, q: &[f64], qd: &[f64], qdd: &[f64]) -> Option<[f64; 6]> {
858        let m = self.motion(q, qd)?;
859        let xi_acc: [f64; 6] = std::array::from_fn(|r| m.xi0[r] + (0..6).map(|c| m.k[r * 6 + c] * qdd[c]).sum::<f64>());
860        let body = self.body();
861        let (mx, c, g) = self.twist_terms(&m, &body, &body);
862        let mut wrench: [f64; 6] =
863            std::array::from_fn(|r| (0..6).map(|k| mx[r * 6 + k] * xi_acc[k]).sum::<f64>() + c[r] - g[r]);
864        let (v_acc, w_acc, w) =
865            ([xi_acc[0], xi_acc[1], xi_acc[2]], [xi_acc[3], xi_acc[4], xi_acc[5]], [m.xi[3], m.xi[4], m.xi[5]]);
866        for (i, leg) in m.legs.iter().enumerate() {
867            let a_high = add(add(v_acc, cross(w_acc, leg.b)), cross(w, cross(w, leg.b)));
868            let a_low = add(scale(leg.t, qdd[i]), scale(leg.t2, qd[i] * qd[i]));
869            let a_mid = scale(add(a_low, a_high), 0.5);
870            let need = |a: V3| [a[0], a[1], a[2] + self.g];
871            let f = add(scale(need(a_high), self.rod_mass / 6.0), scale(need(a_mid), self.rod_mass / 3.0));
872            let t = cross(leg.b, f);
873            for k in 0..3 {
874                wrench[k] += f[k];
875                wrench[3 + k] += t[k];
876            }
877        }
878        let a = Geometry::constraint(&m.legs);
879        let at: Vec<f64> = (0..36).map(|k| a[(k % 6) * 6 + k / 6]).collect();
880        let f = solve(&at, &wrench)?;
881        Some(std::array::from_fn(|i| f[i]))
882    }
883}
884
885impl Mechanism for RotaryPlatform {
886    fn dynamics(&self, q: &[f64], qd: &[f64], mass: &mut [f64], bias: &mut [f64]) {
887        let Some(m) = self.warm_motion(q, qd) else {
888            mass.fill(f64::NAN);
889            bias.fill(f64::NAN);
890            return;
891        };
892        // Each rod's three points (m/6 at its tip C with Jacobian L, m/6 at its joint P with H, 2m/3 at its middle with
893        // (L + H) / 2) give m/3 (L^T L + H^T H) + m/6 (L^T H + H^T L): the H^T H part a point of m/3 on the platform, the
894        // L^T L part m/3 r^2 on the crank (L only in crank i's column, t_i). Their accelerations at theta'' = 0 likewise:
895        // m/3 (L^T a_C + H^T a_P) + m/6 (L^T a_P + H^T a_C), t . a_C = t . t2 theta'^2 = 0. Their weight m/2 (L_z + H_z).
896        let (inertial, weighing) = (self.body().plus(&self.rods_inertia), self.body().plus(&self.rods_weight));
897        let (mx, c, g) = self.twist_terms(&m, &inertial, &weighing);
898        let need: [f64; 6] =
899            std::array::from_fn(|r| (0..6).map(|k| mx[r * 6 + k] * m.xi0[k]).sum::<f64>() + c[r] - g[r]);
900        // M_xi K, then K^T of it.
901        let mk: [f64; 36] = std::array::from_fn(|rc| (0..6).map(|k| mx[rc / 6 * 6 + k] * m.k[k * 6 + rc % 6]).sum());
902        for i in 0..6 {
903            bias[i] = (0..6).map(|r| m.k[r * 6 + i] * need[r]).sum();
904            for j in 0..6 {
905                mass[i * 6 + j] = (0..6).map(|r| m.k[r * 6 + i] * mk[r * 6 + j]).sum();
906            }
907        }
908        let (rod, w) = (self.rod_mass, [m.xi[3], m.xi[4], m.xi[5]]);
909        for (i, leg) in m.legs.iter().enumerate() {
910            let high = Self::joint_jacobian(&m, leg.b);
911            let a_high = add(add([m.xi0[0], m.xi0[1], m.xi0[2]], cross([m.xi0[3], m.xi0[4], m.xi0[5]], leg.b)), {
912                cross(w, cross(w, leg.b))
913            });
914            let a_low = scale(leg.t2, qd[i] * qd[i]);
915            for c in 0..6 {
916                let col = [high[0][c], high[1][c], high[2][c]];
917                let cross_term = rod / 6.0 * dot(leg.t, col);
918                mass[i * 6 + c] += cross_term;
919                mass[c * 6 + i] += cross_term;
920                bias[c] += rod / 6.0 * dot(col, a_low);
921            }
922            mass[i * 6 + i] += self.crank_inertia + rod / 3.0 * dot(leg.t, leg.t);
923            bias[i] += rod / 6.0 * dot(leg.t, a_high)
924                + self.g * (self.crank_mass * self.crank_cg + 0.5 * rod * self.geo.crank) * leg.cos;
925        }
926    }
927
928    /// The body at its centre of mass with its inertia about it, the rods' three points each, the cranks turning about
929    /// their axes, each rotor spinning along its crank's axis.
930    fn frame_momentum(&self, q: &[f64], qd: &[f64], rotor_spin: &[f64]) -> Option<sim_core::FrameMomentum> {
931        use sim_components::base::{add_point, add_spin, add_turning};
932        let m = self.motion(q, qd)?;
933        let mut f = sim_core::FrameMomentum { gravity: [0.0, 0.0, -self.g], ..Default::default() };
934        let body = self.body();
935        let (p, v, w) = ([m.tool[0], m.tool[1], m.tool[2]], [m.xi[0], m.xi[1], m.xi[2]], [m.xi[3], m.xi[4], m.xi[5]]);
936        if body.mass > 0.0 {
937            let rc = scale(mul(&m.r, body.moment), 1.0 / body.mass);
938            add_point(&mut f, body.mass, add(p, rc), add(v, cross(w, rc)));
939            let about_p = matmul(&matmul(&m.r, &body.inertia), &transpose(&m.r));
940            let own: M3 = std::array::from_fn(|i| {
941                std::array::from_fn(|j| {
942                    about_p[i][j] - body.mass * (if i == j { dot(rc, rc) } else { 0.0 } - rc[i] * rc[j])
943                })
944            });
945            let spin = mul(&own, w);
946            (0..3).for_each(|k| f.angular[k] += spin[k]);
947        }
948        for (i, leg) in m.legs.iter().enumerate() {
949            let (v_low, v_high) = (scale(leg.t, qd[i]), add(v, cross(w, leg.b)));
950            add_point(&mut f, self.rod_mass / 6.0, leg.tip, v_low);
951            add_point(&mut f, self.rod_mass / 6.0, leg.joint, v_high);
952            add_point(
953                &mut f,
954                2.0 * self.rod_mass / 3.0,
955                scale(add(leg.tip, leg.joint), 0.5),
956                scale(add(v_low, v_high), 0.5),
957            );
958            let r = self.geo.crank;
959            let dir = scale(sub(leg.tip, self.geo.base[i]), 1.0 / r);
960            add_turning(
961                &mut f,
962                self.geo.base[i],
963                dir,
964                scale(leg.t, 1.0 / r),
965                qd[i],
966                self.crank_inertia,
967                self.crank_mass * self.crank_cg,
968            );
969            add_spin(&mut f, self.geo.axis[i], 1.0, rotor_spin[i]);
970        }
971        Some(f)
972    }
973
974    fn potential(&self, q: &[f64]) -> f64 {
975        let mut tool = [0.0; 6];
976        self.geo.forward(q, &mut tool);
977        let r = Geometry::rotation(&tool);
978        let legs = self.geo.legs_at(q, [tool[0], tool[1], tool[2]], &r);
979        let body = self.body();
980        let rods: f64 = legs.iter().map(|l| 0.5 * self.rod_mass * (l.tip[2] + l.joint[2])).sum();
981        let cranks: f64 = q[..6].iter().map(|t| self.crank_mass * self.crank_cg * t.sin()).sum();
982        self.g * (body.mass * tool[2] + mul(&r, body.moment)[2] + rods + cranks)
983    }
984    fn set_payload_attached(&mut self, attached: bool) {
985        self.attached = attached;
986    }
987
988    fn forward(&self, q: &[f64], tool: &mut [f64]) {
989        self.geo.forward(q, tool);
990    }
991    fn inverse(&self, tool: &[f64], q: &mut [f64]) -> bool {
992        self.geo.inverse(tool, q)
993    }
994    /// Out of reach is told by the joint machine (`inverse`); here a crank too near its dead centre, a ball joint
995    /// beyond its angle, two rods too near each other or a rod too near the platform's or the base's edge, the
996    /// kinematics near a singularity.
997    fn unreachable(&self, tool: &[f64], _slack: f64) -> Option<&'static str> {
998        let legs = self.geo.legs(tool)?;
999        let angles = self.geo.angles(&legs, &Geometry::rotation(tool));
1000        if angles.iter().any(|a| !(FRAC_PI_2 - a[0] >= self.geo.min_margin)) {
1001            return Some("error-rss-dead-centre");
1002        }
1003        if angles.iter().any(|a| !(a[1] <= self.geo.max_crank_joint && a[2] <= self.geo.max_platform_joint)) {
1004            return Some("error-rss-ball-joint");
1005        }
1006        if !(Geometry::clearance(&legs) >= self.geo.min_clearance) {
1007            return Some("error-rss-rods-cross");
1008        }
1009        if !(self.geo.body_clearance(&legs) >= self.geo.min_body_clearance) {
1010            return Some("error-rss-rods-cross-body");
1011        }
1012        if !(self.geo.condition(tool) <= self.geo.max_condition) {
1013            return Some("error-rss-singularity");
1014        }
1015        None
1016    }
1017    fn condition(&self, tool: &[f64]) -> Option<f64> {
1018        Some(self.geo.condition(tool))
1019    }
1020    fn tool_is_joints(&self) -> bool {
1021        false
1022    }
1023
1024    /// Per leg: the rod's angle from the crank's tangent, its force and compression, its angles at both ball joints;
1025    /// then the condition number at the pose.
1026    fn signal_infos(&self) -> Vec<SignalInfo> {
1027        let mut out = Vec::new();
1028        for i in 0..6 {
1029            let id = MOTOR_IDS[i];
1030            out.push(SignalInfo::new(
1031                format!("crank.{id}.dead_centre_angle"),
1032                JOINT_KEYS[i],
1033                "quantity-dead-centre-angle",
1034                "rad",
1035            ));
1036            out.push(SignalInfo::new(format!("rod.{id}.force"), JOINT_KEYS[i], "quantity-rod-force", "N"));
1037            out.push(SignalInfo::new(format!("rod.{id}.compression"), JOINT_KEYS[i], "quantity-rod-compression", "N"));
1038            out.push(SignalInfo::new(
1039                format!("crank.{id}.ball_joint_angle"),
1040                JOINT_KEYS[i],
1041                "quantity-crank-ball-joint-angle",
1042                "rad",
1043            ));
1044            out.push(SignalInfo::new(
1045                format!("platform.{id}.ball_joint_angle"),
1046                JOINT_KEYS[i],
1047                "quantity-platform-ball-joint-angle",
1048                "rad",
1049            ));
1050        }
1051        out.push(SignalInfo::new("kinematics.condition", "group-platform", "quantity-condition-number", ""));
1052        out
1053    }
1054    fn signals(&self, q: &[f64], qd: &[f64], qdd: &[f64], _force: &[f64], out: &mut Vec<f64>) {
1055        let Some(m) = self.motion(q, qd) else {
1056            out.extend(std::iter::repeat_n(f64::NAN, 31));
1057            return;
1058        };
1059        let angles = self.geo.angles(&m.legs, &m.r);
1060        let forces = self.rod_forces(q, qd, qdd).unwrap_or([f64::NAN; 6]);
1061        for i in 0..6 {
1062            out.extend([angles[i][0], forces[i], forces[i].max(0.0), angles[i][1], angles[i][2]]);
1063        }
1064        out.push(self.geo.condition(&m.tool));
1065    }
1066    /// Per leg: the dead centre's margin, the rod's buckling, both ball joints' angles.
1067    fn rating_checks(&self) -> Vec<RatingCheck> {
1068        (0..6)
1069            .flat_map(|i| {
1070                let id = MOTOR_IDS[i];
1071                [
1072                    ("crank-dead-centre", format!("crank.{id}.dead_centre_angle"), self.dead_centre_limit),
1073                    ("rod-buckling", format!("rod.{id}.compression"), self.buckling_limit),
1074                    ("crank-ball-joint", format!("crank.{id}.ball_joint_angle"), self.geo.max_crank_joint),
1075                    ("platform-ball-joint", format!("platform.{id}.ball_joint_angle"), self.geo.max_platform_joint),
1076                ]
1077                .map(|(check, signal, limit)| RatingCheck {
1078                    check,
1079                    signal,
1080                    motor: Some(i),
1081                    limit,
1082                    life: false,
1083                })
1084            })
1085            .collect()
1086    }
1087
1088    fn collision_parts(&self) -> &'static [&'static str] {
1089        &["tool", "payload"]
1090    }
1091
1092    /// Base and platform as hexagons through their joints, each crank and rod, the motor with its gearbox behind each
1093    /// crank along its axis, the payload at its centre of mass.
1094    fn scene(&self, q: &[f64], rotors: &[f64], rotor_speeds: &[f64], out: &mut Scene) {
1095        let mut tool = [0.0; 6];
1096        self.geo.forward(q, &mut tool);
1097        if !tool.iter().all(|v| v.is_finite()) {
1098            return;
1099        }
1100        let r = Geometry::rotation(&tool);
1101        let p = [tool[0], tool[1], tool[2]];
1102        let legs = self.geo.legs_at(q, p, &r);
1103        for i in 0..6 {
1104            let next = (i + 1) % 6;
1105            out.parts.push(Part::new(
1106                "base",
1107                Shape::Segment { to: self.geo.base[next], width: 0.04 },
1108                self.geo.base[i],
1109                [0.55, 0.57, 0.6],
1110            ));
1111            out.parts.push(Part::new(
1112                "platform",
1113                Shape::Segment { to: legs[next].joint, width: 0.04 },
1114                legs[i].joint,
1115                [0.3, 0.45, 0.7],
1116            ));
1117        }
1118        for (i, leg) in legs.iter().enumerate() {
1119            let (b, k) = (self.geo.base[i], self.geo.axis[i]);
1120            out.parts.push(Part::new("crank", Shape::Segment { to: leg.tip, width: 0.04 }, b, [0.45, 0.47, 0.5]));
1121            out.parts.push(Part::new("rod", Shape::Segment { to: leg.joint, width: 0.02 }, leg.tip, [0.85, 0.86, 0.9]));
1122            out.parts.push(Part::new(
1123                "gearbox",
1124                Shape::Segment { to: add(b, scale(k, -0.12)), width: 0.08 },
1125                add(b, scale(k, -0.03)),
1126                [0.25, 0.25, 0.28],
1127            ));
1128            out.parts.push(Part::new(
1129                sim_core::scene::MOTOR_PART,
1130                Shape::Segment { to: add(b, scale(k, -0.25)), width: 0.09 },
1131                add(b, scale(k, -0.12)),
1132                [0.9, 0.45, 0.1],
1133            ));
1134            out.parts.push(
1135                Part::new("rotor-bar", Shape::Box { size: [0.07, 0.004, 0.012] }, add(b, scale(k, -0.27)), [0.1; 3])
1136                    .turned(rotors[i]),
1137            );
1138            out.labels.push(Label {
1139                pos: add(b, add(scale(k, -0.3), [0.0, 0.0, -0.05])),
1140                owner_key: MOTOR_KEYS[i],
1141                value: rotor_speeds[i] * 60.0 / TAU,
1142                unit_key: "unit-rpm",
1143                decimals: 0,
1144            });
1145            out.labels.push(Label {
1146                pos: add(leg.tip, [0.0, 0.0, 0.05]),
1147                owner_key: JOINT_KEYS[i],
1148                value: q[i].to_degrees(),
1149                unit_key: "unit-deg",
1150                decimals: 1,
1151            });
1152        }
1153        out.parts.push(Part::new(
1154            "tool",
1155            Shape::Box { size: [0.1, 0.1, 0.03] },
1156            add(p, mul(&r, [0.0, 0.0, 0.015])),
1157            [0.2, 0.22, 0.26],
1158        ));
1159        if self.attached && self.payload.mass > 0.0 {
1160            let at = scale(self.payload.moment, 1.0 / self.payload.mass);
1161            out.parts.push(Part::new(
1162                "payload",
1163                Shape::Box { size: [0.3, 0.3, 0.3] },
1164                add(p, mul(&r, at)),
1165                [0.2, 0.7, 0.3],
1166            ));
1167        }
1168        out.labels.push(Label {
1169            pos: add(p, [0.0, 0.0, 0.5]),
1170            owner_key: "axis-z",
1171            value: p[2],
1172            unit_key: "unit-m",
1173            decimals: 3,
1174        });
1175    }
1176    fn scene_point(&self, tool: &[f64]) -> Option<[f64; 3]> {
1177        Some([tool[0], tool[1], tool[2]])
1178    }
1179}
1180
1181#[cfg(test)]
1182mod tests;