oxiphysics-python 0.1.0

Python bindings for the OxiPhysics engine
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
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
#![allow(clippy::needless_range_loop)]
// Copyright 2026 COOLJAPAN OU (Team KitaSan)
// SPDX-License-Identifier: Apache-2.0

//! Constraint system API for Python interop.
//!
//! Provides Python-friendly types for rigid body constraint solving,
//! joints, contact constraints, motors, island management, CCD,
//! PBD/XPBD solvers, control systems, friction models, and warm starting.

#![allow(missing_docs)]
#![allow(dead_code)]

use serde::{Deserialize, Serialize};

// ---------------------------------------------------------------------------
// Helper functions
// ---------------------------------------------------------------------------

/// Perform one PGS (Projected Gauss-Seidel) iteration over a set of constraints.
///
/// `lambda` — accumulated impulse per constraint (modified in place).
/// `rhs`    — constraint violation / desired velocity change per constraint.
/// `diag`   — diagonal of the effective-mass matrix per constraint.
/// `lo`     — lower bound per constraint (clamping).
/// `hi`     — upper bound per constraint (clamping).
///
/// Returns the total residual after the iteration.
pub fn solve_pgs_iteration(
    lambda: &mut [f64],
    rhs: &[f64],
    diag: &[f64],
    lo: &[f64],
    hi: &[f64],
) -> f64 {
    let n = lambda.len();
    let mut residual = 0.0;
    for i in 0..n {
        if diag[i].abs() < 1e-15 {
            continue;
        }
        let delta = (rhs[i] - diag[i] * lambda[i]) / diag[i];
        let new_lambda = (lambda[i] + delta).clamp(lo[i], hi[i]);
        let actual_delta = new_lambda - lambda[i];
        lambda[i] = new_lambda;
        residual += actual_delta * actual_delta;
    }
    residual.sqrt()
}

/// Compute the Jacobian row for a distance constraint between two bodies.
///
/// `r_a` — vector from body A's center to the contact point.
/// `r_b` — vector from body B's center to the contact point.
/// `n`   — constraint normal direction (unit vector).
///
/// Returns \[J_lin_a (3), J_ang_a (3), J_lin_b (3), J_ang_b (3)\] = 12 values.
pub fn compute_jacobian(r_a: [f64; 3], r_b: [f64; 3], n: [f64; 3]) -> [f64; 12] {
    // J_lin_a = n, J_ang_a = r_a × n, J_lin_b = -n, J_ang_b = -r_b × n
    let ang_a = cross(r_a, n);
    let ang_b = cross(r_b, n);
    [
        n[0], n[1], n[2], ang_a[0], ang_a[1], ang_a[2], -n[0], -n[1], -n[2], -ang_b[0], -ang_b[1],
        -ang_b[2],
    ]
}

fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
    [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    ]
}

/// Compute the effective mass (inverse denominator) for a constraint.
///
/// `inv_mass_a`, `inv_mass_b` — inverse masses.
/// `inv_inertia_a`, `inv_inertia_b` — diagonal inverse inertia tensors (3 values each).
/// `j` — Jacobian row (12 values from `compute_jacobian`).
///
/// Returns the effective mass = 1 / (J M⁻¹ Jᵀ).
pub fn compute_effective_mass(
    inv_mass_a: f64,
    inv_mass_b: f64,
    inv_inertia_a: [f64; 3],
    inv_inertia_b: [f64; 3],
    j: [f64; 12],
) -> f64 {
    // linear part
    let lin_a = j[0] * j[0] * inv_mass_a + j[1] * j[1] * inv_mass_a + j[2] * j[2] * inv_mass_a;
    let ang_a = j[3] * j[3] * inv_inertia_a[0]
        + j[4] * j[4] * inv_inertia_a[1]
        + j[5] * j[5] * inv_inertia_a[2];
    let lin_b = j[6] * j[6] * inv_mass_b + j[7] * j[7] * inv_mass_b + j[8] * j[8] * inv_mass_b;
    let ang_b = j[9] * j[9] * inv_inertia_b[0]
        + j[10] * j[10] * inv_inertia_b[1]
        + j[11] * j[11] * inv_inertia_b[2];
    let denom = lin_a + ang_a + lin_b + ang_b;
    if denom.abs() < 1e-15 {
        0.0
    } else {
        1.0 / denom
    }
}

/// Clamp an impulse to the friction cone.
///
/// `lambda_n` — normal impulse (must be ≥ 0).
/// `lambda_t` — current tangential impulse vector \[lt_x, lt_y\].
/// `mu`       — friction coefficient.
///
/// Returns the clamped tangential impulse.
pub fn clamp_impulse(lambda_n: f64, lambda_t: [f64; 2], mu: f64) -> [f64; 2] {
    let max_t = mu * lambda_n.max(0.0);
    let mag = (lambda_t[0] * lambda_t[0] + lambda_t[1] * lambda_t[1]).sqrt();
    if mag > max_t && mag > 1e-15 {
        [lambda_t[0] / mag * max_t, lambda_t[1] / mag * max_t]
    } else {
        lambda_t
    }
}

// ---------------------------------------------------------------------------
// Solver type
// ---------------------------------------------------------------------------

/// Constraint solver algorithm selection.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum SolverType {
    /// Projected Gauss-Seidel.
    Pgs,
    /// Temporal Gauss-Seidel (velocity + position level).
    Tgs,
    /// Sequential impulse (SI).
    Si,
}

/// Main constraint solver configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PyConstraintSolver {
    /// Solver algorithm.
    pub solver_type: SolverType,
    /// Number of velocity-level iterations.
    pub velocity_iterations: u32,
    /// Number of position-level iterations (for TGS/non-penetration correction).
    pub position_iterations: u32,
    /// Whether to use warm starting from the previous frame.
    pub warm_start: bool,
    /// Successive over-relaxation factor (1.0 = standard PGS).
    pub sor_factor: f64,
    /// Convergence tolerance.
    pub tolerance: f64,
    /// Maximum allowed penetration before applying a correction impulse.
    pub slop: f64,
}

