aboutsummaryrefslogtreecommitdiff
path: root/dep/include/g3dlite/G3D/CollisionDetection.h
blob: 4add967ed8b14d9ae871b11897d41ad40d3182b2 (plain)
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
/**
  @file CollisionDetection.h


  Moving collision detection for simple primitives.

  @author Morgan McGuire, matrix@graphics3d.com
  @cite Spherical collision based on Paul Nettle's
  ftp://ftp.3dmaileffects.com/pub/FluidStudios/CollisionDetection/Fluid_Studios_Generic_Collision_Detection_for_Games_Using_Ellipsoids.pdf
  and comments by Max McGuire.  Ray-sphere intersection by Eric Haines.
  Box-Box intersection written by Kevin Egan.
  Thanks to Max McGuire of Iron Lore for various bug fixes.

  @created 2001-11-19
  @edited  2006-01-10

  Copyright 2000-2006, Morgan McGuire.
  All rights reserved.
 */

#ifndef G3D_COLLISIONDETECTION_H
#define G3D_COLLISIONDETECTION_H

#include "G3D/platform.h"
#include "G3D/Vector3.h"
#include "G3D/Plane.h"
#include "G3D/Box.h"
#include "G3D/Triangle.h"
#include "G3D/Array.h"
#include "G3D/Ray.h"
#include "G3D/Line.h"

namespace G3D {


/**
  Collision detection primitives and tools for building
  higher order collision detection schemes.

  These routines provide <I>moving</I> and static collision detection.
  Moving collision detection allows the calculation of collisions that
  occur during a period of time -- as opposed to the intersection of
  two static bodies.

  Moving collision detection routines detect collisions between
  <I>only</I> static primitives and moving spheres or points.  Since the
  reference frame can be user defined, these functions can be used to
  detect the collision between two moving bodies by subtracting
  the velocity vector of one object from the velocity vector of the
  sphere or point the detection is to occur with.  This unified
  velocity vector will act as if both objects are moving simultaneously.

  Collisions are detected for single-sided objects only.  That is,
  no collision is detected when <I>leaving</I> a primitive or passing
  through a plane or triangle opposite the normal... except for the
  point-sphere calculation or when otherwise noted.

  For a sphere, the collision location returned is the point in world
  space where the surface of the sphere and the fixed object meet.
  It is <B>not</B> the position of the center of the sphere at
  the time of the collision.

  The collision normal returned is the surface normal to the fixed
  object at the collision location.

  <p>
  <b>Static Collision Detection:</b> (Neither object is moving)

  <table>
  <tr><td></td><td><b>Vector3</b></td><td><b>LineSegment</b></td><td><b>Ray *</b></td><td><b>Line</b></td><td><b>Plane</b></td><td><b>Triangle</b></td><td><b>Sphere</b></td><td><b>Cylinder</b></td><td><b>Capsule</b></td><td><b>AABox</b></td><td><b>Box</b></td></tr>
  <tr><td><b>Vector3</b></td><td>Vector3::operator== Vector3::fuzzyEq G3D::distance</td><td bgcolor=#C0C0C0 colspan=10 ></td></tr>
  <tr><td><b>LineSegment</b></td><td>LineSegment::closestPoint LineSegment::distance CollisionDetection::closestPointOnLineSegment</td><td></td><td bgcolor=#C0C0C0 colspan=9 ></td></tr>
  <tr><td><b>Ray *</b></td><td>Ray::closestPoint Ray::distance</td><td></td><td></td><td bgcolor=#C0C0C0 colspan=8 ></td></tr>
  <tr><td><b>Line</b></td><td>Line::closestPoint Line::distance</td><td></td><td>CollisionDetection::closestPointsBetweenLineAndLine</td><td></td><td bgcolor=#C0C0C0 colspan=7 ></td></tr>
  <tr><td><b>Plane</b></td><td></td><td></td><td></td><td></td><td></td><td bgcolor=#C0C0C0 colspan=6 ></td></tr>
  <tr><td><b>Triangle</b></td><td></td><td></td><td></td><td></td><td></td><td></td><td bgcolor=#C0C0C0 colspan=5 ></td></tr>
  <tr><td><b>Sphere</b></td><td>Sphere::contains</td><td></td><td></td><td></td><td></td><td></td><td></td><td bgcolor=#C0C0C0 colspan=4 ></td></tr>
  <tr><td><b>Cylinder</b></td><td>Cylinder::contains</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td bgcolor=#C0C0C0 colspan=3 ></td></tr>
  <tr><td><b>Capsule</b></td><td>Capsule::contains</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td bgcolor=#C0C0C0 colspan=2 ></td></tr>
  <tr><td><b>AABox</b></td><td>AABox::contains</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td bgcolor=#C0C0C0 colspan=1 ></td></tr>
  <tr><td><b>Box</b></td><td>Box::contains</td><td>(treat as Ray)</td><td>CollisionDetection::collisionTimeForMovingPointFixedBox</td><td>(treat as Ray)</td><td>CollisionDetection::penetrationDepthForFixedBoxFixedPlane</td><td>CollisionDetection::penetrationDepthForFixedBoxFixedPlane</td><td>CollisionDetection::penetrationDepthForFixedSphereFixedBox</td><td>None (use OPCODE)</td><td>CollisionDetection::movingSpherePassesThroughFixedBox</td><td>CollisionDetection::penetrationDepthForFixedBoxFixedBox</td><td>CollisionDetection::penetrationDepthForFixedBoxFixedBox</td></tr>
  </table>

  <p>
  <b>Moving Collision Detection:</b>

  <i>* Note: Moving collision detection against certain primitives is equivalent to static collision
   detection against a bigger primitive.  Ray, Line Segment == ``moving Point''; Capsule ==``moving Sphere''; Plane == ``moving Line''</i>
 */
class CollisionDetection {
private:

    /**
     Default parameter if value passed to a function as reference is
     not to be calculated.  Must be explicitly supported by function.
     */
    static Vector3 ignore;

    /**
     Default parameter if value passed to a function as reference is
     not to be calculated.  Must be explicitly supported by function.
     */
    static bool    ignoreBool;

    /**
     Default parameter if value passed to a function as reference is
     not to be calculated.  Must be explicitly supported by function.
     */
    static Array<Vector3> ignoreArray;


    // Static class!
    CollisionDetection() {}
    virtual ~CollisionDetection() {}

public:

    /**
      Converts an index [0, 15] to the corresponding separating axis.
      Does not return normalized vector in the edge-edge case
      (indices 6 through 15).

      @param separatingAxisIndex    Separating axis.
      @param box1                   Box 1.
      @param box2                   Box 2.

      @return Axis that separates the two boxes.
     */
    static Vector3 separatingAxisForSolidBoxSolidBox(
            const int       separatingAxisIndex,
            const Box &     box1,
            const Box &     box2);

    /**
      Tests whether two boxes have axes that are parallel to
      each other.  If they are, axis1 and axis2 are set to be
      the parallel axes for both box1 and box2 respectively.

      @param ca         Dot products of each of the boxes axes
      @param epsilon    Fudge factor (small unit by which the dot
                        products may vary and still be considered
                        zero).
      @param axis1      Parallel Axis 1. [Post Condition]
      @param axis2      Parallel Axis 2. [Post Condition]

      @return true  - If boxes have a parallel axis
      @return false - otherwise.
     */
    static bool parallelAxisForSolidBoxSolidBox(
            const double*   ca,
            const double    epsilon,
            int &           axis1,
            int &           axis2);

    /**
      Calculates the projected distance between the two boxes along
      the specified separating axis, negative distances correspond
      to an overlap along that separating axis.  The distance is not
      divided by denominator dot(L, L), see
      penetrationDepthForFixedSphereFixedBox() for more details

      @param separatingAxisIndex
      @param a Box 1's bounding sphere vector
      @param b Box 2's bounding sphere vector
      @param D Vector between Box 1 and Box 2's center points
      @param c Pointer to array of dot products of the axes of Box 1
               and Box 2.
      @param ca Pointer to array of unsigned dot products of the axes
                of Box 1 and Box 2.
      @param ad Pointer to array of dot products of Box 1 axes and D.
      @param bd Pointer to array of dot products of Box 2 axes and D.

      @return Projected distance between the two boxes along the
      specified separating axis.
     */
    static float projectedDistanceForSolidBoxSolidBox(
            const int           separatingAxisIndex,
            const Vector3 &     a,
            const Vector3 &     b,
            const Vector3 &     D,
            const double*       c,
            const double*       ca,
            const double*       ad,
            const double*       bd);


    /**
      Creates a set of standard information about two boxes in order to
      solve for their collision.  This information includes a vector to
      the radius of the bounding sphere for each box, the vector between
      each boxes' center and a series of dot products between differing
      important vectors.  These dot products include those between the axes
      of both boxes (signed and unsigned values), and the dot products
      between all the axes of box1 and the boxes' center vector and box2
      and the boxes' center vector.

      @pre The following space requirements must be met:
            - c[]  9 elements
            - ca[] 9 elements
            - ad[] 3 elements
            - bd[] 3 elements

      @cite dobted from David Eberly's papers, variables used in this function
      correspond to variables used in pages 6 and 7 in the pdf
      http://www.magic-software.com/Intersection.html
      http://www.magic-software.com/Documentation/DynamicCollisionDetection.pdf

      @note Links are out-dated. (Kept to preserve origin and authorship)

      @param box1 Box 1
      @param box2 Box 2
      @param a Box 1's bounding sphere vector
      @param b Box 2's bounding sphere vector
      @param D Vector between Box 1 and Box 2's center points
      @param c Pointer to array of dot products of the axes of Box 1
               and Box 2.
      @param ca Pointer to array of unsigned dot products of the axes
                of Box 1 and Box 2.
      @param ad Pointer to array of dot products of Box 1 axes and D.
      @param bd Pointer to array of dot products of Box 2 axes and D.
     */
    static void fillSolidBoxSolidBoxInfo(
            const Box &     box1,
            const Box &     box2,
            Vector3 &       a,
            Vector3 &       b,
            Vector3 &       D,
            double*         c,
            double*         ca,
            double*         ad,
            double*         bd);

