featherstone 0.1.0

Robotics dynamics engine — O(n) forward/inverse dynamics for kinematic trees, contact solvers, and time integration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
//! Generalized-coordinate joint types for articulated body dynamics
//!
//! Each joint type defines its motion subspace, degrees of freedom, and
//! position-to-transform mapping using minimal (generalized) coordinates.
//! Unlike Rapier's constraint-based joints, these have zero drift by construction.
//!
//! Quaternion-based joints (Spherical, Floating) store 4 quaternion parameters
//! for 3 rotational DOF, matching MuJoCo's convention. This means `n_pos() != dof()`
//! for these joint types.

use nalgebra::{UnitQuaternion, Vector3, Vector4};

use super::spatial::{SpatialTransform, SpatialVector};

/// Joint type in generalized coordinates.
///
/// Each variant defines its degrees of freedom (velocity space) and number of
/// position parameters. For quaternion joints, `n_pos() > dof()`.
#[derive(Clone, Debug)]
pub enum GenJoint {
    /// Fixed joint: 0-DOF, rigid connection between parent and child
    Fixed,
    /// Revolute joint: 1-DOF rotation around axis
    Revolute {
        /// Rotation axis (unit vector)
        axis: Vector3<f32>,
    },
    /// Prismatic joint: 1-DOF translation along axis
    Prismatic {
        /// Translation axis (unit vector)
        axis: Vector3<f32>,
    },
    /// Spherical joint: 3-DOF rotation using quaternion (4 position params, 3 velocity DOF)
    Spherical,
    /// Floating joint: 6-DOF (3 translation + quaternion rotation)
    /// Position params: [x, y, z, qw, qx, qy, qz] (7 total, 6 velocity DOF)
    Floating,
    /// Planar joint: 3-DOF (2 translation in-plane + 1 rotation around normal)
    Planar {
        /// Normal to the plane of motion
        normal: Vector3<f32>,
    },
}

impl GenJoint {
    /// Degrees of freedom in velocity space (dimension of qd, qdd, tau).
    pub fn dof(&self) -> usize {
        match self {
            GenJoint::Fixed => 0,
            GenJoint::Revolute { .. } | GenJoint::Prismatic { .. } => 1,
            GenJoint::Spherical | GenJoint::Planar { .. } => 3,
            GenJoint::Floating => 6,
        }
    }

    /// Number of position parameters (dimension of q slice for this joint).
    ///
    /// For quaternion-based joints this differs from `dof()`:
    /// - Spherical: 4 (quaternion w,x,y,z) vs 3 DOF
    /// - Floating: 7 (x,y,z,qw,qx,qy,qz) vs 6 DOF
    pub fn n_pos(&self) -> usize {
        match self {
            GenJoint::Fixed => 0,
            GenJoint::Revolute { .. } | GenJoint::Prismatic { .. } => 1,
            GenJoint::Planar { .. } => 3,
            GenJoint::Spherical => 4,
            GenJoint::Floating => 7,
        }
    }

    /// Compute the joint transform from generalized position values.
    ///
    /// Maps position parameters q to a spatial transform from parent to child frame.
    pub fn transform(&self, q: &[f32]) -> SpatialTransform {
        match self {
            GenJoint::Fixed => SpatialTransform::identity(),

            GenJoint::Revolute { axis } => {
                let angle = q.first().copied().unwrap_or(0.0);
                SpatialTransform::from_axis_angle_translation(*axis, angle, Vector3::zeros())
            }

            GenJoint::Prismatic { axis } => {
                let displacement = q.first().copied().unwrap_or(0.0);
                SpatialTransform::from_translation(*axis * displacement)
            }

            GenJoint::Spherical => {
                let rot = quat_from_slice(q);
                SpatialTransform::from_rotation(rot.to_rotation_matrix().into_inner())
            }

            GenJoint::Floating => {
                if q.len() >= 7 {
                    let trans = Vector3::new(q[0], q[1], q[2]);
                    let rot = quat_from_slice(&q[3..]);
                    SpatialTransform::from_rotation_translation(
                        rot.to_rotation_matrix().into_inner(),
                        trans,
                    )
                } else {
                    SpatialTransform::identity()
                }
            }

            GenJoint::Planar { normal } => {
                if q.len() >= 3 {
                    let (t1, t2) = plane_basis(normal);
                    let trans = t1 * q[0] + t2 * q[1];
                    let rot = SpatialTransform::from_axis_angle_translation(
                        *normal,
                        q[2],
                        Vector3::zeros(),
                    );
                    SpatialTransform::from_rotation_translation(rot.rotation, trans)
                } else {
                    SpatialTransform::identity()
                }
            }
        }
    }