impl PyConstraintSolver {
    /// Create a default PGS solver.
    pub fn default_pgs() -> Self {
        Self {
            solver_type: SolverType::Pgs,
            velocity_iterations: 10,
            position_iterations: 5,
            warm_start: true,
            sor_factor: 1.0,
            tolerance: 1e-4,
            slop: 0.005,
        }
    }

    /// Create a TGS solver (fewer iterations needed).
    pub fn default_tgs() -> Self {
        Self {
            solver_type: SolverType::Tgs,
            velocity_iterations: 4,
            position_iterations: 2,
            warm_start: true,
            sor_factor: 1.3,
            tolerance: 1e-4,
            slop: 0.005,
        }
    }

    /// Solve a simple set of constraints given accumulated lambdas, RHS and diagonal effective masses.
    ///
    /// Returns the final accumulated impulse array.
    pub fn solve(&self, rhs: &[f64], diag: &[f64], lo: &[f64], hi: &[f64]) -> Vec<f64> {
        let n = rhs.len();
        let mut lambda = vec![0.0f64; n];
        for _ in 0..self.velocity_iterations {
            let res = solve_pgs_iteration(&mut lambda, rhs, diag, lo, hi);
            if res < self.tolerance {
                break;
            }
        }
        lambda
    }
}

// ---------------------------------------------------------------------------
// PyJoint
// ---------------------------------------------------------------------------

/// Joint axis and limit specification.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AxisLimits {
    /// Axis direction (unit vector).
    pub axis: [f64; 3],
    /// Lower limit (radians or meters).
    pub lower: f64,
    /// Upper limit.
    pub upper: f64,
    /// Whether limits are enabled.
    pub enabled: bool,
}

impl AxisLimits {
    /// Unlimited joint along an axis.
    pub fn unlimited(axis: [f64; 3]) -> Self {
        Self {
            axis,
            lower: -f64::INFINITY,
            upper: f64::INFINITY,
            enabled: false,
        }
    }

    /// Limited joint.
    pub fn limited(axis: [f64; 3], lower: f64, upper: f64) -> Self {
        Self {
            axis,
            lower,
            upper,
            enabled: true,
        }
    }
}

/// The kind of joint.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum JointKind {
    /// Fully fixed — all 6 DOF locked.
    Fixed,
    /// Revolute (hinge) joint — 1 rotational DOF.
    Revolute(AxisLimits),
    /// Prismatic (sliding) joint — 1 translational DOF.
    Prismatic(AxisLimits),
    /// Ball-and-socket joint with swing and twist limits.
    Ball { swing_limit: f64, twist_limit: f64 },
    /// Spring joint with stiffness and damping.
    Spring {
        stiffness: f64,
        damping: f64,
        rest_length: f64,
    },
}

/// A joint connecting two rigid bodies.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PyJoint {
    /// Unique joint identifier.
    pub id: u32,
    /// Body A handle.
    pub body_a: u32,
    /// Body B handle.
    pub body_b: u32,
    /// Anchor point on body A in local space.
    pub anchor_a: [f64; 3],
    /// Anchor point on body B in local space.
    pub anchor_b: [f64; 3],
    /// Joint type.
    pub kind: JointKind,
    /// Whether this joint is enabled.
    pub enabled: bool,
    /// Joint breaking force (inf = unbreakable).
    pub break_force: f64,
}

impl PyJoint {
    /// Create a fixed joint between two bodies.
    pub fn fixed(
        id: u32,
        body_a: u32,
        body_b: u32,
        anchor_a: [f64; 3],
        anchor_b: [f64; 3],
    ) -> Self {
        Self {
            id,
            body_a,
            body_b,
            anchor_a,
            anchor_b,
            kind: JointKind::Fixed,
            enabled: true,
            break_force: f64::INFINITY,
        }
    }

    /// Create a revolute joint.
    pub fn revolute(id: u32, body_a: u32, body_b: u32, anchor: [f64; 3], axis: [f64; 3]) -> Self {
        Self {
            id,
            body_a,
            body_b,
            anchor_a: anchor,
            anchor_b: anchor,
            kind: JointKind::Revolute(AxisLimits::unlimited(axis)),
            enabled: true,
            break_force: f64::INFINITY,
        }
    }

    /// Create a spring joint.
    #[allow(clippy::too_many_arguments)]
    pub fn spring(
        id: u32,
        body_a: u32,
        body_b: u32,
        anchor_a: [f64; 3],
        anchor_b: [f64; 3],
        stiffness: f64,
        damping: f64,
        rest_length: f64,
    ) -> Self {
        Self {
            id,
            body_a,
            body_b,
            anchor_a,
            anchor_b,
            kind: JointKind::Spring {
                stiffness,
                damping,
                rest_length,
            },
            enabled: true,
            break_force: f64::INFINITY,
        }
    }

    /// Check if the joint is breakable.
    pub fn is_breakable(&self) -> bool {
        self.break_force.is_finite()
    }
}

// ---------------------------------------------------------------------------
// PyContactConstraint
// ---------------------------------------------------------------------------

/// A single contact point constraint between two bodies.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PyContactConstraint {
    /// Body A handle.
    pub body_a: u32,
    /// Body B handle.
    pub body_b: u32,
    /// Contact normal (from B to A, unit vector).
    pub normal: [f64; 3],
    /// Penetration depth (positive = overlap).
    pub penetration: f64,
    /// Contact position in world space.
    pub position: [f64; 3],
    /// Accumulated normal impulse (warm start).
    pub lambda_n: f64,
    /// Accumulated tangent impulse in primary direction.
    pub lambda_t1: f64,
    /// Accumulated tangent impulse in secondary direction.
    pub lambda_t2: f64,
    /// Coefficient of restitution.
    pub restitution: f64,
    /// Coulomb friction coefficient.
    pub friction: f64,
}

