forked from sears2424/Source-PlusPlus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollisionutils.cpp
3262 lines (2782 loc) · 110 KB
/
collisionutils.cpp
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
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Common collision utility methods
//
// $Header: $
// $NoKeywords: $
//=============================================================================//
#if !defined(_STATIC_LINKED) || defined(_SHARED_LIB)
#include "collisionutils.h"
#include "cmodel.h"
#include "mathlib/mathlib.h"
#include "mathlib/vector.h"
#include "tier0/dbg.h"
#include <float.h>
#include "mathlib/vector4d.h"
#include "trace.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define UNINIT -99999.0
//-----------------------------------------------------------------------------
// Clears the trace
//-----------------------------------------------------------------------------
static void Collision_ClearTrace( const Vector &vecRayStart, const Vector &vecRayDelta, CBaseTrace *pTrace )
{
pTrace->startpos = vecRayStart;
pTrace->endpos = vecRayStart;
pTrace->endpos += vecRayDelta;
pTrace->startsolid = false;
pTrace->allsolid = false;
pTrace->fraction = 1.0f;
pTrace->contents = 0;
}
//-----------------------------------------------------------------------------
// Compute the offset in t along the ray that we'll use for the collision
//-----------------------------------------------------------------------------
static float ComputeBoxOffset( const Ray_t& ray )
{
if (ray.m_IsRay)
return 1e-3f;
// Find the projection of the box diagonal along the ray...
float offset = FloatMakePositive(ray.m_Extents[0] * ray.m_Delta[0]) +
FloatMakePositive(ray.m_Extents[1] * ray.m_Delta[1]) +
FloatMakePositive(ray.m_Extents[2] * ray.m_Delta[2]);
// We need to divide twice: Once to normalize the computation above
// so we get something in units of extents, and the second to normalize
// that with respect to the entire raycast.
offset *= InvRSquared( ray.m_Delta );
// 1e-3 is an epsilon
return offset + 1e-3;
}
//-----------------------------------------------------------------------------
// Intersects a swept box against a triangle
//-----------------------------------------------------------------------------
float IntersectRayWithTriangle( const Ray_t& ray,
const Vector& v1, const Vector& v2, const Vector& v3, bool oneSided )
{
// This is cute: Use barycentric coordinates to represent the triangle
// Vo(1-u-v) + V1u + V2v and intersect that with a line Po + Dt
// This gives us 3 equations + 3 unknowns, which we can solve with
// Cramer's rule...
// E1x u + E2x v - Dx t = Pox - Vox
// There's a couple of other optimizations, Cramer's rule involves
// computing the determinant of a matrix which has been constructed
// by three vectors. It turns out that
// det | A B C | = -( A x C ) dot B or -(C x B) dot A
// which we'll use below..
Vector edge1, edge2, org;
VectorSubtract( v2, v1, edge1 );
VectorSubtract( v3, v1, edge2 );
// Cull out one-sided stuff
if (oneSided)
{
Vector normal;
CrossProduct( edge1, edge2, normal );
if (DotProduct( normal, ray.m_Delta ) >= 0.0f)
return -1.0f;
}
// FIXME: This is inaccurate, but fast for boxes
// We want to do a fast separating axis implementation here
// with a swept triangle along the reverse direction of the ray.
// Compute some intermediary terms
Vector dirCrossEdge2, orgCrossEdge1;
CrossProduct( ray.m_Delta, edge2, dirCrossEdge2 );
// Compute the denominator of Cramer's rule:
// | -Dx E1x E2x |
// det | -Dy E1y E2y | = (D x E2) dot E1
// | -Dz E1z E2z |
float denom = DotProduct( dirCrossEdge2, edge1 );
if( FloatMakePositive( denom ) < 1e-6 )
return -1.0f;
denom = 1.0f / denom;
// Compute u. It's gotta lie in the range of 0 to 1.
// | -Dx orgx E2x |
// u = denom * det | -Dy orgy E2y | = (D x E2) dot org
// | -Dz orgz E2z |
VectorSubtract( ray.m_Start, v1, org );
float u = DotProduct( dirCrossEdge2, org ) * denom;
if ((u < 0.0f) || (u > 1.0f))
return -1.0f;
// Compute t and v the same way...
// In barycentric coords, u + v < 1
CrossProduct( org, edge1, orgCrossEdge1 );
float v = DotProduct( orgCrossEdge1, ray.m_Delta ) * denom;
if ((v < 0.0f) || (v + u > 1.0f))
return -1.0f;
// Compute the distance along the ray direction that we need to fudge
// when using swept boxes
float boxt = ComputeBoxOffset( ray );
float t = DotProduct( orgCrossEdge1, edge2 ) * denom;
if ((t < -boxt) || (t > 1.0f + boxt))
return -1.0f;
return clamp( t, 0.f, 1.f );
}
//-----------------------------------------------------------------------------
// computes the barycentric coordinates of an intersection
//-----------------------------------------------------------------------------
bool ComputeIntersectionBarycentricCoordinates( const Ray_t& ray,
const Vector& v1, const Vector& v2, const Vector& v3, float& u, float& v,
float *t )
{
Vector edge1, edge2, org;
VectorSubtract( v2, v1, edge1 );
VectorSubtract( v3, v1, edge2 );
// Compute some intermediary terms
Vector dirCrossEdge2, orgCrossEdge1;
CrossProduct( ray.m_Delta, edge2, dirCrossEdge2 );
// Compute the denominator of Cramer's rule:
// | -Dx E1x E2x |
// det | -Dy E1y E2y | = (D x E2) dot E1
// | -Dz E1z E2z |
float denom = DotProduct( dirCrossEdge2, edge1 );
if( FloatMakePositive( denom ) < 1e-6 )
return false;
denom = 1.0f / denom;
// Compute u. It's gotta lie in the range of 0 to 1.
// | -Dx orgx E2x |
// u = denom * det | -Dy orgy E2y | = (D x E2) dot org
// | -Dz orgz E2z |
VectorSubtract( ray.m_Start, v1, org );
u = DotProduct( dirCrossEdge2, org ) * denom;
// Compute t and v the same way...
// In barycentric coords, u + v < 1
CrossProduct( org, edge1, orgCrossEdge1 );
v = DotProduct( orgCrossEdge1, ray.m_Delta ) * denom;
// Compute the distance along the ray direction that we need to fudge
// when using swept boxes
if( t )
{
float boxt = ComputeBoxOffset( ray );
*t = DotProduct( orgCrossEdge1, edge2 ) * denom;
if( ( *t < -boxt ) || ( *t > 1.0f + boxt ) )
return false;
}
return true;
}
//-----------------------------------------------------------------------------
// Intersects a plane with a triangle (requires barycentric definition)
//-----------------------------------------------------------------------------
int IntersectTriangleWithPlaneBarycentric( const Vector& org, const Vector& edgeU,
const Vector& edgeV, const Vector4D& plane, Vector2D* pIntersection )
{
// This uses a barycentric method, since we need that to determine
// interpolated points, alphas, and normals
// Given the plane equation P dot N + d = 0
// and the barycentric coodinate equation P = Org + EdgeU * u + EdgeV * v
// Plug em in. Intersection occurs at u = 0 or v = 0 or u + v = 1
float orgDotNormal = DotProduct( org, plane.AsVector3D() );
float edgeUDotNormal = DotProduct( edgeU, plane.AsVector3D() );
float edgeVDotNormal = DotProduct( edgeV, plane.AsVector3D() );
int ptIdx = 0;
// u = 0
if ( edgeVDotNormal != 0.0f )
{
pIntersection[ptIdx].x = 0.0f;
pIntersection[ptIdx].y = - ( orgDotNormal - plane.w ) / edgeVDotNormal;
if ((pIntersection[ptIdx].y >= 0.0f) && (pIntersection[ptIdx].y <= 1.0f))
++ptIdx;
}
// v = 0
if ( edgeUDotNormal != 0.0f )
{
pIntersection[ptIdx].x = - ( orgDotNormal - plane.w ) / edgeUDotNormal;
pIntersection[ptIdx].y = 0.0f;
if ((pIntersection[ptIdx].x >= 0.0f) && (pIntersection[ptIdx].x <= 1.0f))
++ptIdx;
}
// u + v = 1
if (ptIdx == 2)
return ptIdx;
if ( edgeVDotNormal != edgeUDotNormal )
{
pIntersection[ptIdx].x = - ( orgDotNormal - plane.w + edgeVDotNormal) /
( edgeUDotNormal - edgeVDotNormal);
pIntersection[ptIdx].y = 1.0f - pIntersection[ptIdx].x;
if ((pIntersection[ptIdx].x >= 0.0f) && (pIntersection[ptIdx].x <= 1.0f) &&
(pIntersection[ptIdx].y >= 0.0f) && (pIntersection[ptIdx].y <= 1.0f))
++ptIdx;
}
Assert( ptIdx < 3 );
return ptIdx;
}
//-----------------------------------------------------------------------------
// Returns true if a box intersects with a sphere
//-----------------------------------------------------------------------------
bool IsSphereIntersectingSphere( const Vector& center1, float radius1,
const Vector& center2, float radius2 )
{
Vector delta;
VectorSubtract( center2, center1, delta );
float distSq = delta.LengthSqr();
float radiusSum = radius1 + radius2;
return (distSq <= (radiusSum * radiusSum));
}
//-----------------------------------------------------------------------------
// Returns true if a box intersects with a sphere
//-----------------------------------------------------------------------------
bool IsBoxIntersectingSphere( const Vector& boxMin, const Vector& boxMax,
const Vector& center, float radius )
{
// See Graphics Gems, box-sphere intersection
float dmin = 0.0f;
float flDelta;
// Unrolled the loop.. this is a big cycle stealer...
if (center[0] < boxMin[0])
{
flDelta = center[0] - boxMin[0];
dmin += flDelta * flDelta;
}
else if (center[0] > boxMax[0])
{
flDelta = boxMax[0] - center[0];
dmin += flDelta * flDelta;
}
if (center[1] < boxMin[1])
{
flDelta = center[1] - boxMin[1];
dmin += flDelta * flDelta;
}
else if (center[1] > boxMax[1])
{
flDelta = boxMax[1] - center[1];
dmin += flDelta * flDelta;
}
if (center[2] < boxMin[2])
{
flDelta = center[2] - boxMin[2];
dmin += flDelta * flDelta;
}
else if (center[2] > boxMax[2])
{
flDelta = boxMax[2] - center[2];
dmin += flDelta * flDelta;
}
return dmin < radius * radius;
}
bool IsBoxIntersectingSphereExtents( const Vector& boxCenter, const Vector& boxHalfDiag,
const Vector& center, float radius )
{
// See Graphics Gems, box-sphere intersection
float dmin = 0.0f;
float flDelta, flDiff;
// Unrolled the loop.. this is a big cycle stealer...
flDiff = FloatMakePositive( center.x - boxCenter.x );
if (flDiff > boxHalfDiag.x)
{
flDelta = flDiff - boxHalfDiag.x;
dmin += flDelta * flDelta;
}
flDiff = FloatMakePositive( center.y - boxCenter.y );
if (flDiff > boxHalfDiag.y)
{
flDelta = flDiff - boxHalfDiag.y;
dmin += flDelta * flDelta;
}
flDiff = FloatMakePositive( center.z - boxCenter.z );
if (flDiff > boxHalfDiag.z)
{
flDelta = flDiff - boxHalfDiag.z;
dmin += flDelta * flDelta;
}
return dmin < radius * radius;
}
//-----------------------------------------------------------------------------
// Returns true if a rectangle intersects with a circle
//-----------------------------------------------------------------------------
bool IsCircleIntersectingRectangle( const Vector2D& boxMin, const Vector2D& boxMax,
const Vector2D& center, float radius )
{
// See Graphics Gems, box-sphere intersection
float dmin = 0.0f;
float flDelta;
if (center[0] < boxMin[0])
{
flDelta = center[0] - boxMin[0];
dmin += flDelta * flDelta;
}
else if (center[0] > boxMax[0])
{
flDelta = boxMax[0] - center[0];
dmin += flDelta * flDelta;
}
if (center[1] < boxMin[1])
{
flDelta = center[1] - boxMin[1];
dmin += flDelta * flDelta;
}
else if (center[1] > boxMax[1])
{
flDelta = boxMax[1] - center[1];
dmin += flDelta * flDelta;
}
return dmin < radius * radius;
}
//-----------------------------------------------------------------------------
// returns true if there's an intersection between ray and sphere
//-----------------------------------------------------------------------------
bool IsRayIntersectingSphere( const Vector &vecRayOrigin, const Vector &vecRayDelta,
const Vector& vecCenter, float flRadius, float flTolerance )
{
// For this algorithm, find a point on the ray which is closest to the sphere origin
// Do this by making a plane passing through the sphere origin
// whose normal is parallel to the ray. Intersect that plane with the ray.
// Plane: N dot P = I, N = D (ray direction), I = C dot N = C dot D
// Ray: P = O + D * t
// D dot ( O + D * t ) = C dot D
// D dot O + D dot D * t = C dot D
// t = (C - O) dot D / D dot D
// Clamp t to (0,1)
// Find distance of the point on the ray to the sphere center.
Assert( flTolerance >= 0.0f );
flRadius += flTolerance;
Vector vecRayToSphere;
VectorSubtract( vecCenter, vecRayOrigin, vecRayToSphere );
float flNumerator = DotProduct( vecRayToSphere, vecRayDelta );
float t;
if (flNumerator <= 0.0f)
{
t = 0.0f;
}
else
{
float flDenominator = DotProduct( vecRayDelta, vecRayDelta );
if ( flNumerator > flDenominator )
t = 1.0f;
else
t = flNumerator / flDenominator;
}
Vector vecClosestPoint;
VectorMA( vecRayOrigin, t, vecRayDelta, vecClosestPoint );
return ( vecClosestPoint.DistToSqr( vecCenter ) <= flRadius * flRadius );
// NOTE: This in an alternate algorithm which I didn't use because I'd have to use a sqrt
// So it's probably faster to do this other algorithm. I'll leave the comments here
// for how to go back if we want to
// Solve using the ray equation + the sphere equation
// P = o + dt
// (x - xc)^2 + (y - yc)^2 + (z - zc)^2 = r^2
// (ox + dx * t - xc)^2 + (oy + dy * t - yc)^2 + (oz + dz * t - zc)^2 = r^2
// (ox - xc)^2 + 2 * (ox-xc) * dx * t + dx^2 * t^2 +
// (oy - yc)^2 + 2 * (oy-yc) * dy * t + dy^2 * t^2 +
// (oz - zc)^2 + 2 * (oz-zc) * dz * t + dz^2 * t^2 = r^2
// (dx^2 + dy^2 + dz^2) * t^2 + 2 * ((ox-xc)dx + (oy-yc)dy + (oz-zc)dz) t +
// (ox-xc)^2 + (oy-yc)^2 + (oz-zc)^2 - r^2 = 0
// or, t = (-b +/- sqrt( b^2 - 4ac)) / 2a
// a = DotProduct( vecRayDelta, vecRayDelta );
// b = 2 * DotProduct( vecRayOrigin - vecCenter, vecRayDelta )
// c = DotProduct(vecRayOrigin - vecCenter, vecRayOrigin - vecCenter) - flRadius * flRadius;
// Valid solutions are possible only if b^2 - 4ac >= 0
// Therefore, compute that value + see if we got it
}
//-----------------------------------------------------------------------------
//
// IntersectInfiniteRayWithSphere
//
// Returns whether or not there was an intersection.
// Returns the two intersection points
//
//-----------------------------------------------------------------------------
bool IntersectInfiniteRayWithSphere( const Vector &vecRayOrigin, const Vector &vecRayDelta,
const Vector &vecSphereCenter, float flRadius, float *pT1, float *pT2 )
{
// Solve using the ray equation + the sphere equation
// P = o + dt
// (x - xc)^2 + (y - yc)^2 + (z - zc)^2 = r^2
// (ox + dx * t - xc)^2 + (oy + dy * t - yc)^2 + (oz + dz * t - zc)^2 = r^2
// (ox - xc)^2 + 2 * (ox-xc) * dx * t + dx^2 * t^2 +
// (oy - yc)^2 + 2 * (oy-yc) * dy * t + dy^2 * t^2 +
// (oz - zc)^2 + 2 * (oz-zc) * dz * t + dz^2 * t^2 = r^2
// (dx^2 + dy^2 + dz^2) * t^2 + 2 * ((ox-xc)dx + (oy-yc)dy + (oz-zc)dz) t +
// (ox-xc)^2 + (oy-yc)^2 + (oz-zc)^2 - r^2 = 0
// or, t = (-b +/- sqrt( b^2 - 4ac)) / 2a
// a = DotProduct( vecRayDelta, vecRayDelta );
// b = 2 * DotProduct( vecRayOrigin - vecCenter, vecRayDelta )
// c = DotProduct(vecRayOrigin - vecCenter, vecRayOrigin - vecCenter) - flRadius * flRadius;
Vector vecSphereToRay;
VectorSubtract( vecRayOrigin, vecSphereCenter, vecSphereToRay );
float a = DotProduct( vecRayDelta, vecRayDelta );
// This would occur in the case of a zero-length ray
if ( a == 0.0f )
{
*pT1 = *pT2 = 0.0f;
return vecSphereToRay.LengthSqr() <= flRadius * flRadius;
}
float b = 2 * DotProduct( vecSphereToRay, vecRayDelta );
float c = DotProduct( vecSphereToRay, vecSphereToRay ) - flRadius * flRadius;
float flDiscrim = b * b - 4 * a * c;
if ( flDiscrim < 0.0f )
return false;
flDiscrim = sqrt( flDiscrim );
float oo2a = 0.5f / a;
*pT1 = ( - b - flDiscrim ) * oo2a;
*pT2 = ( - b + flDiscrim ) * oo2a;
return true;
}
//-----------------------------------------------------------------------------
//
// IntersectRayWithSphere
//
// Returns whether or not there was an intersection.
// Returns the two intersection points, clamped to (0,1)
//
//-----------------------------------------------------------------------------
bool IntersectRayWithSphere( const Vector &vecRayOrigin, const Vector &vecRayDelta,
const Vector &vecSphereCenter, float flRadius, float *pT1, float *pT2 )
{
if ( !IntersectInfiniteRayWithSphere( vecRayOrigin, vecRayDelta, vecSphereCenter, flRadius, pT1, pT2 ) )
return false;
if (( *pT1 > 1.0f ) || ( *pT2 < 0.0f ))
return false;
// Clamp it!
if ( *pT1 < 0.0f )
*pT1 = 0.0f;
if ( *pT2 > 1.0f )
*pT2 = 1.0f;
return true;
}
// returns true if the sphere and cone intersect
// NOTE: cone sine/cosine are the half angle of the cone
bool IsSphereIntersectingCone( const Vector &sphereCenter, float sphereRadius, const Vector &coneOrigin, const Vector &coneNormal, float coneSine, float coneCosine )
{
Vector backCenter = coneOrigin - (sphereRadius / coneSine) * coneNormal;
Vector delta = sphereCenter - backCenter;
float deltaLen = delta.Length();
if ( DotProduct(coneNormal, delta) >= deltaLen*coneCosine )
{
delta = sphereCenter - coneOrigin;
deltaLen = delta.Length();
if ( -DotProduct(coneNormal, delta) >= deltaLen * coneSine )
{
return ( deltaLen <= sphereRadius ) ? true : false;
}
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// returns true if the point is in the box
//-----------------------------------------------------------------------------
bool IsPointInBox( const Vector& pt, const Vector& boxMin, const Vector& boxMax )
{
Assert( boxMin[0] <= boxMax[0] );
Assert( boxMin[1] <= boxMax[1] );
Assert( boxMin[2] <= boxMax[2] );
// on x360, force use of SIMD version.
if (IsX360())
{
return IsPointInBox( LoadUnaligned3SIMD(pt.Base()), LoadUnaligned3SIMD(boxMin.Base()), LoadUnaligned3SIMD(boxMax.Base()) ) ;
}
if ( (pt[0] > boxMax[0]) || (pt[0] < boxMin[0]) )
return false;
if ( (pt[1] > boxMax[1]) || (pt[1] < boxMin[1]) )
return false;
if ( (pt[2] > boxMax[2]) || (pt[2] < boxMin[2]) )
return false;
return true;
}
bool IsPointInCone( const Vector &pt, const Vector &origin, const Vector &axis, float cosAngle, float length )
{
Vector delta = pt - origin;
float dist = VectorNormalize( delta );
float dot = DotProduct( delta, axis );
if ( dot < cosAngle )
return false;
if ( dist * dot > length )
return false;
return true;
}
//-----------------------------------------------------------------------------
// returns true if there's an intersection between two boxes
//-----------------------------------------------------------------------------
bool IsBoxIntersectingBox( const Vector& boxMin1, const Vector& boxMax1,
const Vector& boxMin2, const Vector& boxMax2 )
{
Assert( boxMin1[0] <= boxMax1[0] );
Assert( boxMin1[1] <= boxMax1[1] );
Assert( boxMin1[2] <= boxMax1[2] );
Assert( boxMin2[0] <= boxMax2[0] );
Assert( boxMin2[1] <= boxMax2[1] );
Assert( boxMin2[2] <= boxMax2[2] );
if ( (boxMin1[0] > boxMax2[0]) || (boxMax1[0] < boxMin2[0]) )
return false;
if ( (boxMin1[1] > boxMax2[1]) || (boxMax1[1] < boxMin2[1]) )
return false;
if ( (boxMin1[2] > boxMax2[2]) || (boxMax1[2] < boxMin2[2]) )
return false;
return true;
}
bool IsBoxIntersectingBoxExtents( const Vector& boxCenter1, const Vector& boxHalfDiagonal1,
const Vector& boxCenter2, const Vector& boxHalfDiagonal2 )
{
Vector vecDelta, vecSize;
VectorSubtract( boxCenter1, boxCenter2, vecDelta );
VectorAdd( boxHalfDiagonal1, boxHalfDiagonal2, vecSize );
return ( FloatMakePositive( vecDelta.x ) <= vecSize.x ) &&
( FloatMakePositive( vecDelta.y ) <= vecSize.y ) &&
( FloatMakePositive( vecDelta.z ) <= vecSize.z );
}
//-----------------------------------------------------------------------------
//
// IsOBBIntersectingOBB
//
// returns true if there's an intersection between two OBBs
//
//-----------------------------------------------------------------------------
bool IsOBBIntersectingOBB( const Vector &vecOrigin1, const QAngle &vecAngles1, const Vector& boxMin1, const Vector& boxMax1,
const Vector &vecOrigin2, const QAngle &vecAngles2, const Vector& boxMin2, const Vector& boxMax2, float flTolerance )
{
// FIXME: Simple case AABB check doesn't work because the min and max extents are not oriented based on the angle
// this fast check would only be good for cubes.
/*if ( vecAngles1 == vecAngles2 )
{
const Vector &vecDelta = vecOrigin2 - vecOrigin1;
Vector vecOtherMins, vecOtherMaxs;
VectorAdd( boxMin2, vecDelta, vecOtherMins );
VectorAdd( boxMax2, vecDelta, vecOtherMaxs );
return IsBoxIntersectingBox( boxMin1, boxMax1, vecOtherMins, vecOtherMaxs );
}*/
// OBB test...
cplane_t plane;
bool bFoundPlane = ComputeSeparatingPlane( vecOrigin1, vecAngles1, boxMin1, boxMax1,
vecOrigin2, vecAngles2, boxMin2, boxMax2, flTolerance, &plane );
return (bFoundPlane == false);
}
// NOTE: This is only very slightly faster on high end PCs and x360
#define USE_SIMD_RAY_CHECKS 1
//-----------------------------------------------------------------------------
// returns true if there's an intersection between box and ray
//-----------------------------------------------------------------------------
bool FASTCALL IsBoxIntersectingRay( const Vector& boxMin, const Vector& boxMax,
const Vector& origin, const Vector& vecDelta, float flTolerance )
{
#if USE_SIMD_RAY_CHECKS
// Load the unaligned ray/box parameters into SIMD registers
fltx4 start = LoadUnaligned3SIMD(origin.Base());
fltx4 delta = LoadUnaligned3SIMD(vecDelta.Base());
fltx4 boxMins = LoadUnaligned3SIMD( boxMin.Base() );
fltx4 boxMaxs = LoadUnaligned3SIMD( boxMax.Base() );
fltx4 epsilon = ReplicateX4(flTolerance);
// compute the mins/maxs of the box expanded by the ray extents
// relocate the problem so that the ray start is at the origin.
fltx4 offsetMins = SubSIMD(boxMins, start);
fltx4 offsetMaxs = SubSIMD(boxMaxs, start);
fltx4 offsetMinsExpanded = SubSIMD(offsetMins, epsilon);
fltx4 offsetMaxsExpanded = AddSIMD(offsetMaxs, epsilon);
// Check to see if both the origin (start point) and the end point (delta) are on the front side
// of any of the box sides - if so there can be no intersection
fltx4 startOutMins = CmpLtSIMD(Four_Zeros, offsetMinsExpanded);
fltx4 endOutMins = CmpLtSIMD(delta,offsetMinsExpanded);
fltx4 minsMask = AndSIMD( startOutMins, endOutMins );
fltx4 startOutMaxs = CmpGtSIMD(Four_Zeros, offsetMaxsExpanded);
fltx4 endOutMaxs = CmpGtSIMD(delta,offsetMaxsExpanded);
fltx4 maxsMask = AndSIMD( startOutMaxs, endOutMaxs );
if ( IsAnyNegative(SetWToZeroSIMD(OrSIMD(minsMask,maxsMask))))
return false;
// now build the per-axis interval of t for intersections
fltx4 invDelta = ReciprocalSaturateSIMD(delta);
fltx4 tmins = MulSIMD( offsetMinsExpanded, invDelta );
fltx4 tmaxs = MulSIMD( offsetMaxsExpanded, invDelta );
fltx4 crossPlane = OrSIMD(XorSIMD(startOutMins,endOutMins), XorSIMD(startOutMaxs,endOutMaxs));
// only consider axes where we crossed a plane
tmins = MaskedAssign( crossPlane, tmins, Four_Negative_FLT_MAX );
tmaxs = MaskedAssign( crossPlane, tmaxs, Four_FLT_MAX );
// now sort the interval per axis
fltx4 mint = MinSIMD( tmins, tmaxs );
fltx4 maxt = MaxSIMD( tmins, tmaxs );
// now find the intersection of the intervals on all axes
fltx4 firstOut = FindLowestSIMD3(maxt);
fltx4 lastIn = FindHighestSIMD3(mint);
// NOTE: This is really a scalar quantity now [t0,t1] == [lastIn,firstOut]
firstOut = MinSIMD(firstOut, Four_Ones);
lastIn = MaxSIMD(lastIn, Four_Zeros);
// If the final interval is valid lastIn<firstOut, check for separation
fltx4 separation = CmpGtSIMD(lastIn, firstOut);
return IsAllZeros(separation);
#else
// On the x360, we force use of the SIMD functions.
#if defined(_X360)
if (IsX360())
{
fltx4 delta = LoadUnaligned3SIMD(vecDelta.Base());
return IsBoxIntersectingRay(
LoadUnaligned3SIMD(boxMin.Base()), LoadUnaligned3SIMD(boxMax.Base()),
LoadUnaligned3SIMD(origin.Base()), delta, ReciprocalSIMD(delta), // ray parameters
ReplicateX4(flTolerance) ///< eg from ReplicateX4(flTolerance)
);
}
#endif
Assert( boxMin[0] <= boxMax[0] );
Assert( boxMin[1] <= boxMax[1] );
Assert( boxMin[2] <= boxMax[2] );
// FIXME: Surely there's a faster way
float tmin = -FLT_MAX;
float tmax = FLT_MAX;
for (int i = 0; i < 3; ++i)
{
// Parallel case...
if (FloatMakePositive(vecDelta[i]) < 1e-8)
{
// Check that origin is in the box
// if not, then it doesn't intersect..
if ( (origin[i] < boxMin[i] - flTolerance) || (origin[i] > boxMax[i] + flTolerance) )
return false;
continue;
}
// non-parallel case
// Find the t's corresponding to the entry and exit of
// the ray along x, y, and z. The find the furthest entry
// point, and the closest exit point. Once that is done,
// we know we don't collide if the closest exit point
// is behind the starting location. We also don't collide if
// the closest exit point is in front of the furthest entry point
float invDelta = 1.0f / vecDelta[i];
float t1 = (boxMin[i] - flTolerance - origin[i]) * invDelta;
float t2 = (boxMax[i] + flTolerance - origin[i]) * invDelta;
if (t1 > t2)
{
float temp = t1;
t1 = t2;
t2 = temp;
}
if (t1 > tmin)
tmin = t1;
if (t2 < tmax)
tmax = t2;
if (tmin > tmax)
return false;
if (tmax < 0)
return false;
if (tmin > 1)
return false;
}
return true;
#endif
}
//-----------------------------------------------------------------------------
// returns true if there's an intersection between box and ray
//-----------------------------------------------------------------------------
bool FASTCALL IsBoxIntersectingRay( const Vector& boxMin, const Vector& boxMax,
const Vector& origin, const Vector& vecDelta,
const Vector& vecInvDelta, float flTolerance )
{
#if USE_SIMD_RAY_CHECKS
// Load the unaligned ray/box parameters into SIMD registers
fltx4 start = LoadUnaligned3SIMD(origin.Base());
fltx4 delta = LoadUnaligned3SIMD(vecDelta.Base());
fltx4 boxMins = LoadUnaligned3SIMD( boxMin.Base() );
fltx4 boxMaxs = LoadUnaligned3SIMD( boxMax.Base() );
// compute the mins/maxs of the box expanded by the ray extents
// relocate the problem so that the ray start is at the origin.
boxMins = SubSIMD(boxMins, start);
boxMaxs = SubSIMD(boxMaxs, start);
// Check to see if both the origin (start point) and the end point (delta) are on the front side
// of any of the box sides - if so there can be no intersection
fltx4 startOutMins = CmpLtSIMD(Four_Zeros, boxMins);
fltx4 endOutMins = CmpLtSIMD(delta,boxMins);
fltx4 minsMask = AndSIMD( startOutMins, endOutMins );
fltx4 startOutMaxs = CmpGtSIMD(Four_Zeros, boxMaxs);
fltx4 endOutMaxs = CmpGtSIMD(delta,boxMaxs);
fltx4 maxsMask = AndSIMD( startOutMaxs, endOutMaxs );
if ( IsAnyNegative(SetWToZeroSIMD(OrSIMD(minsMask,maxsMask))))
return false;
// now build the per-axis interval of t for intersections
fltx4 epsilon = ReplicateX4(flTolerance);
fltx4 invDelta = LoadUnaligned3SIMD(vecInvDelta.Base());
boxMins = SubSIMD(boxMins, epsilon);
boxMaxs = AddSIMD(boxMaxs, epsilon);
boxMins = MulSIMD( boxMins, invDelta );
boxMaxs = MulSIMD( boxMaxs, invDelta );
fltx4 crossPlane = OrSIMD(XorSIMD(startOutMins,endOutMins), XorSIMD(startOutMaxs,endOutMaxs));
// only consider axes where we crossed a plane
boxMins = MaskedAssign( crossPlane, boxMins, Four_Negative_FLT_MAX );
boxMaxs = MaskedAssign( crossPlane, boxMaxs, Four_FLT_MAX );
// now sort the interval per axis
fltx4 mint = MinSIMD( boxMins, boxMaxs );
fltx4 maxt = MaxSIMD( boxMins, boxMaxs );
// now find the intersection of the intervals on all axes
fltx4 firstOut = FindLowestSIMD3(maxt);
fltx4 lastIn = FindHighestSIMD3(mint);
// NOTE: This is really a scalar quantity now [t0,t1] == [lastIn,firstOut]
firstOut = MinSIMD(firstOut, Four_Ones);
lastIn = MaxSIMD(lastIn, Four_Zeros);
// If the final interval is valid lastIn<firstOut, check for separation
fltx4 separation = CmpGtSIMD(lastIn, firstOut);
return IsAllZeros(separation);
#else
// On the x360, we force use of the SIMD functions.
#if defined(_X360) && !defined(PARANOID_SIMD_ASSERTING)
if (IsX360())
{
return IsBoxIntersectingRay(
LoadUnaligned3SIMD(boxMin.Base()), LoadUnaligned3SIMD(boxMax.Base()),
LoadUnaligned3SIMD(origin.Base()), LoadUnaligned3SIMD(vecDelta.Base()), LoadUnaligned3SIMD(vecInvDelta.Base()), // ray parameters
ReplicateX4(flTolerance) ///< eg from ReplicateX4(flTolerance)
);
}
#endif
Assert( boxMin[0] <= boxMax[0] );
Assert( boxMin[1] <= boxMax[1] );
Assert( boxMin[2] <= boxMax[2] );
// FIXME: Surely there's a faster way
float tmin = -FLT_MAX;
float tmax = FLT_MAX;
for ( int i = 0; i < 3; ++i )
{
// Parallel case...
if ( FloatMakePositive( vecDelta[i] ) < 1e-8 )
{
// Check that origin is in the box, if not, then it doesn't intersect..
if ( ( origin[i] < boxMin[i] - flTolerance ) || ( origin[i] > boxMax[i] + flTolerance ) )
return false;
continue;
}
// Non-parallel case
// Find the t's corresponding to the entry and exit of
// the ray along x, y, and z. The find the furthest entry
// point, and the closest exit point. Once that is done,
// we know we don't collide if the closest exit point
// is behind the starting location. We also don't collide if
// the closest exit point is in front of the furthest entry point
float t1 = ( boxMin[i] - flTolerance - origin[i] ) * vecInvDelta[i];
float t2 = ( boxMax[i] + flTolerance - origin[i] ) * vecInvDelta[i];
if ( t1 > t2 )
{
float temp = t1;
t1 = t2;
t2 = temp;
}
if (t1 > tmin)
tmin = t1;
if (t2 < tmax)
tmax = t2;
if (tmin > tmax)
return false;
if (tmax < 0)
return false;
if (tmin > 1)
return false;
}
return true;
#endif
}
//-----------------------------------------------------------------------------
// Intersects a ray with a aabb, return true if they intersect
//-----------------------------------------------------------------------------
bool FASTCALL IsBoxIntersectingRay( const Vector& vecBoxMin, const Vector& vecBoxMax, const Ray_t& ray, float flTolerance )
{
// On the x360, we force use of the SIMD functions.
#if defined(_X360)
if (IsX360())
{
return IsBoxIntersectingRay(
LoadUnaligned3SIMD(vecBoxMin.Base()), LoadUnaligned3SIMD(vecBoxMax.Base()),
ray, flTolerance);
}
#endif
if ( !ray.m_IsSwept )
{
Vector rayMins, rayMaxs;
VectorSubtract( ray.m_Start, ray.m_Extents, rayMins );
VectorAdd( ray.m_Start, ray.m_Extents, rayMaxs );
if ( flTolerance != 0.0f )
{
rayMins.x -= flTolerance; rayMins.y -= flTolerance; rayMins.z -= flTolerance;
rayMaxs.x += flTolerance; rayMaxs.y += flTolerance; rayMaxs.z += flTolerance;
}
return IsBoxIntersectingBox( vecBoxMin, vecBoxMax, rayMins, rayMaxs );
}
Vector vecExpandedBoxMin, vecExpandedBoxMax;
VectorSubtract( vecBoxMin, ray.m_Extents, vecExpandedBoxMin );
VectorAdd( vecBoxMax, ray.m_Extents, vecExpandedBoxMax );
return IsBoxIntersectingRay( vecExpandedBoxMin, vecExpandedBoxMax, ray.m_Start, ray.m_Delta, flTolerance );
}
//-----------------------------------------------------------------------------
// returns true if there's an intersection between box and ray (SIMD version)
//-----------------------------------------------------------------------------
#ifdef _X360
bool FASTCALL IsBoxIntersectingRay( fltx4 boxMin, fltx4 boxMax,
fltx4 origin, fltx4 delta, fltx4 invDelta, // ray parameters
fltx4 vTolerance ///< eg from ReplicateX4(flTolerance)
)
#else
bool FASTCALL IsBoxIntersectingRay( const fltx4 &inBoxMin, const fltx4 & inBoxMax,
const fltx4 & origin, const fltx4 & delta, const fltx4 & invDelta, // ray parameters
const fltx4 & vTolerance ///< eg from ReplicateX4(flTolerance)
)
#endif
{
// Load the unaligned ray/box parameters into SIMD registers
// compute the mins/maxs of the box expanded by the ray extents
// relocate the problem so that the ray start is at the origin.
#ifdef _X360
boxMin = SubSIMD(boxMin, origin);
boxMax = SubSIMD(boxMax, origin);
#else
fltx4 boxMin = SubSIMD(inBoxMin, origin);
fltx4 boxMax = SubSIMD(inBoxMax, origin);
#endif
// Check to see if the origin (start point) and the end point (delta) are on the same side
// of any of the box sides - if so there can be no intersection
fltx4 startOutMins = AndSIMD( CmpLtSIMD(Four_Zeros, boxMin), CmpLtSIMD(delta,boxMin) );
fltx4 startOutMaxs = AndSIMD( CmpGtSIMD(Four_Zeros, boxMax), CmpGtSIMD(delta,boxMax) );
if ( IsAnyNegative(SetWToZeroSIMD(OrSIMD(startOutMaxs,startOutMins))))
return false;
// now build the per-axis interval of t for intersections
boxMin = SubSIMD(boxMin, vTolerance);
boxMax = AddSIMD(boxMax, vTolerance);
boxMin = MulSIMD( boxMin, invDelta );
boxMax = MulSIMD( boxMax, invDelta );
// now sort the interval per axis
fltx4 mint = MinSIMD( boxMin, boxMax );
fltx4 maxt = MaxSIMD( boxMin, boxMax );
// now find the intersection of the intervals on all axes
fltx4 firstOut = FindLowestSIMD3(maxt);
fltx4 lastIn = FindHighestSIMD3(mint);
// NOTE: This is really a scalar quantity now [t0,t1] == [lastIn,firstOut]
firstOut = MinSIMD(firstOut, Four_Ones);
lastIn = MaxSIMD(lastIn, Four_Zeros);
// If the final interval is valid lastIn<firstOut, check for separation
fltx4 separation = CmpGtSIMD(lastIn, firstOut);
return IsAllZeros(separation);
}
bool FASTCALL IsBoxIntersectingRay( const fltx4& boxMin, const fltx4& boxMax,
const Ray_t& ray, float flTolerance )
{
fltx4 vTolerance = ReplicateX4(flTolerance);
fltx4 rayStart = LoadAlignedSIMD(ray.m_Start);
fltx4 rayExtents = LoadAlignedSIMD(ray.m_Extents);
if ( !ray.m_IsSwept )
{
fltx4 rayMins, rayMaxs;
rayMins = SubSIMD(rayStart, rayExtents);
rayMaxs = AddSIMD(rayStart, rayExtents);
rayMins = AddSIMD(rayMins, vTolerance);
rayMaxs = AddSIMD(rayMaxs, vTolerance);