    /**
      Performs a simple bounding sphere check between two boxes to determine
      whether these boxes could <i>possibly</i> intersect.  This is a very
      cheap operation (three dot products, two sqrts and a few others).  If
      it returns true, an intersection is possible, but not necessarily
      guaranteed.

      @param a Vector from box A's center to an outer vertex
      @param b Vector from box B's center to an outer vertex
      @param D Distance between the centers of the two boxes

      @return true - if possible intersection
      @return false - otherwise (This does not guarantee an intersection)
     */
    static bool conservativeBoxBoxTest(
            const Vector3 &     a,
            const Vector3 &     b,
            const Vector3 &     D);

    /**
      Determines whether two fixed solid boxes intersect.

      @note To speed up collision detection, the lastSeparatingAxis from
      the previous time step can be passed in and that plane can be
      checked first.  If the separating axis was not saved, or if the
      two boxes intersected then lastSeparatingAxis should equal -1.

      @cite Adobted from David Eberly's papers, variables used in this function
      correspond to variables used in pages 6 and 7 in the pdf
      http://www.magic-software.com/Intersection.html
      http://www.magic-software.com/Documentation/DynamicCollisionDetection.pdf

      @param box1               Box 1.
      @param box2               Box 2.
      @param lastSeparatingAxis Last separating axis.
                                (optimization - see note)

      @return true  - Intersection.
      @return false - otherwise.
     */
    static bool fixedSolidBoxIntersectsFixedSolidBox(
        const Box&      box1,
        const Box&      box2,
        const int       lastSeparatingAxis = -1);

    /**
      Calculates the closest points on two lines with each other.   If the
      lines are parallel then using the starting point, else calculate the
      closest point on each line to the other.

      @note This is very similiar to calculating the intersection of two lines.
      Logically then, the two points calculated would be identical if calculated
      with inifinite precision, but with the finite precision of floating point
      calculations, these values could (will) differ as the line slope approaches
      zero or inifinity.

      @cite variables and algorithm based on derivation at the following website:
            http://softsurfer.com/Archive/algorithm_0106/algorithm_0106.htm

      @param line1      Line 1.
      @param line2      Line 2.
      @param closest1   Closest point on line 1.
      @param closest2   Closest point on line 2.
    */
    static void closestPointsBetweenLineAndLine(
            const Line &    line1,
            const Line &    line2,
            Vector3 &       closest1,
            Vector3 &       closest2);

    /**
      Calculates the depth of penetration between two fixed boxes.
      Contact normal faces away from box1 and into box2.  If there is
      contact, only one contact point is returned.  The minimally
      violated separating plane is computed
         - if the separating axis corresponds to a face
              the contact point is half way between the deepest vertex
              and the face
         - if the separating axis corresponds to two edges
              the contact point is the midpoint of the smallest line
              segment between the two edge lines

      @note This is very similiar to calculating the intersection of two lines.
      Logically then, the two points calculated would be identical if calculated
      with inifinite precision, but with the finite precision of floating point
      calculations, these values could (will) differ as the line slope approaches
      zero or inifinity.

      @cite adobted from David Eberly's papers, variables used in this function
      correspond to variables used in pages 6 and 7 in the pdf
      http://www.magic-software.com/Intersection.html
      http://www.magic-software.com/Documentation/DynamicCollisionDetection.pdf

      @param box1               Box 1
      @param box2               Box 2
      @param contactPoints      Contact point between boxes. [Post Condition]
      @param contactNormals     Surface normal at contact point. [Post Condition]
      @param lastSeparatingAxis Last separating axis. (Used for optimization)

      @return Depth of penetration between the two boxes.  If there is no
       intersection between the boxes, then a negative value is returned.
    */
    static float penetrationDepthForFixedBoxFixedBox(
        const Box&          box1,
        const Box&          box2,
        Array<Vector3>&     contactPoints,
        Array<Vector3>&     contactNormals,
        const int           lastSeparatingAxis = -1);

    /**
      Calculates the depth of penetration between two fixed spheres as well
      as the deepest point of Sphere A that penetrates Sphere B. The normal
      returned points <B>away</B> from the object A, although it may
      represent a perpendicular to either the faces of object B or object A
      depending on their relative orientations.

      @param sphereA        Fixed Sphere A.
      @param sphereB        Fixed Sphere B.
      @param contactPoints  Sphere A's deepest point that penetrates Sphere B.
                            [Post Condition]
      @param contactNormals Normal at penetration point. [Post Condition]

      @return Depth of penetration.  If there is no intersection between the
             objects then the depth will be a negative value.
     */
    static float penetrationDepthForFixedSphereFixedSphere(
        const class Sphere& sphereA,
        const Sphere&       sphereB,
        Array<Vector3>&     contactPoints,
        Array<Vector3>&     contactNormals = ignoreArray);