impl PyContactConstraint {
    /// Create a new contact constraint.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        body_a: u32,
        body_b: u32,
        normal: [f64; 3],
        penetration: f64,
        position: [f64; 3],
        restitution: f64,
        friction: f64,
    ) -> Self {
        Self {
            body_a,
            body_b,
            normal,
            penetration,
            position,
            lambda_n: 0.0,
            lambda_t1: 0.0,
            lambda_t2: 0.0,
            restitution,
            friction,
        }
    }

    /// Clamp the tangential impulses to the friction cone.
    pub fn clamp_friction(&mut self) {
        let clamped = clamp_impulse(
            self.lambda_n,
            [self.lambda_t1, self.lambda_t2],
            self.friction,
        );
        self.lambda_t1 = clamped[0];
        self.lambda_t2 = clamped[1];
    }

    /// Compute the primary and secondary tangent directions orthogonal to the normal.
    pub fn tangent_basis(&self) -> ([f64; 3], [f64; 3]) {
        let n = self.normal;
        let t1 = if n[0].abs() < 0.9 {
            let raw = [0.0 - n[1] * n[1], n[0] * n[1] - 0.0, 0.0];
            // Just use a simple perpendicular
            let t = [1.0 - n[0] * n[0], -n[0] * n[1], -n[0] * n[2]];
            let len = (t[0] * t[0] + t[1] * t[1] + t[2] * t[2]).sqrt();
            if len > 1e-12 {
                [t[0] / len, t[1] / len, t[2] / len]
            } else {
                raw
            }
        } else {
            let t = [-n[1] * n[0], 1.0 - n[1] * n[1], -n[1] * n[2]];
            let len = (t[0] * t[0] + t[1] * t[1] + t[2] * t[2]).sqrt();
            if len > 1e-12 {
                [t[0] / len, t[1] / len, t[2] / len]
            } else {
                [0.0, 1.0, 0.0]
            }
        };
        let t2 = cross(n, t1);
        (t1, t2)
    }
}

// ---------------------------------------------------------------------------
// PyMotorConstraint
// ---------------------------------------------------------------------------

/// PID controller for motor target tracking.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PidGains {
    /// Proportional gain.
    pub kp: f64,
    /// Integral gain.
    pub ki: f64,
    /// Derivative gain.
    pub kd: f64,
    /// Accumulated integral error.
    pub integral: f64,
    /// Previous error (for derivative).
    pub prev_error: f64,
}

impl PidGains {
    /// Create new PID gains.
    pub fn new(kp: f64, ki: f64, kd: f64) -> Self {
        Self {
            kp,
            ki,
            kd,
            integral: 0.0,
            prev_error: 0.0,
        }
    }

    /// Compute PID output given the current error and time step.
    pub fn compute(&mut self, error: f64, dt: f64) -> f64 {
        self.integral += error * dt;
        let derivative = if dt > 1e-15 {
            (error - self.prev_error) / dt
        } else {
            0.0
        };
        self.prev_error = error;
        self.kp * error + self.ki * self.integral + self.kd * derivative
    }

    /// Reset the integral and derivative state.
    pub fn reset(&mut self) {
        self.integral = 0.0;
        self.prev_error = 0.0;
    }
}

/// Motor thermal model to cap torque under sustained load.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MotorThermal {
    /// Current motor temperature (°C).
    pub temperature: f64,
    /// Ambient temperature (°C).
    pub ambient: f64,
    /// Thermal resistance (°C/W).
    pub resistance: f64,
    /// Thermal capacitance (J/°C).
    pub capacitance: f64,
    /// Motor resistance for heat generation (Ω).
    pub motor_resistance: f64,
    /// Temperature derating threshold (°C).
    pub derate_threshold: f64,
    /// Maximum allowed temperature (°C).
    pub max_temperature: f64,
}

impl MotorThermal {
    /// Create a default thermal model.
    pub fn new() -> Self {
        Self {
            temperature: 25.0,
            ambient: 25.0,
            resistance: 0.5,
            capacitance: 100.0,
            motor_resistance: 0.1,
            derate_threshold: 80.0,
            max_temperature: 120.0,
        }
    }

    /// Update temperature given current (A) and time step (s).
    pub fn update(&mut self, current: f64, dt: f64) {
        let heat_in = current * current * self.motor_resistance;
        let heat_out = (self.temperature - self.ambient) / self.resistance;
        self.temperature += (heat_in - heat_out) / self.capacitance * dt;
    }

    /// Compute the torque scale factor (1 = full, < 1 = derated).
    pub fn torque_scale(&self) -> f64 {
        if self.temperature <= self.derate_threshold {
            1.0
        } else {
            let range = self.max_temperature - self.derate_threshold;
            if range < 1e-9 {
                0.0
            } else {
                (1.0 - (self.temperature - self.derate_threshold) / range).max(0.0)
            }
        }
    }
}

impl Default for MotorThermal {
    fn default() -> Self {
        Self::new()
    }
}

/// A motor/actuator constraint driving a joint.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PyMotorConstraint {
    /// Target angular velocity (rad/s). Used in velocity mode.
    pub target_velocity: f64,
    /// Target position (rad or m). Used in position mode.
    pub target_position: f64,
    /// Maximum torque/force (N·m or N).
    pub max_torque: f64,
    /// PID controller.
    pub pid: PidGains,
    /// Whether in position mode (true) or velocity mode (false).
    pub position_mode: bool,
    /// Current applied torque.
    pub applied_torque: f64,
    /// Thermal model.
    pub thermal: MotorThermal,
}

impl PyMotorConstraint {
    /// Create a velocity-mode motor.
    pub fn velocity_mode(target_velocity: f64, max_torque: f64, kp: f64) -> Self {
        Self {
            target_velocity,
            target_position: 0.0,
            max_torque,
            pid: PidGains::new(kp, 0.0, 0.0),
            position_mode: false,
            applied_torque: 0.0,
            thermal: MotorThermal::new(),
        }
    }