    /// Compute the motion subspace matrix S(q).
    ///
    /// S is a 6-by-dof matrix (returned as Vec of column SpatialVectors) that maps
    /// joint velocities to spatial velocities: v_joint = S * qdot_v
    ///
    /// Note: for quaternion joints, S maps from the *velocity* DOF (3 for spherical,
    /// 6 for floating), NOT from the position parameters.
    pub fn motion_subspace(&self, _q: &[f32]) -> Vec<SpatialVector> {
        match self {
            GenJoint::Fixed => vec![],

            GenJoint::Revolute { axis } => {
                vec![SpatialVector::new(*axis, Vector3::zeros())]
            }

            GenJoint::Prismatic { axis } => {
                vec![SpatialVector::new(Vector3::zeros(), *axis)]
            }

            GenJoint::Spherical => {
                // 3 rotation axes (angular velocity components)
                vec![
                    SpatialVector::new(Vector3::x(), Vector3::zeros()),
                    SpatialVector::new(Vector3::y(), Vector3::zeros()),
                    SpatialVector::new(Vector3::z(), Vector3::zeros()),
                ]
            }

            GenJoint::Floating => {
                // 6 DOF: 3 translations + 3 rotations
                vec![
                    SpatialVector::new(Vector3::zeros(), Vector3::x()),
                    SpatialVector::new(Vector3::zeros(), Vector3::y()),
                    SpatialVector::new(Vector3::zeros(), Vector3::z()),
                    SpatialVector::new(Vector3::x(), Vector3::zeros()),
                    SpatialVector::new(Vector3::y(), Vector3::zeros()),
                    SpatialVector::new(Vector3::z(), Vector3::zeros()),
                ]
            }

            GenJoint::Planar { normal } => {
                let (t1, t2) = plane_basis(normal);
                vec![
                    SpatialVector::new(Vector3::zeros(), t1),
                    SpatialVector::new(Vector3::zeros(), t2),
                    SpatialVector::new(*normal, Vector3::zeros()),
                ]
            }
        }
    }

    /// Map position-space derivatives (qdot) to velocity-space values.
    ///
    /// For simple joints (Revolute, Prismatic, Planar), this is identity.
    /// For quaternion joints, converts quaternion derivative to angular velocity:
    ///   ω = 2 * q_conj * qdot  (imaginary part)
    ///
    /// # Arguments
    /// - `q`: current position parameters
    /// - `qdot`: position parameter derivatives (dimension = n_pos())
    ///
    /// # Returns
    /// Velocity-space values (dimension = dof())
    pub fn velocity_from_qdot(&self, q: &[f32], qdot: &[f32]) -> Vec<f32> {
        match self {
            GenJoint::Fixed => vec![],

            GenJoint::Revolute { .. } | GenJoint::Prismatic { .. } => {
                vec![qdot.first().copied().unwrap_or(0.0)]
            }

            GenJoint::Planar { .. } => {
                let mut v = vec![0.0; 3];
                let n = 3.min(qdot.len());
                v[..n].copy_from_slice(&qdot[..n]);
                v
            }

            GenJoint::Spherical => {
                // ω = 2 * Im(q_conj * qdot_quat)
                let quat = quat_from_slice(q);
                let qdot_quat = Vector4::new(
                    qdot.first().copied().unwrap_or(0.0), // w
                    qdot.get(1).copied().unwrap_or(0.0),  // x
                    qdot.get(2).copied().unwrap_or(0.0),  // y
                    qdot.get(3).copied().unwrap_or(0.0),  // z
                );
                let omega = quat_deriv_to_omega(quat, qdot_quat);
                vec![omega.x, omega.y, omega.z]
            }

            GenJoint::Floating => {
                // Linear velocity = d/dt [x,y,z] (identity mapping)
                let vx = qdot.first().copied().unwrap_or(0.0);
                let vy = qdot.get(1).copied().unwrap_or(0.0);
                let vz = qdot.get(2).copied().unwrap_or(0.0);

                // Angular velocity from quaternion derivative
                let quat = quat_from_slice(if q.len() >= 7 { &q[3..] } else { &[] });
                let qdot_quat = Vector4::new(
                    qdot.get(3).copied().unwrap_or(0.0),
                    qdot.get(4).copied().unwrap_or(0.0),
                    qdot.get(5).copied().unwrap_or(0.0),
                    qdot.get(6).copied().unwrap_or(0.0),
                );
                let omega = quat_deriv_to_omega(quat, qdot_quat);

                vec![vx, vy, vz, omega.x, omega.y, omega.z]
            }
        }
    }

