oxiphysics-collision 0.1.1

Collision detection algorithms 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
//! Auto-generated module
//!
//! 🤖 Generated with [SplitRS](https://github.com/cool-japan/splitrs)

#![allow(clippy::needless_range_loop)]
use super::types::{Obb, SatResult};

/// Full 15-axis SAT overlap test between two OBBs (raw-array version).
///
/// Returns `true` if the OBBs overlap on all 15 potential separating axes.
#[allow(dead_code)]
pub fn obb_obb_sat_test(a: &Obb, b: &Obb) -> bool {
    obb_obb_test(a, b).is_some()
}
/// Return the minimum-penetration contact normal for two overlapping OBBs.
///
/// Returns `None` if the OBBs are separated.
#[allow(dead_code)]
pub fn obb_obb_contact_normal(a: &Obb, b: &Obb) -> Option<[f64; 3]> {
    obb_obb_test(a, b).map(|r| r.contact_normal)
}
/// Return the minimum penetration depth for two overlapping OBBs.
///
/// Returns `None` if the OBBs are separated.
#[allow(dead_code)]
pub fn obb_obb_penetration_depth(a: &Obb, b: &Obb) -> Option<f64> {
    obb_obb_test(a, b).map(|r| r.penetration_depth)
}
/// Convert an AABB (min/max corners) to an axis-aligned `Obb`.
#[allow(dead_code)]
pub fn aabb_to_obb(min: [f64; 3], max: [f64; 3]) -> Obb {
    let center = [
        (min[0] + max[0]) * 0.5,
        (min[1] + max[1]) * 0.5,
        (min[2] + max[2]) * 0.5,
    ];
    let half_extents = [
        (max[0] - min[0]) * 0.5,
        (max[1] - min[1]) * 0.5,
        (max[2] - min[2]) * 0.5,
    ];
    Obb::axis_aligned(center, half_extents)
}
/// Project an OBB onto an axis and return `(min, max)` projection values.
#[allow(dead_code)]
pub fn project_obb_onto_axis(obb: &Obb, axis: [f64; 3]) -> (f64, f64) {
    let center_proj = dot3_raw(obb.center, axis);
    let mut radius = 0.0_f64;
    for i in 0..3 {
        radius += obb.half_extents[i] * dot3_raw(obb.rotation[i], axis).abs();
    }
    (center_proj - radius, center_proj + radius)
}
/// Full 15-axis SAT test between two OBBs.
///
/// Tests 3 face normals from A, 3 from B, and 9 edge cross products.
/// Returns `Some(SatResult)` on overlap, `None` if separated.
#[allow(dead_code)]
pub fn obb_obb_test(a: &Obb, b: &Obb) -> Option<SatResult> {
    let diff = sub3_raw(b.center, a.center);
    let mut min_depth = f64::INFINITY;
    let mut best_axis = [0.0, 1.0, 0.0];
    let mut axes: Vec<[f64; 3]> = Vec::with_capacity(15);
    for i in 0..3 {
        axes.push(a.rotation[i]);
    }
    for i in 0..3 {
        axes.push(b.rotation[i]);
    }
    for i in 0..3 {
        for j in 0..3 {
            let c = cross3_raw(a.rotation[i], b.rotation[j]);
            axes.push(c);
        }
    }
    for axis in &axes {
        let len_sq = dot3_raw(*axis, *axis);
        if len_sq < 1e-12 {
            continue;
        }
        let inv_len = 1.0 / len_sq.sqrt();
        let norm_axis = scale3_raw(*axis, inv_len);
        let (min_a, max_a) = project_obb_onto_axis(a, norm_axis);
        let (min_b, max_b) = project_obb_onto_axis(b, norm_axis);
        let overlap = (max_a.min(max_b)) - (min_a.max(min_b));
        if overlap < 0.0 {
            return None;
        }
        if overlap < min_depth {
            min_depth = overlap;
            best_axis = if dot3_raw(diff, norm_axis) >= 0.0 {
                norm_axis
            } else {
                negate3_raw(norm_axis)
            };
        }
    }
    let support_a = obb_support(a, best_axis);
    let support_b = obb_support(b, negate3_raw(best_axis));
    let contact_point = scale3_raw(add3_raw(support_a, support_b), 0.5);
    Some(SatResult {
        penetration_depth: min_depth,
        contact_normal: best_axis,
        contact_point,
    })
}
/// Compute contact points between two overlapping OBBs using the SAT result.
///
/// Returns a set of contact points generated by reference/incident face clipping.
#[allow(dead_code)]
pub fn compute_contact_points(a: &Obb, b: &Obb, sat_result: &SatResult) -> Vec<[f64; 3]> {
    let normal = sat_result.contact_normal;
    let mut best_face_idx = 0usize;
    let mut best_dot = 0.0_f64;
    let mut ref_is_a = true;
    for i in 0..3 {
        let d = dot3_raw(a.rotation[i], normal).abs();
        if d > best_dot {
            best_dot = d;
            best_face_idx = i;
            ref_is_a = true;
        }
        let d2 = dot3_raw(b.rotation[i], normal).abs();
        if d2 > best_dot {
            best_dot = d2;
            best_face_idx = i;
            ref_is_a = false;
        }
    }
    let cp1 = obb_support(a, normal);
    let cp2 = obb_support(b, negate3_raw(normal));
    let mut contacts = vec![scale3_raw(add3_raw(cp1, cp2), 0.5)];
    let ref_obb = if ref_is_a { a } else { b };
    let ref_axis = ref_obb.rotation[best_face_idx];
    let sign = if dot3_raw(ref_axis, normal) > 0.0 {
        1.0
    } else {
        -1.0
    };
    let face_center = add3_raw(
        ref_obb.center,
        scale3_raw(ref_axis, sign * ref_obb.half_extents[best_face_idx]),
    );
    let inc_obb = if ref_is_a { b } else { a };
    let to_inc = sub3_raw(inc_obb.center, face_center);
    let dist_to_plane = dot3_raw(to_inc, ref_axis) * sign;
    if dist_to_plane.abs() < sat_result.penetration_depth + 0.01 {
        let projected = sub3_raw(inc_obb.center, scale3_raw(ref_axis, dist_to_plane * sign));
        contacts.push(projected);
    }
    contacts
}
/// Test an OBB against a sphere.
#[allow(dead_code)]
pub fn obb_sphere_test(obb: &Obb, sphere_center: [f64; 3], radius: f64) -> Option<SatResult> {
    let diff = sub3_raw(sphere_center, obb.center);
    let mut local = [0.0; 3];
    for i in 0..3 {
        local[i] = dot3_raw(diff, obb.rotation[i]);
    }
    let mut clamped = [0.0; 3];
    for i in 0..3 {
        clamped[i] = local[i].clamp(-obb.half_extents[i], obb.half_extents[i]);
    }
    let delta = sub3_raw(local, clamped);
    let dist_sq = dot3_raw(delta, delta);
    if dist_sq > radius * radius {
        return None;
    }
    let dist = dist_sq.sqrt();
    let penetration = radius - dist;
    let mut closest_world = obb.center;
    for i in 0..3 {
        closest_world = add3_raw(closest_world, scale3_raw(obb.rotation[i], clamped[i]));
    }
    let normal = if dist > 1e-10 {
        let n = sub3_raw(sphere_center, closest_world);
        let n_len = len3_raw(n);
        if n_len > 1e-10 {
            scale3_raw(n, 1.0 / n_len)
        } else {
            [0.0, 1.0, 0.0]
        }
    } else {
        let mut best_i = 0;
        let mut best_sep = f64::INFINITY;
        for i in 0..3 {
            let s = obb.half_extents[i] - local[i].abs();
            if s < best_sep {
                best_sep = s;
                best_i = i;
            }
        }
        let sign = if local[best_i] >= 0.0 { 1.0 } else { -1.0 };
        scale3_raw(obb.rotation[best_i], sign)
    };
    let contact_point = add3_raw(closest_world, scale3_raw(normal, penetration * 0.5));
    Some(SatResult {
        penetration_depth: penetration,
        contact_normal: normal,
        contact_point,
    })
}
/// Test an OBB against a capsule defined by two endpoints and a radius.
#[allow(dead_code)]
pub fn obb_capsule_test(obb: &Obb, p0: [f64; 3], p1: [f64; 3], radius: f64) -> Option<SatResult> {
    let seg = sub3_raw(p1, p0);
    let to_center = sub3_raw(obb.center, p0);
    let seg_len_sq = dot3_raw(seg, seg);
    let t = if seg_len_sq > 1e-10 {
        (dot3_raw(to_center, seg) / seg_len_sq).clamp(0.0, 1.0)
    } else {
        0.0
    };
    let closest_on_seg = add3_raw(p0, scale3_raw(seg, t));
    obb_sphere_test(obb, closest_on_seg, radius)
}
/// Support point of an OBB in a given direction.
#[allow(dead_code)]
pub(super) fn obb_support(obb: &Obb, direction: [f64; 3]) -> [f64; 3] {
    let mut p = obb.center;
    for i in 0..3 {
        let sign = if dot3_raw(obb.rotation[i], direction) >= 0.0 {
            1.0
        } else {
            -1.0
        };
        p = add3_raw(p, scale3_raw(obb.rotation[i], sign * obb.half_extents[i]));
    }
    p
}
#[allow(dead_code)]
pub(super) fn dot3_raw(a: [f64; 3], b: [f64; 3]) -> f64 {
    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
#[allow(dead_code)]
pub(super) fn sub3_raw(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}
#[allow(dead_code)]
pub(super) fn add3_raw(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
    [a[0] + b[0], a[1] + b[1], a[2] + b[2]]
}
#[allow(dead_code)]
pub(super) fn scale3_raw(a: [f64; 3], s: f64) -> [f64; 3] {
    [a[0] * s, a[1] * s, a[2] * s]
}
#[allow(dead_code)]
pub(super) fn negate3_raw(a: [f64; 3]) -> [f64; 3] {
    [-a[0], -a[1], -a[2]]
}
#[allow(dead_code)]
pub(super) fn cross3_raw(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],
    ]
}
#[allow(dead_code)]
pub(super) fn len3_raw(a: [f64; 3]) -> f64 {
    (a[0] * a[0] + a[1] * a[1] + a[2] * a[2]).sqrt()
}
/// Test whether an OBB is at least partially inside a view frustum defined
/// by 6 planes (each as `[a, b, c, d]` where `ax + by + cz + d >= 0` is inside).
///
/// Returns `true` if the OBB *might* be visible (passes all frustum planes),
/// `false` if it is definitely outside at least one plane.
#[allow(dead_code)]
pub fn obb_frustum_cull(obb: &Obb, planes: &[[f64; 4]; 6]) -> bool {
    for plane in planes {
        let n = [plane[0], plane[1], plane[2]];
        let d = plane[3];
        let r = obb.half_extents[0] * dot3_raw(obb.rotation[0], n).abs()
            + obb.half_extents[1] * dot3_raw(obb.rotation[1], n).abs()
            + obb.half_extents[2] * dot3_raw(obb.rotation[2], n).abs();
        let dist = dot3_raw(obb.center, n) + d;
        if dist + r < 0.0 {
            return false;
        }
    }
    true
}
/// Test an OBB against a triangle (v0, v1, v2) using SAT.
///
/// Tests the 13 potential separating axes:
/// 1. Triangle normal
/// 2. 3 OBB face normals
/// 3. 9 edge cross-products (3 OBB edges × 3 triangle edges)
///
/// Returns `true` if they overlap (no separating axis found).
#[allow(dead_code)]
pub fn obb_triangle_test(obb: &Obb, v0: [f64; 3], v1: [f64; 3], v2: [f64; 3]) -> bool {
    let t0 = sub3_raw(v0, obb.center);
    let t1 = sub3_raw(v1, obb.center);
    let t2 = sub3_raw(v2, obb.center);
    let p0 = [
        dot3_raw(t0, obb.rotation[0]),
        dot3_raw(t0, obb.rotation[1]),
        dot3_raw(t0, obb.rotation[2]),
    ];
    let p1 = [
        dot3_raw(t1, obb.rotation[0]),
        dot3_raw(t1, obb.rotation[1]),
        dot3_raw(t1, obb.rotation[2]),
    ];
    let p2 = [
        dot3_raw(t2, obb.rotation[0]),
        dot3_raw(t2, obb.rotation[1]),
        dot3_raw(t2, obb.rotation[2]),
    ];
    let he = obb.half_extents;
    let test_axis = |axis: [f64; 3]| -> bool {
        let len_sq = dot3_raw(axis, axis);
        if len_sq < 1e-14 {
            return true;
        }
        let p_a = dot3_raw(p0, axis);
        let p_b = dot3_raw(p1, axis);
        let p_c = dot3_raw(p2, axis);
        let tri_min = p_a.min(p_b).min(p_c);
        let tri_max = p_a.max(p_b).max(p_c);
        let obb_r = he[0] * axis[0].abs() + he[1] * axis[1].abs() + he[2] * axis[2].abs();
        tri_max >= -obb_r && tri_min <= obb_r
    };
    for i in 0..3 {
        let mut axis = [0.0; 3];
        axis[i] = 1.0;
        if !test_axis(axis) {
            return false;
        }
    }
    let e0 = sub3_raw(p1, p0);
    let e1 = sub3_raw(p2, p1);
    let e2 = sub3_raw(p0, p2);
    for &edge in &[e0, e1, e2] {
        for i in 0..3 {
            let mut obb_edge = [0.0; 3];
            obb_edge[i] = 1.0;
            let axis = cross3_raw(obb_edge, edge);
            if !test_axis(axis) {
                return false;
            }
        }
    }
    let tri_normal = cross3_raw(e0, e1);
    if !test_axis(tri_normal) {
        return false;
    }
    true
}
/// Compute the support point of `obb` along `direction` (public API).
#[allow(dead_code)]
pub fn obb_support_point(obb: &Obb, direction: [f64; 3]) -> [f64; 3] {
    obb_support(obb, direction)
}
/// Returns all 8 vertices of the OBB in world space.
#[allow(dead_code)]
pub fn obb_vertices(obb: &Obb) -> [[f64; 3]; 8] {
    let hx = obb.half_extents[0];
    let hy = obb.half_extents[1];
    let hz = obb.half_extents[2];
    let signs: [[f64; 3]; 8] = [
        [-1.0, -1.0, -1.0],
        [1.0, -1.0, -1.0],
        [-1.0, 1.0, -1.0],
        [1.0, 1.0, -1.0],
        [-1.0, -1.0, 1.0],
        [1.0, -1.0, 1.0],
        [-1.0, 1.0, 1.0],
        [1.0, 1.0, 1.0],
    ];
    let extents = [hx, hy, hz];
    let mut verts = [[0.0; 3]; 8];
    for (k, s) in signs.iter().enumerate() {
        let mut v = obb.center;
        for i in 0..3 {
            v = add3_raw(v, scale3_raw(obb.rotation[i], s[i] * extents[i]));
        }
        verts[k] = v;
    }
    verts
}
/// Returns the 12 edges of the OBB as pairs of vertex world-space positions.
#[allow(dead_code)]
pub fn obb_edges(obb: &Obb) -> [([f64; 3], [f64; 3]); 12] {
    let verts = obb_vertices(obb);
    let edge_indices: [(usize, usize); 12] = [
        (0, 1),
        (2, 3),
        (4, 5),
        (6, 7),
        (0, 2),
        (1, 3),
        (4, 6),
        (5, 7),
        (0, 4),
        (1, 5),
        (2, 6),
        (3, 7),
    ];
    let mut edges = [([0.0; 3], [0.0; 3]); 12];
    for (k, &(i, j)) in edge_indices.iter().enumerate() {
        edges[k] = (verts[i], verts[j]);
    }
    edges
}
/// Returns the 6 face centers of the OBB in world space.
#[allow(dead_code)]
pub fn obb_face_centers(obb: &Obb) -> [[f64; 3]; 6] {
    let mut centers = [[0.0; 3]; 6];
    for i in 0..3 {
        let axis = obb.rotation[i];
        let he = obb.half_extents[i];
        centers[2 * i] = add3_raw(obb.center, scale3_raw(axis, he));
        centers[2 * i + 1] = add3_raw(obb.center, scale3_raw(axis, -he));
    }
    centers
}
/// Compute the mean of a set of points.
#[allow(dead_code)]
pub(super) fn points_mean(pts: &[[f64; 3]]) -> [f64; 3] {
    if pts.is_empty() {
        return [0.0; 3];
    }
    let n = pts.len() as f64;
    let mut s = [0.0; 3];
    for p in pts {
        s[0] += p[0];
        s[1] += p[1];
        s[2] += p[2];
    }
    [s[0] / n, s[1] / n, s[2] / n]
}
/// Compute the 3×3 covariance matrix of a set of zero-mean points.
/// Returns the matrix in row-major order: \[\[c00,c01,c02\\],\[c10,c11,c12\],\[c20,c21,c22\]].
#[allow(dead_code)]
pub(super) fn covariance_matrix(pts: &[[f64; 3]], mean: [f64; 3]) -> [[f64; 3]; 3] {
    let mut cov = [[0.0_f64; 3]; 3];
    let n = pts.len() as f64;
    if n < 2.0 {
        return cov;
    }
    for p in pts {
        let d = [p[0] - mean[0], p[1] - mean[1], p[2] - mean[2]];
        for i in 0..3 {
            for j in 0..3 {
                cov[i][j] += d[i] * d[j];
            }
        }
    }
    let inv = 1.0 / (n - 1.0);
    for row in &mut cov {
        for v in row.iter_mut() {
            *v *= inv;
        }
    }
    cov
}
/// Jacobi iteration step to diagonalize a 3×3 symmetric matrix.
/// Modifies `a` in-place and accumulates eigenvectors in `v`.
/// Returns the total off-diagonal sum of squares (convergence metric).
#[allow(dead_code)]
pub(super) fn jacobi_sweep(a: &mut [[f64; 3]; 3], v: &mut [[f64; 3]; 3]) -> f64 {
    let mut off = 0.0_f64;
    for p in 0..3 {
        for q in (p + 1)..3 {
            if a[p][q].abs() < 1e-15 {
                continue;
            }
            let theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q]);
            let t = if theta >= 0.0 {
                1.0 / (theta + (1.0 + theta * theta).sqrt())
            } else {
                1.0 / (theta - (1.0 + theta * theta).sqrt())
            };
            let c = 1.0 / (1.0 + t * t).sqrt();
            let s = t * c;
            let app = a[p][p] - t * a[p][q];
            let aqq = a[q][q] + t * a[p][q];
            a[p][p] = app;
            a[q][q] = aqq;
            a[p][q] = 0.0;
            a[q][p] = 0.0;
            for r in 0..3 {
                if r == p || r == q {
                    continue;
                }
                let arp = c * a[r][p] - s * a[r][q];
                let arq = s * a[r][p] + c * a[r][q];
                a[r][p] = arp;
                a[p][r] = arp;
                a[r][q] = arq;
                a[q][r] = arq;
            }
            for r in 0..3 {
                let vrp = c * v[r][p] - s * v[r][q];
                let vrq = s * v[r][p] + c * v[r][q];
                v[r][p] = vrp;
                v[r][q] = vrq;
            }
        }
    }
    for p in 0..3 {
        for q in (p + 1)..3 {
            off += a[p][q] * a[p][q];
        }
    }
    off
}
/// Compute eigenvalues and eigenvectors of a 3×3 symmetric matrix using Jacobi iteration.
/// Returns (eigenvalues, eigenvectors) where eigenvectors\[i\] is the i-th eigenvector (column).
#[allow(dead_code)]
pub(super) fn eigen_symmetric3(mat: [[f64; 3]; 3]) -> ([f64; 3], [[f64; 3]; 3]) {
    let mut a = mat;
    let mut v = [[0.0_f64; 3]; 3];
    v[0][0] = 1.0;
    v[1][1] = 1.0;
    v[2][2] = 1.0;
    for _ in 0..50 {
        let off = jacobi_sweep(&mut a, &mut v);
        if off < 1e-20 {
            break;
        }
    }
    let eigenvalues = [a[0][0], a[1][1], a[2][2]];
    let eigenvectors = [
        [v[0][0], v[1][0], v[2][0]],
        [v[0][1], v[1][1], v[2][1]],
        [v[0][2], v[1][2], v[2][2]],
    ];
    (eigenvalues, eigenvectors)
}
/// Normalize a raw 3-vector. Returns the unit vector, or \[1,0,0\] if near-zero.
#[allow(dead_code)]
pub(super) fn normalize3_raw(a: [f64; 3]) -> [f64; 3] {
    let len = len3_raw(a);
    if len > 1e-10 {
        [a[0] / len, a[1] / len, a[2] / len]
    } else {
        [1.0, 0.0, 0.0]
    }
}
/// Fit an OBB to a point cloud using PCA.
///
/// The OBB axes are the principal components of the point set.
/// Half-extents are computed from projections along each axis.
///
/// Returns `None` if fewer than 2 points are provided.
#[allow(dead_code)]
pub fn obb_from_points(pts: &[[f64; 3]]) -> Option<Obb> {
    if pts.len() < 2 {
        return None;
    }
    let mean = points_mean(pts);
    let cov = covariance_matrix(pts, mean);
    let (_eigenvalues, eigenvectors) = eigen_symmetric3(cov);
    let axis0 = normalize3_raw(eigenvectors[0]);
    let axis1 = normalize3_raw(eigenvectors[1]);
    let axis2 = normalize3_raw(cross3_raw(axis0, axis1));
    let axes = [axis0, axis1, axis2];
    let mut mins = [f64::INFINITY; 3];
    let mut maxs = [f64::NEG_INFINITY; 3];
    for p in pts {
        let d = sub3_raw(*p, mean);
        for i in 0..3 {
            let proj = dot3_raw(d, axes[i]);
            if proj < mins[i] {
                mins[i] = proj;
            }
            if proj > maxs[i] {
                maxs[i] = proj;
            }
        }
    }
    let half_extents = [
        (maxs[0] - mins[0]) * 0.5,
        (maxs[1] - mins[1]) * 0.5,
        (maxs[2] - mins[2]) * 0.5,
    ];
    let mut center = mean;
    for i in 0..3 {
        let offset = (maxs[i] + mins[i]) * 0.5;
        center = add3_raw(center, scale3_raw(axes[i], offset));
    }
    Some(Obb::from_center_axes(center, axes, half_extents))
}
/// Apply a rigid-body transform (rotation matrix + translation) to an OBB.
///
/// `rotation` is a 3×3 rotation matrix (rows are world-space X, Y, Z).
/// `translation` is the world-space translation to apply.
///
/// Returns a new OBB in the transformed frame.
#[allow(dead_code)]
pub fn obb_transform(obb: &Obb, rotation: [[f64; 3]; 3], translation: [f64; 3]) -> Obb {
    let mut new_center = translation;
    for i in 0..3 {
        new_center[i] += dot3_raw(rotation[i], obb.center);
    }
    let mut new_rotation = [[0.0_f64; 3]; 3];
    for k in 0..3 {
        for i in 0..3 {
            new_rotation[k][i] = dot3_raw(rotation[i], obb.rotation[k]);
        }
    }
    Obb {
        center: new_center,
        half_extents: obb.half_extents,
        rotation: new_rotation,
    }
}
/// Compute the closest point on (or inside) `obb` to the world-space `query` point.
///
/// Returns the closest point in world space.
#[allow(dead_code)]
pub fn obb_closest_point(obb: &Obb, query: [f64; 3]) -> [f64; 3] {
    let diff = sub3_raw(query, obb.center);
    let mut result = obb.center;
    for i in 0..3 {
        let dist = dot3_raw(diff, obb.rotation[i]);
        let clamped = dist.clamp(-obb.half_extents[i], obb.half_extents[i]);
        result = add3_raw(result, scale3_raw(obb.rotation[i], clamped));
    }
    result
}
/// Compute the squared distance from `query` to the surface of `obb`.
///
/// Returns 0 if the point is inside the OBB.
#[allow(dead_code)]
pub fn obb_point_sq_dist(obb: &Obb, query: [f64; 3]) -> f64 {
    let closest = obb_closest_point(obb, query);
    let d = sub3_raw(query, closest);
    dot3_raw(d, d)
}
/// Test whether a line segment from `p0` to `p1` intersects the `obb`.
///
/// Returns `true` if the segment intersects or touches the OBB.
#[allow(dead_code)]
pub fn obb_segment_test(obb: &Obb, p0: [f64; 3], p1: [f64; 3]) -> bool {
    let mid = scale3_raw(add3_raw(p0, p1), 0.5);
    let half_seg = scale3_raw(sub3_raw(p1, p0), 0.5);
    let d = sub3_raw(mid, obb.center);
    for i in 0..3 {
        let e = obb.half_extents[i];
        let t = dot3_raw(d, obb.rotation[i]);
        let r = dot3_raw(half_seg, obb.rotation[i]).abs();
        if t.abs() > e + r {
            return false;
        }
    }
    for i in 0..3 {
        let cross_axis = cross3_raw(half_seg, obb.rotation[i]);
        let len_sq = dot3_raw(cross_axis, cross_axis);
        if len_sq < 1e-14 {
            continue;
        }
        let t = dot3_raw(d, cross_axis);
        let r_a = obb.half_extents[(i + 1) % 3]
            * dot3_raw(obb.rotation[(i + 1) % 3], cross_axis).abs()
            + obb.half_extents[(i + 2) % 3] * dot3_raw(obb.rotation[(i + 2) % 3], cross_axis).abs();
        let r_b = dot3_raw(half_seg, cross_axis).abs();
        if t.abs() > r_a + r_b {
            return false;
        }
    }
    true
}
/// Cast a ray from `origin` in `direction` against an OBB.
///
/// Returns the parametric hit distance `t` (such that `origin + t * direction` is on the OBB surface)
/// or `None` if the ray misses.  Only returns `t >= 0` (forward ray).
#[allow(dead_code)]
pub fn obb_ray_cast(obb: &Obb, origin: [f64; 3], direction: [f64; 3]) -> Option<f64> {
    let d = sub3_raw(origin, obb.center);
    let mut t_min = f64::NEG_INFINITY;
    let mut t_max = f64::INFINITY;
    for i in 0..3 {
        let e = obb.half_extents[i];
        let proj_d = dot3_raw(d, obb.rotation[i]);
        let proj_dir = dot3_raw(direction, obb.rotation[i]);
        if proj_dir.abs() < 1e-12 {
            if proj_d.abs() > e {
                return None;
            }
        } else {
            let inv = 1.0 / proj_dir;
            let t1 = (-e - proj_d) * inv;
            let t2 = (e - proj_d) * inv;
            let (t1, t2) = if t1 < t2 { (t1, t2) } else { (t2, t1) };
            t_min = t_min.max(t1);
            t_max = t_max.min(t2);
            if t_min > t_max {
                return None;
            }
        }
    }
    if t_max < 0.0 {
        return None;
    }
    let t = if t_min >= 0.0 { t_min } else { t_max };
    Some(t)
}
/// Test a single separating axis between two OBBs (raw-array version).
///
/// Returns the overlap on this axis, or `None` if separated.
#[allow(dead_code)]
pub fn sat_test_axis(a: &Obb, b: &Obb, axis: [f64; 3]) -> Option<f64> {
    let len_sq = dot3_raw(axis, axis);
    if len_sq < 1e-14 {
        return Some(0.0);
    }
    let inv = 1.0 / len_sq.sqrt();
    let n = scale3_raw(axis, inv);
    let (min_a, max_a) = project_obb_onto_axis(a, n);
    let (min_b, max_b) = project_obb_onto_axis(b, n);
    let overlap = max_a.min(max_b) - min_a.max(min_b);
    if overlap < 0.0 { None } else { Some(overlap) }
}
/// Run the full 15-axis SAT, returning the axis with minimum overlap.
///
/// Returns `(normal, depth)` where `normal` points from A toward B,
/// or `None` if the OBBs are separated.
#[allow(dead_code)]
pub fn sat_obb_obb(a: &Obb, b: &Obb) -> Option<([f64; 3], f64)> {
    let result = obb_obb_test(a, b)?;
    Some((result.contact_normal, result.penetration_depth))
}
/// Compute the contact point between two OBBs given the minimum-penetration axis.
///
/// Returns the midpoint between the two support points along the axis.
#[allow(dead_code)]
pub fn obb_contact_point(a: &Obb, b: &Obb, normal: [f64; 3]) -> [f64; 3] {
    let sa = obb_support(a, normal);
    let sb = obb_support(b, negate3_raw(normal));
    scale3_raw(add3_raw(sa, sb), 0.5)
}
/// Merge two axis-aligned OBBs (identity rotation) into the smallest enclosing AABB OBB.
///
/// If the OBBs are not axis-aligned the result is still axis-aligned (conservative).
#[allow(dead_code)]
pub fn obb_merge_aabb(a: &Obb, b: &Obb) -> Obb {
    let va = obb_vertices(a);
    let vb = obb_vertices(b);
    let mut min_pt = [f64::INFINITY; 3];
    let mut max_pt = [f64::NEG_INFINITY; 3];
    for v in va.iter().chain(vb.iter()) {
        for i in 0..3 {
            if v[i] < min_pt[i] {
                min_pt[i] = v[i];
            }
            if v[i] > max_pt[i] {
                max_pt[i] = v[i];
            }
        }
    }
    aabb_to_obb(min_pt, max_pt)
}
/// Compute the volume of an OBB (8 * hx * hy * hz).
#[allow(dead_code)]
pub fn obb_volume(obb: &Obb) -> f64 {
    8.0 * obb.half_extents[0] * obb.half_extents[1] * obb.half_extents[2]
}
/// Compute the surface area of an OBB (sum of all 6 face areas).
#[allow(dead_code)]
pub fn obb_surface_area(obb: &Obb) -> f64 {
    let [hx, hy, hz] = obb.half_extents;
    8.0 * (hx * hy + hy * hz + hz * hx)
}
/// Test whether a world-space point is inside `obb`.
#[allow(dead_code)]
pub fn obb_contains_point(obb: &Obb, point: [f64; 3]) -> bool {
    let d = sub3_raw(point, obb.center);
    for i in 0..3 {
        if dot3_raw(d, obb.rotation[i]).abs() > obb.half_extents[i] {
            return false;
        }
    }
    true
}
/// Test whether `inner` is fully contained within `outer`.
#[allow(dead_code)]
pub fn obb_contains_obb(outer: &Obb, inner: &Obb) -> bool {
    for v in &obb_vertices(inner) {
        if !obb_contains_point(outer, *v) {
            return false;
        }
    }
    true
}