    /// Create a position-mode motor with PID gains.
    pub fn position_mode(target_position: f64, max_torque: f64, pid: PidGains) -> Self {
        Self {
            target_velocity: 0.0,
            target_position,
            max_torque,
            pid,
            position_mode: true,
            applied_torque: 0.0,
            thermal: MotorThermal::new(),
        }
    }

    /// Step the motor given the current measured value and time step.
    pub fn step(&mut self, current_value: f64, dt: f64) -> f64 {
        let error = if self.position_mode {
            self.target_position - current_value
        } else {
            self.target_velocity - current_value
        };
        let raw_torque = self.pid.compute(error, dt);
        let scale = self.thermal.torque_scale();
        let torque = raw_torque.clamp(-self.max_torque, self.max_torque) * scale;
        let current = (torque / self.max_torque.max(1e-9)).abs() * 10.0;
        self.thermal.update(current, dt);
        self.applied_torque = torque;
        torque
    }
}

// ---------------------------------------------------------------------------
// PyIsland
// ---------------------------------------------------------------------------

/// Sleeping state of an island.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum IslandSleepState {
    /// Island is awake and being simulated.
    Awake,
    /// Island is dormant (below velocity threshold).
    Sleeping,
    /// Island is in the process of going to sleep.
    Drowsy,
}

/// An island groups bodies and constraints that can interact.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PyIsland {
    /// Unique island id.
    pub id: u32,
    /// Handles of rigid bodies in this island.
    pub bodies: Vec<u32>,
    /// Handles of constraints in this island.
    pub constraints: Vec<u32>,
    /// Sleep state.
    pub sleep_state: IslandSleepState,
    /// Frames below the velocity threshold (used for sleep triggering).
    pub quiet_frames: u32,
    /// Velocity threshold for sleeping (m/s and rad/s combined).
    pub sleep_threshold: f64,
    /// Number of frames needed to trigger sleep.
    pub sleep_frames: u32,
}

impl PyIsland {
    /// Create a new island.
    pub fn new(id: u32) -> Self {
        Self {
            id,
            bodies: Vec::new(),
            constraints: Vec::new(),
            sleep_state: IslandSleepState::Awake,
            quiet_frames: 0,
            sleep_threshold: 0.05,
            sleep_frames: 60,
        }
    }

    /// Add a body to the island.
    pub fn add_body(&mut self, body: u32) {
        if !self.bodies.contains(&body) {
            self.bodies.push(body);
        }
    }

    /// Add a constraint to the island.
    pub fn add_constraint(&mut self, constraint: u32) {
        if !self.constraints.contains(&constraint) {
            self.constraints.push(constraint);
        }
    }

    /// Update sleep state given the maximum body speed this frame.
    pub fn update_sleep(&mut self, max_speed: f64) {
        match self.sleep_state {
            IslandSleepState::Sleeping => {
                if max_speed > self.sleep_threshold * 2.0 {
                    self.sleep_state = IslandSleepState::Awake;
                    self.quiet_frames = 0;
                }
            }
            _ => {
                if max_speed < self.sleep_threshold {
                    self.quiet_frames += 1;
                    if self.quiet_frames >= self.sleep_frames {
                        self.sleep_state = IslandSleepState::Sleeping;
                    } else {
                        self.sleep_state = IslandSleepState::Drowsy;
                    }
                } else {
                    self.quiet_frames = 0;
                    self.sleep_state = IslandSleepState::Awake;
                }
            }
        }
    }

    /// Merge another island into this one.
    pub fn merge(&mut self, other: &PyIsland) {
        for &b in &other.bodies {
            self.add_body(b);
        }
        for &c in &other.constraints {
            self.add_constraint(c);
        }
        if other.sleep_state == IslandSleepState::Awake {
            self.sleep_state = IslandSleepState::Awake;
        }
    }

    /// Whether this island is currently active.
    pub fn is_active(&self) -> bool {
        self.sleep_state != IslandSleepState::Sleeping
    }
}

// ---------------------------------------------------------------------------
// PyCCDResult
// ---------------------------------------------------------------------------

/// Result of a continuous collision detection (CCD) query.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PyCCDResult {
    /// Whether a collision was detected.
    pub hit: bool,
    /// Time of impact in \[0, 1\] (fraction of the time step).
    pub toi: f64,
    /// Contact normal at the time of impact.
    pub normal: [f64; 3],
    /// Witness point on body A.
    pub witness_a: [f64; 3],
    /// Witness point on body B.
    pub witness_b: [f64; 3],
    /// Body A handle.
    pub body_a: u32,
    /// Body B handle.
    pub body_b: u32,
}

impl PyCCDResult {
    /// No collision result.
    pub fn miss(body_a: u32, body_b: u32) -> Self {
        Self {
            hit: false,
            toi: 1.0,
            normal: [0.0, 1.0, 0.0],
            witness_a: [0.0; 3],
            witness_b: [0.0; 3],
            body_a,
            body_b,
        }
    }

    /// Collision result at a given time of impact.
    #[allow(clippy::too_many_arguments)]
    pub fn hit(
        body_a: u32,
        body_b: u32,
        toi: f64,
        normal: [f64; 3],
        witness_a: [f64; 3],
        witness_b: [f64; 3],
    ) -> Self {
        Self {
            hit: true,
            toi: toi.clamp(0.0, 1.0),
            normal,
            witness_a,
            witness_b,
            body_a,
            body_b,
        }
    }

    /// Separation distance between witness points.
    pub fn witness_distance(&self) -> f64 {
        let dx = self.witness_a[0] - self.witness_b[0];
        let dy = self.witness_a[1] - self.witness_b[1];
        let dz = self.witness_a[2] - self.witness_b[2];
        (dx * dx + dy * dy + dz * dz).sqrt()
    }
}