    /// Map velocity-space values to position-space derivatives (qdot).
    ///
    /// Inverse of `velocity_from_qdot`. For quaternion joints, converts angular
    /// velocity to quaternion derivative:
    ///   qdot = 0.5 * q * [0, ω]
    ///
    /// # Arguments
    /// - `q`: current position parameters
    /// - `v`: velocity-space values (dimension = dof())
    ///
    /// # Returns
    /// Position parameter derivatives (dimension = n_pos())
    pub fn qdot_from_velocity(&self, q: &[f32], v: &[f32]) -> Vec<f32> {
        match self {
            GenJoint::Fixed => vec![],

            GenJoint::Revolute { .. } | GenJoint::Prismatic { .. } => {
                vec![v.first().copied().unwrap_or(0.0)]
            }

            GenJoint::Planar { .. } => {
                let mut result = vec![0.0; 3];
                let n = 3.min(v.len());
                result[..n].copy_from_slice(&v[..n]);
                result
            }

            GenJoint::Spherical => {
                // qdot = 0.5 * q * [0, ω]
                let quat = quat_from_slice(q);
                let omega = Vector3::new(
                    v.first().copied().unwrap_or(0.0),
                    v.get(1).copied().unwrap_or(0.0),
                    v.get(2).copied().unwrap_or(0.0),
                );
                let qdot = omega_to_quat_deriv(quat, omega);
                vec![qdot.w, qdot.i, qdot.j, qdot.k]
            }

            GenJoint::Floating => {
                // Translation: identity mapping
                let vx = v.first().copied().unwrap_or(0.0);
                let vy = v.get(1).copied().unwrap_or(0.0);
                let vz = v.get(2).copied().unwrap_or(0.0);

                // Rotation: ω → quaternion derivative
                let quat = quat_from_slice(if q.len() >= 7 { &q[3..] } else { &[] });
                let omega = Vector3::new(
                    v.get(3).copied().unwrap_or(0.0),
                    v.get(4).copied().unwrap_or(0.0),
                    v.get(5).copied().unwrap_or(0.0),
                );
                let qdot = omega_to_quat_deriv(quat, omega);

                vec![vx, vy, vz, qdot.w, qdot.i, qdot.j, qdot.k]
            }
        }
    }

    /// Normalize position parameters (renormalize quaternion for spherical/floating).
    ///
    /// Should be called after integration to maintain unit quaternion constraint.
    pub fn normalize_q(&self, q: &mut [f32]) {
        match self {
            GenJoint::Spherical if q.len() >= 4 => {
                normalize_quat_slice(&mut q[0..4]);
            }
            GenJoint::Floating if q.len() >= 7 => {
                normalize_quat_slice(&mut q[3..7]);
            }
            _ => {} // No normalization needed
        }
    }

