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
//! The Gilbert-Johnson-Keerthi distance algorithm.
//!
//! # What is GJK?
//!
//! The **Gilbert-Johnson-Keerthi (GJK)** algorithm is a fundamental geometric algorithm used
//! to compute the distance between two convex shapes. It's one of the most important algorithms
//! in collision detection and is used extensively in physics engines, robotics, and computer graphics.
//!
//! ## How GJK Works (Simplified)
//!
//! GJK works by operating on the **Minkowski difference** (also called Configuration Space Obstacle or CSO)
//! of two shapes. Instead of directly comparing the shapes, GJK:
//!
//! 1. Constructs a simplex (triangle in 2D, tetrahedron in 3D) within the Minkowski difference
//! 2. Iteratively refines this simplex to find the point closest to the origin
//! 3. The distance from the origin to this closest point equals the distance between the shapes
//!
//! If the origin is **inside** the Minkowski difference, the shapes are intersecting.
//! If the origin is **outside**, the distance to the closest point gives the separation distance.
//!
//! ## When is GJK Used?
//!
//! GJK is used whenever you need to:
//! - **Check if two convex shapes intersect** (collision detection)
//! - **Find the minimum distance** between two convex shapes
//! - **Compute closest points** on two shapes
//! - **Cast a shape along a direction** to find the time of impact (continuous collision detection)
//!
//! ## Key Advantages of GJK
//!
//! - Works with **any convex shape** that can provide a support function
//! - Does **not require the full geometry** of the shapes (only support points)
//! - Very **fast convergence** in most practical cases
//! - Forms the basis for many collision detection systems
//!
//! ## Limitations
//!
//! - Only works with **convex shapes** (use convex decomposition for concave shapes)
//! - When shapes are penetrating, GJK can only detect intersection but not penetration depth
//! (use EPA - Expanding Polytope Algorithm - for penetration depth)
//!
//! # Main Functions in This Module
//!
//! - [`closest_points`] - The core GJK algorithm for finding distance and closest points
//! - [`project_origin`] - Projects the origin onto a shape's boundary
//! - [`cast_local_ray`] - Casts a ray against a shape (used for raycasting)
//! - [`directional_distance`] - Computes how far a shape can move before touching another
//!
//! # Example
//!
//! See individual function documentation for usage examples.
use crateComplexField;
use crate;
use crateSupportMap;
// use query::Proximity;
use crate;
use crate;
use ;
/// Results of the GJK algorithm.
///
/// This enum represents the different outcomes when running the GJK algorithm to find
/// the distance between two shapes. The result depends on whether the shapes are intersecting,
/// how far apart they are, and what information was requested.
///
/// # Understanding the Results
///
/// - **Intersection**: The shapes are overlapping. The origin lies inside the Minkowski difference.
/// - **ClosestPoints**: The exact closest points on both shapes were computed, along with the
/// separation direction.
/// - **Proximity**: The shapes are close but not intersecting. Only an approximate separation
/// direction is provided (used when exact distance computation is not needed).
/// - **NoIntersection**: The shapes are too far apart (beyond the specified `max_dist` threshold).
///
/// # Coordinate Spaces
///
/// All points and vectors in this result are expressed in the **local-space of the first shape**
/// (the shape passed as `g1` to the GJK functions). This is important when working with
/// transformed shapes.
/// The absolute tolerance used by the GJK algorithm.
///
/// This function returns the epsilon (tolerance) value that GJK uses to determine when
/// it has converged to a solution. The tolerance affects:
///
/// - When two points are considered "close enough" to be the same
/// - When the algorithm decides it has found the minimum distance
/// - Numerical stability in edge cases
///
/// The returned value is 10 times the default machine epsilon for the current floating-point
/// precision (f32 or f64). This provides a balance between accuracy and robustness.
///
/// # Returns
///
/// The absolute tolerance value (10 * DEFAULT_EPSILON)
/// Projects the origin onto the boundary of the given shape.
///
/// This function finds the point on the shape's surface that is closest to the origin (0, 0)
/// in 2D or (0, 0, 0) in 3D. This is useful for distance queries and collision detection
/// when you need to know the closest point on a shape.
///
/// # Important: Origin Must Be Outside
///
/// **The origin is assumed to be outside of the shape.** If the origin is inside the shape,
/// this function returns `None`. For penetrating cases, use the EPA (Expanding Polytope Algorithm)
/// instead.
///
/// # Parameters
///
/// - `m`: The position and orientation (isometry) of the shape in world space
/// - `g`: The shape to project onto (must implement `SupportMap`)
/// - `simplex`: A reusable simplex structure for the GJK algorithm. Initialize with
/// `VoronoiSimplex::new()` before first use.
///
/// # Returns
///
/// - `Some(Vector)`: The closest point on the shape's boundary, in the shape's **local space**
/// - `None`: If the origin is inside the shape
///
/// # Example
///
/// ```rust
/// # #[cfg(all(feature = "dim3", feature = "f32"))] {
/// use parry3d::shape::Ball;
/// use parry3d::query::gjk::{project_origin, VoronoiSimplex};
/// use parry3d::math::Pose;
///
/// // Create a ball at position (5, 0, 0)
/// let ball = Ball::new(1.0);
/// let position = Pose::translation(5.0, 0.0, 0.0);
///
/// // Project the origin onto the ball
/// let mut simplex = VoronoiSimplex::new();
/// if let Some(closest_point) = project_origin(&position, &ball, &mut simplex) {
/// println!("Closest point on ball: {:?}", closest_point);
/// // The point will be approximately (-1, 0, 0) in local space
/// // which is the left side of the ball facing the origin
/// }
/// # }
/// ```
///
/// # Performance Note
///
/// The `simplex` parameter can be reused across multiple calls to avoid allocations.
/// This is particularly beneficial when performing many projection queries.
Sized + SupportMap>
/*
* Separating Axis GJK
*/
/// Computes the closest points between two shapes using the GJK algorithm.
///
/// This is the **core function** of the GJK implementation in Parry. It can compute:
/// - Whether two shapes are intersecting
/// - The distance between two separated shapes
/// - The closest points on both shapes
/// - An approximate separation axis when exact distance isn't needed
///
/// # How It Works
///
/// The algorithm operates on the Minkowski difference (CSO) of the two shapes and iteratively
/// builds a simplex that approximates the point closest to the origin. The algorithm terminates
/// when:
/// - The shapes are proven to intersect (origin is inside the CSO)
/// - The minimum distance is found within the tolerance
/// - The shapes are proven to be farther than `max_dist` apart
///
/// # Parameters
///
/// - `pos12`: The relative position of shape 2 with respect to shape 1. This is the isometry
/// that transforms from shape 1's space to shape 2's space.
/// - `g1`: The first shape (must implement `SupportMap`)
/// - `g2`: The second shape (must implement `SupportMap`)
/// - `max_dist`: Maximum distance to check. If shapes are farther than this, the algorithm
/// returns `GJKResult::NoIntersection` early. Use `Real::max_value()` to disable this check.
/// - `exact_dist`: Whether to compute exact closest points:
/// - `true`: Computes exact distance and returns `GJKResult::ClosestPoints`
/// - `false`: May return `GJKResult::Proximity` with only an approximate separation axis,
/// which is faster when you only need to know if shapes are nearby
/// - `simplex`: A reusable simplex structure. Initialize with `VoronoiSimplex::new()` before
/// first use. Can be reused across calls for better performance.
///
/// # Returns
///
/// Returns a [`GJKResult`] which can be:
/// - `Intersection`: The shapes are overlapping
/// - `ClosestPoints(p1, p2, normal)`: The closest points on each shape (when `exact_dist` is true)
/// - `Proximity(axis)`: An approximate separation axis (when `exact_dist` is false)
/// - `NoIntersection(axis)`: The shapes are farther than `max_dist` apart
///
/// # Example: Basic Distance Query
///
/// ```rust
/// # #[cfg(all(feature = "dim3", feature = "f32"))] {
/// use parry3d::shape::{Ball, Cuboid};
/// use parry3d::query::gjk::{closest_points, VoronoiSimplex};
/// use parry3d::math::{Pose, Vector};
///
/// // Create two shapes
/// let ball = Ball::new(1.0);
/// let cuboid = Cuboid::new(Vector::new(1.0, 1.0, 1.0));
///
/// // Position them in space
/// let pos1 = Pose::translation(0.0, 0.0, 0.0);
/// let pos2 = Pose::translation(5.0, 0.0, 0.0);
///
/// // Compute relative position
/// let pos12 = pos1.inv_mul(&pos2);
///
/// // Run GJK
/// let mut simplex = VoronoiSimplex::new();
/// let result = closest_points(
/// &pos12,
/// &ball,
/// &cuboid,
/// f32::MAX, // No distance limit
/// true, // Compute exact distance
/// &mut simplex,
/// );
///
/// match result {
/// parry3d::query::gjk::GJKResult::ClosestPoints(p1, p2, normal) => {
/// println!("Closest point on ball: {:?}", p1);
/// println!("Closest point on cuboid: {:?}", p2);
/// println!("Separation direction: {:?}", normal);
/// let distance = (p2 - p1).length();
/// println!("Distance: {}", distance);
/// }
/// parry3d::query::gjk::GJKResult::Intersection => {
/// println!("Shapes are intersecting!");
/// }
/// _ => {}
/// }
/// # }
/// ```
///
/// # Example: Fast Proximity Check
///
/// ```rust
/// # #[cfg(all(feature = "dim3", feature = "f32"))] {
/// use parry3d::shape::Ball;
/// use parry3d::query::gjk::{closest_points, VoronoiSimplex};
/// use parry3d::math::Pose;
///
/// let ball1 = Ball::new(1.0);
/// let ball2 = Ball::new(1.0);
/// let pos12 = Pose::translation(3.0, 0.0, 0.0);
///
/// let mut simplex = VoronoiSimplex::new();
/// let result = closest_points(
/// &pos12,
/// &ball1,
/// &ball2,
/// 5.0, // Only check up to distance 5.0
/// false, // Don't compute exact distance
/// &mut simplex,
/// );
///
/// match result {
/// parry3d::query::gjk::GJKResult::Proximity(_axis) => {
/// println!("Shapes are close but not intersecting");
/// }
/// parry3d::query::gjk::GJKResult::Intersection => {
/// println!("Shapes are intersecting");
/// }
/// parry3d::query::gjk::GJKResult::NoIntersection(_) => {
/// println!("Shapes are too far apart (> 5.0 units)");
/// }
/// _ => {}
/// }
/// # }
/// ```
///
/// # Performance Tips
///
/// 1. Reuse the `simplex` across multiple queries to avoid allocations
/// 2. Set `exact_dist` to `false` when you only need proximity information
/// 3. Use a reasonable `max_dist` to allow early termination
/// 4. GJK converges fastest when shapes are well-separated
///
/// # Notes
///
/// - All returned points and vectors are in the local-space of shape 1
/// - The algorithm typically converges in 5-10 iterations for well-separated shapes
/// - Maximum iteration count is 100 to prevent infinite loops
/// Casts a ray against a shape using the GJK algorithm.
///
/// This function performs raycasting by testing a ray against a shape to find if and where
/// the ray intersects the shape. It uses a specialized version of GJK that works with rays.
///
/// # What is Raycasting?
///
/// Raycasting shoots a ray (infinite line starting from a point in a direction) and finds
/// where it first hits a shape. This is essential for:
/// - Mouse picking in 3D scenes
/// - Line-of-sight checks
/// - Projectile collision detection
/// - Laser/scanner simulations
///
/// # Parameters
///
/// - `shape`: The shape to cast the ray against (must implement `SupportMap`)
/// - `simplex`: A reusable simplex structure. Initialize with `VoronoiSimplex::new()`.
/// - `ray`: The ray to cast, containing an origin point and direction vector
/// - `max_time_of_impact`: Maximum distance along the ray to check. The ray will be treated
/// as a line segment of length `max_time_of_impact * ray.dir.length()`.
///
/// # Returns
///
/// - `Some((toi, normal))`: If the ray hits the shape
/// - `toi`: Time of impact - multiply by `ray.dir.length()` to get the actual distance
/// - `normal`: Surface normal at the hit point
/// - `None`: If the ray doesn't hit the shape within the maximum distance
///
/// # Example
///
/// ```rust
/// # #[cfg(all(feature = "dim3", feature = "f32"))] {
/// use parry3d::shape::Ball;
/// use parry3d::query::{Ray, gjk::{cast_local_ray, VoronoiSimplex}};
/// use parry3d::math::Vector;
///
/// // Create a ball at the origin
/// let ball = Ball::new(1.0);
///
/// // Create a ray starting at (0, 0, -5) pointing toward +Z
/// let ray = Ray::new(
/// Vector::new(0.0, 0.0, -5.0),
/// Vector::new(0.0, 0.0, 1.0)
/// );
///
/// let mut simplex = VoronoiSimplex::new();
/// if let Some((toi, normal)) = cast_local_ray(&ball, &mut simplex, &ray, f32::MAX) {
/// let hit_point = ray.point_at(toi);
/// println!("Ray hit at: {:?}", hit_point);
/// println!("Surface normal: {:?}", normal);
/// println!("Distance: {}", toi);
/// } else {
/// println!("Ray missed the shape");
/// }
/// # }
/// ```
///
/// # Notes
///
/// - The ray is specified in the local-space of the shape
/// - The returned normal points outward from the shape
/// - For normalized ray directions, `toi` equals the distance to the hit point
/// - This function is typically called by higher-level raycasting APIs
Sized + SupportMap>
/// Computes how far a shape can move in a direction before touching another shape.
///
/// This function answers the question: "If I move shape 1 along this direction, how far
/// can it travel before it touches shape 2?" This is useful for:
/// - Continuous collision detection (CCD)
/// - Movement planning and obstacle avoidance
/// - Computing time-of-impact for moving objects
/// - Safe navigation distances
///
/// # How It Works
///
/// The function casts shape 1 along the given direction vector and finds the first point
/// where it would contact shape 2. It returns:
/// - The distance that can be traveled
/// - The contact normal at the point of first contact
/// - The witness points (closest points) on both shapes at contact
///
/// # Parameters
///
/// - `pos12`: The relative position of shape 2 with respect to shape 1 (isometry from
/// shape 1's space to shape 2's space)
/// - `g1`: The first shape being moved (must implement `SupportMap`)
/// - `g2`: The second shape (static target, must implement `SupportMap`)
/// - `dir`: The direction vector to move shape 1 in (in local-space of shape 1)
/// - `simplex`: A reusable simplex structure. Initialize with `VoronoiSimplex::new()`.
///
/// # Returns
///
/// - `Some((distance, normal, witness1, witness2))`: If contact would occur
/// - `distance`: How far shape 1 can travel before touching shape 2
/// - `normal`: The contact normal at the point of first contact
/// - `witness1`: The contact point on shape 1 (in local-space of shape 1)
/// - `witness2`: The contact point on shape 2 (in local-space of shape 1)
/// - `None`: If no contact would occur (shapes don't intersect along this direction)
///
/// # Example
///
/// ```rust
/// # #[cfg(all(feature = "dim3", feature = "f32"))] {
/// use parry3d::shape::Ball;
/// use parry3d::query::gjk::{directional_distance, VoronoiSimplex};
/// use parry3d::math::{Pose, Vector};
///
/// // Two balls: one at origin, one at (10, 0, 0)
/// let ball1 = Ball::new(1.0);
/// let ball2 = Ball::new(1.0);
/// let pos12 = Pose::translation(10.0, 0.0, 0.0);
///
/// // Move ball1 toward ball2 along the +X axis
/// let direction = Vector::new(1.0, 0.0, 0.0);
///
/// let mut simplex = VoronoiSimplex::new();
/// if let Some((distance, normal, w1, w2)) = directional_distance(
/// &pos12,
/// &ball1,
/// &ball2,
/// direction,
/// &mut simplex
/// ) {
/// println!("Ball1 can move {} units before contact", distance);
/// println!("Contact normal: {:?}", normal);
/// println!("Contact point on ball1: {:?}", w1);
/// println!("Contact point on ball2: {:?}", w2);
/// // Expected: distance ≈ 8.0 (10.0 - 1.0 - 1.0)
/// }
/// # }
/// ```
///
/// # Use Cases
///
/// **1. Continuous Collision Detection:**
/// ```ignore
/// let movement_dir = velocity * time_step;
/// if let Some((toi, normal, _, _)) = directional_distance(...) {
/// if toi < 1.0 {
/// // Collision will occur during this timestep
/// let collision_time = toi * time_step;
/// }
/// }
/// ```
///
/// **2. Safe Movement Distance:**
/// ```ignore
/// let desired_movement = Vector::new(5.0, 0.0, 0.0);
/// if let Some((max_safe_dist, _, _, _)) = directional_distance(...) {
/// let actual_movement = desired_movement.normalize() * max_safe_dist.min(5.0);
/// }
/// ```
///
/// # Notes
///
/// - All inputs and outputs are in the local-space of shape 1
/// - If the shapes are already intersecting, the returned distance is 0.0 and witness
/// points are undefined (set to origin)
/// - The direction vector does not need to be normalized
/// - This function internally uses GJK raycasting on the Minkowski difference
// Ray-cast on the Minkowski Difference `g1 - pos12 * g2`.