// ---------------------------------------------------------------------------
// PyPbdSolver
// ---------------------------------------------------------------------------

/// PBD/XPBD constraint type.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PbdConstraintType {
    /// Distance / stretch constraint.
    Stretch { rest_length: f64, compliance: f64 },
    /// Bending constraint between three particles.
    Bend { rest_angle: f64, compliance: f64 },
    /// Volume conservation constraint.
    Volume { rest_volume: f64, compliance: f64 },
    /// Collision contact constraint.
    Contact { normal: [f64; 3], penetration: f64 },
}

/// A PBD/XPBD constraint connecting particle indices.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PbdConstraint {
    /// Particle indices involved (1, 2 or 3).
    pub particles: Vec<usize>,
    /// Constraint type and parameters.
    pub kind: PbdConstraintType,
    /// Accumulated Lagrange multiplier (XPBD).
    pub lambda: f64,
}

/// Position-based dynamics (XPBD) solver.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PyPbdSolver {
    /// Current particle positions (flat \[x0, y0, z0, x1, ...\]).
    pub positions: Vec<f64>,
    /// Previous particle positions (for XPBD velocity estimation).
    pub prev_positions: Vec<f64>,
    /// Per-particle inverse mass (0 = kinematic/fixed).
    pub inv_masses: Vec<f64>,
    /// Constraints.
    pub constraints: Vec<PbdConstraint>,
    /// Number of substeps per time step.
    pub substeps: u32,
    /// Gravity vector.
    pub gravity: [f64; 3],
}

impl PyPbdSolver {
    /// Create a new PBD solver.
    pub fn new(positions: Vec<f64>, inv_masses: Vec<f64>) -> Self {
        let prev = positions.clone();
        Self {
            positions,
            prev_positions: prev,
            inv_masses,
            constraints: Vec::new(),
            substeps: 8,
            gravity: [0.0, -9.81, 0.0],
        }
    }

    /// Add a stretch constraint between two particles.
    pub fn add_stretch(&mut self, i: usize, j: usize, compliance: f64) {
        let dx = self.positions[3 * i] - self.positions[3 * j];
        let dy = self.positions[3 * i + 1] - self.positions[3 * j + 1];
        let dz = self.positions[3 * i + 2] - self.positions[3 * j + 2];
        let rest = (dx * dx + dy * dy + dz * dz).sqrt();
        self.constraints.push(PbdConstraint {
            particles: vec![i, j],
            kind: PbdConstraintType::Stretch {
                rest_length: rest,
                compliance,
            },
            lambda: 0.0,
        });
    }

    /// Add a volume conservation constraint for a tetrahedron.
    pub fn add_volume(&mut self, i: usize, j: usize, k: usize, l: usize, compliance: f64) {
        self.constraints.push(PbdConstraint {
            particles: vec![i, j, k, l],
            kind: PbdConstraintType::Volume {
                rest_volume: 1.0,
                compliance,
            },
            lambda: 0.0,
        });
    }

    /// Perform one substep of XPBD simulation.
    pub fn substep(&mut self, dt: f64) {
        let h = dt / self.substeps as f64;
        let np = self.positions.len() / 3;
        // Apply gravity and predict positions
        for i in 0..np {
            if self.inv_masses[i] > 0.0 {
                let vx = self.positions[3 * i] - self.prev_positions[3 * i];
                let vy = self.positions[3 * i + 1] - self.prev_positions[3 * i + 1];
                let vz = self.positions[3 * i + 2] - self.prev_positions[3 * i + 2];
                self.prev_positions[3 * i] = self.positions[3 * i];
                self.prev_positions[3 * i + 1] = self.positions[3 * i + 1];
                self.prev_positions[3 * i + 2] = self.positions[3 * i + 2];
                self.positions[3 * i] += vx + self.gravity[0] * h * h;
                self.positions[3 * i + 1] += vy + self.gravity[1] * h * h;
                self.positions[3 * i + 2] += vz + self.gravity[2] * h * h;
            }
        }
        // Reset lambdas
        for c in &mut self.constraints {
            c.lambda = 0.0;
        }
        // Solve stretch constraints (simplified)
        let n_constraints = self.constraints.len();
        for ci in 0..n_constraints {
            if let PbdConstraintType::Stretch {
                rest_length,
                compliance,
            } = self.constraints[ci].kind.clone()
            {
                let parts = self.constraints[ci].particles.clone();
                if parts.len() < 2 {
                    continue;
                }
                let (i, j) = (parts[0], parts[1]);
                let wi = self.inv_masses[i];
                let wj = self.inv_masses[j];
                let w_sum = wi + wj;
                if w_sum < 1e-15 {
                    continue;
                }
                let dx = self.positions[3 * i] - self.positions[3 * j];
                let dy = self.positions[3 * i + 1] - self.positions[3 * j + 1];
                let dz = self.positions[3 * i + 2] - self.positions[3 * j + 2];
                let len = (dx * dx + dy * dy + dz * dz).sqrt();
                if len < 1e-12 {
                    continue;
                }
                let alpha = compliance / (h * h);
                let c_val = len - rest_length;
                let d_lambda = (-c_val - alpha * self.constraints[ci].lambda) / (w_sum + alpha);
                self.constraints[ci].lambda += d_lambda;
                let nx = dx / len;
                let ny = dy / len;
                let nz = dz / len;
                self.positions[3 * i] += wi * d_lambda * nx;
                self.positions[3 * i + 1] += wi * d_lambda * ny;
                self.positions[3 * i + 2] += wi * d_lambda * nz;
                self.positions[3 * j] -= wj * d_lambda * nx;
                self.positions[3 * j + 1] -= wj * d_lambda * ny;
                self.positions[3 * j + 2] -= wj * d_lambda * nz;
            }
        }
    }

