-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathPhysics_Collision.cpp
1760 lines (1363 loc) · 56.2 KB
/
Physics_Collision.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
#include "StdAfx.h"
#include <vphysics/virtualmesh.h>
#include <cmodel.h>
#include "BulletCollision/CollisionDispatch/btInternalEdgeUtility.h"
#include "LinearMath/btConvexHull.h"
#include "LinearMath/btGeometryUtil.h"
#include "Physics_Collision.h"
#include "Physics_Object.h"
#include "convert.h"
#include "Physics_KeyParser.h"
#include "phydata.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define COLLISION_MARGIN 0.015 // 15 mm
// TODO: Use btConvexTriangleMeshShape instead of btConvexHullShape? btw we shouldn't use btConvexTriangleMeshShape, it's not performance friendly
// #define USE_CONVEX_TRIANGLES
// lol hack
extern IVPhysicsDebugOverlay *g_pDebugOverlay;
/****************************
* CLASS CCollisionQuery
****************************/
// FIXME: We don't use triangles to represent shapes internally!
// Low priority, not even used ingame
class CCollisionQuery : public ICollisionQuery {
public:
CCollisionQuery(CPhysCollide *pCollide) {m_pCollide = pCollide;}
// number of convex pieces in the whole solid
int ConvexCount();
// triangle count for this convex piece
int TriangleCount(int convexIndex);
// get the stored game data
uint GetGameData(int convexIndex);
// Gets the triangle's verts to an array
void GetTriangleVerts(int convexIndex, int triangleIndex, Vector *verts);
void SetTriangleVerts(int convexIndex, int triangleIndex, const Vector *verts);
// returns the 7-bit material index
int GetTriangleMaterialIndex(int convexIndex, int triangleIndex);
// sets a 7-bit material index for this triangle
void SetTriangleMaterialIndex(int convexIndex, int triangleIndex, int index7bits);
private:
CPhysCollide * m_pCollide;
};
int CCollisionQuery::ConvexCount() {
if (m_pCollide->IsCompound()) {
btCompoundShape *pShape = m_pCollide->GetCompoundShape();
return pShape->getNumChildShapes();
}
return 0;
}
int CCollisionQuery::TriangleCount(int convexIndex) {
#ifdef USE_CONVEX_TRIANGLES
Assert(convexIndex < m_pCollide->GetCompoundShape()->getNumChildShapes());
//btConvexTriangleMeshShape *pChild = (btConvexTriangleMeshShape *)m_pCollide->GetCompoundShape()->getChildShape(convexIndex);
//return pChild->getNumVertices
return 0;
#else
NOT_IMPLEMENTED
return 0;
#endif
}
unsigned int CCollisionQuery::GetGameData(int convexIndex) {
NOT_IMPLEMENTED
return 0;
}
void CCollisionQuery::GetTriangleVerts(int convexIndex, int triangleIndex, Vector *verts) {
NOT_IMPLEMENTED
}
void CCollisionQuery::SetTriangleVerts(int convexIndex, int triangleIndex, const Vector *verts) {
NOT_IMPLEMENTED
}
int CCollisionQuery::GetTriangleMaterialIndex(int convexIndex, int triangleIndex) {
NOT_IMPLEMENTED
return 0;
}
void CCollisionQuery::SetTriangleMaterialIndex(int convexIndex, int triangleIndex, int index7bits) {
NOT_IMPLEMENTED
}
/****************************
* BYTESWAP DATA DESCRIPTIONS
****************************/
BEGIN_BYTESWAP_DATADESC(collideheader_t)
DEFINE_FIELD(size, FIELD_INTEGER),
DEFINE_FIELD(vphysicsID, FIELD_INTEGER),
DEFINE_FIELD(version, FIELD_SHORT),
DEFINE_FIELD(modelType, FIELD_SHORT),
END_BYTESWAP_DATADESC()
BEGIN_BYTESWAP_DATADESC(compactsurfaceheader_t)
DEFINE_FIELD(surfaceSize, FIELD_INTEGER),
DEFINE_FIELD(dragAxisAreas, FIELD_VECTOR),
DEFINE_FIELD(axisMapSize, FIELD_INTEGER),
END_BYTESWAP_DATADESC()
BEGIN_BYTESWAP_DATADESC(moppsurfaceheader_t)
DEFINE_FIELD(moppSize, FIELD_INTEGER),
END_BYTESWAP_DATADESC()
BEGIN_BYTESWAP_DATADESC(ivpcompactsurface_t)
DEFINE_ARRAY(mass_center, FIELD_FLOAT, 3),
DEFINE_ARRAY(rotation_inertia, FIELD_FLOAT, 3),
DEFINE_FIELD(upper_limit_radius, FIELD_FLOAT),
DEFINE_BITFIELD(bf1, FIELD_INTEGER, 8),
DEFINE_BITFIELD(bf1, FIELD_INTEGER, 24),
DEFINE_FIELD(offset_ledgetree_root, FIELD_INTEGER),
DEFINE_ARRAY(dummy, FIELD_INTEGER, 3),
END_BYTESWAP_DATADESC()
BEGIN_BYTESWAP_DATADESC(ivpcompactmopp_t)
DEFINE_ARRAY(mass_center, FIELD_FLOAT, 3),
DEFINE_ARRAY(rotation_inertia, FIELD_FLOAT, 3),
DEFINE_FIELD(upper_limit_radius, FIELD_FLOAT),
DEFINE_BITFIELD(bf1, FIELD_INTEGER, 8),
DEFINE_BITFIELD(bf1, FIELD_INTEGER, 24),
DEFINE_FIELD(offset_ledgetree_root, FIELD_INTEGER),
DEFINE_FIELD(offset_ledges, FIELD_INTEGER),
DEFINE_FIELD(size_convex_hull, FIELD_INTEGER),
DEFINE_FIELD(dummy, FIELD_INTEGER),
END_BYTESWAP_DATADESC()
BEGIN_BYTESWAP_DATADESC(ivpcompactledge_t)
DEFINE_FIELD(c_point_offset, FIELD_INTEGER),
DEFINE_FIELD(ledgetree_node_offset, FIELD_INTEGER),
DEFINE_BITFIELD(bf1, FIELD_INTEGER, 2),
DEFINE_BITFIELD(bf1, FIELD_INTEGER, 2),
DEFINE_BITFIELD(bf1, FIELD_INTEGER, 4),
DEFINE_BITFIELD(bf1, FIELD_INTEGER, 24),
DEFINE_FIELD(n_triangles, FIELD_SHORT),
DEFINE_FIELD(for_future_use, FIELD_SHORT),
END_BYTESWAP_DATADESC()
BEGIN_BYTESWAP_DATADESC(ivpcompactedge_t)
DEFINE_BITFIELD(bf1, FIELD_INTEGER, 16),
DEFINE_BITFIELD(bf1, FIELD_INTEGER, 15),
DEFINE_BITFIELD(bf1, FIELD_INTEGER, 1),
END_BYTESWAP_DATADESC()
BEGIN_BYTESWAP_DATADESC(ivpcompacttriangle_t)
DEFINE_BITFIELD(bf1, FIELD_INTEGER, 12),
DEFINE_BITFIELD(bf1, FIELD_INTEGER, 12),
DEFINE_BITFIELD(bf1, FIELD_INTEGER, 7),
DEFINE_BITFIELD(bf1, FIELD_INTEGER, 1),
DEFINE_EMBEDDED_ARRAY(c_three_edges, 3)
END_BYTESWAP_DATADESC()
BEGIN_BYTESWAP_DATADESC(ivpcompactledgenode_t)
DEFINE_FIELD(offset_right_node, FIELD_INTEGER),
DEFINE_FIELD(offset_compact_ledge, FIELD_INTEGER),
DEFINE_ARRAY(center, FIELD_FLOAT, 3),
DEFINE_FIELD(radius, FIELD_FLOAT),
DEFINE_ARRAY(box_sizes, FIELD_CHARACTER, 3),
DEFINE_FIELD(free_0, FIELD_CHARACTER),
END_BYTESWAP_DATADESC()
/****************************
* CLASS CPhysCollide
****************************/
CPhysCollide::CPhysCollide(btCollisionShape *pShape) {
m_pShape = pShape;
m_pShape->setUserPointer(this);
m_massCenter.setZero();
}
/****************************
* CLASS CPhysPolySoup
****************************/
class CPhysPolysoup {
public:
CPhysPolysoup() {
}
private:
};
/****************************
* CLASS CPhysicsCollision
****************************/
// NOTE:
// CPhysCollide is usually a btCompoundShape
// CPhysConvex is usually a btConvexHullShape
#define VPHYSICS_ID MAKEID('V', 'P', 'H', 'Y')
#define IVP_COMPACT_SURFACE_ID MAKEID('I', 'V', 'P', 'S')
#define IVP_COMPACT_MOPP_ID MAKEID('M', 'O', 'P', 'P')
CPhysicsCollision::CPhysicsCollision() {
// Default to old behavior
CPhysicsCollision::EnableBBoxCache(true);
}
CPhysicsCollision::~CPhysicsCollision() {
ClearBBoxCache();
}
// FIXME: Why is it important to have an array of pointers?
CPhysConvex *CPhysicsCollision::ConvexFromVerts(Vector **ppVerts, int vertCount) {
if (!ppVerts || vertCount == 0) return NULL;
// Convert the array and call the function below
Vector *pVerts = new Vector[vertCount];
for (int i = 0; i < vertCount; i++) {
pVerts[i] = *ppVerts[i];
}
CPhysConvex *pConvex = ConvexFromVerts(pVerts, vertCount);
delete[] pVerts;
return pConvex;
}
btConvexTriangleMeshShape *CreateTriMeshFromHull(HullResult &res) {
btTriangleIndexVertexArray *pMesh = new btTriangleIndexVertexArray();
btIndexedMesh mesh;
mesh.m_numTriangles = res.mNumIndices / 3;
// Duplicate the output vertex array
mesh.m_numVertices = res.mNumOutputVertices;
btVector3 *pVerts = new btVector3[res.mNumOutputVertices];
for (uint i = 0; i < res.mNumOutputVertices; i++) {
pVerts[i] = res.m_OutputVertices[i];
}
mesh.m_vertexBase = reinterpret_cast<unsigned char*>(pVerts);
mesh.m_vertexStride = sizeof(btVector3);
mesh.m_vertexType = PHY_FLOAT;
// Duplicate the index array
unsigned int *pIndices = new unsigned int[res.mNumIndices];
for (uint i = 0; i < res.mNumIndices; i++) {
pIndices[i] = res.m_Indices[i];
}
mesh.m_triangleIndexBase = (unsigned char *)pIndices;
mesh.m_triangleIndexStride = 3 * sizeof(unsigned short);
pMesh->addIndexedMesh(mesh, PHY_SHORT);
btConvexTriangleMeshShape *pShape = new btConvexTriangleMeshShape(pMesh);
return pShape;
}
// Newer version of the above (just an array, not an array of pointers)
CPhysConvex *CPhysicsCollision::ConvexFromVerts(const Vector *pVerts, int vertCount) {
if (!pVerts || vertCount == 0) return NULL;
btVector3 *pBullVerts = new btVector3[vertCount];
for (int i = 0; i < vertCount; i++) {
ConvertPosToBull(pVerts[i], pBullVerts[i]);
}
HullLibrary lib;
HullResult res;
HullDesc desc(QF_TRIANGLES, vertCount, pBullVerts);
HullError err = lib.CreateConvexHull(desc, res);
// A problem occurred in creating the hull :(
if (err != QE_OK)
return NULL;
// Okay, create a triangle mesh with this.
btConvexTriangleMeshShape *pMesh = CreateTriMeshFromHull(res);
lib.ReleaseResult(res);
return (CPhysConvex *)pMesh;
}
CPhysConvex *CPhysicsCollision::ConvexFromPlanes(float *pPlanes, int planeCount, float mergeDistance) {
NOT_IMPLEMENTED
return NULL;
}
float CPhysicsCollision::ConvexVolume(CPhysConvex *pConvex) {
if (!pConvex) return 0;
btCollisionShape *pShape = (btCollisionShape *)pConvex;
if (pShape->getShapeType() == CONVEX_TRIANGLEMESH_SHAPE_PROXYTYPE) {
btConvexTriangleMeshShape *pTriShape = (btConvexTriangleMeshShape *)pShape;
btTriangleIndexVertexArray *pArr = (btTriangleIndexVertexArray *)pTriShape->getMeshInterface();
btIndexedMesh &pMesh = pArr->getIndexedMeshArray()[0];
btVector3 *pVertexArray = (btVector3 *)pMesh.m_vertexBase;
unsigned short *pIndexArray = (unsigned short *)pMesh.m_triangleIndexBase;
// First, let's calculate the centroid of the shape.
btVector3 centroid(0, 0, 0);
for (int i = 0; i < pMesh.m_numVertices; i++) {
btVector3 vertex = ((btVector3 *)pMesh.m_vertexBase)[i];
centroid += vertex;
}
if (pMesh.m_numVertices > 0)
centroid /= (btScalar)pMesh.m_numVertices;
// Okay, now loop through all of the triangles of the shape. We're going to make the assumption
// that none of the triangles overlap, and it's guaranteed that the centroid is inside the shape.
btScalar sum(0);
for (int i = 0; i < pMesh.m_numTriangles; i++) {
btVector3 v[3];
for (int j = 0; j < 3; j++) {
v[j] = pVertexArray[pIndexArray[i * 3 + j]];
}
// Shorten the var name
btVector3 &c = centroid;
// Okay. We have the 4 vertices we need to perform the volume calculation. Now let's do it.
btMatrix3x3 mat(v[0][0] - c[0], v[1][0] - c[0], v[2][0] - c[0],
v[0][1] - c[1], v[1][1] - c[1], v[2][1] - c[1],
v[0][2] - c[2], v[1][2] - c[2], v[2][2] - c[2]);
// Aaand the volume is 1/6 the determinant of the matrix
sum += mat.determinant() / 6;
}
return sum;
}
NOT_IMPLEMENTED
return 0;
}
float CPhysicsCollision::ConvexSurfaceArea(CPhysConvex *pConvex) {
if (!pConvex) return 0;
btCollisionShape *pShape = (btCollisionShape *)pConvex;
if (pShape->getShapeType() == CONVEX_TRIANGLEMESH_SHAPE_PROXYTYPE) {
btConvexTriangleMeshShape *pTriShape = (btConvexTriangleMeshShape *)pShape;
btTriangleIndexVertexArray *pArr = (btTriangleIndexVertexArray *)pTriShape->getMeshInterface();
btIndexedMesh &pMesh = pArr->getIndexedMeshArray()[0];
btVector3 *pVertexArray = (btVector3 *)pMesh.m_vertexBase;
unsigned short *pIndexArray = (unsigned short *)pMesh.m_triangleIndexBase;
// Loop through all of the triangles in the shape and add up the surface areas
float sum = 0.f;
for (int i = 0; i < pMesh.m_numTriangles; i++) {
btVector3 v[3];
for (int j = 0; j < 3; j++) {
v[j] = pVertexArray[pIndexArray[i * 3 + j]];
}
// Area of a triangle is the length of the cross product of 2 of its sides divided by 2
btVector3 ab = v[1] - v[0];
btVector3 ac = v[2] - v[0];
sum += ab.cross(ac).length() / 2;
}
return sum;
}
NOT_IMPLEMENTED
return 0;
}
void CPhysicsCollision::ConvexFree(CPhysConvex *pConvex) {
if (!pConvex) return;
btCollisionShape *pShape = (btCollisionShape *)pConvex;
if (pShape->getShapeType() == CONVEX_TRIANGLEMESH_SHAPE_PROXYTYPE) {
btStridingMeshInterface *pMesh = ((btConvexTriangleMeshShape *)pShape)->getMeshInterface();
btTriangleIndexVertexArray *pTriArr = (btTriangleIndexVertexArray *)pMesh;
IndexedMeshArray &arr = pTriArr->getIndexedMeshArray();
for (int i = arr.size()-1; i >= 0; i--) {
btIndexedMesh &mesh = arr[i];
// Delete the index and vertex arrays (that we allocated back in VCollideLoad)
unsigned short *indexBase = (unsigned short *)mesh.m_triangleIndexBase;
delete [] indexBase;
btVector3 *vertexBase = (btVector3 *)mesh.m_vertexBase;
delete [] vertexBase;
arr.pop_back();
}
delete pMesh;
delete pShape;
} else {
delete pShape;
}
}
// TODO: Need this to get contents of a convex in a compound shape
void CPhysicsCollision::SetConvexGameData(CPhysConvex *pConvex, unsigned int gameData) {
btConvexShape *pShape = (btConvexShape *)pConvex;
pShape->setUserPointer((void *)gameData);
}
// Appears to use a polyhedron class from mathlib
CPolyhedron *CPhysicsCollision::PolyhedronFromConvex(CPhysConvex *const pConvex, bool bUseTempPolyhedron) {
NOT_IMPLEMENTED
return NULL;
}
CPhysConvex *CPhysicsCollision::ConvexFromConvexPolyhedron(const CPolyhedron &ConvexPolyhedron) {
NOT_IMPLEMENTED
return NULL;
}
void CPhysicsCollision::ConvexesFromConvexPolygon(const Vector &vPolyNormal, const Vector *pPoints, int iPointCount, CPhysConvex **ppOutput) {
NOT_IMPLEMENTED
}
// TODO: Support this, gmod lua Entity:PhysicsInitMultiConvex uses this!
// IVP internally used QHull to generate the convexes.
CPhysPolysoup *CPhysicsCollision::PolysoupCreate() {
return new CPhysPolysoup();
}
void CPhysicsCollision::PolysoupDestroy(CPhysPolysoup *pSoup) {
delete pSoup;
}
void CPhysicsCollision::PolysoupAddTriangle(CPhysPolysoup *pSoup, const Vector &a, const Vector &b, const Vector &c, int materialIndex7bits) {
NOT_IMPLEMENTED
}
// TODO: This will involve convex decomposition, which breaks a concave shape into multiple convex shapes.
// Too complex to write myself, will need a library to do this. QHull does not support this.
CPhysCollide *CPhysicsCollision::ConvertPolysoupToCollide(CPhysPolysoup *pSoup, bool useMOPP) {
NOT_IMPLEMENTED
return NULL;
}
CPhysCollide *CPhysicsCollision::ConvertConvexToCollide(CPhysConvex **ppConvex, int convexCount) {
if (convexCount == 0) return NULL;
btCompoundShape *pCompound = new btCompoundShape;
for (int i = 0; i < convexCount; i++) {
// TODO: Copy the convex and delete all of the convexes in the array, as that's how IVP worked.
btCollisionShape *pShape = (btCollisionShape *)ppConvex[i];
//btCollisionShape *pShape = (btCollisionShape *)btAlignedAlloc(pOldShape->getByteSize(), 16);
//*pShape = *pOldShape; // Now copy the data
pCompound->addChildShape(btTransform::getIdentity(), pShape);
}
pCompound->setMargin(COLLISION_MARGIN);
CPhysCollide *pCollide = new CPhysCollide(pCompound);
return pCollide;
}
CPhysCollide *CPhysicsCollision::ConvertConvexToCollideParams(CPhysConvex **pConvex, int convexCount, const convertconvexparams_t &convertParams) {
NOT_IMPLEMENTED
return ConvertConvexToCollide(pConvex, convexCount);
}
void CPhysicsCollision::AddConvexToCollide(CPhysCollide *pCollide, const CPhysConvex *pConvex, const matrix3x4_t *xform) {
if (!pCollide || !pConvex) return;
if (pCollide->IsCompound()) {
btCompoundShape *pCompound = pCollide->GetCompoundShape();
btCollisionShape *pShape = (btCollisionShape *)pConvex;
btTransform trans = btTransform::getIdentity();
if (xform) {
ConvertMatrixToBull(*xform, trans);
}
pCompound->addChildShape(trans, pShape);
}
}
void CPhysicsCollision::RemoveConvexFromCollide(CPhysCollide *pCollide, const CPhysConvex *pConvex) {
if (!pCollide || !pConvex) return;
if (pCollide->IsCompound()) {
btCompoundShape *pCompound = pCollide->GetCompoundShape();
btCollisionShape *pShape = (btCollisionShape *)pConvex;
// FIXME: Need to recalculate the aabb tree or something
pCompound->removeChildShape(pShape);
}
}
CPhysCollide *CPhysicsCollision::CreateCollide() {
btCompoundShape *pShape = new btCompoundShape();
return new CPhysCollide(pShape);
}
void CPhysicsCollision::DestroyCollide(CPhysCollide *pCollide) {
if (!pCollide || IsCachedBBox(pCollide)) return;
btCollisionShape *pShape = pCollide->GetCollisionShape();
// Compound shape? Delete all of its children.
if (pShape->isCompound()) {
btCompoundShape *pCompound = (btCompoundShape *)pShape;
for (int i = pCompound->getNumChildShapes()-1; i >= 0; i--) {
btCollisionShape *pShape = pCompound->getChildShape(i);
Assert(!pShape->isCompound()); // Compounds shouldn't have compound children.
pCompound->removeChildShapeByIndex(i);
ConvexFree((CPhysConvex *)pShape);
}
delete pCollide;
delete pCompound;
} else if (pShape->getShapeType() == TRIANGLE_MESH_SHAPE_PROXYTYPE) {
// Delete the striding mesh interface (which we allocate)
btStridingMeshInterface *pMesh = ((btTriangleMeshShape *)pShape)->getMeshInterface();
if (((btBvhTriangleMeshShape *)pShape)->getTriangleInfoMap())
delete ((btBvhTriangleMeshShape *)pShape)->getTriangleInfoMap(); // Probably shouldn't be casting this to a btBvhTriangleMeshShape. Whatever.
btTriangleIndexVertexArray *pTriArr = (btTriangleIndexVertexArray *)pMesh;
IndexedMeshArray &arr = pTriArr->getIndexedMeshArray();
for (int i = arr.size() - 1; i >= 0; i--) {
btIndexedMesh &mesh = arr[i];
// Delete the index and vertex arrays (that we allocated back in VCollideLoad)
unsigned short *indexBase = (unsigned short *)mesh.m_triangleIndexBase;
delete[] indexBase;
btVector3 *vertexBase = (btVector3 *)mesh.m_vertexBase;
delete[] vertexBase;
arr.pop_back();
}
delete pMesh;
delete pShape;
delete pCollide;
} else {
// Those dirty liars!
ConvexFree((CPhysConvex *)pCollide);
}
}
int CPhysicsCollision::CollideSize(CPhysCollide *pCollide) {
NOT_IMPLEMENTED
return 0;
}
// TODO: Design a new file format
int CPhysicsCollision::CollideWrite(char *pDest, CPhysCollide *pCollide, bool swap) {
NOT_IMPLEMENTED
return 0;
}
CPhysCollide *CPhysicsCollision::UnserializeCollide(char *pBuffer, int size, int index) {
NOT_IMPLEMENTED
return NULL;
}
float CPhysicsCollision::CollideVolume(CPhysCollide *pCollide) {
btCompoundShape *pCompound = pCollide->GetCompoundShape();
// Loop through the children and sum the volume
float sum = 0.f;
for (int i = 0; i < pCompound->getNumChildShapes(); i++) {
btCollisionShape *pChild = pCompound->getChildShape(i);
sum += ConvexVolume((CPhysConvex *)pChild);
}
return sum;
}
float CPhysicsCollision::CollideSurfaceArea(CPhysCollide *pCollide) {
btCompoundShape *pCompound = pCollide->GetCompoundShape();
// Loop through the children and sum the area
float sum = 0.f;
for (int i = 0; i < pCompound->getNumChildShapes(); i++) {
btCollisionShape *pChild = pCompound->getChildShape(i);
sum += ConvexSurfaceArea((CPhysConvex *)pChild);
}
return sum;
}
// This'll return the farthest possible vector that's still within our collision mesh.
Vector CPhysicsCollision::CollideGetExtent(const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, const Vector &direction) {
if (!pCollide) return collideOrigin;
btVector3 btDirection;
ConvertDirectionToBull(direction, btDirection);
btVector3 origin;
btQuaternion angles;
ConvertPosToBull(collideOrigin, origin);
ConvertRotationToBull(collideAngles, angles);
btTransform trans(angles, origin);
trans *= btTransform(btQuaternion::getIdentity(), pCollide->GetMassCenter()).inverse();
if (pCollide->IsCompound()) {
btVector3 maxExtents(0, 0, 0);
btScalar maxDot = 0;
const btCompoundShape *pCompound = pCollide->GetCompoundShape();
for (int i = 0; i < pCompound->getNumChildShapes(); i++) {
const btCollisionShape *pShape = pCompound->getChildShape(i);
const btTransform &childTrans = pCompound->getChildTransform(i);
if (pShape->isConvex()) {
const btConvexShape *pConvex = (const btConvexShape *)pShape;
btVector3 extents = pConvex->localGetSupportingVertex(btDirection);
extents = childTrans * extents; // Move the extents by the object's transform
if (extents.dot(btDirection) > maxDot) {
maxExtents = extents;
maxDot = extents.dot(btDirection);
}
}
}
btVector3 vec = trans * maxExtents;
Vector hlVec;
ConvertPosToHL(vec, hlVec);
/*
if (g_pDebugOverlay) {
g_pDebugOverlay->AddLineOverlay(collideOrigin, hlVec, 0, 255, 0, true, 5.f);
g_pDebugOverlay->AddBoxOverlay(hlVec, Vector(-4, -4, -4), Vector(4, 4, 4), QAngle(0, 0, 0), 255, 0, 0, 255, 5.f);
}
*/
return hlVec;
} else if (pCollide->IsConvex()) {
const btConvexShape *pConvex = pCollide->GetConvexShape();
btVector3 maxExtents = pConvex->localGetSupportingVertex(btDirection);
btVector3 vec = trans * maxExtents;
Vector hlVec;
ConvertPosToHL(vec, hlVec);
/*
if (g_pDebugOverlay) {
g_pDebugOverlay->AddLineOverlay(collideOrigin, hlVec, 0, 255, 0, true, 5.f);
g_pDebugOverlay->AddBoxOverlay(hlVec, Vector(-4, -4, -4), Vector(4, 4, 4), QAngle(0, 0, 0), 255, 0, 0, 255, 5.f);
}
*/
return hlVec;
}
return collideOrigin;
}
void CPhysicsCollision::CollideGetAABB(Vector *pMins, Vector *pMaxs, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles) {
if (!pCollide || (!pMins && !pMaxs)) return;
// Bullet returns very different AABBs than Havok.
const btCollisionShape *shape = pCollide->GetCollisionShape();
btVector3 pos, mins, maxs;
btMatrix3x3 rot;
ConvertPosToBull(collideOrigin, pos);
ConvertRotationToBull(collideAngles, rot);
btTransform transform(rot, pos);
transform *= btTransform(btQuaternion::getIdentity(), pCollide->GetMassCenter());
shape->getAabb(transform, mins, maxs);
Vector tMins, tMaxs;
ConvertAABBToHL(mins, maxs, tMins, tMaxs);
if (pMins)
*pMins = tMins;
if (pMaxs)
*pMaxs = tMaxs;
}
void CPhysicsCollision::CollideGetMassCenter(CPhysCollide *pCollide, Vector *pOutMassCenter) {
if (!pCollide || !pOutMassCenter) return;
ConvertPosToHL(pCollide->GetMassCenter(), *pOutMassCenter);
}
void CPhysicsCollision::CollideSetMassCenter(CPhysCollide *pCollide, const Vector &massCenter) {
if (!pCollide) return;
btCollisionShape *pShape = pCollide->GetCollisionShape();
btVector3 bullMassCenter;
ConvertPosToBull(massCenter, bullMassCenter);
// Since mass centers are kind of a hack in our implementation, take care of updating the compound shape's children.
// FIXME: May cause some issues with rigid bodies "moving" around, or something.
btVector3 offset = bullMassCenter - pCollide->GetMassCenter();
if (pShape->isCompound()) {
btCompoundShape *pCompound = (btCompoundShape *)pShape;
for (int i = 0; i < pCompound->getNumChildShapes(); i++) {
btTransform childTrans = pCompound->getChildTransform(i);
childTrans.setOrigin(childTrans.getOrigin() + offset);
pCompound->updateChildTransform(i, childTrans);
}
}
pCollide->SetMassCenter(bullMassCenter);
}
Vector CPhysicsCollision::CollideGetOrthographicAreas(const CPhysCollide *pCollide) {
// What is this?
NOT_IMPLEMENTED
return Vector(1, 1, 1); // Documentation says we will return 1,1,1 if ortho areas undefined
}
void CPhysicsCollision::CollideSetOrthographicAreas(CPhysCollide *pCollide, const Vector &areas) {
NOT_IMPLEMENTED
}
void CPhysicsCollision::CollideSetScale(CPhysCollide *pCollide, const Vector &scale) {
if (!pCollide) return;
if (pCollide->IsCompound()) {
btCompoundShape *pCompound = pCollide->GetCompoundShape();
btVector3 bullScale;
bullScale.setX(scale.x);
bullScale.setY(scale.z);
bullScale.setZ(scale.y);
pCompound->setLocalScaling(bullScale);
}
}
void CPhysicsCollision::CollideGetScale(const CPhysCollide *pCollide, Vector &out) {
if (!pCollide) return;
if (pCollide->IsCompound()) {
const btCompoundShape *pCompound = pCollide->GetCompoundShape();
btVector3 scale = pCompound->getLocalScaling();
out.x = scale.getX();
out.y = scale.getZ();
out.z = scale.getY();
}
}
int CPhysicsCollision::CollideIndex(const CPhysCollide *pCollide) {
NOT_IMPLEMENTED
return 0;
}
int CPhysicsCollision::GetConvexesUsedInCollideable(const CPhysCollide *pCollideable, CPhysConvex **pOutputArray, int iOutputArrayLimit) {
if (!pCollideable->IsCompound()) return 0;
const btCompoundShape *pCompound = pCollideable->GetCompoundShape();
int numSolids = pCompound->getNumChildShapes();
for (int i = 0; i < numSolids && i < iOutputArrayLimit; i++) {
const btCollisionShape *pConvex = pCompound->getChildShape(i);
pOutputArray[i] = (CPhysConvex *)pConvex;
}
return numSolids > iOutputArrayLimit ? iOutputArrayLimit : numSolids;
}
CPhysCollide *CPhysicsCollision::GetCachedBBox(const Vector &mins, const Vector &maxs) {
for (int i = 0; i < m_bboxCache.Count(); i++) {
bboxcache_t &cache = m_bboxCache[i];
if (cache.mins == mins && cache.maxs == maxs)
return cache.pCollide;
}
return NULL;
}
void CPhysicsCollision::AddCachedBBox(CPhysCollide *pModel, const Vector &mins, const Vector &maxs) {
int idx = m_bboxCache.AddToTail();
bboxcache_t &cache = m_bboxCache[idx];
cache.pCollide = pModel;
cache.mins = mins;
cache.maxs = maxs;
}
bool CPhysicsCollision::IsCachedBBox(CPhysCollide *pModel) {
for (int i = 0; i < m_bboxCache.Count(); i++) {
bboxcache_t &cache = m_bboxCache[i];
if (cache.pCollide == pModel)
return true;
}
return false;
}
void CPhysicsCollision::ClearBBoxCache() {
for (int i = m_bboxCache.Count() - 1; i >= 0; i--) {
bboxcache_t &cache = m_bboxCache[i];
// Remove the cache first so DestroyCollide doesn't stop.
CPhysCollide *pCollide = cache.pCollide;
m_bboxCache.Remove(i);
DestroyCollide(pCollide);
}
}
bool CPhysicsCollision::GetBBoxCacheSize(int *pCachedSize, int *pCachedCount) {
// pCachedSize is size in bytes
if (pCachedSize)
*pCachedSize = m_bboxCache.Count() * sizeof(bboxcache_t);
if (pCachedCount)
*pCachedCount = m_bboxCache.Count();
// Bool return value is never used.
return false;
}
void CPhysicsCollision::EnableBBoxCache(bool enable) {
m_enableBBoxCache = enable;
}
bool CPhysicsCollision::IsBBoxCacheEnabled() {
return m_enableBBoxCache;
}
CPhysConvex *CPhysicsCollision::BBoxToConvex(const Vector &mins, const Vector &maxs) {
if (mins == maxs) return NULL;
btVector3 btmins, btmaxs;
ConvertAABBToBull(mins, maxs, btmins, btmaxs);
btVector3 halfExtents = (btmaxs - btmins) / 2;
btBoxShape *box = new btBoxShape(halfExtents);
return (CPhysConvex *)box;
}
CPhysCollide *CPhysicsCollision::BBoxToCollide(const Vector &mins, const Vector &maxs) {
// consult with the bbox cache first (this is old vphysics behavior)
if (m_enableBBoxCache) {
CPhysCollide *pCached = GetCachedBBox(mins, maxs);
if (pCached)
return pCached;
}
CPhysConvex *pConvex = BBoxToConvex(mins, maxs);
if (!pConvex) return NULL;
btCompoundShape *pCompound = new btCompoundShape;
pCompound->setMargin(COLLISION_MARGIN);
btVector3 btmins, btmaxs;
ConvertAABBToBull(mins, maxs, btmins, btmaxs);
btVector3 halfExtents = (btmaxs - btmins) / 2;
pCompound->addChildShape(btTransform(btMatrix3x3::getIdentity(), btmins + halfExtents), (btCollisionShape *)pConvex);
CPhysCollide *pCollide = new CPhysCollide(pCompound);
if (m_enableBBoxCache)
AddCachedBBox(pCollide, mins, maxs);
return pCollide;
}
CPhysConvex *CPhysicsCollision::CylinderToConvex(const Vector &mins, const Vector &maxs) {
if (mins == maxs) return NULL;
btVector3 btmins, btmaxs;
ConvertAABBToBull(mins, maxs, btmins, btmaxs);
btVector3 halfSize = (btmaxs - btmins) / 2;
btCylinderShape *pShape = new btCylinderShape(halfSize);
return (CPhysConvex *)pShape;
}
CPhysConvex *CPhysicsCollision::ConeToConvex(const float radius, const float height) {
btConeShape *pShape = new btConeShape(ConvertDistanceToBull(radius), ConvertDistanceToBull(height));
return (CPhysConvex *)pShape;
}
CPhysConvex *CPhysicsCollision::SphereToConvex(const float radius) {
if (radius <= 0) return NULL;
btSphereShape *pShape = new btSphereShape(ConvertDistanceToBull(radius));
return (CPhysConvex *)pShape;
}
void CPhysicsCollision::TraceBox(const Vector &start, const Vector &end, const Vector &mins, const Vector &maxs, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, trace_t *ptr) {
Ray_t ray;
ray.Init(start, end, mins, maxs);
return TraceBox(ray, pCollide, collideOrigin, collideAngles, ptr);
}
void CPhysicsCollision::TraceBox(const Ray_t &ray, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, trace_t *ptr) {
return TraceBox(ray, MASK_ALL, NULL, pCollide, collideOrigin, collideAngles, ptr);
}
class CFilteredRayResultCallback : public btCollisionWorld::ClosestRayResultCallback {
public:
CFilteredRayResultCallback(btVector3 &rayFromWorld, btVector3 &rayToWorld, btCollisionShape *pShape, int contentsMask, IConvexInfo *pConvexInfo): btCollisionWorld::ClosestRayResultCallback(rayFromWorld, rayToWorld) {
m_contentsMask = contentsMask;
m_pConvexInfo = pConvexInfo;
m_pShape = pShape;
}
virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult &rayResult, bool normalInWorldSpace) {
// Test the convex's contents before we do anything else.
// The hit convex ID comes in from convex result's local shape info's triangle ID (stupid but whatever)
if (m_pConvexInfo && rayResult.m_localShapeInfo && rayResult.m_localShapeInfo->m_triangleIndex >= 0) {
btCollisionShape *pShape = ((btCompoundShape *)m_pShape)->getChildShape(rayResult.m_localShapeInfo->m_triangleIndex);
if (pShape) {
int contents = m_pConvexInfo->GetContents(pShape->getUserIndex());
// If none of the contents are within the mask, abort!
if (!(contents & m_contentsMask)) {
return 1;
}
}
}
return btCollisionWorld::ClosestRayResultCallback::addSingleResult(rayResult, normalInWorldSpace);
}
private:
int m_contentsMask;
IConvexInfo * m_pConvexInfo;
btCollisionShape *m_pShape;
};
class CFilteredConvexResultCallback : public btCollisionWorld::ClosestConvexResultCallback {
public:
CFilteredConvexResultCallback(btVector3 &start, btVector3 &end, btCollisionShape *pShape, int contentsMask, IConvexInfo *pConvexInfo) : btCollisionWorld::ClosestConvexResultCallback(start, end) {
m_contentsMask = contentsMask;
m_pConvexInfo = pConvexInfo;
m_pShape = pShape;
}
virtual btScalar addSingleResult(btCollisionWorld::LocalConvexResult &convexResult, bool normalInWorldSpace) {
// Test the convex's contents before we do anything else.
// The hit convex ID comes in from convex result's local shape info's triangle ID (stupid but whatever)
if (m_pConvexInfo && convexResult.m_localShapeInfo && convexResult.m_localShapeInfo->m_triangleIndex >= 0) {
btCollisionShape *pShape = ((btCompoundShape *)m_pShape)->getChildShape(convexResult.m_localShapeInfo->m_triangleIndex);
if (pShape) {
int contents = m_pConvexInfo->GetContents(pShape->getUserIndex());
// If none of the contents are within the mask, abort!
if (!(contents & m_contentsMask)) {
return 1;
}
}
}
return btCollisionWorld::ClosestConvexResultCallback::addSingleResult(convexResult, normalInWorldSpace);
}
private:
int m_contentsMask;
IConvexInfo * m_pConvexInfo;
btCollisionShape *m_pShape;
};
static ConVar bt_visualizetraces("bt_visualizetraces", "0", FCVAR_CHEAT, "Visualize physics traces");
void CPhysicsCollision::TraceBox(const Ray_t &ray, unsigned int contentsMask, IConvexInfo *pConvexInfo, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, trace_t *ptr) {
if (!pCollide || !ptr) return;
// Clear the trace (appears engine does not do this every time)