    /// Default position parameters (identity configuration).
    ///
    /// For quaternion joints, returns unit quaternion [1, 0, 0, 0].
    pub fn default_q(&self) -> Vec<f32> {
        match self {
            GenJoint::Fixed => vec![],
            GenJoint::Revolute { .. } | GenJoint::Prismatic { .. } => vec![0.0],
            GenJoint::Planar { .. } => vec![0.0, 0.0, 0.0],
            GenJoint::Spherical => vec![1.0, 0.0, 0.0, 0.0], // unit quaternion
            GenJoint::Floating => vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], // pos + unit quat
        }
    }
}

// ============================================================================
// Quaternion helpers
// ============================================================================

/// Extract a UnitQuaternion from a slice [w, x, y, z]. Normalizes automatically.
fn quat_from_slice(q: &[f32]) -> UnitQuaternion<f32> {
    if q.len() >= 4 {
        let quat = nalgebra::Quaternion::new(q[0], q[1], q[2], q[3]);
        if quat.norm() < 1e-10 {
            UnitQuaternion::identity()
        } else {
            UnitQuaternion::new_normalize(quat)
        }
    } else {
        UnitQuaternion::identity()
    }
}

/// Convert quaternion derivative to angular velocity: ω = 2 * Im(q_conj * qdot)
fn quat_deriv_to_omega(q: UnitQuaternion<f32>, qdot: Vector4<f32>) -> Vector3<f32> {
    // ω = 2 * (q* ⊗ qdot).xyz
    let qc = q.conjugate();
    let qc_inner = qc.into_inner();
    let qdot_quat = nalgebra::Quaternion::new(qdot[0], qdot[1], qdot[2], qdot[3]);
    let result = qc_inner * qdot_quat;
    Vector3::new(result.i, result.j, result.k) * 2.0
}

/// Convert angular velocity to quaternion derivative: qdot = 0.5 * q ⊗ [0, ω]
fn omega_to_quat_deriv(q: UnitQuaternion<f32>, omega: Vector3<f32>) -> nalgebra::Quaternion<f32> {
    let omega_quat = nalgebra::Quaternion::new(0.0, omega.x, omega.y, omega.z);
    q.into_inner() * omega_quat * 0.5
}

/// Normalize a quaternion stored as [w, x, y, z] in a mutable slice.
fn normalize_quat_slice(q: &mut [f32]) {
    let norm = (q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]).sqrt();
    if norm > 1e-10 {
        let inv = 1.0 / norm;
        q[0] *= inv;
        q[1] *= inv;
        q[2] *= inv;
        q[3] *= inv;
    } else {
        // Reset to identity if degenerate — indicates numerical instability
        // Degenerate quaternion — numerical instability
        #[cfg(feature = "tracing")]
        tracing::warn!("Degenerate quaternion detected (norm={:.2e}), resetting to identity", norm);
        let _ = norm;
        q[0] = 1.0;
        q[1] = 0.0;
        q[2] = 0.0;
        q[3] = 0.0;
    }
}