    /**
      Calculates the depth of penetration between a fixed sphere and a fixed
      box as well as the deepest point of the sphere that penetrates the box
      and the normal at that intersection.

      @note There are three possible intersections between a sphere and box.
      - Sphere completely contained in the box
      - Sphere intersects one edge
      - Sphere intersects one vertex

      The contact point and contact normal vary for each of these situations.
      - Sphere contained in Box:
        - Normal is based on side of least penetration (as is the depth calculation).
        - Point is based on center of sphere
      - Sphere intersects one edge
        - Normal is based on vector from the box center to the point of depth.
        - Point is closest point to the sphere on the line
      - Sphere intersects one vertex
        - Normal is based on vector from the box center to the vertex of penetration.
        - Point is vertex of penetration.

      @cite Adapted from Jim Arvo's method in Graphics Gems
      See also http://www.win.tue.nl/~gino/solid/gdc2001depth.pdf

      @param sphere         Fixed Sphere.
      @param box            Fixed Box.
      @param contactPoints  Sphere point that penetrates the box. [Post Condition]
      @param contactNormals Normal at the penetration point. [Post Condition]

      @return Depth of penetration.  If there is no intersection between the
              objects then the depth will be a negative value.
     */
    static float penetrationDepthForFixedSphereFixedBox(
        const Sphere&       sphere,
        const Box&          box,
        Array<Vector3>&     contactPoints,
        Array<Vector3>&     contactNormals = ignoreArray);

    /**
      Calculates the depth of penetration between a Fixed Sphere and a Fixed
      Plane as well as the deepest point of the sphere that penetrates the plane
      and the plane normal at that intersection.

      @param sphere         Fixed Sphere.
      @param plane          Fixed Plane.
      @param contactPoints  Sphere point that penetrates the plane.
                            [Post Condition]
      @param contactNormals Normal at penetration point. [Post Condition]

      @return Depth of penetration.  If there is no intersection between the
             objects then the depth will be a negative value.
     */
    static float penetrationDepthForFixedSphereFixedPlane(
        const Sphere&       sphereA,
        const class Plane&  planeB,
        Array<Vector3>&     contactPoints,
        Array<Vector3>&     contactNormals = ignoreArray);

    /**
      Calculates the depth of penetration between a fixed box and a fixed
      plane as well as the vertexes of the box that penetrate the plane
      and the plane normals at those intersections.

      @param box            Fixed Box.
      @param plane          Fixed Plane.
      @param contactPoints  Box points that penetrate the plane.
                            [Post Condition]
      @param contactNormals Normals at penetration points [Post Condition]

      @return Depth of penetration.  If there is no intersection between the
             objects then the depth will be a negative value.
    */
    static float penetrationDepthForFixedBoxFixedPlane(
        const Box&          box,
        const Plane&        plane,
        Array<Vector3>&     contactPoints,
        Array<Vector3>&     contactNormals = ignoreArray);

    /**
      Calculates time between the intersection of a moving point and a fixed
      plane.

      @note This is only a one sided collision test.   The side defined by
      the plane's surface normal is the only one tested.  For a two sided
      collision, call the function once for each side's surface normal.

      @param point      Moving point.
      @param velocity   Point's velocity.
      @param plane      Fixed plane.
      @param location   Location of collision. [Post Condition]
                        (Infinite vector on no collision)
      @param outNormal  Plane's surface normal. [Post Condition]

      @return Time til collision.  If there is no collision then the return
              value will be inf().
    */
    static float collisionTimeForMovingPointFixedPlane(
        const Vector3&          point,
        const Vector3&          velocity,
        const class Plane&      plane,
        Vector3&                outLocation,
        Vector3&                outNormal = ignore);

    /**
      Calculates time between the intersection of a moving point and a fixed
      triangle.

      @note This is only a one sided collision test.   The side defined by
      the triangle's surface normal is the only one tested.  For a two sided
      collision, call the function once for each side's surface normal.

      @param orig       Moving point.
      @param dir        Point's velocity.
      @param v0         Triangle vertex 1.
      @param v1         Triangle vertex 2.
      @param v2         Triangle vertex 3
      @param location   Location of collision. [Post Condition]
                        (Infinite vector on no collision)

      @return Time til collision.  If there is no collision then the return
              value will be inf().
    */
    inline static float collisionTimeForMovingPointFixedTriangle(
        const Vector3& orig,
        const Vector3& dir,
        const Vector3& v0,
        const Vector3& v1,
        const Vector3& v2) {
        return Ray::fromOriginAndDirection(orig, dir).intersectionTime(v0, v1, v2);
    }

    /**
      Calculates time between the intersection of a moving point and a fixed
      triangle.

      @note This is only a one sided collision test.   The side defined by
      the triangle's surface normal is the only one tested.  For a two sided
      collision, call the function once for each side's surface normal.

      @param orig       Moving point.
      @param dir        Point's velocity.
      @param v0         Triangle vertex 1.
      @param v1         Triangle vertex 2.
      @param v2         Triangle vertex 3
      @param location   Location of collision. [Post Condition]
                        (Infinite vector on no collision)

      @return Time til collision.  If there is no collision then the return
              value will be inf().
    */
    inline static float collisionTimeForMovingPointFixedTriangle(
        const Vector3& orig,
        const Vector3& dir,
        const Vector3& v0,
        const Vector3& v1,
        const Vector3& v2,
        Vector3&       location) {
        float t = collisionTimeForMovingPointFixedTriangle(orig, dir, v0, v1, v2);
        if (t < inf()) {
            location = orig + dir * t;
        }
        return t;
    }