    /// Step the simulation for one full time step (using substeps).
    pub fn step(&mut self, dt: f64) {
        for _ in 0..self.substeps {
            self.substep(dt);
        }
    }

    /// Return particle count.
    pub fn particle_count(&self) -> usize {
        self.positions.len() / 3
    }
}

// ---------------------------------------------------------------------------
// PyControlSystem
// ---------------------------------------------------------------------------

/// A simple state-space system: dx/dt = A x + B u, y = C x + D u.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PyControlSystem {
    /// System order (n).
    pub order: usize,
    /// State matrix A (n×n, row-major flat).
    pub a_matrix: Vec<f64>,
    /// Input matrix B (n×m, row-major flat).
    pub b_matrix: Vec<f64>,
    /// Output matrix C (p×n, row-major flat).
    pub c_matrix: Vec<f64>,
    /// Feedthrough matrix D (p×m, row-major flat).
    pub d_matrix: Vec<f64>,
    /// Number of inputs (m).
    pub num_inputs: usize,
    /// Number of outputs (p).
    pub num_outputs: usize,
    /// Current state vector (n values).
    pub state: Vec<f64>,
}

impl PyControlSystem {
    /// Create a first-order lag system: dx/dt = -x/tau + u/tau.
    pub fn first_order_lag(tau: f64) -> Self {
        Self {
            order: 1,
            a_matrix: vec![-1.0 / tau],
            b_matrix: vec![1.0 / tau],
            c_matrix: vec![1.0],
            d_matrix: vec![0.0],
            num_inputs: 1,
            num_outputs: 1,
            state: vec![0.0],
        }
    }

    /// Step the system using Euler integration.
    pub fn step_euler(&mut self, u: &[f64], dt: f64) -> Vec<f64> {
        let n = self.order;
        let m = self.num_inputs;
        let p = self.num_outputs;
        // dx = A x + B u
        let mut dx = vec![0.0f64; n];
        for i in 0..n {
            for j in 0..n {
                dx[i] += self.a_matrix[i * n + j] * self.state[j];
            }
            for j in 0..m {
                dx[i] += self.b_matrix[i * m + j] * u.get(j).copied().unwrap_or(0.0);
            }
        }
        for i in 0..n {
            self.state[i] += dx[i] * dt;
        }
        // y = C x + D u
        let mut y = vec![0.0f64; p];
        for i in 0..p {
            for j in 0..n {
                y[i] += self.c_matrix[i * n + j] * self.state[j];
            }
            for j in 0..m {
                y[i] += self.d_matrix[i * m + j] * u.get(j).copied().unwrap_or(0.0);
            }
        }
        y
    }

    /// Compute step response over `n_steps` time steps.
    pub fn step_response(&mut self, dt: f64, n_steps: usize) -> Vec<f64> {
        self.state = vec![0.0; self.order];
        let mut out = Vec::with_capacity(n_steps);
        for _ in 0..n_steps {
            let y = self.step_euler(&[1.0], dt);
            out.push(y[0]);
        }
        out
    }

    /// Evaluate the frequency response (gain) at frequency f (Hz).
    pub fn frequency_gain(&self, f: f64) -> f64 {
        // For first-order system: |G(jw)| = 1/sqrt(1 + (w*tau)^2)
        // Generic approximation: just use the DC gain for now
        let w = 2.0 * std::f64::consts::PI * f;
        // For simple first-order lag: tau = -1/a[0]
        if self.order == 1 && self.a_matrix[0] < 0.0 {
            let tau = -1.0 / self.a_matrix[0];
            let b = self.b_matrix[0] * tau;
            b / (1.0 + (w * tau) * (w * tau)).sqrt()
        } else {
            1.0
        }
    }
}

// ---------------------------------------------------------------------------
// PyFrictionModel
// ---------------------------------------------------------------------------

/// Friction model type.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FrictionModelKind {
    /// Standard Coulomb friction.
    Coulomb,
    /// Anisotropic friction with different coefficients along u and v directions.
    Anisotropic { mu_u: f64, mu_v: f64 },
    /// Velocity-dependent friction (Stribeck curve).
    VelocityDependent {
        mu_static: f64,
        mu_kinetic: f64,
        stribeck_velocity: f64,
    },
    /// Friction cone (3D).
    Cone { mu: f64 },
}

/// Friction model for contact resolution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PyFrictionModel {
    /// Friction model type.
    pub kind: FrictionModelKind,
    /// Global friction coefficient override (used by Coulomb and Cone).
    pub mu: f64,
    /// Regularization parameter to avoid singular Jacobians at zero slip.
    pub epsilon: f64,
}

impl PyFrictionModel {
    /// Standard Coulomb friction.
    pub fn coulomb(mu: f64) -> Self {
        Self {
            kind: FrictionModelKind::Coulomb,
            mu,
            epsilon: 1e-4,
        }
    }

    /// Anisotropic friction.
    pub fn anisotropic(mu_u: f64, mu_v: f64) -> Self {
        Self {
            kind: FrictionModelKind::Anisotropic { mu_u, mu_v },
            mu: mu_u.max(mu_v),
            epsilon: 1e-4,
        }
    }

    /// Velocity-dependent (Stribeck) friction.
    pub fn stribeck(mu_static: f64, mu_kinetic: f64, stribeck_velocity: f64) -> Self {
        Self {
            kind: FrictionModelKind::VelocityDependent {
                mu_static,
                mu_kinetic,
                stribeck_velocity,
            },
            mu: mu_static,
            epsilon: 1e-4,
        }
    }