/// Build an orthonormal basis for a plane given its normal.
pub fn plane_basis(normal: &Vector3<f32>) -> (Vector3<f32>, Vector3<f32>) {
    if normal.norm_squared() < 1e-12 {
        return (Vector3::x(), Vector3::y());
    }
    let n = normal.normalize();
    let hint = if n.x.abs() < 0.9 {
        Vector3::x()
    } else {
        Vector3::y()
    };
    let t1 = n.cross(&hint).normalize();
    let t2 = n.cross(&t1).normalize();
    (t1, t2)
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_relative_eq;
    use nalgebra::Matrix3;
    use std::f32::consts::FRAC_PI_2;

    // --- DOF / n_pos ---

    #[test]
    fn test_dof_and_npos() {
        assert_eq!(GenJoint::Fixed.dof(), 0);
        assert_eq!(GenJoint::Fixed.n_pos(), 0);

        let rev = GenJoint::Revolute {
            axis: Vector3::z(),
        };
        assert_eq!(rev.dof(), 1);
        assert_eq!(rev.n_pos(), 1);

        let pris = GenJoint::Prismatic {
            axis: Vector3::x(),
        };
        assert_eq!(pris.dof(), 1);
        assert_eq!(pris.n_pos(), 1);

        assert_eq!(GenJoint::Spherical.dof(), 3);
        assert_eq!(GenJoint::Spherical.n_pos(), 4);

        assert_eq!(GenJoint::Floating.dof(), 6);
        assert_eq!(GenJoint::Floating.n_pos(), 7);

        let planar = GenJoint::Planar {
            normal: Vector3::z(),
        };
        assert_eq!(planar.dof(), 3);
        assert_eq!(planar.n_pos(), 3);
    }

    // --- Transform ---

    #[test]
    fn test_revolute_transform_90deg() {
        let jt = GenJoint::Revolute {
            axis: Vector3::z(),
        };
        let x = jt.transform(&[FRAC_PI_2]);
        let p = x.rotation * Vector3::x();
        assert_relative_eq!(p.y, 1.0, epsilon = 1e-5);
        assert!(p.x.abs() < 1e-5);
    }

    #[test]
    fn test_prismatic_transform() {
        let jt = GenJoint::Prismatic {
            axis: Vector3::x(),
        };
        let x = jt.transform(&[0.5]);
        assert_relative_eq!(x.translation.x, 0.5, epsilon = 1e-10);
    }

    #[test]
    fn test_fixed_identity() {
        let x = GenJoint::Fixed.transform(&[]);
        assert!((x.rotation - Matrix3::identity()).norm() < 1e-10);
    }

    #[test]
    fn test_spherical_identity_at_unit_quat() {
        let x = GenJoint::Spherical.transform(&[1.0, 0.0, 0.0, 0.0]);
        assert!((x.rotation - Matrix3::identity()).norm() < 1e-6);
    }

    #[test]
    fn test_spherical_90deg_z() {
        // Quaternion for 90° around Z: [cos(45°), 0, 0, sin(45°)]
        let half_angle = FRAC_PI_2 / 2.0;
        let w = half_angle.cos();
        let z = half_angle.sin();
        let x = GenJoint::Spherical.transform(&[w, 0.0, 0.0, z]);
        let p = x.rotation * Vector3::x();
        assert_relative_eq!(p.y, 1.0, epsilon = 1e-5);
        assert!(p.x.abs() < 1e-5);
    }

    #[test]
    fn test_floating_identity() {
        let x = GenJoint::Floating.transform(&[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]);
        assert!((x.rotation - Matrix3::identity()).norm() < 1e-6);
        assert!(x.translation.norm() < 1e-10);
    }

    #[test]
    fn test_floating_translation() {
        let x = GenJoint::Floating.transform(&[1.0, 2.0, 3.0, 1.0, 0.0, 0.0, 0.0]);
        assert_relative_eq!(x.translation.x, 1.0, epsilon = 1e-6);
        assert_relative_eq!(x.translation.y, 2.0, epsilon = 1e-6);
        assert_relative_eq!(x.translation.z, 3.0, epsilon = 1e-6);
    }

    #[test]
    fn test_transform_inverse_round_trip() {
        // For all joint types, transform(q).inverse() * transform(q) ≈ identity
        let joints_and_qs: Vec<(GenJoint, Vec<f32>)> = vec![
            (GenJoint::Revolute { axis: Vector3::z() }, vec![0.7]),
            (GenJoint::Prismatic { axis: Vector3::x() }, vec![1.5]),
            (GenJoint::Spherical, vec![0.9239, 0.0, 0.0, 0.3827]), // 45° around Z
            (
                GenJoint::Floating,
                vec![1.0, 2.0, 3.0, 0.9239, 0.0, 0.0, 0.3827],
            ),
            (GenJoint::Planar { normal: Vector3::z() }, vec![1.0, 2.0, 0.5]),
        ];

        for (joint, q) in &joints_and_qs {
            let x = joint.transform(q);
            let x_inv = x.inverse();
            let composed = x.compose(&x_inv);
            assert!(
                (composed.rotation - Matrix3::identity()).norm() < 1e-5,
                "Round-trip failed for {joint:?}"
            );
            assert!(
                composed.translation.norm() < 1e-5,
                "Round-trip translation failed for {joint:?}"
            );
        }
    }

    // --- Motion subspace ---

    #[test]
    fn test_motion_subspace_dimensions() {
        let joints: Vec<GenJoint> = vec![
            GenJoint::Fixed,
            GenJoint::Revolute { axis: Vector3::z() },
            GenJoint::Prismatic { axis: Vector3::y() },
            GenJoint::Spherical,
            GenJoint::Floating,
            GenJoint::Planar { normal: Vector3::z() },
        ];
        for j in &joints {
            let s = j.motion_subspace(&j.default_q());
            assert_eq!(s.len(), j.dof(), "S columns should equal dof() for {j:?}");
        }
    }

    #[test]
    fn test_motion_subspace_revolute() {
        let jt = GenJoint::Revolute {
            axis: Vector3::z(),
        };
        let s = jt.motion_subspace(&[0.0]);
        assert_eq!(s.len(), 1);
        assert_relative_eq!(s[0].angular().z, 1.0, epsilon = 1e-10);
        assert!(s[0].linear().norm() < 1e-10);
    }

    #[test]
    fn test_motion_subspace_prismatic() {
        let jt = GenJoint::Prismatic {
            axis: Vector3::y(),
        };
        let s = jt.motion_subspace(&[0.0]);
        assert!(s[0].angular().norm() < 1e-10);
        assert_relative_eq!(s[0].linear().y, 1.0, epsilon = 1e-10);
    }

    // --- Velocity mapping ---

    #[test]
    fn test_velocity_round_trip_revolute() {
        let jt = GenJoint::Revolute {
            axis: Vector3::z(),
        };
        let q = vec![0.5];
        let omega = vec![1.0];
        let qdot = jt.qdot_from_velocity(&q, &omega);
        let omega_back = jt.velocity_from_qdot(&q, &qdot);
        assert_relative_eq!(omega_back[0], omega[0], epsilon = 1e-10);
    }

    #[test]
    fn test_velocity_round_trip_spherical() {
        let jt = GenJoint::Spherical;
        let q = vec![1.0, 0.0, 0.0, 0.0]; // identity quaternion
        let omega = vec![0.5, -0.3, 0.7];
        let qdot = jt.qdot_from_velocity(&q, &omega);
        let omega_back = jt.velocity_from_qdot(&q, &qdot);
        for i in 0..3 {
            assert_relative_eq!(omega_back[i], omega[i], epsilon = 1e-5);
        }
    }

    #[test]
    fn test_velocity_round_trip_floating() {
        let jt = GenJoint::Floating;
        let q = vec![1.0, 2.0, 3.0, 1.0, 0.0, 0.0, 0.0];
        let v = vec![0.1, 0.2, 0.3, 0.4, 0.5, 0.6];
        let qdot = jt.qdot_from_velocity(&q, &v);
        let v_back = jt.velocity_from_qdot(&q, &qdot);
        for i in 0..6 {
            assert_relative_eq!(v_back[i], v[i], epsilon = 1e-5);
        }
    }

    // --- Quaternion normalization ---

    #[test]
    fn test_normalize_spherical() {
        let jt = GenJoint::Spherical;
        let mut q = vec![2.0, 0.0, 0.0, 0.0];
        jt.normalize_q(&mut q);
        let norm = (q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]).sqrt();
        assert_relative_eq!(norm, 1.0, epsilon = 1e-7);
    }

    #[test]
    fn test_normalize_floating() {
        let jt = GenJoint::Floating;
        let mut q = vec![1.0, 2.0, 3.0, 0.5, 0.5, 0.5, 0.5];
        jt.normalize_q(&mut q);
        // Translation should be unchanged
        assert_relative_eq!(q[0], 1.0);
        assert_relative_eq!(q[1], 2.0);
        assert_relative_eq!(q[2], 3.0);
        // Quaternion should be normalized
        let norm = (q[3] * q[3] + q[4] * q[4] + q[5] * q[5] + q[6] * q[6]).sqrt();
        assert_relative_eq!(norm, 1.0, epsilon = 1e-7);
    }

    // --- Default q ---

    #[test]
    fn test_default_q_identity_transform() {
        let joints: Vec<GenJoint> = vec![
            GenJoint::Fixed,
            GenJoint::Revolute { axis: Vector3::z() },
            GenJoint::Prismatic { axis: Vector3::x() },
            GenJoint::Spherical,
            GenJoint::Floating,
            GenJoint::Planar { normal: Vector3::z() },
        ];
        for j in &joints {
            let default_q = j.default_q();
            assert_eq!(default_q.len(), j.n_pos(), "default_q len for {j:?}");
            let x = j.transform(&default_q);
            assert!(
                (x.rotation - Matrix3::identity()).norm() < 1e-6,
                "default_q should give identity rotation for {j:?}"
            );
            assert!(
                x.translation.norm() < 1e-10,
                "default_q should give zero translation for {j:?}"
            );
        }
    }

    // ── SLAM Cycle 9: Joint edge case + intent tests ─────────────────

    #[test]
    #[test]
    fn intent_joint_dof_matches_motion_subspace_len() {
        // Intent: motion subspace S(q) must have exactly dof() columns (one SpatialVector per DOF)
        let joints = [
            GenJoint::Fixed,
            GenJoint::Revolute { axis: Vector3::z() },
            GenJoint::Prismatic { axis: Vector3::x() },
            GenJoint::Spherical,
            GenJoint::Floating,
            GenJoint::Planar { normal: Vector3::y() },
        ];
        for j in &joints {
            let q = j.default_q();
            let s = j.motion_subspace(&q);
            assert_eq!(
                s.len(), j.dof(),
                "{:?}: motion_subspace len ({}) != dof ({})", j, s.len(), j.dof()
            );
        }
    }

    #[test]
    fn intent_joint_npos_geq_dof() {
        // Intent: n_pos() >= dof() (quaternion joints have extra params)
        let joints = [
            GenJoint::Fixed,
            GenJoint::Revolute { axis: Vector3::z() },
            GenJoint::Prismatic { axis: Vector3::x() },
            GenJoint::Spherical,
            GenJoint::Floating,
            GenJoint::Planar { normal: Vector3::y() },
        ];
        for j in &joints {
            assert!(
                j.n_pos() >= j.dof(),
                "{:?}: n_pos ({}) must be >= dof ({})", j, j.n_pos(), j.dof()
            );
        }
    }

    #[test]
    fn intent_spherical_quaternion_normalize_preserves_unit() {
        let j = GenJoint::Spherical;
        let mut q = vec![1.0_f32, 0.0, 0.0, 0.0];
        j.normalize_q(&mut q);
        let norm: f32 = q.iter().map(|x| x * x).sum::<f32>().sqrt();
        assert!((norm - 1.0).abs() < 1e-6, "unit quat preserved: norm={}", norm);
    }

    #[test]
    fn intent_spherical_quaternion_normalize_fixes_unnormalized() {
        let j = GenJoint::Spherical;
        let mut q = vec![2.0_f32, 0.0, 0.0, 0.0];
        j.normalize_q(&mut q);
        let norm: f32 = q.iter().map(|x| x * x).sum::<f32>().sqrt();
        assert!((norm - 1.0).abs() < 1e-5, "unnormalized fixed: norm={}", norm);
    }

    // ── SLAM Cycle 2: Joint proptest and intent tests ─────────────────

    use proptest::prelude::*;

    proptest! {
        #[test]
        fn prop_revolute_transform_at_zero_is_identity(
            ax in -1.0f32..1.0, ay in -1.0f32..1.0, az in 0.1f32..1.0,
        ) {
            let len = (ax * ax + ay * ay + az * az).sqrt();
            let axis = Vector3::new(ax / len, ay / len, az / len);
            let joint = GenJoint::Revolute { axis };
            let t = joint.transform(&[0.0]);
            let diff = (t.rotation - Matrix3::identity()).norm();
            prop_assert!(diff < 1e-5, "Transform at q=0 should be identity, got rotation diff={diff}");
            prop_assert!(t.translation.norm() < 1e-5, "Translation at q=0 should be zero");
        }

        #[test]
        fn prop_revolute_velocity_roundtrip(
            angle in -3.0f32..3.0,
            vel in -10.0f32..10.0,
        ) {
            let joint = GenJoint::Revolute { axis: Vector3::z() };
            let q = vec![angle];
            let v_in = vec![vel];
            let qdot = joint.qdot_from_velocity(&q, &v_in);
            let v_out = joint.velocity_from_qdot(&q, &qdot);
            prop_assert!((v_out[0] - vel).abs() < 1e-4,
                "Velocity roundtrip: in={vel}, out={}", v_out[0]);
        }

        #[test]
        fn prop_prismatic_default_q_gives_identity(
            ax in -1.0f32..1.0, ay in -1.0f32..1.0, az in 0.1f32..1.0,
        ) {
            let len = (ax * ax + ay * ay + az * az).sqrt();
            let axis = Vector3::new(ax / len, ay / len, az / len);
            let joint = GenJoint::Prismatic { axis };
            let q = joint.default_q();
            let t = joint.transform(&q);
            prop_assert!(t.translation.norm() < 1e-5, "Default prismatic should have zero translation");
        }

        #[test]
        fn prop_motion_subspace_dimension_equals_dof(
            angle in -3.0f32..3.0,
        ) {
            let joints = vec![
                GenJoint::Revolute { axis: Vector3::z() },
                GenJoint::Prismatic { axis: Vector3::y() },
                GenJoint::Spherical,
                GenJoint::Fixed,
            ];
            for j in &joints {
                let q = j.default_q();
                let s = j.motion_subspace(&q);
                prop_assert_eq!(s.len(), j.dof(),
                    "{:?}: motion subspace columns ({}) != dof ({})", j, s.len(), j.dof());
            }
        }
    }

    #[test]
    fn intent_all_joints_default_q_produces_identity_transform() {
        // Intent: default_q() should produce identity transform for all joint types
        let joints: Vec<GenJoint> = vec![
            GenJoint::Fixed,
            GenJoint::Revolute { axis: Vector3::z() },
            GenJoint::Prismatic { axis: Vector3::y() },
            GenJoint::Spherical,
            GenJoint::Floating,
            GenJoint::Planar { normal: Vector3::y() },
        ];
        for j in &joints {
            let q = j.default_q();
            let t = j.transform(&q);
            let rot_diff = (t.rotation - Matrix3::identity()).norm();
            let trans_diff = t.translation.norm();
            assert!(rot_diff < 1e-4, "{:?}: default rotation should be identity, diff={rot_diff}", j);
            assert!(trans_diff < 1e-4, "{:?}: default translation should be zero, diff={trans_diff}", j);
        }
    }

    #[test]
    fn test_planar_joint_dof_and_npos() {
        let j = GenJoint::Planar { normal: Vector3::y() };
        assert_eq!(j.dof(), 3, "planar = 3 DOF");
        assert_eq!(j.n_pos(), 3, "planar = 3 pos params");
    }

    #[test]
    fn test_floating_joint_velocity_roundtrip() {
        let j = GenJoint::Floating;
        let q = j.default_q(); // 7 params: [x,y,z,w,qx,qy,qz]
        let v = vec![1.0_f32, 2.0, 3.0, 0.1, 0.2, 0.3]; // 6 DOF velocity
        let qdot = j.qdot_from_velocity(&q, &v);
        let v_back = j.velocity_from_qdot(&q, &qdot);
        for i in 0..6 {
            assert!((v_back[i] - v[i]).abs() < 0.01,
                "floating velocity roundtrip failed at [{i}]: in={}, out={}", v[i], v_back[i]);
        }
    }

    #[test]
    fn test_spherical_joint_3dof_motion_subspace() {
        let j = GenJoint::Spherical;
        let q = j.default_q();
        let s = j.motion_subspace(&q);
        assert_eq!(s.len(), 3, "spherical should have 3 motion subspace columns");
    }
}