    /**
      Calculates time between the intersection of a moving point and a fixed
      triangle.

      @note This is only a one sided collision test.   The side defined by
      the triangle's surface normal is the only one tested.  For a two sided
      collision, call the function once for each side's surface normal.

      @param orig       Moving point.
      @param dir        Point's velocity.
      @param tri        Fixed triangle.
      @param location   Location of collision. [Post Condition]
                        (Infinite vector on no collision)
      @param normal     Triangle's surface normal. [Post Condition]

      @return Time til collision.  If there is no collision then the return
              value will be inf().
    */
    inline static float collisionTimeForMovingPointFixedTriangle(
        const Vector3&  orig,
        const Vector3&  dir,
        const Triangle& tri,
        Vector3&        location = ignore,
        Vector3&        normal   = ignore) {

        float t = collisionTimeForMovingPointFixedTriangle(
            orig, dir, tri.vertex(0), tri.vertex(1), tri.vertex(2));

        if ((t < inf()) && (&location != &ignore)) {
            location = orig + dir * t;
            normal   = tri.normal();
        }
        return t;
    }

    /**
      Calculates time between the intersection of a moving point and a fixed
      triangle.

      @note This is only a one sided collision test.   The side defined by
      the triangle's surface normal is the only one tested.  For a two sided
      collision, call the function once for each side's surface normal.

      @param orig       Moving point.
      @param dir        Point's velocity.
      @param v0         Triangle vertex 1.
      @param v1         Triangle vertex 2.
      @param v2         Triangle vertex 3
      @param location   Location of collision. [Post Condition]
                        (Infinite vector on no collision)
      @param normal     Triangle's surface normal. [Post Condition]

      @return Time til collision.  If there is no collision then the return
              value will be inf().
    */
    inline static float collisionTimeForMovingPointFixedTriangle(
        const Vector3& orig,
        const Vector3& dir,
        const Vector3& v0,
        const Vector3& v1,
        const Vector3& v2,
        Vector3&       location,
        Vector3&       normal) {
        float t = collisionTimeForMovingPointFixedTriangle(orig, dir, v0, v1, v2);
        if (t < inf()) {
            location = orig + dir * t;
            normal   = (v2 - v0).cross(v1 - v0).direction();
        }
        return t;
    }

    /**
     Unlike other methods, does not support an output normal.
     If the ray origin is inside the box, returns inf() but inside
     is set to true.
     <B>Beta API</B>

     @cite Andrew Woo, from "Graphics Gems", Academic Press, 1990
     @cite Optimized code by Pierre Terdiman, 2000 (~20-30% faster on my Celeron 500)
     @cite Epsilon value added by Klaus Hartmann
     @cite http://www.codercorner.com/RayAABB.cpp
     */
    static float collisionTimeForMovingPointFixedAABox(
        const Vector3&          point,
        const Vector3&          velocity,
        const class AABox&      box,
        Vector3&                outLocation,
        bool&                   inside = ignoreBool,
        Vector3&                outNormal = ignore);

    /**
     Calculates time between the intersection of a moving point and a fixed
     Axis-Aligned Box (AABox).

     @note Avoids the sqrt from collisionTimeForMovingPointFixedAABox.

     @param point       Moving point.
     @param velocity    Sphere's velocity.
     @param box         Fixed AAbox.
     @param location    Location of collision. [Post Condition]
     @param Inside      Does the ray originate inside the box? [Post Condition]
     @param normal      Box's surface normal to collision [Post Condition]

     @return Time til collision.  If there is no collision then the return
             value will be inf().
    */
    static bool collisionLocationForMovingPointFixedAABox(
        const Vector3&          point,
        const Vector3&          velocity,
        const class AABox&      box,
        Vector3&                outLocation,
        bool&                   inside = ignoreBool,
        Vector3&                normal = ignore);

    /**
     Calculates time between the intersection of a moving point and a fixed
     sphere.

     @note When ray is starts inside the rectangle, the exiting intersection
     is detected.

     @param point       Moving point.
     @param velocity    Point's velocity.
     @param Sphere      Fixed Sphere.
     @param location    Location of collision. [Post Condition]
     @param outNormal   Sphere's surface normal to collision [Post Condition]

     @return Time til collision.  If there is no collision then the return
             value will be inf().
    */
    static float collisionTimeForMovingPointFixedSphere(
        const Vector3&          point,
        const Vector3&          velocity,
        const class Sphere&     sphere,
        Vector3&                outLocation,
        Vector3&                outNormal = ignore);