    /// Compute the friction force limit given normal force and slip velocity.
    pub fn friction_limit(&self, normal_force: f64, slip_speed: f64) -> f64 {
        let mu = match &self.kind {
            FrictionModelKind::Coulomb => self.mu,
            FrictionModelKind::Cone { mu } => *mu,
            FrictionModelKind::Anisotropic { mu_u, mu_v } => mu_u.max(*mu_v),
            FrictionModelKind::VelocityDependent {
                mu_static,
                mu_kinetic,
                stribeck_velocity,
            } => {
                let alpha = (-slip_speed / stribeck_velocity).exp();
                mu_kinetic + (mu_static - mu_kinetic) * alpha
            }
        };
        mu * normal_force.max(0.0)
    }
}

// ---------------------------------------------------------------------------
// PyWarmStart
// ---------------------------------------------------------------------------

/// Cached impulse from the previous frame for warm starting.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CachedImpulse {
    /// Body pair key (body_a, body_b).
    pub key: (u32, u32),
    /// Cached normal impulse.
    pub lambda_n: f64,
    /// Cached tangential impulse \[t1, t2\].
    pub lambda_t: [f64; 2],
    /// Frame counter (for aging).
    pub age: u32,
}

/// Warm start cache for constraint impulses.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PyWarmStart {
    /// Cached impulses from the previous solve.
    pub cache: Vec<CachedImpulse>,
    /// Fraction of cached impulse to apply at the start of the next frame.
    pub aging_factor: f64,
    /// Minimum quality threshold to keep a cached impulse.
    pub quality_threshold: f64,
    /// Maximum number of frames to keep a cached impulse.
    pub max_age: u32,
}

impl PyWarmStart {
    /// Create a new warm-start cache.
    pub fn new() -> Self {
        Self {
            cache: Vec::new(),
            aging_factor: 0.85,
            quality_threshold: 0.5,
            max_age: 3,
        }
    }

    /// Store an impulse for the next frame.
    pub fn store(&mut self, key: (u32, u32), lambda_n: f64, lambda_t: [f64; 2]) {
        if let Some(c) = self.cache.iter_mut().find(|c| c.key == key) {
            c.lambda_n = lambda_n;
            c.lambda_t = lambda_t;
            c.age = 0;
        } else {
            self.cache.push(CachedImpulse {
                key,
                lambda_n,
                lambda_t,
                age: 0,
            });
        }
    }

    /// Retrieve the cached impulse for a body pair, scaled by aging factor.
    pub fn retrieve(&self, key: (u32, u32)) -> Option<(f64, [f64; 2])> {
        self.cache.iter().find(|c| c.key == key).map(|c| {
            (
                c.lambda_n * self.aging_factor,
                [
                    c.lambda_t[0] * self.aging_factor,
                    c.lambda_t[1] * self.aging_factor,
                ],
            )
        })
    }

    /// Age all cached impulses and remove expired ones.
    pub fn age_and_prune(&mut self) {
        for c in &mut self.cache {
            c.age += 1;
        }
        self.cache.retain(|c| c.age <= self.max_age);
    }

    /// Clear all cached impulses.
    pub fn clear(&mut self) {
        self.cache.clear();
    }
}

impl Default for PyWarmStart {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_solve_pgs_basic() {
        let mut lam = vec![0.0f64];
        let rhs = [1.0];
        let diag = [2.0];
        let lo = [0.0];
        let hi = [10.0];
        let res = solve_pgs_iteration(&mut lam, &rhs, &diag, &lo, &hi);
        assert!(res >= 0.0);
        assert!(lam[0] > 0.0);
    }

    #[test]
    fn test_solve_pgs_clamped() {
        let mut lam = vec![0.0f64];
        let rhs = [100.0];
        let diag = [1.0];
        let lo = [0.0];
        let hi = [5.0];
        solve_pgs_iteration(&mut lam, &rhs, &diag, &lo, &hi);
        assert!(lam[0] <= 5.0);
    }

    #[test]
    fn test_compute_jacobian() {
        let j = compute_jacobian([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0]);
        assert_eq!(j.len(), 12);
        assert!((j[0] - 1.0).abs() < 1e-9);
        assert!((j[6] + 1.0).abs() < 1e-9);
    }

    #[test]
    fn test_compute_effective_mass() {
        let j = compute_jacobian([0.0; 3], [0.0; 3], [1.0, 0.0, 0.0]);
        let em = compute_effective_mass(1.0, 1.0, [1.0; 3], [1.0; 3], j);
        assert!(em > 0.0);
    }

    #[test]
    fn test_clamp_impulse_within_cone() {
        let out = clamp_impulse(10.0, [0.5, 0.5], 0.8);
        let mag = (out[0] * out[0] + out[1] * out[1]).sqrt();
        assert!(mag <= 10.0 * 0.8 + 1e-9);
    }

    #[test]
    fn test_clamp_impulse_outside_cone() {
        let out = clamp_impulse(1.0, [5.0, 5.0], 0.5);
        let mag = (out[0] * out[0] + out[1] * out[1]).sqrt();
        assert!((mag - 0.5).abs() < 1e-9);
    }

    #[test]
    fn test_constraint_solver_pgs() {
        let solver = PyConstraintSolver::default_pgs();
        assert_eq!(solver.solver_type, SolverType::Pgs);
        let lambda = solver.solve(&[1.0, 1.0], &[2.0, 2.0], &[0.0, 0.0], &[10.0, 10.0]);
        assert_eq!(lambda.len(), 2);
        assert!(lambda[0] >= 0.0);
    }

    #[test]
    fn test_joint_fixed() {
        let j = PyJoint::fixed(0, 1, 2, [0.0; 3], [0.0; 3]);
        assert!(!j.is_breakable());
        assert!(j.enabled);
    }

    #[test]
    fn test_joint_spring() {
        let j = PyJoint::spring(1, 0, 1, [0.0; 3], [1.0, 0.0, 0.0], 100.0, 5.0, 1.0);
        matches!(j.kind, JointKind::Spring { .. });
    }

