Skip to main content

sim_components/
rigid.rs

1//! Rigid bodies in a serial chain: read from a URDF file, with their dynamics by the recursive Newton-Euler algorithm
2//! (Luh, Walker and Paul 1980; Craig, "Introduction to Robotics", chapter 6). A chain of revolute and prismatic joints
3//! on a fixed base; fixed joints are merged into the body before them.
4//!
5//! The URDF subset read: `<robot>` with `<link>` (its `<inertial>`: `<origin xyz rpy>`, `<mass value>`, `<inertia ixx
6//! ixy ixz iyy iyz izz>`) and `<joint type="revolute|continuous|prismatic|fixed">` (`<parent link>`, `<child link>`,
7//! `<origin xyz rpy>`, `<axis xyz>`, `<limit lower upper>`). Visuals, collisions, meshes, transmissions, Gazebo tags
8//! and comments are skipped. No xacro: run `xacro` first. The links must form one chain from the root (no branches).
9
10use sim_core::ConfigError;
11
12pub type V3 = [f64; 3];
13pub type M3 = [[f64; 3]; 3];
14
15pub fn add(a: V3, b: V3) -> V3 {
16    [a[0] + b[0], a[1] + b[1], a[2] + b[2]]
17}
18fn scale(a: V3, k: f64) -> V3 {
19    [a[0] * k, a[1] * k, a[2] * k]
20}
21pub fn dot(a: V3, b: V3) -> f64 {
22    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
23}
24pub fn cross(a: V3, b: V3) -> V3 {
25    [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
26}
27pub fn mul(m: &M3, v: V3) -> V3 {
28    [dot(m[0], v), dot(m[1], v), dot(m[2], v)]
29}
30/// m^T v.
31fn tmul(m: &M3, v: V3) -> V3 {
32    std::array::from_fn(|i| m[0][i] * v[0] + m[1][i] * v[1] + m[2][i] * v[2])
33}
34pub fn matmul(a: &M3, b: &M3) -> M3 {
35    std::array::from_fn(|r| std::array::from_fn(|c| a[r][0] * b[0][c] + a[r][1] * b[1][c] + a[r][2] * b[2][c]))
36}
37const IDENTITY: M3 = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
38
39/// URDF's roll-pitch-yaw: R = Rz(yaw) Ry(pitch) Rx(roll).
40pub fn rpy(r: V3) -> M3 {
41    let (sr, cr) = r[0].sin_cos();
42    let (sp, cp) = r[1].sin_cos();
43    let (sy, cy) = r[2].sin_cos();
44    [
45        [cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr],
46        [sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr],
47        [-sp, cp * sr, cp * cr],
48    ]
49}
50
51/// Rotation by `angle` about the unit vector `k` (Rodrigues).
52pub fn about(k: V3, angle: f64) -> M3 {
53    let (s, c) = angle.sin_cos();
54    let v = 1.0 - c;
55    [
56        [c + k[0] * k[0] * v, k[0] * k[1] * v - k[2] * s, k[0] * k[2] * v + k[1] * s],
57        [k[1] * k[0] * v + k[2] * s, c + k[1] * k[1] * v, k[1] * k[2] * v - k[0] * s],
58        [k[2] * k[0] * v - k[1] * s, k[2] * k[1] * v + k[0] * s, c + k[2] * k[2] * v],
59    ]
60}
61
62pub fn transpose(m: &M3) -> M3 {
63    std::array::from_fn(|i| std::array::from_fn(|j| m[j][i]))
64}
65
66/// The rotation vector (axis times angle, angle up to pi) of a rotation matrix.
67pub fn log(r: &M3) -> V3 {
68    let vee = [r[2][1] - r[1][2], r[0][2] - r[2][0], r[1][0] - r[0][1]];
69    let cos = ((r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0).clamp(-1.0, 1.0);
70    let sin = 0.5 * dot(vee, vee).sqrt();
71    let angle = sin.atan2(cos);
72    if angle < 1e-6 {
73        // sin a / a = 1 - a^2/6: below 1e-6 rad the correction is under 1e-12 of the angle.
74        return vee.map(|v| 0.5 * v * (1.0 + angle * angle / 6.0));
75    }
76    if angle < std::f64::consts::PI - 1e-6 {
77        return vee.map(|v| v * angle / (2.0 * sin));
78    }
79    // Near a half turn R + I = 2 k k^T (cos a + 1 small): the axis from its largest diagonal entry, its sign from vee.
80    let i = (0..3).max_by(|&a, &b| r[a][a].total_cmp(&r[b][b])).unwrap_or(0);
81    let col: V3 = std::array::from_fn(|k| r[k][i] + if k == i { 1.0 } else { 0.0 });
82    let norm = dot(col, col).sqrt();
83    let sign = if dot(col, vee) < 0.0 { -1.0 } else { 1.0 };
84    col.map(|v| sign * v / norm * angle)
85}
86
87/// The rotation of a rotation vector.
88pub fn exp(r: V3) -> M3 {
89    let angle = dot(r, r).sqrt();
90    if angle == 0.0 { IDENTITY } else { about(r.map(|v| v / angle), angle) }
91}
92
93/// The unit quaternion (w, x, y, z) of a rotation vector.
94pub fn quaternion(r: V3) -> [f64; 4] {
95    let angle = dot(r, r).sqrt();
96    let (s, c) = (0.5 * angle).sin_cos();
97    // sin(a/2) / a -> 1/2 for a small angle.
98    let k = if angle > 1e-12 { s / angle } else { 0.5 };
99    [c, k * r[0], k * r[1], k * r[2]]
100}
101
102/// The rotation vector of a unit quaternion, the angle up to pi (q and -q are the same rotation).
103pub fn from_quaternion(q: [f64; 4]) -> V3 {
104    let q = if q[0] < 0.0 { q.map(|v| -v) } else { q };
105    let s = (q[1] * q[1] + q[2] * q[2] + q[3] * q[3]).sqrt();
106    let angle = 2.0 * s.atan2(q[0]);
107    let k = if s > 1e-12 { angle / s } else { 2.0 };
108    [k * q[1], k * q[2], k * q[3]]
109}
110
111/// Spherical linear interpolation of two orientations given as rotation vectors: the turn from `a` to `b` about one
112/// fixed axis, the shorter way, `s` of it done (Shoemake 1985). As a rotation vector.
113pub fn slerp(a: V3, b: V3, s: f64) -> V3 {
114    let (qa, mut qb) = (quaternion(a), quaternion(b));
115    let mut cos: f64 = (0..4).map(|i| qa[i] * qb[i]).sum();
116    if cos < 0.0 {
117        (qb, cos) = (qb.map(|v| -v), -cos);
118    }
119    let angle = cos.clamp(-1.0, 1.0).acos();
120    let (wa, wb) = if angle < 1e-9 {
121        (1.0 - s, s)
122    } else {
123        (((1.0 - s) * angle).sin() / angle.sin(), (s * angle).sin() / angle.sin())
124    };
125    let q: [f64; 4] = std::array::from_fn(|i| wa * qa[i] + wb * qb[i]);
126    let norm = q.iter().map(|v| v * v).sum::<f64>().sqrt();
127    from_quaternion(q.map(|v| v / norm))
128}
129
130/// The rotation vector of `slerp(a, b, s)` and its first and second derivative by `s`, in closed form. The slerp turns
131/// at the constant angular velocity w = log(q_b q_a*) in space, so the rotation vector r has r' = J^-1 w with the
132/// inverse left Jacobian J^-1 = I - [r]/2 + c [r]^2 (c = 1/theta^2 - cot(theta/2) / (2 theta), theta = |r|), and r''
133/// follows by differentiating that along r'. Valid past the slerp's ends too, short of theta = 2 pi.
134pub fn slerp_rates(a: V3, b: V3, s: f64) -> [V3; 3] {
135    let (qa, mut qb) = (quaternion(a), quaternion(b));
136    if (0..4).map(|i| qa[i] * qb[i]).sum::<f64>() < 0.0 {
137        qb = qb.map(|v| -v);
138    }
139    // q_b q_a*: the conjugate has the vector part of q_a negated.
140    let (va, vb) = ([-qa[1], -qa[2], -qa[3]], [qb[1], qb[2], qb[3]]);
141    let rel = add(add(scale(va, qb[0]), scale(vb, qa[0])), cross(vb, va));
142    let w = from_quaternion([qb[0] * qa[0] - dot(vb, va), rel[0], rel[1], rel[2]]);
143    let r = slerp(a, b, s);
144    let theta = dot(r, r).sqrt();
145    // c and c' / theta, by their series where the closed forms lose their digits to cancelling.
146    let (c, c_over) = if theta < 0.05 {
147        let t2 = theta * theta;
148        (1.0 / 12.0 + t2 / 720.0 + t2 * t2 / 30240.0, 1.0 / 360.0 + t2 / 7560.0)
149    } else {
150        let (tan, sin) = ((0.5 * theta).tan(), (0.5 * theta).sin());
151        let c_by_theta = -2.0 / theta.powi(3) + 0.25 / (theta * sin * sin) + 0.5 / (theta * theta * tan);
152        (1.0 / (theta * theta) - 0.5 / (theta * tan), c_by_theta / theta)
153    };
154    let (rw, rrw_of) = (cross(r, w), |v: V3| cross(r, v));
155    let rrw = rrw_of(rw);
156    let first = add(sub(w, scale(rw, 0.5)), scale(rrw, c));
157    let (fw, f_rw) = (cross(first, w), cross(first, rw));
158    let second = add(add(scale(fw, -0.5), scale(add(f_rw, rrw_of(fw)), c)), scale(rrw, c_over * dot(r, first)));
159    [r, first, second]
160}
161
162/// Mass, centre of mass and inertia about it, in a body's frame.
163#[derive(Debug, Clone, Copy, PartialEq, Default)]
164pub struct Inertial {
165    pub mass: f64,
166    pub com: V3,
167    pub inertia: M3,
168}
169
170impl Inertial {
171    /// A point mass at `com`.
172    pub fn point(mass: f64, com: V3) -> Inertial {
173        Inertial { mass, com, inertia: [[0.0; 3]; 3] }
174    }
175
176    /// The two bodies as one, `other` given in a frame that `rot`, `pos` put into this one (parallel axis theorem).
177    pub fn merged(&self, other: &Inertial, rot: &M3, pos: V3) -> Inertial {
178        let m = self.mass + other.mass;
179        if m <= 0.0 {
180            return *self;
181        }
182        let oc = add(mul(rot, other.com), pos);
183        let com = scale(add(scale(self.com, self.mass), scale(oc, other.mass)), 1.0 / m);
184        let shift = |mass: f64, d: V3| -> M3 {
185            std::array::from_fn(|r| {
186                std::array::from_fn(|c| mass * (if r == c { dot(d, d) } else { 0.0 } - d[r] * d[c]))
187            })
188        };
189        let turned = matmul(&matmul(rot, &other.inertia), &transpose(rot));
190        let (a, b) = (shift(self.mass, sub(self.com, com)), shift(other.mass, sub(oc, com)));
191        let inertia =
192            std::array::from_fn(|r| std::array::from_fn(|c| self.inertia[r][c] + a[r][c] + turned[r][c] + b[r][c]));
193        Inertial { mass: m, com, inertia }
194    }
195
196    /// Mass, first moment m c and inertia about the frame's origin all times `factor`, then `moment` added to the first
197    /// moment, the mass and the inertia about the origin kept (the parameters the dynamics is linear in); back as mass,
198    /// centre and inertia about it. `factor` has to be positive.
199    pub fn changed(&self, factor: f64, moment: V3) -> Inertial {
200        let shift = |m: f64, c: V3| -> M3 {
201            std::array::from_fn(|r| std::array::from_fn(|k| m * (if r == k { dot(c, c) } else { 0.0 } - c[r] * c[k])))
202        };
203        let about_origin = shift(self.mass, self.com);
204        let mass = factor * self.mass;
205        let com = scale(add(scale(self.com, factor * self.mass), moment), 1.0 / mass);
206        let back = shift(mass, com);
207        let inertia = std::array::from_fn(|r| {
208            std::array::from_fn(|k| factor * (self.inertia[r][k] + about_origin[r][k]) - back[r][k])
209        });
210        Inertial { mass, com, inertia }
211    }
212}
213
214fn sub(a: V3, b: V3) -> V3 {
215    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
216}
217
218/// One moving joint and the body it carries.
219#[derive(Debug, Clone, PartialEq)]
220pub struct Body {
221    pub name: String,
222    /// Where the joint sits in the frame of the body before it, at zero joint position.
223    pub origin_rot: M3,
224    pub origin_pos: V3,
225    /// Unit axis in the joint's frame.
226    pub axis: V3,
227    pub prismatic: bool,
228    pub inertial: Inertial,
229    /// The joint's limits from the file (rad or m); `None` for a continuous joint.
230    pub limits: Option<(f64, f64)>,
231}
232
233/// A body of a chain as it moves (`Chain::body_states`), in the base frame: its inertial (the payload merged into the
234/// last), its frame's rotation and origin, its joint's axis, its centre of mass and that centre's velocity, and its
235/// angular velocity.
236#[derive(Debug, Clone, Copy, PartialEq)]
237pub struct BodyState {
238    pub inertial: Inertial,
239    pub rot: M3,
240    pub origin: V3,
241    pub axis: V3,
242    pub com: V3,
243    pub velocity: V3,
244    pub spin: V3,
245}
246
247/// A serial chain on a fixed base, z up in the base frame.
248#[derive(Debug, Clone, PartialEq)]
249pub struct Chain {
250    pub bodies: Vec<Body>,
251    /// A frame fixed to the last body (a flange or tool after fixed joints), in its frame.
252    pub tip_rot: M3,
253    pub tip_pos: V3,
254}
255
256/// Each joint's frame in the base frame: rotation and position.
257pub type Frames = Vec<(M3, V3)>;
258
259/// Bodies a chain's dynamics keep their working values for on the stack; a longer chain takes the heap.
260const ON_STACK: usize = 12;
261
262/// `f` with room for `n` values: the dynamics run four times a step, and the heap's allocations were a tenth of the
263/// work on a six-joint arm.
264fn scratch<T: Copy + Default, R>(n: usize, f: impl FnOnce(&mut [T]) -> R) -> R {
265    if n <= ON_STACK { f(&mut [T::default(); ON_STACK][..n]) } else { f(&mut vec![T::default(); n]) }
266}
267
268impl Chain {
269    pub fn len(&self) -> usize {
270        self.bodies.len()
271    }
272    pub fn is_empty(&self) -> bool {
273        self.bodies.is_empty()
274    }
275
276    /// The joint's own motion: rotation and offset of body i's frame against the joint's frame at zero.
277    fn joint_motion(b: &Body, q: f64) -> (M3, V3) {
278        if b.prismatic { (IDENTITY, scale(b.axis, q)) } else { (about(b.axis, q), [0.0; 3]) }
279    }
280
281    /// Body i's frame in the frame before it: R_i and p_i.
282    fn link(&self, i: usize, q: f64) -> (M3, V3) {
283        let b = &self.bodies[i];
284        let (r, d) = Self::joint_motion(b, q);
285        (matmul(&b.origin_rot, &r), add(b.origin_pos, mul(&b.origin_rot, d)))
286    }
287
288    /// Every body's frame in the base frame at joint positions `q`.
289    pub fn frames(&self, q: &[f64]) -> Frames {
290        let (mut rot, mut pos) = (IDENTITY, [0.0; 3]);
291        (0..self.len())
292            .map(|i| {
293                let (r, p) = self.link(i, q[i]);
294                pos = add(pos, mul(&rot, p));
295                rot = matmul(&rot, &r);
296                (rot, pos)
297            })
298            .collect()
299    }
300
301    /// The tip's position in the base frame.
302    pub fn tip(&self, q: &[f64]) -> (M3, V3) {
303        let (rot, pos) = *self.frames(q).last().unwrap_or(&(IDENTITY, [0.0; 3]));
304        (matmul(&rot, &self.tip_rot), add(pos, mul(&rot, self.tip_pos)))
305    }
306
307    /// Recursive Newton-Euler: the joint torques (forces for prismatic joints) that give the accelerations `qdd` at
308    /// positions `q` and speeds `qd` under gravity `g` (m/s^2, along -z of the base), `extra` a payload (mass, centre and
309    /// inertia about it) in the last body's frame. Out: `tau`.
310    pub fn inverse_dynamics(
311        &self,
312        q: &[f64],
313        qd: &[f64],
314        qdd: &[f64],
315        g: f64,
316        extra: Option<Inertial>,
317        tau: &mut [f64],
318    ) {
319        let links: Vec<(M3, V3)> = (0..self.len()).map(|i| self.link(i, q[i])).collect();
320        self.newton_euler(&links, qd, qdd, g, extra, tau);
321    }
322
323    /// `inverse_dynamics` with each body's frame in the one before it (`link`) worked out already: the mass matrix
324    /// takes n + 1 passes at the same positions, and the links' rotations are most of a pass's work.
325    fn newton_euler(
326        &self,
327        links: &[(M3, V3)],
328        qd: &[f64],
329        qdd: &[f64],
330        g: f64,
331        extra: Option<Inertial>,
332        tau: &mut [f64],
333    ) {
334        scratch(self.len(), |forces| self.newton_euler_into(links, qd, qdd, g, extra, tau, forces));
335    }
336
337    /// `newton_euler` with room for each body's force and moment.
338    fn newton_euler_into(
339        &self,
340        links: &[(M3, V3)],
341        qd: &[f64],
342        qdd: &[f64],
343        g: f64,
344        extra: Option<Inertial>,
345        tau: &mut [f64],
346        forces: &mut [(V3, V3)],
347    ) {
348        let n = self.len();
349        // The base accelerates up by g instead of gravity pulling down.
350        let (mut w, mut dw, mut a) = ([0.0; 3], [0.0; 3], [0.0, 0.0, g]);
351        for i in 0..n {
352            let b = &self.bodies[i];
353            let (r, p) = links[i];
354            // The previous origin's acceleration carried to this origin, then into this frame.
355            let a_here = tmul(&r, add(a, add(cross(dw, p), cross(w, cross(w, p)))));
356            let (w_in, dw_in) = (tmul(&r, w), tmul(&r, dw));
357            if b.prismatic {
358                (w, dw) = (w_in, dw_in);
359                a = add(a_here, add(scale(cross(w, b.axis), 2.0 * qd[i]), scale(b.axis, qdd[i])));
360            } else {
361                w = add(w_in, scale(b.axis, qd[i]));
362                dw = add(add(dw_in, scale(b.axis, qdd[i])), scale(cross(w_in, b.axis), qd[i]));
363                a = a_here;
364            }
365            let mut body = b.inertial;
366            if let (true, Some(payload)) = (i + 1 == n, extra) {
367                body = body.merged(&payload, &IDENTITY, [0.0; 3]);
368            }
369            let ac = add(a, add(cross(dw, body.com), cross(w, cross(w, body.com))));
370            let force = scale(ac, body.mass);
371            let moment = add(mul(&body.inertia, dw), cross(w, mul(&body.inertia, w)));
372            forces[i] = (force, add(moment, cross(body.com, force)));
373        }
374        // Back from the tip: what each body passes to the one before it, about its own origin.
375        let (mut f, mut m) = ([0.0; 3], [0.0; 3]);
376        for i in (0..n).rev() {
377            let (fi, mi) = forces[i];
378            let (f_next, m_next) = match links.get(i + 1) {
379                Some((r, p)) => {
380                    let fr = mul(r, f);
381                    (fr, add(mul(r, m), cross(*p, fr)))
382                }
383                None => ([0.0; 3], [0.0; 3]),
384            };
385            f = add(fi, f_next);
386            m = add(mi, m_next);
387            tau[i] = dot(if self.bodies[i].prismatic { f } else { m }, self.bodies[i].axis);
388        }
389    }
390
391    /// The mass matrix M (n x n, row by row): column j is the inverse dynamics at rest without gravity for a unit
392    /// acceleration of joint j.
393    pub fn mass_matrix(&self, q: &[f64], extra: Option<Inertial>, out: &mut [f64]) {
394        let links: Vec<(M3, V3)> = (0..self.len()).map(|i| self.link(i, q[i])).collect();
395        self.mass_matrix_at(&links, extra, out);
396    }
397
398    /// The mass matrix from each body's Jacobian, in one pass along the chain: M = sum over the bodies k of
399    /// m_k Jv_k^T Jv_k + Jw_k^T I_k Jw_k, its centre of mass's and its rotation's Jacobian over the joints up to it (a
400    /// revolute joint j moves it by a_j x (c_k - o_j) and turns it by a_j, a prismatic one moves it by a_j), I_k its
401    /// inertia about its centre in the base frame. The same matrix as n passes of Newton-Euler with a unit acceleration
402    /// each, at a fraction of the work.
403    fn mass_matrix_at(&self, links: &[(M3, V3)], extra: Option<Inertial>, out: &mut [f64]) {
404        let n = self.len();
405        scratch(n, |axes| {
406            scratch(n, |origins| scratch(n, |columns| self.mass_matrix_into(links, extra, out, axes, origins, columns)))
407        });
408    }
409
410    /// `mass_matrix_at` with room for the joints' axes and origins and a body's Jacobian columns.
411    fn mass_matrix_into(
412        &self,
413        links: &[(M3, V3)],
414        extra: Option<Inertial>,
415        out: &mut [f64],
416        axes: &mut [V3],
417        origins: &mut [V3],
418        columns: &mut [(V3, V3)],
419    ) {
420        let n = self.len();
421        out[..n * n].fill(0.0);
422        let (mut rot, mut pos) = (IDENTITY, [0.0; 3]);
423        for k in 0..n {
424            let (r, p) = links[k];
425            pos = add(pos, mul(&rot, p));
426            rot = matmul(&rot, &r);
427            let b = &self.bodies[k];
428            axes[k] = mul(&rot, b.axis);
429            origins[k] = pos;
430            let mut body = b.inertial;
431            if let (true, Some(payload)) = (k + 1 == n, extra) {
432                body = body.merged(&payload, &IDENTITY, [0.0; 3]);
433            }
434            let c = add(pos, mul(&rot, body.com));
435            let turned = matmul(&matmul(&rot, &body.inertia), &transpose(&rot));
436            for j in 0..=k {
437                columns[j] = if self.bodies[j].prismatic {
438                    (axes[j], [0.0; 3])
439                } else {
440                    (cross(axes[j], sub(c, origins[j])), axes[j])
441                };
442            }
443            let columns = &columns[..=k];
444            for (i, (vi, wi)) in columns.iter().enumerate() {
445                let iw = mul(&turned, *wi);
446                for (j, (vj, wj)) in columns.iter().enumerate() {
447                    out[i * n + j] += body.mass * dot(*vi, *vj) + dot(iw, *wj);
448                }
449            }
450        }
451    }
452
453    /// The mass matrix (`mass_matrix`) and the torques at zero acceleration (velocity terms and gravity,
454    /// `inverse_dynamics` with q'' = 0) at once, the links worked out once for both.
455    pub fn dynamics(&self, q: &[f64], qd: &[f64], g: f64, extra: Option<Inertial>, mass: &mut [f64], bias: &mut [f64]) {
456        let n = self.len();
457        scratch(n, |links: &mut [(M3, V3)]| {
458            for (i, link) in links.iter_mut().enumerate() {
459                *link = self.link(i, q[i]);
460            }
461            self.mass_matrix_at(links, extra, mass);
462            scratch(q.len(), |rest: &mut [f64]| self.newton_euler(links, qd, rest, g, extra, bias));
463        });
464    }
465
466    /// Potential energy in gravity g: the sum of m g z of every centre of mass.
467    pub fn potential(&self, q: &[f64], g: f64, extra: Option<Inertial>) -> f64 {
468        let frames = self.frames(q);
469        let n = self.len();
470        frames
471            .iter()
472            .enumerate()
473            .map(|(i, (rot, pos))| {
474                let b = &self.bodies[i].inertial;
475                let mut energy = b.mass * g * add(*pos, mul(rot, b.com))[2];
476                if let (true, Some(payload)) = (i + 1 == n, extra) {
477                    energy += payload.mass * g * add(*pos, mul(rot, payload.com))[2];
478                }
479                energy
480            })
481            .sum()
482    }
483
484    /// Every body in the base frame at joints `q` and speeds `qd`, `extra` merged into the last (`BodyState`).
485    pub fn body_states(&self, q: &[f64], qd: &[f64], extra: Option<Inertial>) -> Vec<BodyState> {
486        let frames = self.frames(q);
487        let n = self.len();
488        let mut out: Vec<BodyState> = Vec::with_capacity(n);
489        for (k, &(rot, origin)) in frames.iter().enumerate() {
490            let b = &self.bodies[k];
491            let mut inertial = b.inertial;
492            if let (true, Some(payload)) = (k + 1 == n, extra) {
493                inertial = inertial.merged(&payload, &IDENTITY, [0.0; 3]);
494            }
495            let (axis, com) = (mul(&rot, b.axis), add(origin, mul(&rot, inertial.com)));
496            // A revolute joint j moves the centre by a_j x (c - o_j) q_j' and turns it by a_j q_j'; a prismatic one moves
497            // it by a_j q_j'.
498            let (mut velocity, mut spin) = ([0.0; 3], [0.0; 3]);
499            for (j, before) in out.iter().map(|s| (s.axis, s.origin)).chain([(axis, origin)]).enumerate() {
500                let (a, o) = before;
501                if self.bodies[j].prismatic {
502                    velocity = add(velocity, scale(a, qd[j]));
503                } else {
504                    velocity = add(velocity, scale(cross(a, sub(com, o)), qd[j]));
505                    spin = add(spin, scale(a, qd[j]));
506                }
507            }
508            out.push(BodyState { inertial, rot, origin, axis, com, velocity, spin });
509        }
510        out
511    }
512
513    /// The chain's linear momentum and its angular momentum about the base's origin, at joints `q` and speeds `qd`.
514    pub fn momentum(&self, q: &[f64], qd: &[f64], extra: Option<Inertial>) -> (V3, V3) {
515        let (mut linear, mut angular) = ([0.0; 3], [0.0; 3]);
516        for b in self.body_states(q, qd, extra) {
517            let p = scale(b.velocity, b.inertial.mass);
518            let turned = matmul(&matmul(&b.rot, &b.inertial.inertia), &transpose(&b.rot));
519            linear = add(linear, p);
520            angular = add(angular, add(cross(b.com, p), mul(&turned, b.spin)));
521        }
522        (linear, angular)
523    }
524
525    /// Reads a chain from URDF text.
526    pub fn from_urdf(text: &str) -> Result<Self, ConfigError> {
527        let bad = |what: &str| ConfigError::Invalid(format!("urdf: {what}"));
528        let elements = xml_elements(text).map_err(|e| bad(&e))?;
529        // Links by name with their inertials; joints as (type, parent, child, origin, axis, limits).
530        let mut links: Vec<(String, Inertial)> = Vec::new();
531        struct Joint {
532            kind: String,
533            parent: String,
534            child: String,
535            rot: M3,
536            pos: V3,
537            axis: V3,
538            limits: Option<(f64, f64)>,
539        }
540        let mut joints: Vec<Joint> = Vec::new();
541        let mut i = 0;
542        while i < elements.len() {
543            let e = &elements[i];
544            match (e.name.as_str(), e.depth) {
545                ("link", 1) => {
546                    let name = e.attr("name").ok_or_else(|| bad("a link without a name"))?.to_string();
547                    let mut inertial = Inertial::default();
548                    let (mut rot, mut origin) = (IDENTITY, [0.0; 3]);
549                    let mut k = i + 1;
550                    let mut in_inertial = false;
551                    while k < elements.len() && elements[k].depth > 1 {
552                        let c = &elements[k];
553                        if c.depth == 2 {
554                            in_inertial = c.name == "inertial";
555                        } else if in_inertial && c.depth == 3 {
556                            match c.name.as_str() {
557                                "origin" => {
558                                    origin = c.vec("xyz")?;
559                                    rot = rpy(c.vec("rpy")?);
560                                }
561                                "mass" => inertial.mass = c.number("value")?,
562                                "inertia" => {
563                                    let v = |k: &str| c.number(k);
564                                    let (xx, xy, xz, yy, yz, zz) =
565                                        (v("ixx")?, v("ixy")?, v("ixz")?, v("iyy")?, v("iyz")?, v("izz")?);
566                                    inertial.inertia = [[xx, xy, xz], [xy, yy, yz], [xz, yz, zz]];
567                                }
568                                _ => {}
569                            }
570                        }
571                        k += 1;
572                    }
573                    if !(inertial.mass >= 0.0) || inertial.inertia.iter().flatten().any(|v| !v.is_finite()) {
574                        return Err(bad(&format!("the inertial of link {name}")));
575                    }
576                    inertial.com = origin;
577                    inertial.inertia = matmul(&matmul(&rot, &inertial.inertia), &transpose(&rot));
578                    links.push((name, inertial));
579                    i = k;
580                    continue;
581                }
582                ("joint", 1) => {
583                    let kind = e.attr("type").ok_or_else(|| bad("a joint without a type"))?.to_string();
584                    let mut j = Joint {
585                        kind,
586                        parent: String::new(),
587                        child: String::new(),
588                        rot: IDENTITY,
589                        pos: [0.0; 3],
590                        axis: [1.0, 0.0, 0.0],
591                        limits: None,
592                    };
593                    let mut k = i + 1;
594                    while k < elements.len() && elements[k].depth > 1 {
595                        let c = &elements[k];
596                        if c.depth == 2 {
597                            match c.name.as_str() {
598                                "parent" => j.parent = c.attr("link").unwrap_or_default().to_string(),
599                                "child" => j.child = c.attr("link").unwrap_or_default().to_string(),
600                                "origin" => {
601                                    j.pos = c.vec("xyz")?;
602                                    j.rot = rpy(c.vec("rpy")?);
603                                }
604                                "axis" => j.axis = c.vec("xyz")?,
605                                // URDF's default for a bound left out is 0; a range that is empty or upside down is refused.
606                                "limit" if c.attr("lower").is_some() || c.attr("upper").is_some() => {
607                                    let bound =
608                                        |name: &str| if c.attr(name).is_some() { c.number(name) } else { Ok(0.0) };
609                                    let (lower, upper) = (bound("lower")?, bound("upper")?);
610                                    if lower >= upper {
611                                        return Err(bad(&format!("the limits of the joint to {}", j.child)));
612                                    }
613                                    j.limits = Some((lower, upper));
614                                }
615                                _ => {}
616                            }
617                        }
618                        k += 1;
619                    }
620                    joints.push(j);
621                    i = k;
622                    continue;
623                }
624                _ => {}
625            }
626            i += 1;
627        }
628        // The root: the link that is no joint's child.
629        let root = links
630            .iter()
631            .find(|(name, _)| joints.iter().all(|j| &j.child != name))
632            .ok_or_else(|| bad("no root link"))?
633            .0
634            .clone();
635        let inertial_of = |name: &str| {
636            links.iter().find(|(n, _)| n == name).map(|(_, i)| *i).ok_or_else(|| bad(&format!("no link {name}")))
637        };
638        let mut chain = Chain { bodies: Vec::new(), tip_rot: IDENTITY, tip_pos: [0.0; 3] };
639        // Fixed joints before the first moving one fold into where it sits on the base.
640        let (mut pre_rot, mut pre_pos) = (IDENTITY, [0.0; 3]);
641        let mut current = root;
642        let mut passed = vec![current.clone()];
643        loop {
644            let next: Vec<&Joint> = joints.iter().filter(|j| j.parent == current).collect();
645            let j = match next[..] {
646                [] => break,
647                [j] => j,
648                _ => return Err(bad(&format!("link {current} branches; only a serial chain is read"))),
649            };
650            let child = inertial_of(&j.child)?;
651            match j.kind.as_str() {
652                "fixed" => {
653                    // Into the body before it, or on the way to the first joint.
654                    let (rot, pos) = (matmul(&chain.tip_rot, &j.rot), add(chain.tip_pos, mul(&chain.tip_rot, j.pos)));
655                    if let Some(last) = chain.bodies.last_mut() {
656                        last.inertial = last.inertial.merged(&child, &rot, pos);
657                        (chain.tip_rot, chain.tip_pos) = (rot, pos);
658                    } else {
659                        pre_pos = add(pre_pos, mul(&pre_rot, j.pos));
660                        pre_rot = matmul(&pre_rot, &j.rot);
661                    }
662                }
663                "revolute" | "continuous" | "prismatic" => {
664                    // Over the largest component first, so that neither a huge nor a tiny axis overflows its square.
665                    let largest = j.axis.iter().fold(0f64, |m, a| m.max(a.abs()));
666                    let axis = j.axis.map(|a| a / largest);
667                    let norm = dot(axis, axis).sqrt();
668                    if !(largest > 0.0) {
669                        return Err(bad(&format!("the axis of the joint to {}", j.child)));
670                    }
671                    let (rot, pos) = if chain.bodies.is_empty() {
672                        (matmul(&pre_rot, &j.rot), add(pre_pos, mul(&pre_rot, j.pos)))
673                    } else {
674                        (matmul(&chain.tip_rot, &j.rot), add(chain.tip_pos, mul(&chain.tip_rot, j.pos)))
675                    };
676                    let limits = if j.kind == "continuous" { None } else { j.limits };
677                    chain.bodies.push(Body {
678                        name: j.child.clone(),
679                        origin_rot: rot,
680                        origin_pos: pos,
681                        axis: scale(axis, 1.0 / norm),
682                        prismatic: j.kind == "prismatic",
683                        inertial: child,
684                        limits,
685                    });
686                    (chain.tip_rot, chain.tip_pos) = (IDENTITY, [0.0; 3]);
687                }
688                other => return Err(bad(&format!("joint type {other} is not read"))),
689            }
690            // Joints that lead back to a link passed would be walked for ever.
691            if passed.contains(&j.child) {
692                return Err(bad(&format!("link {} closes a loop; only a serial chain is read", j.child)));
693            }
694            current = j.child.clone();
695            passed.push(current.clone());
696        }
697        if chain.bodies.is_empty() {
698            return Err(bad("no moving joint"));
699        }
700        // Each number of the file is finite, but sums and products of huge ones (a link merged far out) need not be.
701        let finite = |b: &Body| {
702            let i = &b.inertial;
703            let numbers = b.origin_rot.iter().flatten().chain(&b.origin_pos).chain(&b.axis).chain(&i.com);
704            numbers.chain(i.inertia.iter().flatten()).chain([&i.mass]).all(|v| v.is_finite())
705        };
706        if let Some(b) = chain.bodies.iter().find(|b| !finite(b)) {
707            return Err(bad(&format!("the numbers of link {} are too large", b.name)));
708        }
709        if !chain.tip_rot.iter().flatten().chain(&chain.tip_pos).all(|v| v.is_finite()) {
710            return Err(bad("the numbers of the tool are too large"));
711        }
712        Ok(chain)
713    }
714}
715
716/// One XML start tag: its name, depth (the root at 0) and attributes.
717#[derive(Debug, Clone)]
718struct Element {
719    name: String,
720    depth: usize,
721    attrs: Vec<(String, String)>,
722}
723
724impl Element {
725    fn attr(&self, name: &str) -> Option<&str> {
726        self.attrs.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str())
727    }
728    fn number(&self, name: &str) -> Result<f64, ConfigError> {
729        self.attr(name)
730            .and_then(|v| v.trim().parse::<f64>().ok())
731            .filter(|v| v.is_finite())
732            .ok_or_else(|| ConfigError::Invalid(format!("urdf: {} {name}", self.name)))
733    }
734    /// Three numbers apart by spaces; zero where the attribute is left out (URDF's default).
735    fn vec(&self, name: &str) -> Result<V3, ConfigError> {
736        let Some(text) = self.attr(name) else { return Ok([0.0; 3]) };
737        let v: Vec<f64> = text
738            .split_whitespace()
739            .map(|t| t.parse::<f64>())
740            .collect::<Result<_, _>>()
741            .map_err(|_| ConfigError::Invalid(format!("urdf: {} {name}", self.name)))?;
742        match v[..] {
743            [a, b, c] if v.iter().all(|x| x.is_finite()) => Ok([a, b, c]),
744            _ => Err(ConfigError::Invalid(format!("urdf: {} {name}", self.name))),
745        }
746    }
747}
748
749/// The start tags of an XML document in order, with their depth. Comments, processing instructions, declarations and
750/// text are skipped; end tags only count the depth. Enough for URDF, not a general XML reader (no entities but the
751/// five standard ones, no CDATA).
752fn xml_elements(text: &str) -> Result<Vec<Element>, String> {
753    let mut out = Vec::new();
754    let (mut rest, mut depth) = (text, 0usize);
755    while let Some(start) = rest.find('<') {
756        rest = &rest[start..];
757        if let Some(after) = rest.strip_prefix("<!--") {
758            let end = after.find("-->").ok_or("a comment that does not end")?;
759            rest = &after[end + 3..];
760            continue;
761        }
762        if rest.starts_with("<?") || rest.starts_with("<!") {
763            let end = rest.find('>').ok_or("a declaration that does not end")?;
764            rest = &rest[end + 1..];
765            continue;
766        }
767        // A '>' inside a quoted attribute does not end the tag.
768        let (mut quote, mut end) = (None, None);
769        for (k, ch) in rest.char_indices().skip(1) {
770            match (quote, ch) {
771                (None, '"' | '\'') => quote = Some(ch),
772                (Some(q), c) if c == q => quote = None,
773                (None, '>') => {
774                    end = Some(k);
775                    break;
776                }
777                _ => {}
778            }
779        }
780        let end = end.ok_or("a tag that does not end")?;
781        let tag = &rest[1..end];
782        rest = &rest[end + 1..];
783        if let Some(closing) = tag.strip_prefix('/') {
784            depth = depth.checked_sub(1).ok_or_else(|| format!("</{}> without its start", closing.trim()))?;
785            continue;
786        }
787        let empty = tag.ends_with('/');
788        let tag = tag.trim_end_matches('/');
789        let name_end = tag.find(char::is_whitespace).unwrap_or(tag.len());
790        let mut attrs = Vec::new();
791        let mut a = tag[name_end..].trim_start();
792        while !a.is_empty() {
793            let eq = a.find('=').ok_or("an attribute without a value")?;
794            let key = a[..eq].trim().to_string();
795            let v = a[eq + 1..].trim_start();
796            let q = v.chars().next().filter(|c| *c == '"' || *c == '\'').ok_or("an attribute value without quotes")?;
797            let close = v[1..].find(q).ok_or("an attribute value that does not end")?;
798            let value = v[1..1 + close]
799                .replace("&lt;", "<")
800                .replace("&gt;", ">")
801                .replace("&quot;", "\"")
802                .replace("&apos;", "'")
803                .replace("&amp;", "&");
804            attrs.push((key, value));
805            a = v[close + 2..].trim_start();
806        }
807        out.push(Element { name: tag[..name_end].to_string(), depth, attrs });
808        if !empty {
809            depth += 1;
810        }
811    }
812    if depth != 0 {
813        return Err("tags that are not closed".into());
814    }
815    Ok(out)
816}
817
818#[cfg(test)]
819mod tests {
820    use super::*;
821
822    /// A double pendulum in the x-z plane: two revolute joints about y, links 1 m and 0.5 m, point masses 2 kg and 1 kg at
823    /// their ends, and a fixed tool 0.6 m from the elbow with 0.5 kg that merges into the second body.
824    const PENDULUM: &str = r#"<?xml version="1.0"?>
825<!-- a test chain -->
826<robot name="pendulum">
827  <link name="base"/>
828  <link name="upper"><inertial><origin xyz="1 0 0" rpy="0 0 0"/><mass value="2"/><inertia ixx="0" ixy="0" ixz="0" iyy="0" iyz="0" izz="0"/></inertial>
829    <visual><geometry><box size="1 0.1 0.1"/></geometry></visual></link>
830  <link name="lower"><inertial><origin xyz="0.5 0 0"/><mass value="1"/><inertia ixx="0" ixy="0" ixz="0" iyy="0" iyz="0" izz="0"/></inertial></link>
831  <link name="tool"><inertial><origin xyz="0 0 0"/><mass value="0.5"/><inertia ixx="0" ixy="0" ixz="0" iyy="0" iyz="0" izz="0"/></inertial></link>
832  <joint name="j1" type="revolute"><parent link="base"/><child link="upper"/><origin xyz="0 0 0" rpy="0 0 0"/><axis xyz="0 -1 0"/><limit lower="-3" upper="3" effort="10" velocity="1"/></joint>
833  <joint name="j2" type="continuous"><parent link="upper"/><child link="lower"/><origin xyz="1 0 0"/><axis xyz="0 -1 0"/></joint>
834  <joint name="flange" type="fixed"><parent link="lower"/><child link="tool"/><origin xyz="0.6 0 0"/></joint>
835</robot>"#;
836
837    /// The textbook double pendulum (Craig, example 6.5), with the tool's 0.5 kg at 0.6 m on the second link: the
838    /// second body is 1.5 kg with its centre at (0.5 + 0.3) / 1.5 = 0.53333 m and 0.25 + 0.18 = 0.43 kg m^2 about the
839    /// joint. Axes about -y turn x towards +z, so the angles lift the links. At q = (0, 90 degrees), at rest, gravity
840    /// 9.81: tau1 = 2 9.81 1 + 1.5 9.81 1 = 34.335 N m (the second link points up), tau2 = 0. M at q2 = 90 degrees:
841    /// M11 = 2 + 1.5 1 + 0.43 = 3.93 (cos q2 = 0), M12 = 0.43, M22 = 0.43. With qd1 = 1 rad/s the centrifugal force
842    /// on the second body's centre pulls it outwards along the first link: tau2 = m2 l1 c2 sin(q2) qd1^2 = 1.5 1 0.53333
843    /// = 0.8 N m (gravity off).
844    #[test]
845    fn newton_euler_gives_the_textbook_pendulum() {
846        let chain = Chain::from_urdf(PENDULUM).unwrap();
847        assert_eq!(chain.len(), 2);
848        assert_eq!(chain.bodies[0].limits, Some((-3.0, 3.0)));
849        assert_eq!(chain.bodies[1].limits, None);
850        let close = |a: f64, b: f64, what: &str| assert!((a - b).abs() < 1e-9, "{what}: {a} against {b} by hand");
851        close(chain.bodies[1].inertial.mass, 1.5, "merged mass");
852        close(chain.bodies[1].inertial.com[0], 0.8 / 1.5, "merged centre");
853        let q = [0.0, std::f64::consts::FRAC_PI_2];
854        let mut tau = [0.0; 2];
855        chain.inverse_dynamics(&q, &[0.0; 2], &[0.0; 2], 9.81, None, &mut tau);
856        close(tau[0], 34.335, "tau1");
857        close(tau[1], 0.0, "tau2");
858        let mut m = [0.0; 4];
859        chain.mass_matrix(&q, None, &mut m);
860        for (got, want) in m.iter().zip([3.93, 0.43, 0.43, 0.43]) {
861            close(*got, want, "M");
862        }
863        chain.inverse_dynamics(&q, &[1.0, 0.0], &[0.0; 2], 0.0, None, &mut tau);
864        close(tau[1], 0.8, "centrifugal");
865        // The potential: the first mass at height 0, the second body's centre 0.53333 m above the elbow.
866        close(chain.potential(&q, 9.81, None), 1.5 * 9.81 * 0.8 / 1.5, "potential");
867        // The tool tip 0.6 m above the elbow at (1, 0, 0.6); a payload anywhere above the elbow adds its weight times the
868        // reach of 1 m to tau1.
869        let (_, tip) = chain.tip(&q);
870        close(tip[0], 1.0, "tip x");
871        close(tip[2], 0.6, "tip z");
872        chain.inverse_dynamics(&q, &[0.0; 2], &[0.0; 2], 9.81, Some(Inertial::point(2.0, [1.1, 0.0, 0.0])), &mut tau);
873        close(tau[0], 34.335 + 2.0 * 9.81, "payload");
874    }
875
876    /// The energy check of the dynamics: d/dt (T + V) = qd . tau. Over a small step with the accelerations M^-1 (tau - h),
877    /// the change of T + V matches the power put in, for a random-ish pose of a 3D chain.
878    #[test]
879    fn the_dynamics_conserve_energy() {
880        let urdf = r#"<robot name="r"><link name="b"/>
881            <link name="l1"><inertial><origin xyz="0.1 0.02 0.3" rpy="0.1 0.2 0.3"/><mass value="5"/><inertia ixx="0.1" ixy="0.01" ixz="0" iyy="0.12" iyz="0.02" izz="0.05"/></inertial></link>
882            <link name="l2"><inertial><origin xyz="0.2 0 0.05"/><mass value="3"/><inertia ixx="0.02" ixy="0" ixz="0.003" iyy="0.06" iyz="0" izz="0.05"/></inertial></link>
883            <link name="l3"><inertial><origin xyz="0 0.1 0"/><mass value="1"/><inertia ixx="0.01" ixy="0" ixz="0" iyy="0.004" iyz="0" izz="0.01"/></inertial></link>
884            <joint name="a" type="revolute"><parent link="b"/><child link="l1"/><origin xyz="0 0 0.4"/><axis xyz="0 0 1"/><limit lower="-3" upper="3"/></joint>
885            <joint name="b" type="revolute"><parent link="l1"/><child link="l2"/><origin xyz="0.1 0 0.3" rpy="1.5707963 0 0"/><axis xyz="0 0 1"/><limit lower="-3" upper="3"/></joint>
886            <joint name="c" type="prismatic"><parent link="l2"/><child link="l3"/><origin xyz="0.4 0 0"/><axis xyz="1 0 0"/><limit lower="0" upper="0.2"/></joint></robot>"#;
887        let chain = Chain::from_urdf(urdf).unwrap();
888        let (q0, qd0, tau) = ([0.3, -0.7, 0.1], [0.5, -0.4, 0.2], [1.0, -2.0, 3.0]);
889        let accel = |q: &[f64], qd: &[f64]| -> Vec<f64> {
890            let mut m = [0.0; 9];
891            chain.mass_matrix(q, None, &mut m);
892            let mut h = [0.0; 3];
893            chain.inverse_dynamics(q, qd, &[0.0; 3], 9.81, None, &mut h);
894            let rhs: Vec<f64> = (0..3).map(|i| tau[i] - h[i]).collect();
895            crate::chain::solve(&m, &rhs).unwrap()
896        };
897        let energy = |q: &[f64], qd: &[f64]| {
898            let mut m = [0.0; 9];
899            chain.mass_matrix(q, None, &mut m);
900            let kinetic: f64 =
901                (0..3).map(|i| (0..3).map(|j| qd[i] * m[i * 3 + j] * qd[j]).sum::<f64>()).sum::<f64>() * 0.5;
902            kinetic + chain.potential(q, 9.81, None)
903        };
904        // RK4 over 1 ms; the energy gained is the work of tau (constant) over the joint travel.
905        let dt = 1e-3;
906        let f = |s: &[f64]| -> Vec<f64> {
907            let a = accel(&s[..3], &s[3..]);
908            s[3..].iter().copied().chain(a).collect()
909        };
910        let s0: Vec<f64> = q0.iter().chain(&qd0).copied().collect();
911        let step = |s: &[f64], k: &[f64], h: f64| -> Vec<f64> { s.iter().zip(k).map(|(a, b)| a + h * b).collect() };
912        let k1 = f(&s0);
913        let k2 = f(&step(&s0, &k1, dt / 2.0));
914        let k3 = f(&step(&s0, &k2, dt / 2.0));
915        let k4 = f(&step(&s0, &k3, dt));
916        let s1: Vec<f64> = (0..6).map(|i| s0[i] + dt / 6.0 * (k1[i] + 2.0 * k2[i] + 2.0 * k3[i] + k4[i])).collect();
917        let work: f64 = (0..3).map(|i| tau[i] * (s1[i] - s0[i])).sum();
918        let gained = energy(&s1[..3], &s1[3..]) - energy(&q0, &qd0);
919        assert!((gained - work).abs() < 1e-9, "gained {gained} J, work {work} J");
920    }
921
922    #[test]
923    fn bad_urdf_is_refused() {
924        for bad in [
925            "<robot><link name=\"a\"/>",
926            "<robot><link name=\"a\"/></robot>",
927            "<robot><link name=\"a\"/><link name=\"b\"/><joint name=\"j\" type=\"planar\"><parent link=\"a\"/><child link=\"b\"/></joint></robot>",
928        ] {
929            assert!(Chain::from_urdf(bad).is_err(), "{bad}");
930        }
931    }
932
933    /// URDF's limits: a bound left out is 0, an empty or upside-down range is refused (it would turn the stops inside
934    /// out).
935    #[test]
936    fn urdf_limits_default_to_zero_and_must_be_a_range() {
937        let urdf = |limit: &str| {
938            format!(
939                "<robot><link name=\"a\"/><link name=\"b\"><inertial><mass value=\"1\"/><inertia ixx=\"1\" ixy=\"0\" ixz=\"0\" iyy=\"1\" iyz=\"0\" izz=\"1\"/></inertial></link><joint name=\"j\" type=\"prismatic\"><parent link=\"a\"/><child link=\"b\"/><axis xyz=\"0 0 1\"/>{limit}</joint></robot>"
940            )
941        };
942        assert_eq!(
943            Chain::from_urdf(&urdf("<limit upper=\"0.3\" effort=\"1\" velocity=\"1\"/>")).unwrap().bodies[0].limits,
944            Some((0.0, 0.3))
945        );
946        assert!(Chain::from_urdf(&urdf("<limit lower=\"0.2\" upper=\"0.0\"/>")).is_err());
947    }
948
949    /// 2 kg with its centre at (0.1, 0, 0) and inertia diag(0.01, 0.02, 0.03) about it, times 3 with 0.2 kg m more first
950    /// moment along y. By hand: about the frame, diag(0.01, 0.02 + 2 · 0.01, 0.03 + 2 · 0.01) = diag(0.01, 0.04, 0.05),
951    /// times 3; mass 6 kg; first moment (0.6, 0.2, 0), centre (0.1, 1/30, 0), c · c = 0.011111; back about the centre:
952    /// xx 0.03 − 6 (0.011111 − 0.01) = 0.023333, yy 0.12 − 6 (0.011111 − 0.001111) = 0.06, zz 0.15 − 6 · 0.011111 =
953    /// 0.083333, xy 0 + 6 · 0.1 / 30 = 0.02. The factor 1 without a moment gives the body back.
954    #[test]
955    fn a_links_change_scales_its_parameters_about_its_frame_and_moves_its_centre() {
956        let body = Inertial {
957            mass: 2.0,
958            com: [0.1, 0.0, 0.0],
959            inertia: [[0.01, 0.0, 0.0], [0.0, 0.02, 0.0], [0.0, 0.0, 0.03]],
960        };
961        let changed = body.changed(3.0, [0.0, 0.2, 0.0]);
962        let close = |a: f64, b: f64| (a - b).abs() < 1e-12;
963        assert!(close(changed.mass, 6.0) && close(changed.com[0], 0.1) && close(changed.com[1], 1.0 / 30.0));
964        let expected = [[0.07 / 3.0, 0.02, 0.0], [0.02, 0.06, 0.0], [0.0, 0.0, 0.25 / 3.0]];
965        for r in 0..3 {
966            for c in 0..3 {
967                assert!(close(changed.inertia[r][c], expected[r][c]), "{:?}", changed.inertia);
968            }
969        }
970        let same = body.changed(1.0, [0.0; 3]);
971        assert!((0..3).all(|r| (0..3).all(|c| close(same.inertia[r][c], body.inertia[r][c]))) && same.com == body.com);
972    }
973
974    /// A payload's own inertia counts about the last joint: on the textbook pendulum (second body 0.43 kg m^2 about the
975    /// elbow), 2 kg at 0.6 m along the second link with 0.05 kg m^2 about its centre around the joint's axis (y). At
976    /// rest, no gravity, q2'' = 1 rad/s^2: tau2 = 0.43 + 2 * 0.6^2 + 0.05 = 1.2 N m, of which the point mass alone gives
977    /// 1.15 N m.
978    #[test]
979    fn a_payloads_inertia_adds_its_torque_about_the_last_joint() {
980        let chain = Chain::from_urdf(PENDULUM).unwrap();
981        let mut tau = [0.0; 2];
982        let solid = Inertial {
983            mass: 2.0,
984            com: [0.6, 0.0, 0.0],
985            inertia: [[0.01, 0.0, 0.0], [0.0, 0.05, 0.0], [0.0, 0.0, 0.02]],
986        };
987        chain.inverse_dynamics(&[0.0; 2], &[0.0; 2], &[0.0, 1.0], 0.0, Some(solid), &mut tau);
988        assert!((tau[1] - 1.2).abs() < 1e-12, "{} N m against 1.2 by hand", tau[1]);
989        chain.inverse_dynamics(
990            &[0.0; 2],
991            &[0.0; 2],
992            &[0.0, 1.0],
993            0.0,
994            Some(Inertial::point(2.0, [0.6, 0.0, 0.0])),
995            &mut tau,
996        );
997        assert!((tau[1] - 1.15).abs() < 1e-12, "{} N m against 1.15 by hand", tau[1]);
998    }
999
1000    /// The slerp midpoint of a quarter turn about x and a quarter turn about y. By hand with quaternions:
1001    /// qa = (c, s, 0, 0), qb = (c, 0, s, 0), c = s = cos 45 deg; cos of the angle between them c^2 = 1/2, so 60 degrees;
1002    /// the midpoint (qa + qb) / |qa + qb| = (2c, s, s, 0) / sqrt(4c^2 + 2s^2) = (2, 1, 1, 0) / sqrt(6): its angle
1003    /// 2 acos(2 / sqrt 6) = 70.53 deg about (1, 1, 0) / sqrt 2, the rotation vector 1.2310 (0.70711, 0.70711, 0).
1004    /// The linear blend of the rotation vectors, (pi/4, pi/4, 0), is 1.1107 rad about the same axis: 6.9 degrees short.
1005    #[test]
1006    fn the_slerp_midpoint_of_two_quarter_turns_is_worked_out_by_hand() {
1007        use std::f64::consts::FRAC_PI_2;
1008        let mid = slerp([FRAC_PI_2, 0.0, 0.0], [0.0, FRAC_PI_2, 0.0], 0.5);
1009        let angle = 2.0 * (2.0 / 6f64.sqrt()).acos();
1010        let want = [angle / 2f64.sqrt(), angle / 2f64.sqrt(), 0.0];
1011        assert!((angle - 1.230_959_417).abs() < 1e-9);
1012        assert!((0..3).all(|i| (mid[i] - want[i]).abs() < 1e-12), "{mid:?} against {want:?}");
1013        // The ends, and the round trip through the quaternion.
1014        let end = slerp([FRAC_PI_2, 0.0, 0.0], [0.0, FRAC_PI_2, 0.0], 1.0);
1015        assert!((end[1] - FRAC_PI_2).abs() < 1e-12 && end[0].abs() < 1e-12);
1016        let r = [0.3, -1.2, 2.0];
1017        let back = from_quaternion(quaternion(r));
1018        assert!((0..3).all(|i| (back[i] - r[i]).abs() < 1e-12));
1019        // log inverts exp, near a half turn too.
1020        let half = [0.0, 0.0, std::f64::consts::PI - 1e-9];
1021        let again = log(&exp(half));
1022        assert!((0..3).all(|i| (again[i] - half[i]).abs() < 1e-7), "{again:?}");
1023    }
1024}