    /**
     Calculates time between the intersection of a moving point and a fixed
     box.

     @note If the point is already inside the box, no collision: inf is returned.

     @param point       Moving point.
     @param velocity    Sphere's velocity.
     @param box         Fixed box.
     @param location    Position of collision. [Post Condition]
     @param outNormal   Box's surface normal to collision [Post Condition]

     @return Time til collision.  If there is no collision then the return
             value will be inf().
    */
    static float collisionTimeForMovingPointFixedBox(
        const Vector3&          point,
        const Vector3&          velocity,
        const class  Box&       box,
        Vector3&                outLocation,
        Vector3&                outNormal = ignore);

    /**
     Calculates time between the intersection of a moving point and a fixed
     rectangle defined by the points v0, v1, v2, & v3.

     @note This is only a one sided collision test.   The side defined by
     the rectangle's surface normal is the only one tested.  For a two sided
     collision, call the function once for each side's surface normal.

     @param point       Moving point.
     @param velocity    Sphere's velocity.
     @param v0          Rectangle vertex 1.
     @param v1          Rectangle vertex 2.
     @param v2          Rectangle vertex 3
     @param v3          Rectangle vertex 4.
     @param location    Location of collision [Post Condition]
     @param outNormal   Rectangle's surface normal. [Post Condition]

     @return Time til collision.  If there is no collision then the return
             value will be inf().
    */
    static float collisionTimeForMovingPointFixedRectangle(
        const Vector3&          point,
        const Vector3&          velocity,
        const Vector3&          v0,
        const Vector3&          v1,
        const Vector3&          v2,
        const Vector3&          v3,
        Vector3&                outLocation,
        Vector3&                outNormal = ignore);

    /**
     Calculates time between the intersection of a moving point and a fixed
     capsule.

     @param point       Moving point.
     @param velocity    Point's velocity.
     @param capsule     Fixed capsule.
     @param location    Location of collision. [Post Condition]
     @param outNormal   Capsule's surface normal to collision [Post Condition]

     @return Time til collision.  If there is no collision then the return
             value will be inf().
    */
    static float collisionTimeForMovingPointFixedCapsule(
        const Vector3&          point,
        const Vector3&          velocity,
        const class Capsule&    capsule,
        Vector3&                outLocation,
        Vector3&                outNormal = ignore);

    /**
     Calculates time between the intersection of a moving sphere and a fixed
     triangle.

     @param sphere      Moving sphere.
     @param velocity    Sphere's velocity.
     @param plane       Fixed Plane.
     @param location    Location of collision -- not center position of sphere
                        at the collision time. [Post Condition]
     @param outNormal   Box's surface normal to collision [Post Condition]

     @return Time til collision.  If there is no collision then the return
             value will be inf().
     */
    static float collisionTimeForMovingSphereFixedPlane(
        const class Sphere&     sphere,
        const Vector3&          velocity,
        const class Plane&      plane,
        Vector3&                outLocation,
        Vector3&                outNormal = ignore);

    /**
     Calculates time between the intersection of a moving sphere and a fixed
     triangle.

     @param sphere      Moving sphere.
     @param velocity    Sphere's velocity.
     @param triangle    Fixed Triangle.
     @param location    Location of collision -- not center position of sphere
                        at the collision time. [Post Condition]
     @param outNormal   Box's surface normal to collision [Post Condition]

     @return Time til collision.  If there is no collision then the return
             value will be inf().
    */
    static float collisionTimeForMovingSphereFixedTriangle(
        const class Sphere&     sphere,
        const Vector3&          velocity,
        const Triangle&       triangle,
        Vector3&                outLocation,
        Vector3&                outNormal = ignore);

    /**
     Calculates time between the intersection of a moving sphere and a fixed
     rectangle defined by the points v0, v1, v2, & v3.

     @param sphere      Moving sphere.
     @param velocity    Sphere's velocity.
     @param v0          Rectangle vertex 1.
     @param v1          Rectangle vertex 2.
     @param v2          Rectangle vertex 3
     @param v3          Rectangle vertex 4.
     @param location    Location of collision -- not center position of sphere
                        at the collision time. [Post Condition]
     @param outNormal   Box's surface normal to collision [Post Condition]

     @return Time til collision.  If there is no collision then the return
             value will be inf().
    */
    static float collisionTimeForMovingSphereFixedRectangle(
        const class Sphere&     sphere,
        const Vector3&          velocity,
        const Vector3&          v0,
        const Vector3&          v1,
        const Vector3&          v2,
        const Vector3&          v3,
        Vector3&                outLocation,
        Vector3&                outNormal = ignore);

    /**
     Calculates time between the intersection of a moving sphere and a fixed
     box.

     @note This function will not detect an intersection between a moving object
     that is already interpenetrating the fixed object.

     @param sphere      Moving sphere.
     @param velocity    Sphere's velocity.
     @param box         Fixed box.
     @param location    Location of collision -- not center position of sphere
                        at the collision time. [Post Condition]
     @param outNormal   Box's surface normal to collision [Post Condition]

     @return Time til collision.  If there is no collision then the return
             value will be inf().
    */
    static float collisionTimeForMovingSphereFixedBox(
        const class Sphere&     sphere,
        const Vector3&          velocity,
        const class Box&        box,
        Vector3&                outLocation,
        Vector3&                outNormal = ignore);