    #[test]
    fn test_contact_constraint_clamp_friction() {
        let mut c = PyContactConstraint::new(0, 1, [0.0, 1.0, 0.0], 0.01, [0.0; 3], 0.0, 0.5);
        c.lambda_n = 10.0;
        c.lambda_t1 = 8.0;
        c.lambda_t2 = 0.0;
        c.clamp_friction();
        assert!(c.lambda_t1 <= 5.0 + 1e-9);
    }

    #[test]
    fn test_contact_constraint_tangent_basis() {
        let c = PyContactConstraint::new(0, 1, [0.0, 1.0, 0.0], 0.01, [0.0; 3], 0.0, 0.5);
        let (t1, t2) = c.tangent_basis();
        // t1 and t2 should be perpendicular to normal
        let dot1 = t1[0] * 0.0 + t1[1] * 1.0 + t1[2] * 0.0;
        assert!(dot1.abs() < 1e-9);
        let _ = t2;
    }

    #[test]
    fn test_pid_gains() {
        let mut pid = PidGains::new(1.0, 0.0, 0.0);
        let out = pid.compute(2.0, 0.01);
        assert!((out - 2.0).abs() < 1e-9);
    }

    #[test]
    fn test_pid_reset() {
        let mut pid = PidGains::new(1.0, 1.0, 0.0);
        pid.compute(1.0, 0.1);
        pid.reset();
        assert_eq!(pid.integral, 0.0);
    }

    #[test]
    fn test_motor_thermal() {
        let mut th = MotorThermal::new();
        assert!((th.torque_scale() - 1.0).abs() < 1e-9);
        th.temperature = 100.0;
        assert!(th.torque_scale() < 1.0);
        th.temperature = 120.0;
        assert!(th.torque_scale() <= 0.0);
    }

    #[test]
    fn test_motor_constraint_step() {
        let mut motor = PyMotorConstraint::velocity_mode(10.0, 100.0, 2.0);
        let torque = motor.step(0.0, 0.01);
        assert!(torque.abs() > 0.0);
    }

    #[test]
    fn test_island_sleep() {
        let mut island = PyIsland::new(0);
        island.add_body(1);
        assert!(island.is_active());
        for _ in 0..60 {
            island.update_sleep(0.01); // below threshold
        }
        assert_eq!(island.sleep_state, IslandSleepState::Sleeping);
        island.update_sleep(1.0); // wake up
        assert_eq!(island.sleep_state, IslandSleepState::Awake);
    }

    #[test]
    fn test_island_merge() {
        let mut a = PyIsland::new(0);
        a.add_body(1);
        let mut b = PyIsland::new(1);
        b.add_body(2);
        a.merge(&b);
        assert_eq!(a.bodies.len(), 2);
    }

    #[test]
    fn test_ccd_result_miss() {
        let r = PyCCDResult::miss(0, 1);
        assert!(!r.hit);
        assert!((r.toi - 1.0).abs() < 1e-9);
    }

    #[test]
    fn test_ccd_result_hit() {
        let r = PyCCDResult::hit(0, 1, 0.3, [0.0, 1.0, 0.0], [0.0; 3], [0.0, 0.01, 0.0]);
        assert!(r.hit);
        assert!((r.toi - 0.3).abs() < 1e-9);
    }

    #[test]
    fn test_pbd_solver_stretch() {
        let positions = vec![0.0, 0.0, 0.0, 2.0, 0.0, 0.0];
        let inv_masses = vec![1.0, 1.0];
        let mut solver = PyPbdSolver::new(positions, inv_masses);
        solver.add_stretch(0, 1, 1e-4);
        solver.step(0.016);
        // Particles should have moved due to gravity
        assert!(solver.positions[1] < 0.0); // y should be negative
    }

    #[test]
    fn test_pbd_particle_count() {
        let pos = vec![0.0; 9]; // 3 particles
        let inv = vec![1.0; 3];
        let s = PyPbdSolver::new(pos, inv);
        assert_eq!(s.particle_count(), 3);
    }

    #[test]
    fn test_control_system_step_response() {
        let mut sys = PyControlSystem::first_order_lag(0.1);
        let resp = sys.step_response(0.01, 50);
        assert_eq!(resp.len(), 50);
        // Should converge toward 1.0
        assert!(*resp.last().unwrap() > 0.5);
    }

    #[test]
    fn test_control_system_frequency() {
        let sys = PyControlSystem::first_order_lag(0.1);
        let dc = sys.frequency_gain(0.0);
        assert!(dc > 0.0);
        let hf = sys.frequency_gain(100.0);
        assert!(hf < dc);
    }

    #[test]
    fn test_friction_model_coulomb() {
        let fm = PyFrictionModel::coulomb(0.5);
        assert!((fm.friction_limit(10.0, 0.0) - 5.0).abs() < 1e-9);
    }

    #[test]
    fn test_friction_model_stribeck() {
        let fm = PyFrictionModel::stribeck(1.0, 0.5, 0.1);
        let f_static = fm.friction_limit(10.0, 0.0);
        let f_kinetic = fm.friction_limit(10.0, 1.0);
        assert!(f_static >= f_kinetic);
    }

    #[test]
    fn test_warm_start_store_retrieve() {
        let mut ws = PyWarmStart::new();
        ws.store((0, 1), 5.0, [1.0, 2.0]);
        let r = ws.retrieve((0, 1));
        assert!(r.is_some());
        let (ln, _lt) = r.unwrap();
        assert!((ln - 5.0 * 0.85).abs() < 1e-9);
    }

    #[test]
    fn test_warm_start_age_prune() {
        let mut ws = PyWarmStart::new();
        ws.store((0, 1), 5.0, [0.0, 0.0]);
        for _ in 0..=ws.max_age {
            ws.age_and_prune();
        }
        assert!(ws.retrieve((0, 1)).is_none());
    }

    #[test]
    fn test_warm_start_clear() {
        let mut ws = PyWarmStart::new();
        ws.store((0, 1), 1.0, [0.0, 0.0]);
        ws.clear();
        assert!(ws.cache.is_empty());
    }
}