    /**
     Calculates time between the intersection of a moving sphere and a fixed
     sphere.

     @note This won't detect a collision if the sphere is already interpenetrating
           the fixed sphere.

     @param movingSphere    Moving sphere.
     @param velocity        Sphere's velocity.
     @param fixedSphere     Fixed Sphere.
     @param location        Location of collision -- not center position of sphere
                            at the collision time. [Post Condition]
     @param outNormal       Sphere's surface normal to collision [Post Condition]

     @return Time til collision.  If there is no collision then the return
             value will be inf().
    */
    static float collisionTimeForMovingSphereFixedSphere(
        const class Sphere&     sphere,
        const Vector3&          velocity,
        const class Sphere&     fixedSphere,
        Vector3&                outLocation,
        Vector3&                outNormal = ignore);

    /**
     Calculates time between the intersection of a moving sphere and a fixed
     capsule.

     @note This won't detect a collision if the sphere is already
           interpenetrating the capsule.

     @param sphere      Moving sphere.
     @param velocity    Sphere's velocity.
     @param capsule     Fixed capsule.
     @param location    Location of collision -- not center position of sphere
                        at the collision time. [Post Condition]
     @param outNormal   Capsule's surface normal to the collision [Post Condition]

     @return Time til collision.  If there is no collision then the return
             value will be inf().
    */
    static float collisionTimeForMovingSphereFixedCapsule(
        const class Sphere&     sphere,
        const Vector3&          velocity,
        const class Capsule&    capsule,
        Vector3&                outLocation,
        Vector3&                outNormal = ignore);

    /**
     Finds the direction of bounce that a sphere would have when it
     intersects an object with the  given time of collision, the
     collision location and the collision normal.

     @note This function works like a pong style ball bounce.

     @param sphere              Moving sphere.
     @param velocity            Sphere's velocity.
     @param collisionTime       Time of collision.
     @param collisionLocation   Collision location.
     @param collisionNormal     Surface collision normal.

     @return Direction of bounce.
    */
    static Vector3 bounceDirection(
        const class Sphere&     sphere,
        const Vector3&          velocity,
        const float             collisionTime,
        const Vector3&          collisionLocation,
        const Vector3&          collisionNormal);

    /**
     Finds the direction of slide given a moving sphere, its velocity, the
     time of collision and the collision location.  This function works as
     if the sphere intersects the surface and continues to hug it.

     @note The result will work well for calculating the movement of a player
     who collides with an object and continues moving along the object instead
     of just bouncing off it.

     @param sphere              Moving sphere.
     @param velocity            Sphere's velocity.
     @param collisionTime       Time of collision
     @param collisionLocation   Collision location.

     @return Direction of slide.
    */
    static Vector3 slideDirection(
        const class Sphere&     sphere,
        const Vector3&          velocity,
        const float             collisionTime,
        const Vector3&          collisionLocation);

    /**
     Finds the closest point on a line segment to a given point.

     @param v0 line vertex 1.
     @param v1 line vertex 2.
     @param point External point.

     @return Closests point to <code>point</code> on the line segment.
    */
    static Vector3 closestPointOnLineSegment(
        const Vector3&          v0,
        const Vector3&          v1,
        const Vector3&          point);

    /**
     Finds the closest point on a line segment to a given point.

     @note This is an optimization to closestPointOnLineSegment.  Edge length
     and direction can be used in this function if already pre-calculated.  This
     prevents doing the same work twice.

     @param v0 line vertex 1.
     @param v1 line vertex 2.
     @param edgeDirection The direction of the segment (unit length).
     @param edgeLength The length of the segment.
     @param point External point.

     @return Closests point to <code>point</code> on the line segment.
    */
    static Vector3 closestPointOnLineSegment(
        const Vector3&          v0,
        const Vector3&          v1,
        const Vector3&          edgeDirection,
        float                  edgeLength,
        const Vector3&          point);

    /**
     Finds the closest point on the perimeter of the triangle to an external point;
     given a triangle defined by three points v0, v1, & v2, and the external point.

     @param v0 Triangle vertex 1.
     @param v1 Triangle vertex 2.
     @param v2 Triangle vertex 3.
     @param point External point.

     @return Closests point to <code>point</code> on the perimeter of the
     triangle.
    */
    static Vector3 closestPointToTrianglePerimeter(
        const Vector3&          v0,
        const Vector3&          v1,
        const Vector3&          v2,
        const Vector3&          point);

    /**
     Finds the closest point on the perimeter of the triangle to an external point;
     given a triangle defined by the array of points v, its edge directions and
     their lengths, as well as the external point.

     @note This is an optimization to closestPointToTrianglePerimeter.  Edge length
     and direction can be used in this function if already pre-calculated.  This
     prevents doing the same work twice.

     @param v0 Triangle vertex 1.
     @param v1 Triangle vertex 2.
     @param v2 Triangle vertex 3.
     @param point External point.

     @return Closests point to <code>point</code> on the perimeter of the
     triangle.
    */
    static Vector3 closestPointToTrianglePerimeter(
        const Vector3           v[3],
        const Vector3           edgeDirection[3],
        const double            edgeLength[3],
        const Vector3&          point);

    /**
     Tests whether a point is contained within the triangle defined by
     v0, v1, & v2 and its plane's normal.

     @param v0 Triangle vertex 1.
     @param v1 Triangle vertex 2.
     @param v2 Triangle vertex 3.
     @param normal Normal to triangle's plane.
     @param point The point in question.
     @param primaryAxis Primary axis of triangle.  This will be detected
            if not given. This parameter is provided as an optimization.

     @return true  - if point is inside the triangle.
     @return false - otherwise
    */
    static bool isPointInsideTriangle(
        const Vector3&          v0,
        const Vector3&          v1,
        const Vector3&          v2,
        const Vector3&          normal,
        const Vector3&          point,
        Vector3::Axis  primaryAxis = Vector3::DETECT_AXIS);

     /**
      Tests for the intersection of a moving sphere and a fixed box in a
      given time limit.

      @note Returns true if any part of the sphere is inside the box
            during the time period (inf means "ever").  Useful for
            performing bounding-box collision detection.

      @param sphere         Moving sphere.
      @param velocity   Velocity of moving sphere.
      @param box        Fixed box.
      @param timeLimit  Time limit for intersection test.

      @return true  -  if the two objects will touch.
      @return false - if there is no intersection.
    */
    static bool movingSpherePassesThroughFixedBox(
        const Sphere&           sphere,
        const Vector3&          velocity,
        const Box&              box,
        double                  timeLimit = inf());

    /**
     Tests for the intersection of a moving sphere and a fixed sphere in a
     given time limit.

     @note This function will not detect an intersection between a moving object
     that is already interpenetrating the fixed object.

     @param sphere      Moving sphere.
     @param velocity    Velocity of moving sphere.
     @param fixedSphere Fixed sphere.
     @param timeLimit   Time limit for intersection test.

     @return true  -  if the two spheres will touch.
     @return false - if there is no intersection.
    */
    static bool movingSpherePassesThroughFixedSphere(
        const Sphere&           sphere,
        const Vector3&          velocity,
        const Sphere&           fixedSphere,
        double                  timeLimit = inf());

    /**
     Tests for the intersection of two fixed spheres.

     @param sphere1 Fixed sphere 1.
     @param sphere2 Fixed sphere 2.

     @return true -  if the two spheres touch.
     @return false - if there is no intersection.
    */
    static bool fixedSolidSphereIntersectsFixedSolidSphere(
        const Sphere&           sphere1,
        const Sphere&           sphere2);

    /**
     Tests for the intersection of a fixed sphere and a fixed box.

     @param sphere Fixed sphere.
     @param box    Fixed box.

     @return true  -  if the two objects touch.
     @return false - if there is no intersection.
    */
    static bool fixedSolidSphereIntersectsFixedSolidBox(
        const Sphere&           sphere,
        const Box&              box);

    /**
     Tests whether a point is inside a rectangle defined by the vertexes
     v0, v1, v2, & v3, and the rectangle's plane normal.

     @param v0 Rectangle vertex 1.
     @param v1 Rectangle vertex 2.
     @param v2 Rectangle vertex 3.
     @param v3 Rectangle vertex 4.
     @param normal Normal to rectangle's plane.
     @param point The point in question.

     @return true  - if point is inside the rectangle.
     @return false - otherwise
    */
    static bool isPointInsideRectangle(
        const Vector3&          v0,
        const Vector3&          v1,
        const Vector3&          v2,
        const Vector3&          v3,
        const Vector3&          normal,
        const Vector3&          point);

    /**
     Finds the closest point on the perimeter of the rectangle to an
     external point; given a rectangle defined by four points v0, v1,
     v2, & v3, and the external point.

     @param v0 Rectangle vertex 1.
     @param v1 Rectangle vertex 2.
     @param v2 Rectangle vertex 3.
     @param v3 Rectangle vertex 4.
     @param point External point.

     @return Closests point to <code>point</code> on the perimeter of the
     rectangle.
     */
    static Vector3 closestPointToRectanglePerimeter(
        const Vector3&          v0,
        const Vector3&          v1,
        const Vector3&          v2,
        const Vector3&          v3,
        const Vector3&          point);

     /**
      Finds the closest point in the rectangle to an external point; Given
      a rectangle defined by four points v0, v1, v2, & v3, and the external
      point.

      @param v0 Rectangle vertex 1.
      @param v1 Rectangle vertex 2.
      @param v2 Rectangle vertex 3
      @param v3 Rectangle vertex 4.
      @param point External point.

      @return Closet point in the rectangle to the external point.
      */
     static Vector3 closestPointToRectangle(
        const Vector3&          v0,
        const Vector3&          v1,
        const Vector3&          v2,
        const Vector3&          v3,
        const Vector3&          point);
};

} // namespace

#endif // G3D_COLLISIONDETECTION_H